text
stringlengths
14
6.51M
{******************************************************************************* 作者: dmzn@163.com 2007-11-11 描述: 添加,修改(程序标识,实体标识) 备注: &."程序标识"用于标识一个程序的身份. &."实体标识"表示一个程序内的某个功能,它包括若干字典项. &."程序标识"是"实体标识"等于空的一个特例. *******************************************************************************} unit UFormEntity; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TFrmEntity = class(TForm) BtnSave: TButton; Button2: TButton; Panel1: TPanel; Edit_Entity: TLabeledEdit; Edit_Prog: TLabeledEdit; Label1: TLabel; Edit_Desc: TLabeledEdit; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BtnSaveClick(Sender: TObject); procedure Edit_ProgKeyPress(Sender: TObject; var Key: Char); private procedure LoadData(const nProgID,nEntity: string); {*载入数据*} public { Public declarations } end; function ShowAddEntityForm: Boolean; function ShowEditEntityForm(const nProgID,nEntity: string): Boolean; //入口函数 implementation {$R *.dfm} uses UMgrDataDict, USysDict, ULibFun, USysConst; //------------------------------------------------------------------------------ //Date: 2007-11-11 //Desc: 添加实体标识 function ShowAddEntityForm: Boolean; begin with TFrmEntity.Create(Application) do begin Caption := '添加实体'; Result := ShowModal = mrOK; Free; end; end; //Date: 2007-11-11 //Parm: 程序标识;实体标识 //Desc: 修改nProgID下的nEntity实体 function ShowEditEntityForm(const nProgID,nEntity: string): Boolean; begin with TFrmEntity.Create(Application) do begin Caption := '修改实体'; LoadData(nProgID, nEntity); Result := ShowModal = mrOK; Free; end; end; //------------------------------------------------------------------------------ //Desc: 载入当前实体数据 procedure TFrmEntity.LoadData(const nProgID,nEntity: string); var nList: TList; nIdx: integer; begin Edit_Prog.Text := nProgID; Edit_Entity.Text := nEntity; Edit_Prog.ReadOnly := True; Edit_Entity.ReadOnly := True; if not gSysEntityManager.LoadProgList then Exit; nList := gSysEntityManager.ProgList; for nIdx:=nList.Count - 1 downto 0 do with PEntityItemData(nList[nIdx])^ do if (CompareText(nProgID, FProgID) = 0) and (CompareText(nEntity, FEntity) = 0) then begin Edit_Desc.Text := FTitle; end; end; //------------------------------------------------------------------------------ procedure TFrmEntity.FormCreate(Sender: TObject); begin LoadFormConfig(Self); end; procedure TFrmEntity.FormClose(Sender: TObject; var Action: TCloseAction); begin SaveFormConfig(Self); end; //------------------------------------------------------------------------------ //Desc: 跳转焦点 procedure TFrmEntity.Edit_ProgKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then begin Key := #0; Perform(WM_NEXTDLGCTL, 0, 0); end; end; //Desc: 保存实体 procedure TFrmEntity.BtnSaveClick(Sender: TObject); var nItem: TEntityItemData; begin Edit_Prog.Text := Trim(Edit_Prog.Text); Edit_Entity.Text := Trim(Edit_Entity.Text); Edit_Desc.Text := Trim(Edit_Desc.Text); if (Edit_Prog.Text = '') then begin ShowMsg('请输入"程序标识"', sHint); Exit; end; if (Edit_Desc.Text = '') then begin ShowMsg('请输入"标识描述"', sHint); Exit; end; nItem.FProgID := Edit_Prog.Text; nItem.FEntity := Edit_Entity.Text; nItem.FTitle := Edit_Desc.Text; if gSysEntityManager.AddEntityToDB(nItem) then begin ShowMsg('数据提交成功', sHint); ModalResult := mrOK; end else ShowMsg('数据提交失败', sHint); end; end.
{******************************************************************************* * * * PentireFMX * * * * https://github.com/gmurt/PentireFMX * * * * Copyright 2020 Graham Murt * * * * email: graham@kernow-software.co.uk * * * * 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 forthe specific language governing permissions and * * limitations under the License. * * * *******************************************************************************} unit ksColorButton; interface uses Classes, FMX.Controls, FMX.Objects, FMX.StdCtrls, FMX.Types, System.UITypes; type TksColorButtonStyle = (ksbsGray, ksbsGreen, ksbsRed, ksbsBlue, ksbsWhite, ksbsCustom); [ComponentPlatformsAttribute( pidAllPlatforms )] TksColorButton = class(TRectangle) private FColor: TAlphaColor; FFontColor: TAlphaColor; FHighlightColor: TAlphaColor; FBorderColor: TAlphaColor; FLabel: TLabel; FStyle: TksColorButtonStyle; FBorderRadius: single; function GetText: string; procedure SetText(const Value: string); procedure SetStyle(const Value: TksColorButtonStyle); procedure UpdateButton; procedure SetColours(ANormal, AHighlight, ABorder, AFont: TAlphaColor); procedure SetBorderRadius(const Value: single); procedure SetFontColor(const Value: TAlphaColor); protected procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override; procedure DoMouseLeave; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Hint; property Style: TksColorButtonStyle read FStyle write SetStyle default ksbsGreen; property Text: string read GetText write SetText; property BorderRadius: single read FBorderRadius write SetBorderRadius; property FontColor: TAlphaColor read FFontColor write SetFontColor; end; procedure Register; implementation uses System.UIConsts; procedure Register; begin RegisterComponents('Pentire FMX', [TksColorButton]); end; { TksColorButton } constructor TksColorButton.Create(AOwner: TComponent); begin inherited; FLabel := TLabel.Create(Self); FLabel.Stored := False; FLabel.Align := TAlignLayout.Client; FLabel.StyledSettings := [TStyledSetting.Family,TStyledSetting.Style]; FLabel.Font.Size := 14; FLabel.TextSettings.HorzAlign := TTextAlign.Center; FLabel.TextSettings.FontColor := claWhite; FLabel.Text := 'Button'; AddObject(FLabel); Stroke.Color := claBlack; FStyle := ksbsGreen; Width := 100; Height := 40; //FBorderRadius := 0; UpdateButton; end; destructor TksColorButton.Destroy; begin FLabel.Free; inherited; end; procedure TksColorButton.DoMouseLeave; begin inherited; if FStyle <> ksbsCustom then Fill.Color := FColor; Opacity := 1; end; function TksColorButton.GetText: string; begin Result := FLabel.Text; end; procedure TksColorButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin inherited; Opacity := 0.75; end; procedure TksColorButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin inherited; Opacity := 1; end; procedure TksColorButton.SetStyle(const Value: TksColorButtonStyle); begin if FStyle <> Value then begin FStyle := Value; UpdateButton; end; end; procedure TksColorButton.SetBorderRadius(const Value: single); begin if FBorderRadius <> Value then begin FBorderRadius := Value; XRadius := Value; YRadius := Value; UpdateButton; end; end; procedure TksColorButton.SetColours(ANormal, AHighlight, ABorder, AFont: TAlphaColor); begin FColor := ANormal; FHighlightColor := AHighlight; FBorderColor := ABorder; FFontColor := AFont; Fill.Color := FColor; Stroke.Color := ABorder; FLabel.TextSettings.FontColor := AFont; end; procedure TksColorButton.SetFontColor(const Value: TAlphaColor); begin FFontColor := Value; UpdateButton; end; procedure TksColorButton.SetText(const Value: string); begin FLabel.Text := Value; end; procedure TksColorButton.UpdateButton; begin if FStyle = ksbsCustom then Exit; case FStyle of ksbsGray: SetColours(claGainsboro, claSilver, claGray, claBlack); ksbsGreen: SetColours($FF4BD44B, $FF2FB92F, claForestgreen, clawhite); ksbsRed: SetColours(claRed, $FFC90101, $FFC90101, clawhite); ksbsWhite: SetColours(claWhite, claGainsboro, claSilver, claDimgray); ksbsBlue: SetColours(claSteelblue, $FF80ABCF, claNavy, clawhite); end; end; end.
unit uPhotoSort; interface uses Classes, Winapi.Messages, System.SysUtils; const WM_ADDFILE = WM_USER + 0; WM_CLEAR = WM_USER + 1; WM_SAVEFILE = WM_USER + 2; WM_LOADED = WM_USER + 3; type TPhoto = class FName: string; FDate: TDateTime; FChecked: Boolean; constructor Create(const FileName: string; FileDate: TDateTime); end; TPhotoSort = class(TList) private FFmtStngs: TFormatSettings; FAddPrefix: string; FSrcFolder: string; FCurrItem: TPhoto; FOnCopyFile: TNotifyEvent; FOnAddFile: TNotifyEvent; FOwnerHwnd: THandle; FLoadPhotosThread: TThread; FThreadTerminated: Boolean; FLoaded: Boolean; function Get(Index: Integer): TPhoto; procedure Put(Index: Integer; const Value: TPhoto); // procedure DoAddFile; protected procedure Notify(Ptr: Pointer; Action: TListNotification); override; public constructor Create(AOwnerHwnd: THandle); destructor Destroy; override; function Add(const FileName: string; FileDate: TDate): Integer; overload; public procedure LoadPhotos(const SrcFolder: string); overload; procedure LoadPhotos; overload; procedure ExecLoadPhotos(const ASrcFolder: string); function SavePhotos(const ADstFolder: string): Boolean; procedure TerminateThreads; public property Items[Index: Integer]: TPhoto read Get write Put; default; property OnCopyFile: TNotifyEvent read FOnCopyFile write FOnCopyFile; property AddPrefix: string read FAddPrefix write FAddPrefix; property OnAddFile: TNotifyEvent read FOnAddFile write FOnAddFile; property Loaded: Boolean read FLoaded; end; implementation uses Winapi.Windows, CCR.Exif, uMainForm; { TPhotoSort } function TPhotoSort.Add(const FileName: string; FileDate: TDate): Integer; begin Result := inherited Add(TPhoto.Create(FileName, FileDate)); FCurrItem := Self[Result]; PostMessage(FOwnerHwnd, WM_ADDFILE, Integer(Self[Result]), 0); end; constructor TPhotoSort.Create(AOwnerHwnd: THandle); begin inherited Create; FOwnerHwnd := AOwnerHwnd; FFmtStngs.DateSeparator := '_'; FLoaded := False; end; destructor TPhotoSort.Destroy; begin FThreadTerminated := True; // TerminateThreads; inherited; end; procedure TPhotoSort.ExecLoadPhotos(const ASrcFolder: string); begin FSrcFolder := IncludeTrailingPathDelimiter(ASrcFolder); FLoadPhotosThread := TThread.CreateAnonymousThread( procedure() begin try LoadPhotos; except end; end); FLoadPhotosThread.Start; // Sleep(50); // FThreadTerminated := True; // FLoadPhotosThread.Terminate; end; function TPhotoSort.Get(Index: Integer): TPhoto; begin Result := TPhoto(inherited Get(Index)); end; procedure TPhotoSort.LoadPhotos; var SearchRec: TSearchRec; // поисковая переменная FindRes: Integer; FileDate: TDateTime; ExifData: TExifData; begin Clear; FThreadTerminated := False; FLoaded := False; PostMessage(FOwnerHwnd, WM_CLEAR, 0, 0); try ExifData := TExifData.Create; try FindRes := System.SysUtils.FindFirst(FSrcFolder + '*.jpg', faAnyFile, SearchRec); while FindRes = 0 do begin ExifData.LoadFromJPEG(FSrcFolder + SearchRec.Name); if ExifData.Empty then FileDate := SearchRec.TimeStamp else FileDate := ExifData.DateTime; Add(SearchRec.Name, FileDate); if FThreadTerminated then Exit else FindRes := FindNext(SearchRec); end; FLoaded := Count > 0; PostMessage(FOwnerHwnd, WM_LOADED, Integer(FLoaded), 0); finally System.SysUtils.FindClose(SearchRec); ExifData.Free; end; except end; end; procedure TPhotoSort.LoadPhotos(const SrcFolder: string); begin FSrcFolder := IncludeTrailingPathDelimiter(SrcFolder); LoadPhotos; end; procedure TPhotoSort.Notify(Ptr: Pointer; Action: TListNotification); begin if Action = lnDeleted then TPhoto(Ptr).Free; end; procedure TPhotoSort.Put(Index: Integer; const Value: TPhoto); begin inherited Put(Index, Pointer(Value)); end; function TPhotoSort.SavePhotos(const ADstFolder: string): Boolean; var I: Integer; FileFolder: string; begin // FormatSettings.DateSeparator := '_'; Result := False; for I := 0 to Count - 1 do begin if not Items[I].FChecked then Continue; FileFolder := IncludeTrailingPathDelimiter(ADstFolder) + FormatDateTime('yyyy', Items[I].FDate, FFmtStngs) + '\' + FormatDateTime('mm', Items[I].FDate, FFmtStngs) + '\' + FormatDateTime('yyyy_mm_dd', Items[I].FDate, FFmtStngs); Result := ForceDirectories(FileFolder); if not Result then Exit; Result := CopyFile(PWideChar(FSrcFolder + Items[I].FName), PWideChar(FileFolder + '\' + Trim(FAddPrefix) + Items[I].FName), False); if not Result then Exit; if Assigned(FOnCopyFile) then FOnCopyFile(Items[I]); end; end; procedure TPhotoSort.TerminateThreads; begin FThreadTerminated := True; try if Assigned(FLoadPhotosThread) and FLoadPhotosThread.Started and (not FLoadPhotosThread.Finished) then begin FLoadPhotosThread.Terminate; FLoadPhotosThread.WaitFor; end; except end; end; { TPhoto } constructor TPhoto.Create(const FileName: string; FileDate: TDateTime); begin FName := FileName; FDate := FileDate; end; end.
unit frmExplorerOptions; interface uses //delphi & libs Classes, ComCtrls, Controls, Dialogs, ExtCtrls, Graphics, Messages, Forms, StdCtrls, SysUtils, Variants, Windows, //sdu & LibreCrypt utils SDUFilenameEdit_U, OTFEFreeOTFEDLL_U, SDUStdCtrls, CommonSettings, Shredder, ExplorerSettings, // LibreCrypt forms fmeAutorunOptions, // fmeBaseOptions, frmCommonOptions, SDUFrames, fmeVolumeSelect, Spin64; type TLanguageTranslation = record Name: String; Code: String; Contact: String; end; PLanguageTranslation = ^TLanguageTranslation; TfrmExplorerOptions = class (TfrmCommonOptions) tsGeneral: TTabSheet; tsAdvanced: TTabSheet; tsWebDAV: TTabSheet; tsAutorun: TTabSheet; fmeOptions_Autorun1: TfmeAutorunOptions; gbAdvanced: TGroupBox; lblMRUMaxItemCountInst: TLabel; lblMRUMaxItemCount: TLabel; lblOverwritePasses: TLabel; lblOverwriteMethod: TLabel; lblMoveDeletionMethod: TLabel; ckAdvancedMountDlg: TSDUCheckBox; ckRevertVolTimestamps: TSDUCheckBox; pnlVertSplit: TPanel; seMRUMaxItemCount: TSpinEdit64; seOverwritePasses: TSpinEdit64; cbOverwriteMethod: TComboBox; cbMoveDeletionMethod: TComboBox; ckPreserveTimestampsOnStoreExtract: TSDUCheckBox; ckAllowTabsInPasswords: TSDUCheckBox; ckAllowNewlinesInPasswords: TSDUCheckBox; gbWebDAV: TGroupBox; lblDefaultDriveLetter: TLabel; ckWebDAV: TSDUCheckBox; cbDrive: TComboBox; gbWebDAVAdvanced: TGroupBox; Label6: TLabel; fedWebDAVLogDebug: TSDUFilenameEdit; fedWebDAVLogAccess: TSDUFilenameEdit; edWebDAVShareName: TEdit; ckOverwriteCacheOnDismount: TSDUCheckBox; ckWebDAVLogAccess: TSDUCheckBox; ckWebDAVLogDebug: TSDUCheckBox; ckExploreAfterMount: TSDUCheckBox; ckPromptMountSuccessful: TSDUCheckBox; gbGeneral: TGroupBox; tlab: TLabel; lblChkUpdatesFreq: TLabel; Label1: TLabel; ckDisplayToolbar: TSDUCheckBox; Panel1: TPanel; ckShowPasswords: TSDUCheckBox; cbLanguage: TComboBox; pbLangDetails: TButton; ckDisplayToolbarLarge: TSDUCheckBox; ckDisplayToolbarCaptions: TSDUCheckBox; cbChkUpdatesFreq: TComboBox; ckShowHiddenItems: TSDUCheckBox; ckHideKnownFileExtns: TSDUCheckBox; ckStoreLayout: TSDUCheckBox; cbDefaultStoreOp: TComboBox; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure pbLangDetailsClick(Sender: TObject); procedure cbLanguageChange(Sender: TObject); procedure ckStoreLayoutClick(Sender: TObject); procedure ckWebDAVClick(Sender: TObject); private FLanguages: array of TLanguageTranslation; FFlagClearLayoutOnSave: Boolean; FWarnUserChangesRequireRemount: Boolean; procedure _SetLanguageSelection(langCode: String); function GetSelectedLanguage(): TLanguageTranslation; function GetLanguage(idx: Integer): TLanguageTranslation; procedure _PopulateLanguages; function GetOverwriteMethod: TShredMethod; procedure SetOverwriteMethod(useMethod: TShredMethod); procedure _NudgeCheckbox(chkBox: TCheckBox); procedure _PopulateOverwriteMethods; //procs to set up/read/write tabs procedure _EnableDisableControlsAdvancedExplorer; procedure _ReadSettingsAdvancedExplorer(config: TExplorerSettings); procedure _InitializeAdvancedExplorer; procedure _WriteSettingsAdvanced(config: TExplorerSettings); procedure _EnableDisableControlsGeneral; procedure _InitializeGeneral; procedure _ReadSettingsGeneral(config: TExplorerSettings); procedure _WriteSettingsGeneral(config: TExplorerSettings); procedure _EnableDisableControlsWebDAV; procedure _InitializeWebDAV; procedure _ReadSettingsWebDAV(config: TExplorerSettings); procedure _WriteSettingsWebDAV(config: TExplorerSettings); protected procedure AllTabs_WriteSettings(config: TCommonSettings); override; procedure AllTabs_InitAndReadSettings(config: TCommonSettings); override; procedure EnableDisableControls(); override; public procedure ChangeLanguage(langCode: String); override; end; implementation {$R *.dfm} uses //delphi & libs ShlObj, // Required for CSIDL_PROGRAMS //sdu & LibreCrypt utils OTFEFreeOTFEBase_U, SDUDialogs, SDUGeneral, SDUi18n, lcDialogs, lcConsts, commonconsts, lcTypes // LibreCrypt forms ; {$IFDEF _NEVER_DEFINED} // This is just a dummy const to fool dxGetText when extracting message // information // This const is never used; it's #ifdef'd out - SDUCRLF in the code refers to // picks up SDUGeneral.SDUCRLF const SDUCRLF = ''#13#10; {$ENDIF} const // CONTROL_MARGIN_LBL_TO_CONTROL = 5; // Vertical spacing between checkboxes, and min horizontal spacing between // checkbox label and the vertical separator line // Set to 6 for now as that looks reasonable. 10 is excessive, 5 is a bit // cramped CHKBOX_CONTROL_MARGIN = 6; procedure TfrmExplorerOptions.AllTabs_InitAndReadSettings( config: TCommonSettings); begin inherited; fmeOptions_Autorun1.Initialize; fmeOptions_Autorun1.ReadSettings(config); _InitializeAdvancedExplorer; _ReadSettingsAdvancedExplorer(config as TExplorerSettings); _InitializeWebDAV; _ReadSettingsWebDAV(config as TExplorerSettings); _InitializeGeneral; _ReadSettingsGeneral(config as TExplorerSettings); end; procedure TfrmExplorerOptions._WriteSettingsGeneral(config: TExplorerSettings); procedure GetGreyedCheckbox(chkBox: TCheckbox; var stateOne: Boolean; var stateTwo: Boolean); begin if (chkBox.State <> cbGrayed) then begin stateOne := chkBox.Checked; stateTwo := chkBox.Checked; end; end; var useLang: TLanguageTranslation; dso: TDefaultStoreOp; uf: TUpdateFrequency; begin // General... GetGreyedCheckbox( ckDisplayToolbar, config.OptShowToolbarVolume, config.OptShowToolbarExplorer ); GetGreyedCheckbox( ckDisplayToolbarLarge, config.OptToolbarVolumeLarge, config.OptToolbarExplorerLarge ); GetGreyedCheckbox( ckDisplayToolbarCaptions, config.OptToolbarVolumeCaptions, config.OptToolbarExplorerCaptions ); config.OptShowPasswords := ckShowPasswords.Checked; config.OptShowHiddenItems := ckShowHiddenItems.Checked; config.OptHideKnownFileExtns := ckHideKnownFileExtns.Checked; config.OptStoreLayout := ckStoreLayout.Checked; config.FlagClearLayoutOnSave := FFlagClearLayoutOnSave; useLang := GetSelectedLanguage(); config.OptLanguageCode := useLang.Code; // Decode default store op config.OptDefaultStoreOp := dsoPrompt; for dso := low(dso) to high(dso) do begin if (DefaultStoreOpTitle(dso) = cbDefaultStoreOp.Items[cbDefaultStoreOp.ItemIndex]) then begin config.OptDefaultStoreOp := dso; break; end; end; // Decode update frequency config.OptUpdateChkFrequency := ufNever; for uf := low(uf) to high(uf) do begin if (UpdateFrequencyTitle(uf) = cbChkUpdatesFreq.Items[cbChkUpdatesFreq.ItemIndex]) then begin config.OptUpdateChkFrequency := uf; break; end; end; end; procedure TfrmExplorerOptions._WriteSettingsAdvanced(config: TExplorerSettings); var mdm: TMoveDeletionMethod; begin // Advanced... config.OptAdvancedMountDlg := ckAdvancedMountDlg.Checked; config.OptRevertVolTimestamps := ckRevertVolTimestamps.Checked; config.OptPreserveTimestampsOnStoreExtract := ckPreserveTimestampsOnStoreExtract.Checked; config.OptAllowNewlinesInPasswords := ckAllowNewlinesInPasswords.Checked; config.OptAllowTabsInPasswords := ckAllowTabsInPasswords.Checked; config.OptMRUList.MaxItems := seMRUMaxItemCount.Value; // Decode move deletion method config.OptMoveDeletionMethod := mdmPrompt; for mdm := low(mdm) to high(mdm) do begin if (MoveDeletionMethodTitle(mdm) = cbMoveDeletionMethod.Items[cbMoveDeletionMethod.ItemIndex]) then begin config.OptMoveDeletionMethod := mdm; break; end; end; config.OptOverwriteMethod := GetOverwriteMethod(); config.OptOverwritePasses := seOverwritePasses.Value; end; procedure TfrmExplorerOptions._ReadSettingsAdvancedExplorer(config: TExplorerSettings); var mdm: TMoveDeletionMethod; idx: Integer; useIdx: Integer; begin // Advanced... ckAdvancedMountDlg.Checked := config.OptAdvancedMountDlg; ckRevertVolTimestamps.Checked := config.OptRevertVolTimestamps; ckPreserveTimestampsOnStoreExtract.Checked := config.OptPreserveTimestampsOnStoreExtract; ckAllowNewlinesInPasswords.Checked := config.OptAllowNewlinesInPasswords; ckAllowTabsInPasswords.Checked := config.OptAllowTabsInPasswords; seMRUMaxItemCount.Value := config.OptMRUList.MaxItems; // Populate and set move deletion method cbMoveDeletionMethod.Items.Clear(); idx := -1; useIdx := -1; for mdm := low(mdm) to high(mdm) do begin Inc(idx); cbMoveDeletionMethod.Items.Add(MoveDeletionMethodTitle(mdm)); if (config.OptMoveDeletionMethod = mdm) then begin useIdx := idx; end; end; cbMoveDeletionMethod.ItemIndex := useIdx; SetOverwriteMethod(config.OptOverwriteMethod); seOverwritePasses.Value := config.OptOverwritePasses; end; procedure TfrmExplorerOptions._PopulateOverwriteMethods(); var sm: TShredMethod; begin cbOverwriteMethod.Items.Clear(); for sm := low(TShredMethodTitle) to high(TShredMethodTitle) do begin cbOverwriteMethod.Items.Add(ShredMethodTitle(sm)); end; end; procedure TfrmExplorerOptions._SetLanguageSelection(langCode: String); var useIdx: Integer; currLang: TLanguageTranslation; i: Integer; begin useIdx := 0; for i := 0 to (cbLanguage.items.Count - 1) do begin currLang := GetLanguage(i); if (currLang.Code = langCode) then begin useIdx := i; break; end; end; cbLanguage.ItemIndex := useIdx; end; procedure TfrmExplorerOptions.SetOverwriteMethod(useMethod: TShredMethod); var i: Integer; begin for i := 0 to (cbOverwriteMethod.items.Count - 1) do begin if (cbOverwriteMethod.items[i] = ShredMethodTitle(useMethod)) then begin cbOverwriteMethod.ItemIndex := i; break; end; end; end; function TfrmExplorerOptions.GetOverwriteMethod(): TShredMethod; var sm: TShredMethod; begin Result := smPseudorandom; for sm := low(sm) to high(sm) do begin if (cbOverwriteMethod.items[cbOverwriteMethod.ItemIndex] = ShredMethodTitle(sm)) then begin Result := sm; break; end; end; end; procedure TfrmExplorerOptions.AllTabs_WriteSettings(config: TCommonSettings); begin inherited; fmeOptions_Autorun1.WriteSettings(config); _WriteSettingsAdvanced(config as TExplorerSettings); _WriteSettingsWebDAV(config as TExplorerSettings); _WriteSettingsGeneral(config as TExplorerSettings); end; procedure TfrmExplorerOptions.cbLanguageChange(Sender: TObject); var useLang: TLanguageTranslation; langIdx: Integer; begin inherited; // Preserve selected language; the selected language gets change by the // PopulateLanguages() call langIdx := cbLanguage.ItemIndex; useLang := GetSelectedLanguage(); TfrmCommonOptions(Owner).ChangeLanguage(useLang.Code); // Repopulate the languages list; translation would have translated them all _PopulateLanguages(); // Restore selected cbLanguage.ItemIndex := langIdx; EnableDisableControls(); end; procedure TfrmExplorerOptions.ChangeLanguage(langCode: String); var tmpConfig: TExplorerSettings; begin tmpConfig := TExplorerSettings.Create(); try tmpConfig.Assign(GetSettings()); AllTabs_WriteSettings(tmpConfig); SDUSetLanguage(langCode); try SDURetranslateComponent(self); except on E: Exception do begin SDUTranslateComponent(self); end; end; AllTabs_InitAndReadSettings(tmpConfig); finally tmpConfig.Free(); end; // Call EnableDisableControls() as this re-jigs the "Save above settings to:" // label EnableDisableControls(); end; procedure TfrmExplorerOptions.ckStoreLayoutClick(Sender: TObject); begin inherited; if not (ckStoreLayout.Checked) then begin FFlagClearLayoutOnSave := SDUConfirmYN(Format( _('You have turned off the option to automatically save the window layout on exiting.' + SDUCRLF + SDUCRLF + 'Would you like to reset %s to its default window layout the next time it is started?'), [Application.Title])); end; end; procedure TfrmExplorerOptions.ckWebDAVClick(Sender: TObject); begin inherited; if SDUOSVistaOrLater() then begin SDUMessageDlg( RS_DRIVEMAPPING_NOT_SUPPORTED_UNDER_VISTA_AND_7 + SDUCRLF + Format( _('Opened containers will only be mapped to drive letters when %s is run under Windows 2000/Windows XP'), [Application.Title]), mtInformation ); end else if FWarnUserChangesRequireRemount then begin SDUMessageDlg( _('The changes you make here will only take effect when you next open a container'), mtInformation ); FWarnUserChangesRequireRemount := False; end; EnableDisableControls(); end; { TODO 1 -otdk -crefactor : whats with all the moving controls - try just using designer } // This adjusts the width of a checkbox, and resets it caption so it // autosizes. If it autosizes such that it's too wide, it'll drop the width // and repeat procedure TfrmExplorerOptions._NudgeCheckbox(chkBox: TCheckBox); var tmpCaption: String; maxWidth: Integer; useWidth: Integer; lastTriedWidth: Integer; begin tmpCaption := chkBox.Caption; maxWidth := (pnlVertSplit.left - CHKBOX_CONTROL_MARGIN) - chkBox.Left; useWidth := maxWidth; chkBox.Caption := 'X'; chkBox.Width := useWidth; lastTriedWidth := useWidth; chkBox.Caption := tmpCaption; while ((chkBox.Width > maxWidth) and (lastTriedWidth > 0)) do begin // 5 used here; just needs to be something sensible to reduce the // width by; 1 would do pretty much just as well useWidth := useWidth - 5; chkBox.Caption := 'X'; chkBox.Width := useWidth; lastTriedWidth := useWidth; chkBox.Caption := tmpCaption; end; end; procedure TfrmExplorerOptions._InitializeAdvancedExplorer(); const // Min horizontal spacing between label and control to the right of it LABEL_CONTROL_MARGIN = 10; // procedure NudgeFocusControl(lbl: TLabel); // begin // if (lbl.FocusControl <> nil) then begin // lbl.FocusControl.Top := lbl.Top + lbl.Height + CONTROL_MARGIN_LBL_TO_CONTROL; // end; // // end; procedure NudgeLabel(lbl: TLabel); var maxWidth: Integer; begin if (pnlVertSplit.left > lbl.left) then begin maxWidth := (pnlVertSplit.left - LABEL_CONTROL_MARGIN) - lbl.left; end else begin maxWidth := (lbl.Parent.Width - LABEL_CONTROL_MARGIN) - lbl.left; end; lbl.Width := maxWidth; end; var stlChkBoxOrder: TStringList; YPos: Integer; i: Integer; currChkBox: TCheckBox; groupboxMargin: Integer; begin inherited; SDUCenterControl(gbAdvanced, ccHorizontal); SDUCenterControl(gbAdvanced, ccVertical, 25); // Re-jig label size to take cater for differences in translation lengths // Size so the max. right is flush with the max right of pbLangDetails // lblMRUMaxItemCount.width := (pbLangDetails.left + pbLangDetails.width) - lblMRUMaxItemCount.left; groupboxMargin := ckAdvancedMountDlg.left; lblMRUMaxItemCount.Width := (gbAdvanced.Width - groupboxMargin) - lblMRUMaxItemCount.left; lblMoveDeletionMethod.Width := (gbAdvanced.Width - groupboxMargin) - lblMoveDeletionMethod.left; lblOverwriteMethod.Width := (gbAdvanced.Width - groupboxMargin) - lblOverwriteMethod.left; lblOverwritePasses.Width := (gbAdvanced.Width - groupboxMargin) - lblOverwritePasses.left; pnlVertSplit.Caption := ''; pnlVertSplit.bevelouter := bvLowered; pnlVertSplit.Width := 3; // Here we re-jig the checkboxes so that they are nicely spaced vertically. // This is needed as some language translation require the checkboxes to have // more than one line of text // // !! IMPORTANT !! // When adding a checkbox: // 1) Add it to stlChkBoxOrder below (doesn't matter in which order these // are added) // 2) Make sure the checkbox is a TSDUCheckBox, not just a normal Delphi // TCheckBox // 3) Make sure it's autosize property is TRUE // stlChkBoxOrder := TStringList.Create(); try // stlChkBoxOrder is used to order the checkboxes in their vertical order; // this allows checkboxes to be added into the list below in *any* order, // and it'll still work stlChkBoxOrder.Sorted := True; stlChkBoxOrder.AddObject(Format('%.5d', [ckAdvancedMountDlg.Top]), ckAdvancedMountDlg); stlChkBoxOrder.AddObject(Format('%.5d', [ckRevertVolTimestamps.Top]), ckRevertVolTimestamps); stlChkBoxOrder.AddObject(Format('%.5d', [ckPreserveTimestampsOnStoreExtract.Top]), ckPreserveTimestampsOnStoreExtract); stlChkBoxOrder.AddObject(Format('%.5d', [ckAllowNewlinesInPasswords.Top]), ckAllowNewlinesInPasswords); stlChkBoxOrder.AddObject(Format('%.5d', [ckAllowTabsInPasswords.Top]), ckAllowTabsInPasswords); currChkBox := TCheckBox(stlChkBoxOrder.Objects[0]); YPos := currChkBox.Top; YPos := YPos + currChkBox.Height; for i := 1 to (stlChkBoxOrder.Count - 1) do begin currChkBox := TCheckBox(stlChkBoxOrder.Objects[i]); currChkBox.Top := YPos + CHKBOX_CONTROL_MARGIN; // Sort out the checkbox's height _NudgeCheckbox(currChkBox); YPos := currChkBox.Top; YPos := YPos + currChkBox.Height; end; finally stlChkBoxOrder.Free(); end; // Nudge labels so they're as wide as can be allowed NudgeLabel(lblMoveDeletionMethod); NudgeLabel(lblOverwriteMethod); NudgeLabel(lblOverwritePasses); NudgeLabel(lblMRUMaxItemCount); NudgeLabel(lblMRUMaxItemCountInst); // Here we move controls associated with labels, such that they appear // underneath the label // NudgeFocusControl(lblMRUMaxItemCount); // NudgeFocusControl(lblMoveDeletionMethod); // NudgeFocusControl(lblOverwriteMethod); // NudgeFocusControl(lblOverwritePasses); _PopulateOverwriteMethods(); end; procedure TfrmExplorerOptions._EnableDisableControlsAdvancedExplorer(); var userEnterPasses: Boolean; begin inherited; userEnterPasses := (TShredMethodPasses[GetOverwriteMethod()] <= 0); SDUEnableControl(seOverwritePasses, userEnterPasses); if not (userEnterPasses) then begin seOverwritePasses.Value := TShredMethodPasses[GetOverwriteMethod()]; end; end; procedure TfrmExplorerOptions.EnableDisableControls; begin inherited; _EnableDisableControlsGeneral(); _EnableDisableControlsAdvancedExplorer(); _EnableDisableControlsWebDAV(); end; procedure TfrmExplorerOptions.FormCreate(Sender: TObject); begin inherited; // Set active page to the first one pcOptions.ActivePage := tsGeneral; end; procedure TfrmExplorerOptions.FormShow(Sender: TObject); begin inherited; // Push the "Advanced" tab to the far end; even after the "PKCS#11" tab tsAdvanced.PageIndex := (pcOptions.PageCount - 1); end; function TfrmExplorerOptions.GetLanguage( idx: Integer): TLanguageTranslation; begin Result := (PLanguageTranslation(cbLanguage.Items.Objects[idx]))^; end; procedure TfrmExplorerOptions.pbLangDetailsClick(Sender: TObject); var rcdLanguage: TLanguageTranslation; begin inherited; rcdLanguage := GetSelectedLanguage(); SDUMessageDlg( Format(_('Language name: %s'), [rcdLanguage.Name]) + SDUCRLF + Format(_('Language code: %s'), [rcdLanguage.Code]) + SDUCRLF + Format(_('Translator: %s'), [rcdLanguage.Contact]) ); end; procedure TfrmExplorerOptions._EnableDisableControlsWebDAV(); begin inherited; SDUEnableControl(ckExploreAfterMount, ckWebDAV.Checked); SDUEnableControl(ckPromptMountSuccessful, ckWebDAV.Checked); SDUEnableControl(cbDrive, ckWebDAV.Checked); SDUEnableControl(gbWebDAVAdvanced, ckWebDAV.Checked); SDUEnableControl(fedWebDAVLogAccess, (ckWebDAV.Checked and ckWebDAVLogAccess.Checked)); SDUEnableControl(fedWebDAVLogDebug, (ckWebDAV.Checked and ckWebDAVLogDebug.Checked)); if not (ckWebDAVLogAccess.Checked) then begin fedWebDAVLogAccess.Filename := ''; end; if not (ckWebDAVLogDebug.Checked) then begin fedWebDAVLogDebug.Filename := ''; end; end; procedure TfrmExplorerOptions._EnableDisableControlsGeneral(); begin inherited; // Language at index 0 is "(Default)" SDUEnableControl(pbLangDetails, (cbLanguage.ItemIndex > 0)); SDUEnableControl( ckDisplayToolbarLarge, (ckDisplayToolbar.Checked or (ckDisplayToolbar.State = cbGrayed)) ); SDUEnableControl(ckDisplayToolbarCaptions, (ckDisplayToolbar.Checked and ckDisplayToolbarLarge.Checked)); // Only allow captions if the user has selected large icons if (ckDisplayToolbarLarge.state = cbUnchecked) then begin ckDisplayToolbarCaptions.Checked := False; end; end; procedure TfrmExplorerOptions._InitializeWebDAV(); var driveLetter: Char; begin inherited; FWarnUserChangesRequireRemount := True; SDUCenterControl(gbWebDAV, ccHorizontal); SDUCenterControl(gbWebDAV, ccVertical, 25); cbDrive.Items.Clear(); cbDrive.Items.Add(USE_DEFAULT); // for driveLetter:='C' to 'Z' do for driveLetter := 'A' to 'Z' do cbDrive.Items.Add(driveLetter + ':'); end; procedure TfrmExplorerOptions._InitializeGeneral(); // procedure NudgeFocusControl(lbl: TLabel); // begin // if (lbl.FocusControl <> nil) then begin // lbl.FocusControl.Top := lbl.Top + lbl.Height + CONTROL_MARGIN_LBL_TO_CONTROL; // end; // // end; var stlChkBoxOrder: TStringList; YPos: Integer; i: Integer; currChkBox: TCheckBox; begin inherited; FFlagClearLayoutOnSave := False; SDUCenterControl(gbGeneral, ccHorizontal); SDUCenterControl(gbGeneral, ccVertical, 25); pnlVertSplit.Caption := ''; pnlVertSplit.bevelouter := bvLowered; pnlVertSplit.Width := 3; _PopulateLanguages(); // Here we re-jig the checkboxes so that they are nicely spaced vertically. // This is needed as some language translation require the checkboxes to have // more than one line of text // // !! IMPORTANT !! // When adding a checkbox: // 1) Add it to stlChkBoxOrder below (doesn't matter in which order these // are added) // 2) Make sure the checkbox is a TSDUCheckBox, not just a normal Delphi // TCheckBox // 3) Make sure it's autosize property is TRUE // stlChkBoxOrder := TStringList.Create(); try // stlChkBoxOrder is used to order the checkboxes in their vertical order; // this allows checkboxes to be added into the list below in *any* order, // and it'll still work stlChkBoxOrder.Sorted := True; stlChkBoxOrder.AddObject(Format('%.5d', [ckDisplayToolbar.Top]), ckDisplayToolbar); stlChkBoxOrder.AddObject(Format('%.5d', [ckShowPasswords.Top]), ckShowPasswords); stlChkBoxOrder.AddObject(Format('%.5d', [ckDisplayToolbarLarge.Top]), ckDisplayToolbarLarge); stlChkBoxOrder.AddObject(Format('%.5d', [ckDisplayToolbarCaptions.Top]), ckDisplayToolbarCaptions); stlChkBoxOrder.AddObject(Format('%.5d', [ckShowHiddenItems.Top]), ckShowHiddenItems); stlChkBoxOrder.AddObject(Format('%.5d', [ckHideKnownFileExtns.Top]), ckHideKnownFileExtns); stlChkBoxOrder.AddObject(Format('%.5d', [ckStoreLayout.Top]), ckStoreLayout); currChkBox := TCheckBox(stlChkBoxOrder.Objects[0]); YPos := currChkBox.Top; YPos := YPos + currChkBox.Height; for i := 1 to (stlChkBoxOrder.Count - 1) do begin currChkBox := TCheckBox(stlChkBoxOrder.Objects[i]); if currChkBox.Visible then begin currChkBox.Top := YPos + CHKBOX_CONTROL_MARGIN; // Sort out the checkbox's height _NudgeCheckbox(currChkBox); YPos := currChkBox.Top; YPos := YPos + currChkBox.Height; end; end; finally stlChkBoxOrder.Free(); end; // Here we move controls associated with labels, such that they appear // underneath the label // NudgeFocusControl(lblLanguage); // NudgeFocusControl(lblMRUMaxItemCount); end; procedure TfrmExplorerOptions._ReadSettingsWebDAV(config: TExplorerSettings); var prevWarnUserChangesRequireRemount: Boolean; begin // Temporarily set FWarnUserChangesRequireRemount to FALSE - otherwise we'll // get the warning message as the frame is loaded! prevWarnUserChangesRequireRemount := FWarnUserChangesRequireRemount; FWarnUserChangesRequireRemount := False; ckWebDAV.Checked := config.OptWebDAVEnableServer; FWarnUserChangesRequireRemount := prevWarnUserChangesRequireRemount; ckExploreAfterMount.Checked := config.OptExploreAfterMount; ckPromptMountSuccessful.Checked := config.OptPromptMountSuccessful; // Default drive letter if (config.OptDefaultDriveLetter = #0) then cbDrive.ItemIndex := 0 else cbDrive.ItemIndex := cbDrive.Items.IndexOf(config.OptDefaultDriveLetter + ':'); ckOverwriteCacheOnDismount.Checked := config.OptOverwriteWebDAVCacheOnDismount; edWebDAVShareName.Text := config.OptWebDavShareName; fedWebDAVLogAccess.Filename := config.OptWebDavLogAccess; fedWebDAVLogDebug.Filename := config.OptWebDavLogDebug; ckWebDAVLogAccess.Checked := (trim(fedWebDAVLogAccess.Filename) <> ''); ckWebDAVLogDebug.Checked := (trim(fedWebDAVLogDebug.Filename) <> ''); end; procedure TfrmExplorerOptions._ReadSettingsGeneral(config: TExplorerSettings); procedure SetupGreyedCheckbox(chkBox: TCheckbox; stateOne: Boolean; stateTwo: Boolean); begin if (stateOne = stateTwo) then begin chkBox.Checked := stateOne; end else begin chkBox.State := cbGrayed; end; chkBox.Tag := Ord(chkBox.State); end; var uf: TUpdateFrequency; dso: TDefaultStoreOp; idx: Integer; useIdx: Integer; begin // General... SetupGreyedCheckbox( ckDisplayToolbar, config.OptShowToolbarVolume, config.OptShowToolbarExplorer ); SetupGreyedCheckbox( ckDisplayToolbarLarge, config.OptToolbarVolumeLarge, config.OptToolbarExplorerLarge ); SetupGreyedCheckbox( ckDisplayToolbarCaptions, config.OptToolbarVolumeCaptions, config.OptToolbarExplorerCaptions ); ckShowPasswords.Checked := config.OptShowPasswords; ckShowHiddenItems.Checked := config.OptShowHiddenItems; ckHideKnownFileExtns.Checked := config.OptHideKnownFileExtns; ckStoreLayout.Checked := config.OptStoreLayout; // In case language code not found; reset to "(Default)" entry; at index 0 _SetLanguageSelection(config.OptLanguageCode); // Populate and set default store op dropdown cbDefaultStoreOp.Items.Clear(); idx := -1; useIdx := -1; for dso := low(dso) to high(dso) do begin Inc(idx); cbDefaultStoreOp.Items.Add(DefaultStoreOpTitle(dso)); if (config.OptDefaultStoreOp = dso) then begin useIdx := idx; end; end; cbDefaultStoreOp.ItemIndex := useIdx; // Populate and set update frequency dropdown cbChkUpdatesFreq.Items.Clear(); idx := -1; useIdx := -1; for uf := low(uf) to high(uf) do begin // Daily and weekly disabled for now; not sure what the load on the // server would be like Inc(idx); cbChkUpdatesFreq.Items.Add(UpdateFrequencyTitle(uf)); if (config.OptUpdateChkFrequency = uf) then begin useIdx := idx; end; end; cbChkUpdatesFreq.ItemIndex := useIdx; end; procedure TfrmExplorerOptions._WriteSettingsWebDAV(config: TExplorerSettings); begin config.OptWebDAVEnableServer := ckWebDAV.Checked; config.OptExploreAfterMount := ckExploreAfterMount.Checked; config.OptPromptMountSuccessful := ckPromptMountSuccessful.Checked; // Default drive letter if (cbDrive.ItemIndex = 0) then begin config.OptDefaultDriveLetter := #0; end else begin config.OptDefaultDriveLetter := DriveLetterChar(cbDrive.Items[cbDrive.ItemIndex][1]); end; config.OptOverwriteWebDAVCacheOnDismount := ckOverwriteCacheOnDismount.Checked; config.OptWebDavShareName := edWebDAVShareName.Text; config.OptWebDavLogDebug := fedWebDAVLogDebug.Filename; config.OptWebDavLogAccess := fedWebDAVLogAccess.Filename; end; procedure TfrmExplorerOptions._PopulateLanguages(); var i: Integer; origLangCode: String; langCodes: TStringList; sortedList: TStringList; begin // Store language information for later use... langCodes := TStringList.Create(); try // Get all language codes... SDUGetLanguageCodes(langCodes); // +1 to include "Default" SetLength(FLanguages, langCodes.Count); // Spin though the languages, getting their corresponding human-readable // names origLangCode := SDUGetCurrentLanguageCode(); try for i := 0 to (langCodes.Count - 1) do begin SDUSetLanguage(langCodes[i]); FLanguages[i].Code := langCodes[i]; FLanguages[i].Name := _(CONST_LANGUAGE_ENGLISH); FLanguages[i].Contact := SDUGetTranslatorNameAndEmail(); // Force set contact details for English version; the dxgettext software sets // this to some stupid default if (langCodes[i] = ISO639_ALPHA2_ENGLISH) then begin FLanguages[i].Contact := ENGLISH_TRANSLATION_CONTACT; end; end; finally // Flip back to original language... SDUSetLanguage(origLangCode); end; finally langCodes.Free(); end; // Add "default" into the list SetLength(FLanguages, (length(FLanguages) + 1)); FLanguages[length(FLanguages) - 1].Code := ''; FLanguages[length(FLanguages) - 1].Name := _('(Default)'); FLanguages[length(FLanguages) - 1].Contact := ''; // Populate list sortedList := TStringList.Create(); try for i := 0 to (length(FLanguages) - 1) do begin sortedList.AddObject(FLanguages[i].Name, @(FLanguages[i])); end; sortedList.Sorted := True; sortedList.Sorted := False; cbLanguage.Items.Assign(sortedList) finally sortedList.Free(); end; end; function TfrmExplorerOptions.GetSelectedLanguage: TLanguageTranslation; begin Result := GetLanguage(cbLanguage.ItemIndex); end; end.
unit Unit_Indy_Functions; { ******************************************************************************* * * * # # # # #### # # # ####### * # ## # # # # # # # # * # # # # # # # # # # # * # # # # # # # # # # * # # # # # # # # # # * # # ## ##### # # ####### * * * * ##### # # * # # # # * # # # # * # ### # * # # # * # # # * ##### # * * * ##### ##### # # # * # # # # # # # ## * # # # # # # # # # * # ### # # # # # # * # # # # # # # * # # # # # # # * ##### ##### ####### # # ******************************************************************************* } interface uses IdBaseComponent, IdContext, IdComponent, IdTCPConnection, IdTCPClient, StdCtrls, SysUtils, Variants, Classes, Graphics, Controls, Forms, Unit_Indy_Classes, IdGlobal; type TGenericRecord<TRecordType> = class private FValue: TRecordType; FIsNil: Boolean; public /// <summary> /// Convert Byte to Record , outputtype : TRecordType /// </summary> /// <param name="ABuffer"> /// Byte Array /// </param> function ByteArrayToMyRecord(ABuffer: TIdBytes): TRecordType; // class function ByteArrayToMyRecord(ABuffer: TBytes): TRecordType; static; /// <summary> /// Store a Record into a BYTE Array /// </summary> /// <param name="aRecord"> /// adjust this record definition to your needs /// </param> function MyRecordToByteArray(aRecord: TRecordType): TIdBytes; // class function MyRecordToByteArray(aRecord: TRecordType): TBytes; static; property Value: TRecordType read FValue write FValue; property IsNil: Boolean read FIsNil write FIsNil; end; /// <summary> /// Function for transfer of Bytes Arrays via INDY 10 TCP IP Servers /// </summary> function ReceiveBuffer(AClient: TIdTCPClient; var ABuffer: TIdBytes) : Boolean; overload; /// <summary> /// Function for transfer of Bytes Arrays via INDY 10 TCP IP Servers /// </summary> function SendBuffer(AClient: TIdTCPClient; ABuffer: TIdBytes): Boolean; overload; /// <summary> /// Function for transfer of Bytes Arrays via INDY 10 TCP IP Servers /// </summary> function ReceiveBuffer(AContext: TIdContext; var ABuffer: TIdBytes) : Boolean; overload; /// <summary> /// Function for transfer of Bytes Arrays via INDY 10 TCP IP Servers /// </summary> function SendBuffer(AContext: TIdContext; ABuffer: TIdBytes): Boolean; overload; /// <summary> /// Function for transfer of STREAMS /// </summary> function SendStream(AContext: TIdContext; AStream: TStream): Boolean; overload; /// <summary> /// Function for transfer of STREAMS /// </summary> function ReceiveStream(AContext: TIdContext; var AStream: TStream) : Boolean; overload; /// <summary> /// Function for transfer of STREAMS /// </summary> function ReceiveStream(AClient: TIdTCPClient; var AStream: TStream) : Boolean; overload; /// <summary> /// Function for transfer of STREAMS /// </summary> function SendStream(AClient: TIdTCPClient; AStream: TStream): Boolean; overload; /// <summary> /// Convert Byte to Record , outputtype : TRecordType /// </summary> /// <param name="ABuffer"> /// Byte Array /// </param> function ByteArrayToMyRecord(ABuffer: TIdBytes): TMyRecord; /// <summary> /// Store a Record into a BYTE Array /// </summary> /// <param name="aRecord"> /// adjust this record definition to your needs /// </param> function MyRecordToByteArray(aRecord: TMyRecord): TIdBytes; /// <summary> /// Function for File transmission /// </summary> /// <param name="AClient"> /// TCP Client /// </param> function ClientSendFile(AClient: TIdTCPClient; Filename: String): Boolean; /// <summary> /// ClientReceiveFile Function for File transmission /// </summary> /// <param name="AClient"> /// TCP Client /// </param> function ClientReceiveFile(AClient: TIdTCPClient; Filename: String): Boolean; /// <summary> /// ServerSendFile Function for File transmission /// </summary> /// <param name="AContext"> /// TCP Server /// </param> function ServerSendFile(AContext: TIdContext; Filename: String): Boolean; /// <summary> /// ServerReceiveFile Function for File transmission /// </summary> /// <param name="AContext"> /// TCP Server /// </param> function ServerReceiveFile(AContext: TIdContext; ServerFilename: String; var ClientFilename: String): Boolean; implementation /// /// ------------- HELPER FUNCTION FOR RECORD EXCHANGE --------------------- /// function ReceiveBuffer(AClient: TIdTCPClient; var ABuffer: TIdBytes) : Boolean; overload; var LSize: LongInt; begin Result := True; try LSize := AClient.IOHandler.ReadLongInt(); AClient.IOHandler.ReadBytes(ABuffer, LSize, False); except Result := False; end; end; function SendBuffer(AClient: TIdTCPClient; ABuffer: TIdBytes): Boolean; overload; begin try Result := True; try AClient.IOHandler.Write(LongInt(Length(ABuffer))); AClient.IOHandler.WriteBufferOpen; AClient.IOHandler.Write(ABuffer, Length(ABuffer)); AClient.IOHandler.WriteBufferFlush; finally AClient.IOHandler.WriteBufferClose; end; except Result := False; end; end; function SendBuffer(AContext: TIdContext; ABuffer: TIdBytes): Boolean; overload; begin try Result := True; try AContext.Connection.IOHandler.Write(LongInt(Length(ABuffer))); AContext.Connection.IOHandler.WriteBufferOpen; AContext.Connection.IOHandler.Write(ABuffer, Length(ABuffer)); AContext.Connection.IOHandler.WriteBufferFlush; finally AContext.Connection.IOHandler.WriteBufferClose; end; except Result := False; end; end; function ReceiveBuffer(AContext: TIdContext; var ABuffer: TIdBytes) : Boolean; overload; var LSize: LongInt; begin Result := True; try LSize := AContext.Connection.IOHandler.ReadLongInt(); AContext.Connection.IOHandler.ReadBytes(ABuffer, LSize, False); except Result := False; end; end; /// /// --------------------- HELP FUNCTION FOR STREAM EXCHANGE -------------- /// function ReceiveStream(AContext: TIdContext; var AStream: TStream) : Boolean; overload; var LSize: LongInt; begin Result := True; try LSize := AContext.Connection.IOHandler.ReadLongInt(); AContext.Connection.IOHandler.ReadStream(AStream, LSize, False); except Result := False; end; end; function ReceiveStream(AClient: TIdTCPClient; var AStream: TStream) : Boolean; overload; var LSize: LongInt; begin Result := True; try LSize := AClient.IOHandler.ReadLongInt(); AClient.IOHandler.ReadStream(AStream, LSize, False); except Result := False; end; end; function SendStream(AContext: TIdContext; AStream: TStream): Boolean; overload; var StreamSize: LongInt; begin try Result := True; try StreamSize := (AStream.Size); AStream.Seek(0, soFromBeginning); AContext.Connection.IOHandler.Write(LongInt(StreamSize)); AContext.Connection.IOHandler.WriteBufferOpen; AContext.Connection.IOHandler.Write(AStream, 0, False); AContext.Connection.IOHandler.WriteBufferFlush; finally AContext.Connection.IOHandler.WriteBufferClose; end; except Result := False; end; end; function SendStream(AClient: TIdTCPClient; AStream: TStream): Boolean; overload; var StreamSize: LongInt; begin try Result := True; try StreamSize := (AStream.Size); AStream.Seek(0, soFromBeginning); // AClient.IOHandler.LargeStream := True; // AClient.IOHandler.SendBufferSize := 32768; AClient.IOHandler.Write(LongInt(StreamSize)); AClient.IOHandler.WriteBufferOpen; AClient.IOHandler.Write(AStream, 0, False); AClient.IOHandler.WriteBufferFlush; finally AClient.IOHandler.WriteBufferClose; end; except Result := False; end; end; /// /// --------------- HELPER FUNCTIONS FOR FILES EXCHANGE ---------------- /// function ClientSendFile(AClient: TIdTCPClient; Filename: String): Boolean; begin AClient.IOHandler.LargeStream := True; // fully support large streams Result := True; try AClient.IOHandler.WriteFile(Filename); // send file stream data except Result := False; end; end; function ClientReceiveFile(AClient: TIdTCPClient; Filename: String): Boolean; begin /// todo ...... end; function ServerSendFile(AContext: TIdContext; Filename: String): Boolean; begin /// todo ...... end; function ServerReceiveFile(AContext: TIdContext; ServerFilename: String; var ClientFilename: String): Boolean; var // LSize: String; AStream: TFileStream; begin try Result := True; AStream := TFileStream.Create(ServerFilename, fmCreate + fmShareDenyNone); try AContext.Connection.IOHandler.ReadStream(AStream); finally FreeAndNil(AStream); end; except Result := False; end; end; /// /// --------------- HELPER FUNCTION FOR RECORD EXCHANGE ------------------ /// (not using generic syntax features of DELPHI 2009 and better ) function MyRecordToByteArray(aRecord: TMyRecord): TIdBytes; var LSource: PAnsiChar; begin LSource := PAnsiChar(@aRecord); SetLength(Result, SizeOf(TMyRecord)); Move(LSource[0], Result[0], SizeOf(TMyRecord)); end; function ByteArrayToMyRecord(ABuffer: TIdBytes): TMyRecord; var LDest: PAnsiChar; begin LDest := PAnsiChar(@Result); Move(ABuffer[0], LDest[0], SizeOf(TMyRecord)); end; function TGenericRecord<TRecordType>.MyRecordToByteArray (aRecord: TRecordType): TIdBytes; var LSource: PAnsiChar; begin LSource := PAnsiChar(@aRecord); SetLength(Result, SizeOf(TRecordType)); Move(LSource[0], Result[0], SizeOf(TRecordType)); end; function TGenericRecord<TRecordType>.ByteArrayToMyRecord(ABuffer: TIdBytes) : TRecordType; var LDest: PAnsiChar; begin LDest := PAnsiChar(@Result); Move(ABuffer[0], LDest[0], SizeOf(TRecordType)); end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [NFE_DETALHE_IMPOSTO_ISSQN] The MIT License Copyright: Copyright (C) 2014 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit NfeDetalheImpostoIssqnVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils; type [TEntity] [TTable('NFE_DETALHE_IMPOSTO_ISSQN')] TNfeDetalheImpostoIssqnVO = class(TVO) private FID: Integer; FID_NFE_DETALHE: Integer; FBASE_CALCULO_ISSQN: Extended; FALIQUOTA_ISSQN: Extended; FVALOR_ISSQN: Extended; FMUNICIPIO_ISSQN: Integer; FITEM_LISTA_SERVICOS: Integer; FVALOR_DEDUCAO: Extended; FVALOR_OUTRAS_RETENCOES: Extended; FVALOR_DESCONTO_INCONDICIONADO: Extended; FVALOR_DESCONTO_CONDICIONADO: Extended; FVALOR_RETENCAO_ISS: Extended; FINDICADOR_EXIGIBILIDADE_ISS: Integer; FCODIGO_SERVICO: String; FMUNICIPIO_INCIDENCIA: Integer; FPAIS_SEVICO_PRESTADO: Integer; FNUMERO_PROCESSO: String; FINDICADOR_INCENTIVO_FISCAL: Integer; //Usado no lado cliente para controlar quais registros serão persistidos FPersiste: String; public [TId('ID')] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_NFE_DETALHE', 'Id Nfe Detalhe', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdNfeDetalhe: Integer read FID_NFE_DETALHE write FID_NFE_DETALHE; [TColumn('BASE_CALCULO_ISSQN', 'Base Calculo Issqn', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property BaseCalculoIssqn: Extended read FBASE_CALCULO_ISSQN write FBASE_CALCULO_ISSQN; [TColumn('ALIQUOTA_ISSQN', 'Aliquota Issqn', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property AliquotaIssqn: Extended read FALIQUOTA_ISSQN write FALIQUOTA_ISSQN; [TColumn('VALOR_ISSQN', 'Valor Issqn', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorIssqn: Extended read FVALOR_ISSQN write FVALOR_ISSQN; [TColumn('MUNICIPIO_ISSQN', 'Municipio Issqn', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property MunicipioIssqn: Integer read FMUNICIPIO_ISSQN write FMUNICIPIO_ISSQN; [TColumn('ITEM_LISTA_SERVICOS', 'Item Lista Servicos', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property ItemListaServicos: Integer read FITEM_LISTA_SERVICOS write FITEM_LISTA_SERVICOS; [TColumn('VALOR_DEDUCAO', 'Valor Deducao', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorDeducao: Extended read FVALOR_DEDUCAO write FVALOR_DEDUCAO; [TColumn('VALOR_OUTRAS_RETENCOES', 'Valor Outras Retencoes', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorOutrasRetencoes: Extended read FVALOR_OUTRAS_RETENCOES write FVALOR_OUTRAS_RETENCOES; [TColumn('VALOR_DESCONTO_INCONDICIONADO', 'Valor Desconto Incondicionado', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorDescontoIncondicionado: Extended read FVALOR_DESCONTO_INCONDICIONADO write FVALOR_DESCONTO_INCONDICIONADO; [TColumn('VALOR_DESCONTO_CONDICIONADO', 'Valor Desconto Condicionado', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorDescontoCondicionado: Extended read FVALOR_DESCONTO_CONDICIONADO write FVALOR_DESCONTO_CONDICIONADO; [TColumn('VALOR_RETENCAO_ISS', 'Valor Retencao Iss', 168, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorRetencaoIss: Extended read FVALOR_RETENCAO_ISS write FVALOR_RETENCAO_ISS; [TColumn('INDICADOR_EXIGIBILIDADE_ISS', 'Indicador Exigibilidade Iss', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IndicadorExigibilidadeIss: Integer read FINDICADOR_EXIGIBILIDADE_ISS write FINDICADOR_EXIGIBILIDADE_ISS; [TColumn('CODIGO_SERVICO', 'Codigo Servico', 160, [ldGrid, ldLookup, ldCombobox], False)] property CodigoServico: String read FCODIGO_SERVICO write FCODIGO_SERVICO; [TColumn('MUNICIPIO_INCIDENCIA', 'Municipio Incidencia', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property MunicipioIncidencia: Integer read FMUNICIPIO_INCIDENCIA write FMUNICIPIO_INCIDENCIA; [TColumn('PAIS_SEVICO_PRESTADO', 'Pais Sevico Prestado', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property PaisSevicoPrestado: Integer read FPAIS_SEVICO_PRESTADO write FPAIS_SEVICO_PRESTADO; [TColumn('NUMERO_PROCESSO', 'Numero Processo', 240, [ldGrid, ldLookup, ldCombobox], False)] property NumeroProcesso: String read FNUMERO_PROCESSO write FNUMERO_PROCESSO; [TColumn('INDICADOR_INCENTIVO_FISCAL', 'Indicador Incentivo Fiscal', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IndicadorIncentivoFiscal: Integer read FINDICADOR_INCENTIVO_FISCAL write FINDICADOR_INCENTIVO_FISCAL; [TColumn('PERSISTE', 'Persiste', 60, [], True)] property Persiste: String read FPersiste write FPersiste; end; implementation initialization Classes.RegisterClass(TNfeDetalheImpostoIssqnVO); finalization Classes.UnRegisterClass(TNfeDetalheImpostoIssqnVO); end.
unit libCV.Core; {$mode objfpc}{$H+} interface uses Classes, SysUtils, DynLibs, libCV.Types; type POpenCV = ^TOpenCV; TOpenCV = class private type TCreateImage = function(Size: TCvSize; Depth: Int32; Channels: Int32): PIplImage; cdecl; TReleaseImage = procedure(var Image: PIplImage); cdecl; TMatchTemplate = procedure(Image, Template, Result: PIplImage; Method: Integer; Mask: PIplImage = nil); cdecl; private FLibCore: TLibHandle; FLibImgProc: TLibHandle; _CreateImage: TCreateImage; _ReleaseImage: TReleaseImage; _MatchTemplate: TMatchTemplate; public function Load(Path: String): Boolean; function CreateImage(Width, Height: Int32; Depth, Channels: Int32): PIplImage; overload; function CreateImage(Matrix: TIntegerMatrix): PIplImage; overload; procedure ReleaseImage(var Image: PIplImage); function MatchTemplate(Image, Template, Mask: PIplImage; Method: Int32): TFloatMatrix; overload; function MatchTemplate(Image, Template, Mask: TIntegerMatrix; Method: Int32): TFloatMatrix; overload; destructor Destroy; override; constructor Create; end; var OpenCV: TOpenCV; implementation (* function TOpenCV.CreateImage(Bitmap: TBitmap): PIplImage; type TRGB32 = packed record B, G, R, A: Byte; end; TRGB24 = packed record B, G, R: Byte; end; var Y: Int32; Source: ^TRGB32; Dest: ^TRGB24; Hi: PtrUInt; begin if (Bitmap = nil) then Exit(nil); Result := _CreateImage(CVSize(Bitmap.Width, Bitmap.Height), IPL_DEPTH_8U, 3); for Y := 0 to Result^.Height - 1 do begin Source := Bitmap.ScanLine[Y]; Dest := Pointer(Result^.ImageData + Y * Result^.WidthStep); Hi := PtrUInt(Dest) + Result^.Width * SizeOf(TRGB24); while (PtrUInt(Dest) <= Hi) do begin Dest^.R := Source^.R; Dest^.G := Source^.G; Dest^.B := Source^.B; Inc(Dest); Inc(Source); end; end; end; *) function TOpenCV.MatchTemplate(Image, Template, Mask: PIplImage; Method: Int32): TFloatMatrix; var Mat: PIplImage; begin Mat := _CreateImage(CVSize(Image^.Width - Template^.Width + 1, Image^.Height - Template^.Height + 1), IPL_DEPTH_32F, 1); try _MatchTemplate(Image, Template, Mat, Method, Mask); Result := Mat^.AsFloatMatrix(); finally _ReleaseImage(Mat); end; end; function TOpenCV.MatchTemplate(Image, Template, Mask: TIntegerMatrix; Method: Int32): TFloatMatrix; var cvImg, cvTemplate, cvMask: PIplImage; begin cvImg := CreateImage(Image); cvTemplate := CreateImage(Template); cvMask := CreateImage(Mask); try Result := MatchTemplate(cvImg, cvTemplate, cvMask, Method); finally ReleaseImage(cvImg); ReleaseImage(cvTemplate); ReleaseImage(cvMask); end; end; function TOpenCV.CreateImage(Width, Height: Int32; Depth, Channels: Int32): PIplImage; begin Result := _CreateImage(CVSize(Width, Height), Depth, Channels); end; function TOpenCV.CreateImage(Matrix: TIntegerMatrix): PIplImage; type TRGB32Matrix = array of array of packed record B, G, R, A: Byte; end; TRGB24 = packed record B, G, R: Byte; end; var X, Y: Int32; Source: TRGB32Matrix; Dest: ^TRGB24; begin if (Length(Matrix) = 0) or (Length(Matrix[0]) = 0) then Exit(nil); Result := _CreateImage(CVSize(Length(Matrix[0]), Length(Matrix)), IPL_DEPTH_8U, 3); Source := TRGB32Matrix(Matrix); for Y := 0 to Result^.Height - 1 do begin Dest := Pointer(Result^.ImageData + Y * Result^.WidthStep); for X := 0 to Result^.Width - 1 do begin Dest^.R := Source[Y, X].B; // Matrix store colors in inverted order, so we just do R = B, B = R. Dest^.G := Source[Y, X].G; Dest^.B := Source[Y, X].R; Inc(Dest); end; end; end; procedure TOpenCV.ReleaseImage(var Image: PIplImage); begin if (Image <> nil) then _ReleaseImage(Image); end; function TOpenCV.Load(Path: String): Boolean; const cv_libCore = 'libopencv_core' + {$IFDEF CPU32}'32'{$ELSE}'64'{$ENDIF} + '.' + SharedSuffix; cv_libImgProc = 'libopencv_imgproc' + {$IFDEF CPU32}'32'{$ELSE}'64'{$ENDIF} + '.' + SharedSuffix; procedure NotFound(Name: String); begin raise Exception.Create(QuotedStr(Name) + ' not found'); end; begin Result := True; if (FLibCore > 0) and (FLibImgProc > 0) then Exit; try FLibCore := LoadLibrary(IncludeTrailingPathDelimiter(Path) + cv_libCore); if (FLibCore = NilHandle) then NotFound(cv_libCore); FLibImgProc := LoadLibrary(IncludeTrailingPathDelimiter(Path) + cv_libImgProc); if (FLibImgProc = NilHandle) then NotFound(cv_libImgProc); _CreateImage := TCreateImage(GetProcAddress(FLibCore, 'cvCreateImage')); if (_CreateImage = nil) then NotFound('cvCreateImage'); _ReleaseImage := TReleaseImage(GetProcAddress(FLibCore, 'cvReleaseImage')); if (_ReleaseImage = nil) then NotFound('cvReleaseImage'); _MatchTemplate := TMatchTemplate(GetProcAddress(FLibImgProc, 'cvMatchTemplate')); if (_MatchTemplate = nil) then NotFound('cvMatchTemplate'); except on e: Exception do begin Writeln('Failed to load OpenCV: ', e.Message); Result := False; end; end; end; destructor TOpenCV.Destroy; begin if (FLibCore > 0) then FreeLibrary(FLibCore); if (FLibImgProc > 0) then FreeLibrary(FLibImgProc); inherited Destroy; end; constructor TOpenCV.Create; begin FLibCore := 0; FLibImgProc := 0; end; initialization OpenCV := TOpenCV.Create(); finalization OpenCV.Free(); end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs; type TForm1 = class(TForm) private { Private declarations } FText: String; FIsActive: Boolean; procedure SetIsActive(const Value: Boolean); procedure SetText(const Value: String); public { Public declarations } property Text: String read FText write SetText; property IsActive: Boolean read FIsActive write SetIsActive; end; var Form1: TForm1; implementation {$R *.dfm} { TForm1 } procedure TForm1.SetIsActive(const Value: Boolean); begin FIsActive := Value; end; procedure TForm1.SetText(const Value: String); begin FText := Value; end; end.
{ ******************************************************************************* Title: T2Ti ERP Description: Janela de filtro que será utilizada por toda a aplicação The MIT License Copyright: Copyright (C) 2015 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> @author Albert Eije (T2Ti.COM) @version 2.0 ******************************************************************************* } unit UFiltro; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, ComCtrls, JvgGroupBox, JvExStdCtrls, JvGroupBox, JvExExtCtrls, JvRadioGroup, IWSystem, Menus, DBClient, JvExControls, JvEnterTab, JvComponentBase, UBase, DB, LabeledCtrls, VO, Rtti, Atributos; type TItemListBox = class private FCampo: string; public property Campo: string read FCampo write FCampo; end; TFFiltro = class(TFBase) BotaoResult: TBitBtn; JvgGroupBox1: TJvgGroupBox; ListaCampos: TListBox; ListaOperadores: TListBox; Label1: TLabel; Label2: TLabel; GrupoEOU: TJvRadioGroup; JvgGroupBox2: TJvgGroupBox; Label6: TLabel; MemoSQL: TMemo; ListaCriterios: TListBox; JvgGroupBox3: TJvgGroupBox; Label3: TLabel; ListaSalvos: TListBox; Label4: TLabel; BotaoAdicionaCriterio: TSpeedButton; BotaoRemoveCriterio: TSpeedButton; BotaoSalvarFiltro: TSpeedButton; BotaoAplicarFiltro: TSpeedButton; BotaoLimparCriterios: TSpeedButton; BotalESC: TBitBtn; PopupMenu: TPopupMenu; CarregarFiltro1: TMenuItem; ExcluirFiltro1: TMenuItem; EditExpressao: TLabeledMaskEdit; function defineEOU: String; function defineOperador: String; procedure CarregaFiltros; procedure BotaoAplicarFiltroClick(Sender: TObject); procedure BotaoAdicionaCriterioClick(Sender: TObject); procedure BotaoRemoveCriterioClick(Sender: TObject); procedure BotaoLimparCriteriosClick(Sender: TObject); procedure BotaoSalvarFiltroClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure CarregarFiltro1Click(Sender: TObject); procedure ExcluirFiltro1Click(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditExpressaoEnter(Sender: TObject); procedure ListaCamposClick(Sender: TObject); private { Private declarations } public { Public declarations } QuemChamou: String; CDSUtilizado: TClientDataSet; DataSetField: TField; DataSet: TClientDataSet; VO: TVO; procedure FormataCampoData; procedure PopulaListaCamposComVO(pListBox: TCustomListBox; pVO: TVO); end; var FFiltro: TFFiltro; implementation uses UDataModule; {$R *.dfm} procedure TFFiltro.PopulaListaCamposComVO(pListBox: TCustomListBox; pVO: TVO); var Contexto: TRttiContext; Tipo: TRttiType; Propriedade: TRttiProperty; Atributo: TCustomAttribute; Item: TItemListBox; begin try Contexto := TRttiContext.Create; Tipo := Contexto.GetType(pVO.ClassType); while pListBox.Items.Count > 0 do begin Item := TItemListBox(pListBox.Items.Objects[0]); Item.Free; pListBox.Items.Delete(0); end; for Propriedade in Tipo.GetProperties do begin for Atributo in Propriedade.GetAttributes do begin if Atributo is TId then begin Item := TItemListBox.Create; Item.Campo := 'ID'; pListBox.AddItem(Item.Campo, Item); end else if Atributo is Atributos.TColumn then begin Item := TItemListBox.Create; Item.Campo := (Atributo as Atributos.TColumn).Caption; pListBox.AddItem(Item.Campo, Item); end; end; end; finally Contexto.Free; end; end; procedure TFFiltro.CarregaFiltros; var F: TSearchRec; Ret: Integer; begin ListaSalvos.Clear; Ret := FindFirst(gsAppPath + 'Filtros\*.*', faAnyFile, F); try while Ret = 0 do begin if Copy(F.Name, 1, Length(QuemChamou) + 1) = QuemChamou + 'L' then ListaSalvos.Items.Add(Copy(F.Name, Length(QuemChamou) + 2, Length(F.Name))); Ret := FindNext(F); end; finally FindClose(F); end; end; procedure TFFiltro.CarregarFiltro1Click(Sender: TObject); begin if ListaSalvos.ItemIndex = -1 then begin Application.MessageBox('Selecione um filtro para carregar.', 'Erro', MB_OK + MB_ICONERROR); end else begin MemoSQL.Lines.LoadFromFile(gsAppPath + 'Filtros\' + QuemChamou + 'M' + ListaSalvos.Items.Strings[ListaSalvos.ItemIndex]); ListaCriterios.Items.LoadFromFile(gsAppPath + 'Filtros\' + QuemChamou + 'L' + ListaSalvos.Items.Strings[ListaSalvos.ItemIndex]); end; end; function TFFiltro.defineEOU: String; begin if GrupoEOU.ItemIndex = 0 then result := ' AND' else result := ' OR'; end; function TFFiltro.defineOperador: String; var idx: Integer; begin idx := ListaCampos.ItemIndex; DataSetField := DataSet.FindField(DataSet.FieldList.Fields[idx].FieldName); if (DataSetField.DataType = ftDateTime) then begin result := ' IN ' + '(' + Quotedstr(FormatDateTime('yyyy-mm-dd', StrToDate(EditExpressao.Text))) + ')'; end else begin case ListaOperadores.ItemIndex of 0: begin result := '=' + Quotedstr(EditExpressao.Text); end; 1: begin result := '<>' + Quotedstr(EditExpressao.Text); end; 2: begin result := '<' + Quotedstr(EditExpressao.Text); end; 3: begin result := '>' + Quotedstr(EditExpressao.Text); end; 4: begin result := '<=' + Quotedstr(EditExpressao.Text); end; 5: begin result := '>=' + Quotedstr(EditExpressao.Text); end; 6: begin result := ' IS NULL '; end; 7: begin result := ' IS NOT NULL '; end; 8: begin result := ' LIKE ' + Quotedstr(EditExpressao.Text + '*'); end; 9: begin result := ' LIKE ' + Quotedstr('*' + EditExpressao.Text); end; 10: begin result := ' LIKE ' + Quotedstr('*' + EditExpressao.Text + '*'); end; end; end; end; procedure TFFiltro.EditExpressaoEnter(Sender: TObject); begin CustomKeyPreview := False; FormataCampoData; EditExpressao.SelectAll; end; procedure TFFiltro.ExcluirFiltro1Click(Sender: TObject); begin if ListaSalvos.ItemIndex = -1 then begin Application.MessageBox('Selecione um filtro para excluir.', 'Erro', MB_OK + MB_ICONERROR); end else begin DeleteFile(gsAppPath + 'Filtros\' + QuemChamou + 'M' + ListaSalvos.Items.Strings[ListaSalvos.ItemIndex]); DeleteFile(gsAppPath + 'Filtros\' + QuemChamou + 'L' + ListaSalvos.Items.Strings[ListaSalvos.ItemIndex]); CarregaFiltros; BotaoLimparCriterios.Click; end; end; procedure TFFiltro.FormActivate(Sender: TObject); begin PopulaListaCamposComVO(ListaCampos, VO); CarregaFiltros; ListaCampos.ItemIndex := 0; ListaOperadores.ItemIndex := 0; ListaSalvos.SetFocus; end; procedure TFFiltro.BotaoAdicionaCriterioClick(Sender: TObject); var Criterio: String; ConsultaSQL: String; idx: Integer; begin if ListaCampos.ItemIndex = -1 then begin Application.MessageBox('É necessário selecionar um campo.', 'Erro', MB_OK + MB_ICONERROR); end else begin Criterio := ''; ConsultaSQL := ''; idx := ListaCampos.ItemIndex; if ListaCriterios.Count > 0 then begin Criterio := '[' + GrupoEOU.Items.Strings[GrupoEOU.ItemIndex] + ']'; ConsultaSQL := defineEOU; end; if (ListaOperadores.ItemIndex = 6) or (ListaOperadores.ItemIndex = 7) then begin // Critério Criterio := Criterio + ' ' + '[' + DataSet.FieldList.Fields[idx].FieldName + ']' + ' [' + ListaOperadores.Items.Strings[ListaOperadores.ItemIndex] + '] '; ListaCriterios.Items.Add(Criterio); // Consulta SQL ConsultaSQL := ConsultaSQL + ' ' + '[' + DataSet.FieldList.Fields[idx].FieldName + ']' + defineOperador; MemoSQL.Lines.Add(ConsultaSQL); end else begin if EditExpressao.Text <> '' then begin // Critério Criterio := Criterio + ' ' + '[' + DataSet.FieldList.Fields[idx].FieldName + ']' + ' [' + ListaOperadores.Items.Strings[ListaOperadores.ItemIndex] + '] ' + '"' + EditExpressao.Text + '"'; ListaCriterios.Items.Add(Criterio); // Consulta SQL ConsultaSQL := ConsultaSQL + ' ' + '[' + DataSet.FieldList.Fields[idx].FieldName + ']' + defineOperador; MemoSQL.Lines.Add(ConsultaSQL); end else begin Application.MessageBox('Não existe expressão para filtro.', 'Erro', MB_OK + MB_ICONERROR); EditExpressao.SetFocus; end; end; end; end; procedure TFFiltro.BotaoRemoveCriterioClick(Sender: TObject); begin if ListaCriterios.ItemIndex = -1 then begin Application.MessageBox('Selecione um critério para remover.', 'Erro', MB_OK + MB_ICONERROR); end else begin if (ListaCriterios.ItemIndex = 0) and (ListaCriterios.Items.Count > 1) then begin if Application.MessageBox('Primeiro critério selecionado. Existem outros critérios. Todos os critérios serão excluídos. Continua?', 'Pergunta do sistema', MB_YesNo + MB_IconQuestion) = IdYes then begin ListaCriterios.Clear; MemoSQL.Clear; end; end else begin MemoSQL.Lines.Delete(ListaCriterios.ItemIndex); ListaCriterios.DeleteSelected; end; end; end; procedure TFFiltro.BotaoSalvarFiltroClick(Sender: TObject); var NomeFiltro: String; begin if ListaCriterios.ItemIndex = -1 then begin Application.MessageBox('Não existem critérios para salvar um filtro.', 'Erro', MB_OK + MB_ICONERROR); end else begin NomeFiltro := InputBox('Nome do filtro', 'Informe o nome do filtro para armazenamento:', ''); if Trim(NomeFiltro) <> '' then begin if not DirectoryExists(gsAppPath + 'Filtros\') then CreateDir(gsAppPath + 'Filtros\'); ListaCriterios.Items.SaveToFile(gsAppPath + 'Filtros\' + QuemChamou + 'L' + NomeFiltro); MemoSQL.Lines.SaveToFile(gsAppPath + 'Filtros\' + QuemChamou + 'M' + NomeFiltro); CarregaFiltros; end; end; end; procedure TFFiltro.BotaoAplicarFiltroClick(Sender: TObject); begin BotaoResult.Click; end; procedure TFFiltro.BotaoLimparCriteriosClick(Sender: TObject); begin ListaCriterios.Clear; MemoSQL.Clear; end; procedure TFFiltro.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_F2 then BotaoAdicionaCriterio.Click; if Key = VK_F4 then BotaoRemoveCriterio.Click; if Key = VK_F5 then BotaoAplicarFiltro.Click; if Key = VK_F11 then BotaoLimparCriterios.Click; if Key = VK_F12 then BotaoSalvarFiltro.Click; end; procedure TFFiltro.ListaCamposClick(Sender: TObject); begin inherited; FormataCampoData; end; procedure TFFiltro.FormataCampoData; var Item: String; idx: Integer; begin DataSet := CDSUtilizado; idx := ListaCampos.ItemIndex; Item := DataSet.FieldList.Fields[idx].FieldName; DataSetField := DataSet.FindField(Item); if DataSetField.DataType = ftDateTime then begin EditExpressao.EditMask := '99/99/9999;1;_'; EditExpressao.Clear; end else EditExpressao.EditMask := ''; EditExpressao.Clear; end; end.
// Copyright 2018 by John Kouraklis and Contributors. All Rights Reserved. // // 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 Casbin.Model.Types; interface uses Casbin.Core.Base.Types, Casbin.Model.Sections.Types, System.Generics.Collections, Casbin.Effect.Types, Casbin.Watcher.Types; type IModel = interface (IBaseInterface) ['{A1B8A09F-0562-4C15-B9F3-74537C5A9E27}'] function section (const aSection: TSectionType; const aSlim: Boolean = true): string; function assertions (const aSection: TSectionType): TList<string>; procedure addDefinition (const aSection: TSectionType; const aTag: string; const aAssertion: string); overload; procedure addDefinition (const aSection: TSectionType; const aAssertion: string); overload; procedure addModel(const aModel: string); function assertionExists (const aAssertion: string): Boolean; function effectCondition: TEffectCondition; function toOutputString: string; // Watchers procedure registerWatcher (const aWatcher: IWatcher); procedure unregisterWatcher (const aWatcher: IWatcher); procedure notifyWatchers; end; implementation end.
unit SlottingPlacementDataPoster; interface uses PersistentObjects, DBGate, BaseObjects, DB, SlottingPlacement, Organization, CoreTransfer; type TRackDataPoster = class(TImplementedDataPoster) public function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; TPartPlacementTypeDataPoster = class(TImplementedDataPoster) public function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; TPartPlacementDataPoster = class(TImplementedDataPoster) private FAllPartPlacementTypes: TPartPlacementTypes; public property AllPartPlacementTypes: TPartPlacementTypes read FAllPartPlacementTypes write FAllPartPlacementTypes; function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; TSlottingPlacementDataPoster = class(TImplementedDataPoster) private FPartPlacements: TPartPlacements; FAllOrganizations: TOrganizations; FAllCoreTransfers: TCoreTransfers; public property AllPartPlacements: TPartPlacements read FPartPlacements write FPartPlacements; property AllOrganizations: TOrganizations read FAllOrganizations write FAllOrganizations; property AllCoreTransfers: TCoreTransfers read FAllCoreTransfers write FAllCoreTransfers; function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; TBoxPictureDataPoster = class(TImplementedDataPoster) public function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; TBoxDataPoster = class(TImplementedDataPoster) protected // локальная сортировка procedure LocalSort(AObjects: TIDObjects); override; public function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; TSlottingBoxDataPoster = class(TImplementedDataPoster) public function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; TWellBoxDataPoster = class(TImplementedDataPoster) private FRacks: TRacks; public property Racks: TRacks read FRacks write FRacks; function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; TPlacementQualityDataPoster = class(TImplementedDataPoster) public function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; constructor Create; override; end; implementation uses Facade, SysUtils, Slotting, Variants, ClientCommon, Well, StrUtils, GeneralizedSection; function SortBoxes(Item1, Item2: Pointer): Integer; var b1, b2: TBox; iNum1, iNum2: integer; begin Result := 0; b1 := TBox(Item1); b2 := TBox(Item2); // косяк try iNum1 := ExtractInt(b1.Name); except iNum1 := 0; end; try iNum2 := ExtractInt(b2.Name); except iNum2 := 0; end; if iNum1 > iNum2 then Result := 1 else if iNum1 < iNum2 then Result := -1 else if iNum1 = iNum2 then begin if b1.Name > b2.Name then Result := 1 else if b1.Name < b2.Name then Result := -1 else Result := 0; end; end; { TPartPlacementTypeDataPoster } constructor TPartPlacementTypeDataPoster.Create; begin inherited; Options := [soSingleDataSource, soGetKeyValue]; DataSourceString := 'tbl_Part_Placement_Property'; KeyFieldNames := 'Placement_Property_ID'; FieldNames := 'Placement_Property_ID, vch_Placement_Property_Name'; AccessoryFieldNames := 'Placement_Property_ID, vch_Placement_Property_Name'; AutoFillDates := false; Sort := 'vch_Placement_Property_Name'; end; function TPartPlacementTypeDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := inherited DeleteFromDB(AObject, ACollection); end; function TPartPlacementTypeDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; s: TPartPlacementType; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin s := AObjects.Add as TPartPlacementType; s.ID := ds.FieldByName('Placement_Property_ID').AsInteger; s.Name := trim(ds.FieldByName('vch_Placement_Property_Name').AsString); ds.Next; end; ds.First; end; end; function TPartPlacementTypeDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TDataSet; p: TPartPlacementType; begin Result := inherited PostToDB(AObject, ACollection); ds := TMainFacade.GetInstance.DBGates.Add(Self); p := AObject as TPartPlacementType; ds.FieldByName('Placement_Property_ID').AsInteger := p.ID; ds.FieldByName('vch_Placement_Property_Name').AsString := trim(p.Name); ds.Post; if p.ID = 0 then p.ID := ds.FieldByName('Placement_Property_ID').AsInteger; end; { TPartPlacementDataPoster } constructor TPartPlacementDataPoster.Create; begin inherited; Options := [soSingleDataSource, soGetKeyValue]; DataSourceString := 'tbl_Part_Placement_Dict'; KeyFieldNames := 'Part_Placement_ID'; FieldNames := 'Part_Placement_ID, vch_Part_Placement, Placement_Property_ID, Main_Placement_ID'; AccessoryFieldNames := 'Part_Placement_ID, vch_Part_Placement, Placement_Property_ID, Main_Placement_ID'; AutoFillDates := false; Sort := 'vch_Part_Placement'; end; function TPartPlacementDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := 0; end; function TPartPlacementDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; s: TPartPlacement; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin s := AObjects.Add as TPartPlacement; s.ID := ds.FieldByName('Part_Placement_ID').AsInteger; s.Name := trim(ds.FieldByName('vch_Part_Placement').AsString); s.PartPlacementType := AllPartPlacementTypes.ItemsByID[ds.FieldByName('Placement_Property_ID').AsInteger] as TPartPlacementType; s.MainPlacementID := ds.FieldByName('Main_Placement_ID').AsInteger; ds.Next; end; ds.First; end; end; function TPartPlacementDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := 0; end; { TSlottingPlacementDataPoster } constructor TSlottingPlacementDataPoster.Create; begin inherited; Options := []; DataSourceString := 'VW_SLOTTING_PLACEMENT'; DataPostString := 'tbl_Slotting_Placement'; DataDeletionString := 'tbl_Slotting_Placement'; KeyFieldNames := 'WELL_UIN'; FieldNames := 'WELL_UIN, VCH_OWNER_PART_PLACEMENT, VCH_WAREHOUSE_BOX_NUMBERS, NUM_BOX_FINAL_COUNT, STATE_PART_PLACEMENT_ID, NUM_BOX_COUNT, CORE_OWNER_ORGANIZATION_ID, VCH_RACK_LIST_GS, VCH_RACK_LIST, NUM_CORE_FINAL_YIELD, NUM_CORE_YIELD, ' + 'NUM_CORE_FINAL_YIELD_GS, NUM_CORE_YIELD_GS, NUM_BOX_FINAL_COUNT_GS, VCH_TRANSFER_HISTORY, CORE_REPLACEMENT_ID, CORE_REPLACEMENT_TASK_ID'; AccessoryFieldNames := 'WELL_UIN, VCH_OWNER_PART_PLACEMENT, VCH_WAREHOUSE_BOX_NUMBERS, NUM_BOX_FINAL_COUNT, STATE_PART_PLACEMENT_ID, NUM_BOX_COUNT, CORE_OWNER_ORGANIZATION_ID'; AutoFillDates := false; Sort := ''; end; function TSlottingPlacementDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := inherited DeleteFromDb(AObject, ACollection); end; function TSlottingPlacementDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; s: TSlottingPlacement; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin s := AObjects.Add as TSlottingPlacement; s.ID := ds.FieldByName('Well_UIN').AsInteger; s.StatePartPlacement := AllPartPlacements.ItemsByID[ds.FieldByName('STATE_PART_PLACEMENT_ID').AsInteger] as TPartPlacement; s.OwnerPartPlacement := trim(ds.FieldByName('VCH_OWNER_PART_PLACEMENT').AsString); s.BoxCount := ds.FieldByName('num_Box_Count').AsInteger; s.FinalBoxCount := ds.FieldByName('NUM_BOX_FINAL_COUNT').AsInteger; s.FinalBoxCountWithGenSection := ds.FieldByName('NUM_BOX_FINAL_COUNT_GS').AsInteger; s.SampleBoxNumbers := trim(ds.FieldByName('VCH_WAREHOUSE_BOX_NUMBERS').AsString); s.RackList := trim(ds.FieldByName('VCH_RACK_LIST').AsString); s.RackListWithGenSection := trim(ds.FieldByName('VCH_RACK_LIST_GS').AsString); s.CoreFinalYield := ds.FieldByName('NUM_CORE_FINAL_YIELD').AsFloat; s.CoreYield := ds.FieldByName('NUM_CORE_YIELD').AsFloat; s.CoreFinalYieldWithGenSection := ds.FieldByName('NUM_CORE_FINAL_YIELD_GS').AsFloat; s.CoreYieldWithGenSection := ds.FieldByName('NUM_CORE_YIELD_GS').AsFloat; s.TransferHistory := Trim(ds.FieldByName('VCH_TRANSFER_HISTORY').AsString); if Assigned(AllCoreTransfers) then begin s.LastCoreTransfer := AllCoreTransfers.ItemsByID[ds.FieldByName('CORE_REPLACEMENT_ID').AsInteger]; if Assigned(s.LastCoreTransfer) then s.LastCoreTransferTask := (s.LastCoreTransfer as TCoreTransfer).CoreTransferTasks.ItemsByID[ds.FieldByName('CORE_REPLACEMENT_TASK_ID').AsInteger]; end; if Assigned(AllOrganizations) then s.Organization := AllOrganizations.ItemsById[ds.FieldByName('CORE_OWNER_ORGANIZATION_ID').AsInteger] as TOrganization; ds.Next; end; ds.First; end; end; function TSlottingPlacementDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TDataSet; s: TSlottingPlacement; begin Result := inherited PostToDB(AObject, ACollection); ds := TMainFacade.GetInstance.DBGates.Add(Self); s := AObject as TSlottingPlacement; ds.FieldByName('Well_UIN').AsInteger := s.Owner.ID; if not Assigned(s.StatePartPlacement) then s.StatePartPlacement := AllPartPlacements.CoreLibrary; ds.FieldByName('STATE_PART_PLACEMENT_ID').AsInteger := s.StatePartPlacement.ID; ds.FieldByName('VCH_OWNER_PART_PLACEMENT').AsString := s.OwnerPartPlacement; ds.FieldByName('num_Box_Count').AsInteger := s.BoxCount; ds.FieldByName('num_Box_Final_Count').AsInteger := s.FinalBoxCount; if Assigned(s.Organization) then ds.FieldByName('CORE_OWNER_ORGANIZATION_ID').AsInteger := s.Organization.ID else ds.FieldByName('CORE_OWNER_ORGANIZATION_ID').Value := null; ds.Post; if s.ID = 0 then s.ID := ds.FieldByName('Well_UIN').AsInteger; end; { TBoxDataPoster } constructor TBoxDataPoster.Create; begin inherited; Options := [soSingleDataSource, soGetKeyValue]; DataSourceString := 'tbl_Box'; KeyFieldNames := 'Box_UIN'; FieldNames := 'Box_UIN, vch_Box_Number, Rack_ID'; AccessoryFieldNames := 'Box_UIN, vch_Box_Number, Rack_ID'; AutoFillDates := false; Sort := ''; end; function TBoxDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := inherited DeleteFromDB(AObject, ACollection); end; function TBoxDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; b: TBox; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin b := AObjects.Add as TBox; b.ID := ds.FieldByName('Box_UIN').AsInteger; b.BoxNumber := trim(ds.FieldByName('vch_Box_Number').AsString); ds.Next; end; ds.First; end; LocalSort(AObjects); end; procedure TBoxDataPoster.LocalSort(AObjects: TIDObjects); begin AObjects.Sort(SortBoxes); end; function TBoxDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var b: TBox; ds: TDataSet; begin Result := 0; try ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Active then ds.Open; if (ds.Locate(KeyFieldNames, AObject.ID, [])) or (AObject.ID > 0) then ds.Edit else ds.Append; except on E: Exception do begin raise; end; end; b := AObject as TBox; if b.ID >= 0 then ds.FieldByName('Box_UIN').AsInteger := b.ID; if not (b.Rack is TNullRack) then ds.FieldByName('RACK_ID').AsInteger := b.Rack.ID else ds.FieldByName('RACK_ID').Value := null; ds.FieldByName('vch_Box_Number').AsString := b.BoxNumber; ds.Post; if b.ID <= 0 then b.ID := ds.FieldByName('Box_UIN').AsInteger; end; { TSlottingBoxDataPoster } constructor TSlottingBoxDataPoster.Create; begin inherited; Options := []; DataSourceString := 'vw_Slotting_Box'; DataPostString := 'tbl_Slotting_Box'; DataDeletionString := 'tbl_Slotting_Box'; KeyFieldNames := 'Box_UIN; Slotting_UIN'; FieldNames := 'Box_UIN, Slotting_UIN, Part_Placement_ID, VCH_BOX_NUMBER, VCH_RACK, VCH_SHELF, VCH_CELL'; AccessoryFieldNames := 'Box_UIN, Slotting_UIN'; AutoFillDates := false; Sort := ''; end; function TSlottingBoxDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; var ds: TCommonServerDataSet; begin Result := 0; ds := TMainFacade.GetInstance.DBGates.Add(Self); try // находим строку соответствующую ключу //ds.Refresh; ds.First; if ds.Locate(ds.KeyFieldNames, varArrayOf([AObject.ID, AObject.Collection.Owner.ID]), []) then ds.Delete except Result := -1; end; end; function TSlottingBoxDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; sb: TSlottingBox; s: TSlotting; w: TWell; b: TBox; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin s := AObjects.Owner as TSlotting; w := nil; if s.Owner is TWell then w := s.Owner as TWell else if s is TGeneralizedSectionSlotting then w := (s as TGeneralizedSectionSlotting).Well; b := w.SlottingPlacement.Boxes.ItemsByID[ds.FieldByName('Box_UIN').AsInteger] as TBox; if Assigned(b) then begin sb := AObjects.Add as TSlottingBox; sb.Assign(b); end; ds.Next; end; ds.First; end; end; function TSlottingBoxDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var b: TSlottingBox; ds: TDataSet; begin Result := 0; b := AObject as TSlottingBox; try ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Active then ds.Open; if ds.Locate(KeyFieldNames, varArrayOf([AObject.ID, b.Collection.Owner.ID]), []) then ds.Edit else ds.Append; except on E: Exception do begin raise; end; end; ds.FieldByName('Box_UIN').AsInteger := b.ID; ds.FieldByName('Slotting_UIN').AsInteger := b.Collection.Owner.ID; ds.Post; end; { TWellBoxDataPoster } constructor TWellBoxDataPoster.Create; begin inherited; Options := [soSingleDataSource, soGetKeyValue]; DataSourceString := 'tbl_Box'; KeyFieldNames := 'Box_UIN'; FieldNames := 'Box_UIN, vch_Box_Number, Rack_ID'; AccessoryFieldNames := 'Box_UIN, vch_Box_Number, Rack_ID'; AutoFillDates := false; Sort := ''; end; function TWellBoxDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := 0; end; function TWellBoxDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var wb: TWellBox; w: TSlottingPlacement; ds: TDataSet; r: TRack; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin w := AObjects.Owner as TSlottingPlacement; wb := w.Boxes.Add as TWellBox; wb.ID := ds.FieldByName('Box_UIN').AsInteger; wb.BoxNumber := trim(ds.FieldByName('vch_Box_Number').AsString); if Assigned(FRacks) then begin r := Racks.ItemsById[ds.FieldByName('Rack_ID').AsInteger] as TRack; if Assigned(r) then wb.Rack := r else wb.Rack := TNullRack.GetInstance; end else wb.Rack := TNullRack.GetInstance; ds.Next; end; ds.First; end; end; function TWellBoxDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var b: TBox; ds: TDataSet; begin Result := 0; try ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Active then ds.Open; if (ds.Locate(KeyFieldNames, AObject.ID, [])) or (AObject.ID > 0) then ds.Edit else ds.Append; except on E: Exception do begin raise; end; end; b := AObject as TBox; if b.ID >= 0 then ds.FieldByName('Box_UIN').AsInteger := b.ID; if Assigned(b.Rack) and (not (b.Rack is TNullRack)) then ds.FieldByName('RACK_ID').AsInteger := b.Rack.ID else ds.FieldByName('RACK_ID').Value := null; ds.FieldByName('vch_Box_Number').AsString := b.BoxNumber; ds.Post; if b.ID <= 0 then b.ID := ds.FieldByName('Box_UIN').AsInteger; end; { TBoxPictureDataPoster } constructor TBoxPictureDataPoster.Create; begin inherited; Options := [soKeyInsert]; DataSourceString := 'TBL_BOX_PICTURE'; DataPostString := 'SPD_ADD_BOX_PICTURE'; DataDeletionString := 'SPD_DELETE_BOX_PICTURE'; KeyFieldNames := 'BOX_PICTURE_UIN'; FieldNames := 'BOX_PICTURE_UIN, BOX_UIN, VCH_BOX_PICTURE_PATH'; AccessoryFieldNames := 'BOX_PICTURE_UIN, BOX_UIN, VCH_BOX_PICTURE_PATH'; AutoFillDates := false; Sort := ''; end; function TBoxPictureDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := inherited DeleteFromDB(AObject, ACollection); end; function TBoxPictureDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; bp: TBoxPicture; sLocalName: string; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin bp := AObjects.Add as TBoxPicture; bp.ID := ds.FieldByName('BOX_PICTURE_UIN').AsInteger; bp.RemoteName := ExtractFileName(ds.FieldByName('VCH_BOX_PICTURE_PATH').AsString); sLocalName := StringReplace(bp.RemoteName, IntToStr(bp.Collection.Owner.ID), '', [rfReplaceAll]); while sLocalName[1] = '_' do sLocalName := MidStr(sLocalName, 2, Length(sLocalName)); bp.LocalName := sLocalName; // а localpath будет когда мы куда-нибудь скачаем их ds.Next; end; ds.First; end; end; function TBoxPictureDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; var bp: TBoxPicture; ds: TDataSet; begin Result := 0; bp := AObject as TBoxPicture; try ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Active then ds.Open; if (ds.Locate(KeyFieldNames, bp.ID, [])) or (bp.ID > 0) then ds.Edit else ds.Append; except on E: Exception do begin raise; end; end; if bp.ID >= 0 then ds.FieldByName('BOX_PICTURE_UIN').AsInteger := bp.ID; ds.FieldByName('BOX_UIN').AsInteger := bp.Collection.Owner.ID; ds.FieldByName('VCH_BOX_PICTURE_PATH').AsString := bp.RemoteFullName; ds.Post; bp.ID := ds.FieldByName('BOX_PICTURE_UIN').AsInteger; end; { TPlacementQualityDataPoster } constructor TPlacementQualityDataPoster.Create; begin inherited; Options := [soSingleDataSource]; DataSourceString := 'tbl_Placement_Quality'; KeyFieldNames := 'PLACEMENT_QUALITY_ID'; FieldNames := 'PLACEMENT_QUALITY_ID, VCH_PLACEMENT_QUALITY_NAME'; AccessoryFieldNames := 'PLACEMENT_QUALITY_ID, VCH_PLACEMENT_QUALITY_NAME'; AutoFillDates := false; Sort := ''; end; function TPlacementQualityDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; s: TPlacementQuality; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin s := AObjects.Add as TPlacementQuality; s.ID := ds.FieldByName('Placement_Quality_ID').AsInteger; s.Name := ds.FieldByName('vch_Placement_Quality_Name').AsString; ds.Next; end; ds.First; end; end; { TRackDataPoster } constructor TRackDataPoster.Create; begin inherited; Options := [soSingleDataSource, soGetKeyValue]; DataSourceString := 'tbl_Rack'; KeyFieldNames := 'Rack_ID'; FieldNames := 'Rack_ID, vch_Rack_Name, Part_Placement_ID'; AccessoryFieldNames := 'Rack_ID, vch_Rack_Name, Part_Placement_ID'; AutoFillDates := false; Sort := 'vch_Rack_Name'; end; function TRackDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := 0; end; function TRackDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; s: TRack; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin s := AObjects.Add as TRack; s.ID := ds.FieldByName('Rack_ID').AsInteger; s.Name := trim(ds.FieldByName('vch_Rack_Name').AsString); s.ShortName := trim(ds.FieldByName('vch_Rack_Name').AsString); ds.Next; end; ds.First; end; end; function TRackDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := 0; end; end.
unit PWInfoCoordWell; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, CommonFrame, StdCtrls, Buttons, ExtCtrls, ComCtrls, Well, BaseObjects, Mask, CommonValueDictFrame; type TfrmInfoCoordWell = class(TfrmCommonFrame) lbl5: TLabel; lbl6: TLabel; lbl7: TLabel; lbl8: TLabel; rb1: TRadioButton; rbtn: TRadioButton; edtY: TEdit; edtX: TEdit; edtGradX: TMaskEdit; edtGradY: TMaskEdit; frmFilterSource: TfrmFilter; grp1: TGroupBox; pnl: TPanel; grp: TGroupBox; dtmEnteringDate: TDateTimePicker; private function GetValueCoord (i, j: Integer; s : string) : string; function GetWell: TWell; protected procedure FillControls(ABaseObject: TIDObject); override; procedure ClearControls; override; procedure FillParentControls; override; procedure RegisterInspector; override; function GetParentCollection: TIDObjects; override; public property Well: TWell read GetWell; procedure Save(AObject: TIDObject = nil); override; procedure Remove; constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var frmInfoCoordWell: TfrmInfoCoordWell; implementation uses facade, Coord, MaskUtils; {$R *.dfm} { TfrmInfoCoordWell } procedure TfrmInfoCoordWell.ClearControls; begin inherited; edtGradX.Clear; edtGradY.Clear; edtX.Clear; edtY.Clear; dtmEnteringDate.DateTime := Date; frmFilterSource.AllObjects := (TMainFacade.GetInstance as TMainFacade).AllSourcesCoord; frmFilterSource.cbxActiveObject.Text := '<не указан>'; end; constructor TfrmInfoCoordWell.Create(AOwner: TComponent); begin inherited; edtGradX.EditMask := '00\°00\' + '''' + '00' + DecimalSeparator + '00\' + '''' + '''' + ';1;_'; edtGradY.EditMask := '00\°00\' + '''' + '00' + DecimalSeparator + '00\' + '''' + '''' + ';1;_'; //edtGradX.Text := '__°__' + '''' + '__' + DecimalSeparator + '00' + '''' + ''''; end; destructor TfrmInfoCoordWell.Destroy; begin inherited; end; procedure TfrmInfoCoordWell.FillControls(ABaseObject: TIDObject); begin inherited; if Assigned (Well) then with Well do begin if Assigned (Coord) then begin edtGradX.Text := IntToStr(Coord.X_grad) + '\°' + IntToStr(Coord.X_min) + '\' + '''' + FloatToStrF(Coord.X_sec, ffFixed, 4, 2) + '\'; edtGradY.Text := IntToStr(Coord.Y_grad) + '\°' + IntToStr(Coord.Y_min) + '\' + '''' + FloatToStrF(Coord.Y_sec, ffFixed, 4, 2) + '\'; dtmEnteringDate.DateTime := Coord.dtmEnteringDate; if Assigned (Coord.SourceCoord) then begin frmFilterSource.ActiveObject := Coord.SourceCoord; frmFilterSource.cbxActiveObject.Text := Coord.SourceCoord.Name; end; end; end; end; procedure TfrmInfoCoordWell.FillParentControls; begin inherited; end; function TfrmInfoCoordWell.GetParentCollection: TIDObjects; begin Result := nil; end; function TfrmInfoCoordWell.GetValueCoord(i, j: Integer; s: string): string; var k : Integer; begin Result := ''; for k := i to j do Result := Result + s[k]; end; function TfrmInfoCoordWell.GetWell: TWell; begin Result := EditingObject as TWell; end; procedure TfrmInfoCoordWell.RegisterInspector; begin inherited; end; procedure TfrmInfoCoordWell.Remove; begin if MessageBox(0, 'Вы действительно хотите удалить координаты выбранной скважины?', 'Предупреждение', MB_YESNO + MB_ICONWARNING + MB_APPLMODAL) = ID_YES then begin Well.Coords.Remove(Well.Coord); //66°48'33,828'' //59°54'50,609'' ShowMessage('Координаты были удалены.'); end; end; procedure TfrmInfoCoordWell.Save(AObject: TIDObject = nil); begin inherited; with Well do begin // 3-Южно-Шапкинская (-ое) if Not Assigned (Coord) then Well.Coords.Add; Coord.coordX := 3600 * StrToInt(GetValueCoord(1, 2, edtGradX.Text)) + 60 * StrToInt(GetValueCoord(4, 5, edtGradX.Text)) + StrToFloat(GetValueCoord(7, Length(edtGradX.Text) - 2, edtGradX.Text)); Coord.coordY := 3600 * StrToInt(GetValueCoord(1, 2, edtGradY.Text)) + 60 * StrToInt(GetValueCoord(4, 5, edtGradY.Text)) + StrToFloat(GetValueCoord(7, Length(edtGradY.Text) - 2, edtGradY.Text)); if Assigned (frmFilterSource.ActiveObject) then Coord.SourceCoord := frmFilterSource.ActiveObject as TSourceCoord; end; end; end.
unit uDocument; interface uses Classes; type TDocument = class(TPersistent) protected fExpiryDate : String; fExtraValues: String; fIssueDate: String; fIssuer: String; fIssuerDepartmentCode: String; fNumber: String; fSeries: String; fType: Integer; published property ExpiryDate : String read fExpiryDate write fExpiryDate; property ExtraValues: String read fExtraValues write fExtraValues; property IssueDate: String read fIssueDate write fIssueDate; property Issuer: String read fIssuer write fIssuer; property IssuerDepartmentCode: String read fIssuerDepartmentCode write fIssuerDepartmentCode; property Number: String read fNumber write fNumber; property Series: String read fSeries write fSeries; property TypeCode: Integer read fType write fType; end; implementation end.
unit SpellCheckerForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, cmpCWSpellChecker, cmpCWRichEdit, cmpPersistentPosition; const WM_SETUP = WM_USER + $200; type TfmSpellChecker = class(TForm) Label1: TLabel; lblSuggestions: TLabel; btnChange: TButton; btnChangeAll: TButton; btnSkipAll: TButton; btnSkip: TButton; btnAdd: TButton; btnCancel: TButton; btnFinish: TButton; reText: TExRichEdit; lvSuggestions: TListView; PersistentPosition1: TPersistentPosition; procedure FormShow(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnSkipClick(Sender: TObject); procedure btnChangeClick(Sender: TObject); procedure btnChangeAllClick(Sender: TObject); procedure lvSuggestionsDblClick(Sender: TObject); procedure btnAddClick(Sender: TObject); procedure btnSkipAllClick(Sender: TObject); private fChecker : TCWSpellChecker; fText : WideString; fBadWord : WideString; fBadSS : Integer; fIgnoreWords : TStringList; fSS, fSE : Integer; fQuoteChars: string; procedure ErrorFoundAt (ss, se : Integer; suggestions : TStrings); procedure NextWord; function GetChangedWord : WideString; procedure WmSetup (var message : TMessage); message WM_SETUP; protected procedure UpdateActions; override; procedure Loaded; override; public destructor Destroy; override; procedure Initialize (checker : TCWSpellChecker; ss, se : Integer; suggestions : TStrings); property QuoteChars : string read fQuoteChars write fQuoteChars; end; var fmSpellChecker: TfmSpellChecker; implementation uses unitCharsetMap; {$R *.dfm} { TfmSpellChecker } procedure TfmSpellChecker.Initialize(checker : TCWSpellChecker; ss, se : Integer; suggestions : TStrings); begin fChecker := checker; fText := fChecker.ExRichEdit.Text; reText.CodePage := fChecker.ExRichEdit.CodePage; reText.Text := fText; fChecker.ExRichEdit.SetRawSelection(ss, se); fSS := ss; fSE := se; reText.SetRawSelection (ss, se); fBadWord := fChecker.ExRichEdit.SelText; ErrorFoundAt (ss, se, suggestions); end; procedure TfmSpellChecker.FormDestroy(Sender: TObject); begin fmSpellChecker := Nil end; procedure TfmSpellChecker.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree end; procedure TfmSpellChecker.ErrorFoundAt(ss, se: Integer; suggestions: TStrings); var i : Integer; begin fBadSS := ss; lvSuggestions.Items.BeginUpdate; try lvSuggestions.Items.Clear; for i := 0 to suggestions.Count - 1 do with lvSuggestions.Items.Add do Caption := suggestions [i]; finally lvSuggestions.Items.EndUpdate end end; procedure TfmSpellChecker.UpdateActions; var errorFound : boolean; canChange : boolean; begin errorFound := fBadWord <> ''; if errorFound then begin btnSkip.Enabled := True; btnSkipAll.Enabled := True; canChange := (lvSuggestions.ItemIndex <> -1) or (reText.Text <> fText); btnChange.Enabled := canChange; btnChangeAll.Enabled := canChange; end else begin btnSkip.Enabled := False; btnSkipAll.Enabled := False; btnChange.Enabled := False; btnChangeAll.Enabled := False; end end; procedure TfmSpellChecker.btnSkipClick(Sender: TObject); begin NextWord end; procedure TfmSpellChecker.NextWord; var ss, se : Integer; suggestions : TStrings; ok : boolean; begin repeat reText.GetRawSelection(ss, se); suggestions := TStringList.Create; try ok := fChecker.Check(fText, se + 1, ss, se, suggestions); if not ok then begin fChecker.ExRichEdit.SetRawSelection(ss, se); reText.SetRawSelection (ss, se); fBadWord := fChecker.ExRichEdit.SelText; if not Assigned (fIgnoreWords) or (fIgnoreWords.IndexOf(fBadWord) = -1) then begin ErrorFoundAt (ss, se, suggestions); break end end else begin ModalResult := mrOK; break end finally suggestions.Free end until False end; procedure TfmSpellChecker.btnChangeClick(Sender: TObject); begin if reText.Text <> fText then begin fText := reText.Text; fChecker.ExRichEdit.Text := fText end else begin fChecker.ExRichEdit.SelText := lvSuggestions.Selected.Caption; fText := fChecker.ExRichEdit.Text; reText.SelText := lvSuggestions.Selected.Caption end; NextWord end; procedure TfmSpellChecker.btnChangeAllClick(Sender: TObject); var ss : Integer; newWord : string; begin if reText.Text <> fText then newWord := GetChangedWord else newWord := lvSuggestions.Selected.Caption; ss := fBadSS - 1; fText := Copy (fText, 1, ss) + StringReplace (Copy (fText, ss + 1, MaxInt), fBadWord, newWord, [rfReplaceAll, rfIgnoreCase]); fChecker.ExRichEdit.Text := fText; reText.Text := fText; reText.SetRawSelection(ss + 1, ss + 1 + Length (newWord)); NextWord; end; procedure TfmSpellChecker.lvSuggestionsDblClick(Sender: TObject); begin btnChangeClick (nil) end; function TfmSpellChecker.GetChangedWord: WideString; var changedText : WideString; p, l, ew : Integer; ch : WideChar; begin changedText := reText.Text; l := Length (changedText); p := fBadSS; ew := -1; while p < l do begin ch := changedText [p]; if IsWideCharAlNum (ch) or (word (ch) = Word ('''')) then ew := p else break; Inc (p) end; if ew = -1 then result := '' else result := Copy (changedText, fBadSS, ew - fBadSS + 1); end; procedure TfmSpellChecker.btnAddClick(Sender: TObject); begin fChecker.Add (fBadWord); NextWord end; destructor TfmSpellChecker.Destroy; begin fIgnoreWords.Free; inherited; end; procedure TfmSpellChecker.btnSkipAllClick(Sender: TObject); begin if not Assigned (fIgnoreWords) then begin fIgnoreWords := TStringList.Create; fIgnoreWords.CaseSensitive := False end; fIgnoreWords.Add(fBadWord); NextWord end; procedure TfmSpellChecker.FormShow(Sender: TObject); begin reText.SetRawSelection (fSS, fSE); PostMessage (handle, WM_SETUP, 0, 0); end; procedure TfmSpellChecker.WmSetup(var message: TMessage); begin end; procedure TfmSpellChecker.Loaded; begin inherited; end; end.
unit Vector4iComparatorTest; {$mode objfpc}{$H+} {$CODEALIGN LOCALMIN=16} interface uses Classes, SysUtils, fpcunit, testregistry, BaseTestCase, native, BZVectorMath; type TVector4iComparatorTest = class(TIntVectorBaseTestCase) published procedure TestCompare; procedure TestCompareFalse; procedure TestOpAdd; procedure TestOpAddInt; procedure TestOpSub; procedure TestOpSubInt; procedure TestOpMul; procedure TestOpMulInt; procedure TestOpMulSingle; procedure TestOpDiv; procedure TestOpDivInt; procedure TestOpNegate; procedure TestOpEquality; procedure TestOpNotEquals; {* procedure TestOpAnd; procedure TestOpAndInt; procedure TestOpOr; procedure TestOpOrInt; procedure TestOpXor; procedure TestOpXorInt; *} procedure TestDivideBy2; procedure TestAbs; procedure TestOpMin; procedure TestOpMinInt; procedure TestOpMax; procedure TestOpMaxInt; procedure TestOpClamp; procedure TestOpClampInt; procedure TestMulAdd; procedure TestMulDiv; procedure TestShuffle; procedure TestSwizzle; procedure TestCombine; procedure TestCombine2; procedure TestCombine3; procedure TestMinXYZComponent; procedure TestMaxXYZComponent; end; implementation procedure TVector4iComparatorTest.TestCompare; begin AssertTrue('Test Values do not match'+n4it1.ToString+' --> '+a4it1.ToString, Compare(n4it1,a4it1)); end; procedure TVector4iComparatorTest.TestCompareFalse; begin AssertFalse('Test Values do not match'+n4it1.ToString+' --> '+a4it2.ToString, Compare(n4it1,a4it2)); end; procedure TVector4iComparatorTest.TestOpAdd; begin n4it3 := n4it1 + n4it2; a4it3 := a4it1 + a4it2; AssertTrue('Vector4i: Op Add does not match'+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestOpAddInt; begin n4it3 := n4it1 + b2; a4it3 := a4it1 + b2; AssertTrue('Vector4i: Op Add Int does not match'+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestOpSub; begin n4it3 := n4it1 - n4it2; a4it3 := a4it1 - a4it2; AssertTrue('Vector4i: Op Sub does not match'+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestOpSubInt; begin n4it3 := n4it1 - b2; a4it3 := a4it1 - b2; AssertTrue('Vector4i: Op Sub Int does not match'+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestOpMul; begin n4it3 := n4it1 * n4it2; a4it3 := a4it1 * a4it2; AssertTrue('Vector4i: Op Mul does not match '+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestOpMulInt; begin n4it3 := n4it1 * b2; a4it3 := a4it1 * b2; AssertTrue('Vector4i: Op Mul Int does not match '+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestOpMulSingle; begin n4it3 := n4it1 * fs1; a4it3 := a4it1 * fs1; AssertTrue('Vector4i: Op Mul Single does not match'+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestOpDiv; begin n4it3 := n4it1 div n4it2; a4it3 := a4it1 div a4it2; AssertTrue('Vector4i: Op Div does not match '+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestOpDivInt; begin n4it3 := n4it1 div b2; a4it3 := a4it1 div b2; AssertTrue('Vector4i: Op Div Int does not match '+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestOpNegate; begin n4it3 := -n4it1; a4it3 := -a4it1; AssertTrue('Vector4i: Op negate does not match '+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestOpEquality; begin nb := n4it1 = n4it1; ab := a4it1 = a4it1; AssertTrue('Vector = does not match '+nb.ToString+' --> '+ab.ToString, (nb = ab)); nb := n4it1 = n4it2; ab := a4it1 = a4it2; AssertTrue('Vector = does not match '+nb.ToString+' --> '+ab.ToString, (nb = ab)); end; procedure TVector4iComparatorTest.TestOpNotEquals; begin nb := n4it1 <> n4it1; ab := a4it1 <> a4it1; AssertTrue('Vector <> does not match '+nb.ToString+' --> '+ab.ToString, (nb = ab)); nb := n4it1 <> n4it2; ab := a4it1 <> a4it2; AssertTrue('Vector <> doos not match '+nb.ToString+' --> '+ab.ToString, (nb = ab)); end; {* procedure TVector4iComparatorTest.TestOpAnd; begin n4it3 := n4it1 and n4it2; a4it3 := a4it1 and a4it2; AssertTrue('Vector4i: And does not match'+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestOpAndInt; begin n4it3 := n4it1 and b2; a4it3 := a4it1 and b2; AssertTrue('Vector4i: And Int does not match'+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestOpOr; begin n4it3 := n4it1 or n4it2; a4it3 := a4it1 or a4it2; AssertTrue('Vector4i: Or does not match'+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestOpOrInt; begin n4it3 := n4it1 or b2; a4it3 := a4it1 or b2; AssertTrue('Vector4i: Or Int does not match'+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestOpXor; begin n4it3 := n4it1 xor n4it2; a4it3 := a4it1 xor a4it2; AssertTrue('Vector4i: Xor does not match'+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestOpXorInt; begin n4it3 := n4it1 xor b2; a4it3 := a4it1 xor b2; AssertTrue('Vector4i: Xor Int does not match'+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; *} procedure TVector4iComparatorTest.TestDivideBy2; begin n4it3 := n4it1.DivideBy2; a4it3 := a4it1.DivideBy2; AssertTrue('Vector4i: DivideBy2 does not match'+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestAbs; begin n4it3 := n4it1.abs; a4it3 := a4it1.abs; AssertTrue('Vector4i: Abs does not match'+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestOpMin; begin n4it3 := n4it1.Min(n4it2); a4it3 := a4it1.Min(a4it2); AssertTrue('Vector4i: Min does not match'+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestOpMinInt; begin n4it3 := n4it1.Min(b2); a4it3 := a4it1.Min(b2); AssertTrue('Vector4i: Min Int does not match'+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestOpMax; begin n4it3 := n4it1.Max(n4it2); a4it3 := a4it1.Max(a4it2); AssertTrue('Vector4i: Max does not match'+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestOpMaxInt; begin n4it3 := n4it1.Max(b2); a4it3 := a4it1.Max(b2); AssertTrue('Vector4i: Max Int does not match'+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestOpClamp; begin n4it3 := n4it1.Clamp(n4it1,n4it2); a4it3 := a4it1.Clamp(a4it1,a4it2); AssertTrue('Vector4i: Clamp does not match'+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestOpClampInt; begin n4it3 := n4it1.Clamp(b2, b5); a4it3 := a4it1.Clamp(b2, b5); AssertTrue('Vector4i: Clamp Int does not match'+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestMulAdd; begin n4it3 := n4it1.MulAdd(n4it1,n4it2); a4it3 := a4it1.MulAdd(a4it1,a4it2); AssertTrue('Vector4i: MulAdd does not match'+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestMulDiv; begin n4it3 := n4it1.MulDiv(n4it1,n4it2); a4it3 := a4it1.MulDiv(a4it1,a4it2); AssertTrue('Vector4i: MulDiv does not match'+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestShuffle; begin n4it3 := n4it1.Shuffle(1,2,3,0); a4it3 := a4it1.Shuffle(1,2,3,0); AssertTrue('Vector4i: Shuffle no match'+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestSwizzle; begin n4it3 := n4it1.Swizzle(swWYXZ); a4it3 := a4it1.Swizzle(swWYXZ); AssertTrue('Vector4i: Swizzle no match'+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestCombine; begin n4it3 := n4it1.Combine(n4it1,fs1); a4it3 := a4it1.Combine(a4it1,fs1); AssertTrue('Vector4i: Combine does not match'+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestCombine2; begin n4it3 := n4it1.Combine2(n4it1,fs1,fs2); a4it3 := a4it1.Combine2(a4it1,fs1,fs2); AssertTrue('Vector4i: Combine2 does not match'+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3, a4it3)); end; procedure TVector4iComparatorTest.TestCombine3; begin n4it4 := n4it1.Swizzle(swAGRB); a4it4 := a4it1.Swizzle(swAGRB); n4it3 := n4it1.Combine3(n4it1,n4it4,fs1,fs2, fs2); a4it3 := a4it1.Combine3(a4it1,a4it4,fs1,fs2, fs2); AssertTrue('Vector4i: Combine2 does not match'+n4it3.ToString+' --> '+a4it3.ToString, Compare(n4it3,a4it3)); end; procedure TVector4iComparatorTest.TestMinXYZComponent; begin b4 := n4it1.MinXYZComponent; b8 := a4it1.MinXYZComponent; AssertEquals('Vector4i: MinXYZComponent no match', b4, b8); end; procedure TVector4iComparatorTest.TestMaxXYZComponent; begin b4 := n4it1.MaxXYZComponent; b8 := a4it1.MaxXYZComponent; AssertEquals('Vector4i: MaxXYZComponent no match', b4, b8); end; initialization RegisterTest(REPORT_GROUP_VECTOR4I, TVector4iComparatorTest); end.
{AUTEUR : FRANCKY23012301 - 2008 ------- Gratuit pour une utilisation non commerciale} unit DrumSet; interface uses Windows, Messages, SysUtils, Classes, Controls, Graphics, Dialogs; type TOnNote_Event = procedure(Sender: TObject; ANote: byte) of object; TOnSilence_Event = procedure(Sender: TObject) of object; TTouch = (Nothing, HitHat, BassDrum, FloorTom, Snare, RideCymbal, CrashCymbal, TomFirst, TomSecond); TDrum = record Key: char; Note: byte; end; TDrumSet = class(TCustomControl) private fHitHat: TDrum; fBassDrum: TDrum; fFloorTom: TDrum; fSnare: TDrum; fRideCymbal: TDrum; fCrashCymbal: TDrum; fTomFirst: TDrum; fTomSecond: TDrum; fSpace: char; fOnNoteEvent: TOnNote_Event; fOnSilenceEvent: TOnSilence_Event; fTouch: TTouch; procedure Draw_Circle(X, Y, Width, SizePen, Coeff: integer; PenColor, BrushColor: TColor); procedure Draw_Cymbale(X, Y, Width: integer); procedure Draw_HitHat(X, Y, Width: integer); procedure Draw_Tom(X, Y, Width: integer); procedure Draw_FoodPedal(X, Y, Width, Height: integer); procedure Draw_Seat(X, Y, Width: integer); procedure Draw_BassDrum(X, Y, Width: integer); procedure Draw_DownFixation(X, Y, DimCircle, YFix: integer); procedure Draw_UpFixation(X, Y, DimCircle, YFix: integer); protected procedure ReSize; Override; procedure Paint; Override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure KeyPress(var Key: char); override; procedure KeyDown(var Key: word; Shift: TShiftState); override; procedure KeyUp(var Key: word; Shift: TShiftState); override; published property Key_HitHat: char Read fHitHat.Key Write fHitHat.Key; property Key_BassDrum: char Read fBassDrum.Key Write fBassDrum.Key; property Key_FloorTom: char Read fFloorTom.Key Write fFloorTom.Key; property Key_Snare: char Read fSnare.Key Write fSnare.Key; property Key_RideCymbal: char Read fRideCymbal.Key Write fRideCymbal.Key; property Key_CrashCymbal: char Read fCrashCymbal.Key Write fCrashCymbal.Key; property Key_TomFirst: char Read fTomFirst.Key Write fTomFirst.Key; property Key_TomSecond: char Read fTomSecond.Key Write fTomSecond.Key; property Space: char Read fSpace Write fSpace; property Color; property OnNote_Event: TOnNote_Event Read fOnNoteEvent Write fOnNoteEvent; property OnSilence_Event: TOnSilence_Event Read fOnSilenceEvent Write fOnSilenceEvent; end; procedure Register; implementation procedure Register; begin RegisterComponents('Music_Pro', [TDrumSet]); end; constructor TDrumSet.Create(AOwner: TComponent); begin inherited; FOnNoteEvent := nil; FOnSilenceEvent := nil; fHitHat.Key := 'A'; fBassDrum.Key := 'B'; fFloorTom.Key := 'C'; fSnare.Key := 'D'; fRideCymbal.Key := 'E'; fCrashCymbal.Key := 'F'; fTomFirst.Key := 'G'; fTomSecond.Key := 'H'; fHitHat.Note := 42; fBassDrum.Note := 33; fFloorTom.Note := 41; fSnare.Note := 31; fRideCymbal.Note := 59; fCrashCymbal.Note := 49; fTomFirst.Note := 48; fTomSecond.Note := 47; fTouch := Nothing; doublebuffered := True; end; destructor TDrumSet.Destroy; begin inherited Destroy; end; procedure TDrumSet.Paint; var XTouch, YTouch, WidthTouch: cardinal; begin inherited; Draw_BassDrum(Width div 2, 1 * Height div 3, Width div 8); Draw_Cymbale(Width div 5, 1 * Height div 3, Width div 6); Draw_Cymbale(4 * Width div 5, 1 * Height div 3, Width div 6); Draw_HitHat(9 * Width div 10, 3 * Height div 4, Width div 6); Draw_Tom(4 * Width div 10, 1 * Height div 3, Width div 7); Draw_Tom(6 * Width div 10, 1 * Height div 3, Width div 7); Draw_Tom(3 * Width div 10, 3 * Height div 4, Width div 7); Draw_Tom(7 * Width div 10, 3 * Height div 4, Width div 6); Draw_FoodPedal(Width div 2, 3 * Height div 5, 5, 8); Draw_Seat(Width div 2, 6 * Height div 7, Width div 9); XTouch := 0; YTouch := 0; WidthTouch := Width div 10; case fTouch of HitHat: begin XTouch := 9 * Width div 10; YTouch := 3 * Height div 4; end; BassDrum: begin XTouch := Width div 2; YTouch := 1 * Height div 3; end; FloorTom: begin XTouch := 3 * Width div 10; YTouch := 3 * Height div 4; end; Snare: begin XTouch := 7 * Width div 10; YTouch := 3 * Height div 4; end; RideCymbal: begin XTouch := Width div 5; YTouch := Height div 3; end; CrashCymbal: begin XTouch := 4 * Width div 5; YTouch := Height div 3; end; TomFirst: begin XTouch := 4 * Width div 10; YTouch := 1 * Height div 3; end; TomSecond: begin XTouch := 6 * Width div 10; YTouch := 1 * Height div 3; end; end; if fTouch <> Nothing then Draw_Circle(XTouch, YTouch, WidthTouch, 1, 100, ClRed, ClRed); end; procedure TDrumSet.Draw_Circle(X, Y, Width, SizePen, Coeff: integer; PenColor, BrushColor: TColor); var Rect: TRect; begin Rect.Left := Round(X - (Width div 2) * (Coeff / 100)); Rect.Right := Round(X + (Width div 2) * (Coeff / 100)); Rect.Top := Round(Y + (Width div 2) * (Coeff / 100)); Rect.Bottom := Round(Y - (Width div 2) * (Coeff / 100)); with Canvas do begin Pen.Width := SizePen; Pen.Color := PenColor; Brush.Color := BrushColor; Ellipse(Rect); end; end; procedure TDrumSet.Draw_Cymbale(X, Y, Width: integer); begin Draw_Circle(X, Y, Width, 2, 100, ClBlack, $0033AEE3); Draw_Circle(X, Y, Width, 2, 90, ClBlack, $0064C1EA); Draw_Circle(X, Y, Width, 1, 80, ClBlack, $0001D8FE); Draw_Circle(X, Y, Width, 1, 50, ClBlack, $0001EBFE); Draw_Circle(X, Y, Width, 1, 25, ClBlack, $0002F0FD); Draw_Circle(X, Y, Width, 4, 5, ClBlack, ClBlack); end; procedure TDrumSet.Draw_HitHat(X, Y, Width: integer); begin Draw_Cymbale(Round(1.02 * X), Round(1.02 * Y), Width); Draw_Cymbale(X, Y, Width); end; procedure TDrumSet.Draw_Tom(X, Y, Width: integer); begin Draw_Circle(X, Y - Width div 2, Width, 2, 15, ClBlack, ClBlack); Draw_Circle(X, Y + Width div 2, Width, 2, 15, ClBlack, ClBlack); Draw_Circle(X - Width div 2, Y, Width, 2, 15, ClBlack, ClBlack); Draw_Circle(X + Width div 2, Y, Width, 2, 15, ClBlack, ClBlack); Draw_Circle(Round(X + 0.7 * Width / 2), Round(Y + 0.7 * Width / 2), Width, 2, 15, ClBlack, ClBlack); Draw_Circle(Round(X - 0.7 * Width / 2), Round(Y + 0.7 * Width / 2), Width, 2, 15, ClBlack, ClBlack); Draw_Circle(Round(X + 0.7 * Width / 2), Round(Y - 0.7 * Width / 2), Width, 2, 15, ClBlack, ClBlack); Draw_Circle(Round(X - 0.7 * Width / 2), Round(Y - 0.7 * Width / 2), Width, 2, 15, ClBlack, ClBlack); Draw_Circle(X, Y, Width, 2, 100, ClBlack, ClWhite); Draw_Circle(X, Y, Width, 2, 85, ClWhite, $00F2F2F2); end; procedure TDrumSet.Draw_FoodPedal(X, Y, Width, Height: integer); var Points: array[1..4] of TPoint; begin Points[1] := Point(X - Width, Y + Height); Points[2] := Point(Round(X - 1.4 * Width), Y - Height); Points[3] := Point(Round(X + 1.4 * Width), Y - Height); Points[4] := Point(X + Width, Y + Height); Canvas.Pen.Color := ClBlack; Canvas.Brush.Color := ClBlack; Canvas.Polygon(Points); end; procedure TDrumSet.Draw_Seat(X, Y, Width: integer); begin Draw_Circle(X, Y, Width, 2, 100, ClBlack, ClBlack); with Canvas do begin Pen.Width := 5; Pen.Color := ClWhite; Brush.Color := ClWhite; MoveTo(x, Y - Width div 3); LineTo(x, Y + Width div 3); MoveTo(X - Width div 3, Y); LineTo(X + Width div 3, y); end; end; procedure TDrumSet.Draw_BassDrum(X, Y, Width: integer); begin Draw_Circle(X, Y, Width, 2, 100, ClBlack, ClBlack); with Canvas do begin Pen.Width := 2; Pen.Color := ClBlack; Brush.Color := $00DADADA; Rectangle(X - Width div 2, Y + 3 * Width div 5, X + Width div 2, Y - 3 * Width div 5); Rectangle(X - Round(1.15 * Width / 2), Y + 3 * Width div 5, X - Width div 2, Y - 3 * Width div 5); Rectangle(X + Round(1.15 * Width / 2), Y + 3 * Width div 5, X + Width div 2, Y - 3 * Width div 5); Rectangle(X - Round(1.25 * Width / 2), Y + Round(2.5 * Width / 5), X - Round(1.15 * Width / 2), Y + Round(1.5 * Width / 5)); Rectangle(X + Round(1.25 * Width / 2), Y + Round(2.5 * Width / 5), X + Round(1.15 * Width / 2), Y + Round(1.5 * Width / 5)); Rectangle(X - Round(1.25 * Width / 2), Y - Round(2.5 * Width / 5), X - Round(1.15 * Width / 2), Y - Round(1.5 * Width / 5)); Rectangle(X + Round(1.25 * Width / 2), Y - Round(2.5 * Width / 5), X + Round(1.15 * Width / 2), Y - Round(1.5 * Width / 5)); MoveTo(X - Round(1.25 * Width / 2), Y - Round(2.5 * Width / 5)); LineTo(X + Round(1.25 * Width / 2) - Pen.Width, Y - Round(2.5 * Width / 5)); MoveTo(X - Round(1.25 * Width / 2), Y + Round(2.5 * Width / 5)); LineTo(X + Round(1.25 * Width / 2) - Pen.Width, Y + Round(2.5 * Width / 5)); Draw_DownFixation(X - Width div 7, Y + Round(1.5 * Width / 5), 7, Y + 3 * Width div 5); Draw_DownFixation(X - 2 * Width div 5, Y + Round(1.5 * Width / 5), 7, Y + 3 * Width div 5); Draw_DownFixation(X + Width div 7, Y + Round(1.5 * Width / 5), 7, Y + 3 * Width div 5); Draw_DownFixation(X + 2 * Width div 5, Y + Round(1.5 * Width / 5), 7, Y + 3 * Width div 5); Draw_UpFixation(X - Width div 7, Y - Round(1.5 * Width / 5), 7, Y - 3 * Width div 5); Draw_UpFixation(X - 2 * Width div 5, Y - Round(1.5 * Width / 5), 7, Y - 3 * Width div 5); Draw_UpFixation(X + Width div 7, Y - Round(1.5 * Width / 5), 7, Y - 3 * Width div 5); Draw_UpFixation(X + 2 * Width div 5, Y - Round(1.5 * Width / 5), 7, Y - 3 * Width div 5); end; end; procedure TDrumSet.Draw_DownFixation(X, Y, DimCircle, YFix: integer); begin Draw_Circle(X, Y, DimCircle, 1, 100, ClBlack, $00DADADA); with Canvas do begin MoveTo(X, Y + DimCircle div 2); LineTo(Round(0.995 * X), YFix); MoveTo(X, Y + DimCircle div 2); LineTo(X, YFix); MoveTo(X, Y + DimCircle div 2); LineTo(Round(1.005 * X), YFix); end; end; procedure TDrumSet.Draw_UpFixation(X, Y, DimCircle, YFix: integer); begin Draw_Circle(X, Y, DimCircle, 1, 100, ClBlack, $00DADADA); with Canvas do begin MoveTo(X, Y - DimCircle div 2); LineTo(Round(0.995 * X), YFix); MoveTo(X, Y - DimCircle div 2); LineTo(X, YFix); MoveTo(X, Y - DimCircle div 2); LineTo(Round(1.005 * X), YFix); end; end; procedure TDrumSet.ReSize; begin InHerited; Width := 537; Height := 201; end; procedure TDrumSet.KeyPress(var Key: char); begin inherited KeyPress(Key); if (Key = fSpace) then fOnSilenceEvent(Self); if (Key = Self.fHitHat.Key) and (Assigned(fOnNoteEvent)) then fOnNoteEvent(Self, fHitHat.Note); if (Key = fBassDrum.Key) and (Assigned(fOnNoteEvent)) then fOnNoteEvent(Self, fBassDrum.Note); if (Key = fFloorTom.Key) and (Assigned(fOnNoteEvent)) then fOnNoteEvent(Self, fFloorTom.Note); if (Key = fSnare.Key) and (Assigned(fOnNoteEvent)) then fOnNoteEvent(Self, fSnare.Note); if (Key = fRideCymbal.Key) and (Assigned(fOnNoteEvent)) then fOnNoteEvent(Self, fRideCymbal.Note); if (Key = fCrashCymbal.Key) and (Assigned(fOnNoteEvent)) then fOnNoteEvent(Self, fCrashCymbal.Note); if (Key = fTomFirst.Key) and (Assigned(fOnNoteEvent)) then fOnNoteEvent(Self, fTomFirst.Note); if (Key = fTomSecond.Key) and (Assigned(fOnNoteEvent)) then fOnNoteEvent(Self, fTomSecond.Note); end; procedure TDrumSet.KeyDown(var Key: word; Shift: TShiftState); begin inherited; fTouch := Nothing; if char(Key) = fHitHat.Key then fTouch := HitHat; if char(Key) = fBassDrum.Key then fTouch := BassDrum; if char(Key) = fFloorTom.Key then fTouch := FloorTom; if char(Key) = fSnare.Key then fTouch := Snare; if char(Key) = fRideCymbal.Key then fTouch := RideCymbal; if char(Key) = fCrashCymbal.Key then fTouch := CrashCymbal; if char(Key) = fTomFirst.Key then fTouch := TomFirst; if char(Key) = fTomSecond.Key then fTouch := TomSecond; Invalidate; end; procedure TDrumSet.KeyUp(var Key: word; Shift: TShiftState); begin inherited; fTouch := Nothing; Invalidate; end; end.
unit MD.Cards; interface uses System.SysUtils, System.Classes, FMX.Types, MD.ColorPalette, FMX.Controls, FMX.Graphics, System.Types; type TMDCard = class(TControl) private { Private declarations } FMaterialColor: TMaterialColor; FFill: TBrush; function GetFill: TBrush; procedure SetFill(const Value: TBrush); function GetMaterialColor: TMaterialColor; virtual; procedure SetMaterialColor(const Value: TMaterialColor); virtual; protected { Protected declarations } property Fill: TBrush read GetFill write SetFill; property CanFocus default False; procedure Paint; override; procedure FillChanged(Sender: TObject); virtual; public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; published { Published declarations } property Align; property Anchors; property ClipParent; property Cursor; property DragMode; property EnableDragHighlight; property Enabled; property Locked; property Height; property HitTest default True; property Padding; property Opacity; property Margins; property PopupMenu; property Position; property RotationAngle; property RotationCenter; property Scale; property Size; property TouchTargetExpansion; property Visible; property Width; property MaterialColor: TMaterialColor read GetMaterialColor write SetMaterialColor; { Events } property OnPainting; property OnPaint; property OnResize; { Drag and Drop events } property OnDragEnter; property OnDragLeave; property OnDragOver; property OnDragDrop; property OnDragEnd; { Mouse events } property OnClick; property OnDblClick; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnMouseWheel; property OnMouseEnter; property OnMouseLeave; end; implementation { TMDCard } constructor TMDCard.Create(AOwner: TComponent); begin inherited; Self.ClipChildren := True; Self.Height := 400; Self.Width := 350; Self.CanFocus := False; Self.TabStop := False; Self.HitTest := False; FMaterialColor := TMaterialColors.White; FFill := TBrush.Create(TBrushKind.Solid, FMaterialColor); FFill.OnChanged := FillChanged; end; destructor TMDCard.Destroy; begin FreeAndNil(FFill); inherited; end; procedure TMDCard.FillChanged(Sender: TObject); begin Repaint; end; function TMDCard.GetFill: TBrush; begin Result := FFill; end; function TMDCard.GetMaterialColor: TMaterialColor; begin Result := FMaterialColor; end; procedure TMDCard.Paint; begin inherited; Canvas.BeginScene; Canvas.FillRect(TRectF.Create(0, 0, Self.Width, Self.Height), 5, 5, [TCorner.TopLeft, TCorner.TopRight, TCorner.BottomLeft, TCorner.BottomRight], AbsoluteOpacity, FFill, TCornerType.Round); Canvas.EndScene; end; procedure TMDCard.SetFill(const Value: TBrush); begin FFill.Assign(Value); end; procedure TMDCard.SetMaterialColor(const Value: TMaterialColor); begin FMaterialColor := Value; if Assigned(FFill) then FFill.Color := FMaterialColor; end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [NOTA_FISCAL_DETALHE] The MIT License Copyright: Copyright (C) 2014 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit NotaFiscalDetalheVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, DB, SysUtils, EcfProdutoVO; type [TEntity] [TTable('ECF_NOTA_FISCAL_DETALHE')] TNotaFiscalDetalheVO = class(TVO) private FID: Integer; FID_NF_CABECALHO: Integer; FID_PRODUTO: Integer; FCFOP: Integer; FITEM: Integer; FQUANTIDADE: Extended; FVALOR_UNITARIO: Extended; FVALOR_TOTAL: Extended; FBASE_ICMS: Extended; FTAXA_ICMS: Extended; FICMS: Extended; FICMS_OUTRAS: Extended; FICMS_ISENTO: Extended; FTAXA_DESCONTO: Extended; FDESCONTO: Extended; FTAXA_ISSQN: Extended; FISSQN: Extended; FTAXA_PIS: Extended; FPIS: Extended; FTAXA_COFINS: Extended; FCOFINS: Extended; FTAXA_ACRESCIMO: Extended; FACRESCIMO: Extended; FTAXA_IPI: Extended; FIPI: Extended; FCANCELADO: String; FCST: String; FMOVIMENTA_ESTOQUE: String; FECF_ICMS_ST: String; FNOME_CAIXA: String; FID_GERADO_CAIXA: Integer; FDATA_SINCRONIZACAO: TDateTime; FHORA_SINCRONIZACAO: String; FEcfProdutoVO: TEcfProdutoVO; FProdutoGtin: String; FProdutoDescricaoPdv: String; public constructor Create; override; destructor Destroy; override; [TId('ID')] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_NF_CABECALHO', 'Id Nf Cabecalho', 80, [], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdNfCabecalho: Integer read FID_NF_CABECALHO write FID_NF_CABECALHO; [TColumn('ID_PRODUTO', 'Id Produto', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdProduto: Integer read FID_PRODUTO write FID_PRODUTO; [TColumnDisplay('PRODUTO.GTIN', 'Gtin', 150, [ldGrid, ldLookup], ftString, 'EcfProdutoVO.TEcfProdutoVO', True)] property ProdutoGtin: String read FProdutoGtin write FProdutoGtin; [TColumnDisplay('PRODUTO.DESCRICAO_PDV', 'Descrição PDV', 150, [ldGrid, ldLookup], ftString, 'EcfProdutoVO.TEcfProdutoVO', True)] property ProdutoDescricaoPdv: String read FProdutoDescricaoPdv write FProdutoDescricaoPdv; [TColumn('CFOP', 'Cfop', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property Cfop: Integer read FCFOP write FCFOP; [TColumn('ITEM', 'Item', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property Item: Integer read FITEM write FITEM; [TColumn('QUANTIDADE', 'Quantidade', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property Quantidade: Extended read FQUANTIDADE write FQUANTIDADE; [TColumn('VALOR_UNITARIO', 'Valor Unitario', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorUnitario: Extended read FVALOR_UNITARIO write FVALOR_UNITARIO; [TColumn('VALOR_TOTAL', 'Valor Total', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property ValorTotal: Extended read FVALOR_TOTAL write FVALOR_TOTAL; [TColumn('BASE_ICMS', 'Base Icms', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property BaseIcms: Extended read FBASE_ICMS write FBASE_ICMS; [TColumn('TAXA_ICMS', 'Taxa Icms', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TaxaIcms: Extended read FTAXA_ICMS write FTAXA_ICMS; [TColumn('ICMS', 'Icms', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property Icms: Extended read FICMS write FICMS; [TColumn('ICMS_OUTRAS', 'Icms Outras', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property IcmsOutras: Extended read FICMS_OUTRAS write FICMS_OUTRAS; [TColumn('ICMS_ISENTO', 'Icms Isento', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property IcmsIsento: Extended read FICMS_ISENTO write FICMS_ISENTO; [TColumn('TAXA_DESCONTO', 'Taxa Desconto', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TaxaDesconto: Extended read FTAXA_DESCONTO write FTAXA_DESCONTO; [TColumn('DESCONTO', 'Desconto', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property Desconto: Extended read FDESCONTO write FDESCONTO; [TColumn('TAXA_ISSQN', 'Taxa Issqn', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TaxaIssqn: Extended read FTAXA_ISSQN write FTAXA_ISSQN; [TColumn('ISSQN', 'Issqn', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property Issqn: Extended read FISSQN write FISSQN; [TColumn('TAXA_PIS', 'Taxa Pis', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TaxaPis: Extended read FTAXA_PIS write FTAXA_PIS; [TColumn('PIS', 'Pis', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property Pis: Extended read FPIS write FPIS; [TColumn('TAXA_COFINS', 'Taxa Cofins', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TaxaCofins: Extended read FTAXA_COFINS write FTAXA_COFINS; [TColumn('COFINS', 'Cofins', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property Cofins: Extended read FCOFINS write FCOFINS; [TColumn('TAXA_ACRESCIMO', 'Taxa Acrescimo', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TaxaAcrescimo: Extended read FTAXA_ACRESCIMO write FTAXA_ACRESCIMO; [TColumn('ACRESCIMO', 'Acrescimo', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property Acrescimo: Extended read FACRESCIMO write FACRESCIMO; [TColumn('TAXA_IPI', 'Taxa Ipi', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property TaxaIpi: Extended read FTAXA_IPI write FTAXA_IPI; [TColumn('IPI', 'Ipi', 128, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftFloatComSeparador, taRightJustify)] property Ipi: Extended read FIPI write FIPI; [TColumn('CANCELADO', 'Cancelado', 8, [ldGrid, ldLookup, ldCombobox], False)] property Cancelado: String read FCANCELADO write FCANCELADO; [TColumn('CST', 'Cst', 24, [ldGrid, ldLookup, ldCombobox], False)] property Cst: String read FCST write FCST; [TColumn('MOVIMENTA_ESTOQUE', 'Movimenta Estoque', 8, [ldGrid, ldLookup, ldCombobox], False)] property MovimentaEstoque: String read FMOVIMENTA_ESTOQUE write FMOVIMENTA_ESTOQUE; [TColumn('ECF_ICMS_ST', 'Ecf Icms St', 32, [ldGrid, ldLookup, ldCombobox], False)] property EcfIcmsSt: String read FECF_ICMS_ST write FECF_ICMS_ST; [TColumn('NOME_CAIXA', 'Nome Caixa', 64, [ldGrid, ldLookup, ldCombobox], False)] property NomeCaixa: String read FNOME_CAIXA write FNOME_CAIXA; [TColumn('ID_GERADO_CAIXA', 'Id Gerado Caixa', 80, [ldGrid, ldLookup, ldCombobox], False)] property IdGeradoCaixa: Integer read FID_GERADO_CAIXA write FID_GERADO_CAIXA; [TColumn('DATA_SINCRONIZACAO', 'Data Sinronizacao', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataSincronizacao: TDateTime read FDATA_SINCRONIZACAO write FDATA_SINCRONIZACAO; [TColumn('HORA_SINCRONIZACAO', 'Hora Sincronizacao', 64, [ldGrid, ldLookup, ldCombobox], False)] property HoraSincronizacao: String read FHORA_SINCRONIZACAO write FHORA_SINCRONIZACAO; [TAssociation('ID', 'ID_PRODUTO')] property EcfProdutoVO: TEcfProdutoVO read FEcfProdutoVO write FEcfProdutoVO; end; implementation constructor TNotaFiscalDetalheVO.Create; begin inherited; FEcfProdutoVO := TEcfProdutoVO.Create; end; destructor TNotaFiscalDetalheVO.Destroy; begin FreeAndNil(FEcfProdutoVO); inherited; end; initialization Classes.RegisterClass(TNotaFiscalDetalheVO); finalization Classes.UnRegisterClass(TNotaFiscalDetalheVO); end.
// ---------------------------------------------------------------------------- // Unit : PxBOOTPServer.pas - a part of PxLib // Author : Matthias Hryniszak // Date : 2005-03-30 // Version : 1.0 // Description : A BOOTP server for use with microcontrollers. // Default client port is 68 and default server port is 67. To // change the default values create a file bootp.conf and in // section [General] set ClientPort and ServerPort values. // In section [Hosts] host configuration can be stored. Every // host configuration is described in form // MAC_ADDRESS=IP|NETMASK|DEFAULT_GW // where // MAC_ADDRESS - MAC address (hardware address) // IP - IP address // NETMASK - Netmask // DEFAULT_GW - Default gateway // To provide additional/different configuration kinds simply // override the GetClientInfo() protected method and return true // if the request has been successfully processed. If you call the // inherited method you can use the build-in system to retrieve // client configuration. // Changes log : 2005-03-30 - initial version // ToDo : Testing. // ---------------------------------------------------------------------------- unit PxBOOTPServer; {$I PxDefines.inc} interface uses Windows, Classes, SysUtils, IniFiles, Winsock, PxBase, PxLog, PxThread; const DEFAULT_SERVER_PORT = 67; // server responds to this port with replies DEFAULT_CLIENT_PORT = 68; // client sends to this port requests type UINT8 = Byte; UINT16 = Word; UINT32 = Cardinal; TPxBOOTPEntry = class (TObject) private FMAC: String; FIP: String; FNetmask: String; FGateway: String; public constructor Create(AMAC, AIP, ANetmask, AGateway: String); class function ParseConfigParams(Config: String; var IP, Netmask, Gateway: String): Boolean; property MAC: String read FMAC; property IP : String read FIP; property Netmask: String read FNetmask; property Gateway: String read FGateway; end; TPxBOOTPEntries = class (TList) private function GetItem(Index: Integer): TPxBOOTPEntry; public constructor Create; property Items[Index: Integer]: TPxBOOTPEntry read GetItem; default; end; TPxBOOTPServer = class (TPxThread) private FServerPort: Word; FClientPort: Word; FServerSocket: TSocket; FClientSocket: TSocket; FEntries: TPxBOOTPEntries; protected function GetClientInfo(MAC: String; var IP, Netmask, Gateway: String): Boolean; virtual; procedure Execute; override; public constructor Create; destructor Destroy; override; procedure Terminate; property ServerPort: Word read FServerPort write FServerPort; property ClientPort: Word read FClientPort write FClientPort; property Entries: TPxBOOTPEntries read FEntries; end; function GetLocalIPAddress: LongWord; implementation const BOOTP_REQUEST = 1; BOOTP_REPLY = 2; BOOTP_RESET = 255; BOOTP_HTYPE_ETHERNET = 1; BOOTP_HWLEN_ETHERNET = 6; BOOTP_OPTION_SUBNETMASK = 1; BOOTP_OPTION_DEFGW = 3; BOOTP_OPTION_CLIENT = 5; function GetLocalIPAddress: LongWord; function LookupHostAddr(const hn: string): String; var h: PHostEnt; begin Result := ''; if hn <> '' then begin if hn[1] in ['0'..'9'] then begin if inet_addr(pchar(hn)) <> INADDR_NONE then Result := hn; end else begin h := gethostbyname(PChar(hn)); if h <> nil then with h^ do Result := Format('%d.%d.%d.%d', [Ord(h_addr^[0]), Ord(h_addr^[1]), Ord(h_addr^[2]), Ord(h_addr^[3])]); end; end else Result := '0.0.0.0'; end; function LocalHostName: String; var Name: array[0..255] of Char; begin Result := ''; if gethostname(name, SizeOf(name)) = 0 then Result := Name; end; begin Result := inet_addr(PChar(LookupHostAddr(LocalHostName))); end; type // taken from rfc951.txt; r - retrived only, w - sent only, x - retrived and sent TBOOTPData = packed record // awaited: BOOTP_REPLY {x} op : UINT8; // packet op code / message type. // 1 = BOOTREQUEST, 2 = BOOTREPLY // awaited: BOOTP_HTYPE_ETHERNET {x} htype : UINT8; // hardware address type, see ARP section in "Assigned Numbers" RFC. // '1' = 10mb ethernet // awaited: BOOTP_HWLEN_ETHERNET {x} hlen : UINT8; // hardware address length (eg '6' for 10mb ethernet). // skipped {w} hops : UINT8; // client sets to zero, optionally used by gateways in cross-gateway booting. // awaited: $CA0332F1 {x} xid : UINT32; // transaction ID, a random number, used to match this boot request with the responses it generates. // skipped {w} secs : UINT16; // filled in by client, seconds elapsed since client started trying to boot. // skipped unused : UINT16; // unused // skipped ciaddr : UINT32; // client IP address; filled in by client in bootrequest if known. // awaited: IP ADDRESS {r} yiaddr : UINT32; // 'your' (client) IP address; filled by server if client doesn't know its own address (ciaddr was 0). // skipped siaddr : UINT32; // server IP address; returned in bootreply by server. // skipped giaddr : UINT32; // gateway IP address, used in optional cross-gateway booting. // awaited: Hardware address - do not change and it will be OK ! {x} chaddr : array[0..15] of UINT8; // client hardware address, filled in by client. // skipped sname : array[0..63] of UINT8; // optional server host name, null terminated string. // skipped filename: array[0..127] of UINT8; // boot file name, null terminated string; 'generic' name or null in bootrequest, // fully qualified directory-path name in bootreply. case Integer of 0: ( vend: array[0..63] of UINT8; // optional vendor-specific area, e.g. could be hardware type/serial on request, or 'capability' / remote ); // file system handle on reply. This info may be set aside for use by a third phase bootstrap or kernel. 1: ( {r} subnet: packed record op : UINT8; // BOOTP_OPTION_SUBNETMASK (1) size : UINT8; // 4 snmask: UINT32; // subnet mask end; {r} gateway: packed record op : UINT8; // BOOTP_OPTION_DEFGW (3) size : UINT8; // 4 gw : UINT32; // default gateway end; {r} client: packed record op : UINT8; // BOOTP_OPTION_CLIENT (3) size : UINT8; // 4 gw : UINT32; // default client to send data to end; ); end; { TPxBOOTPEntry } constructor TPxBOOTPEntry.Create(AMAC, AIP, ANetmask, AGateway: String); begin inherited Create; FMAC := AMAC; FIP := AIP; FNetmask := ANetmask; FGateway := AGateway; if (MAC = '') or (IP = '') or (Netmask = '') or (Gateway = '') then Fail; end; class function TPxBOOTPEntry.ParseConfigParams(Config: String; var IP, Netmask, Gateway: String): Boolean; var P: Integer; begin Result := True; P := Pos('|', Config); if P <> 0 then begin IP := Copy(Config, 1, P - 1); Delete(Config, 1, P); end else Result := False; P := Pos('|', Config); if P <> 0 then begin Netmask := Copy(Config, 1, P - 1); Delete(Config, 1, P); end else Result := False; if Config <> '' then Gateway := Config else Result := False; end; { TPxBOOTPEntries } { Private declarations } function TPxBOOTPEntries.GetItem(Index: Integer): TPxBOOTPEntry; begin Result := TObject(Get(Index)) as TPxBOOTPEntry; end; { Public declarations } constructor TPxBOOTPEntries.Create; var I: Integer; IniFile: TIniFile; Entries: TStrings; Entry: TPxBOOTPEntry; IP, Netmask, Gateway: String; begin inherited Create; Entries := TStringList.Create; try IniFile := TIniFile.Create(ChangeFileExt(ParamStr(0), '.conf')); try IniFile.ReadSection('hosts', Entries); for I := 0 to Entries.Count - 1 do if TPxBOOTPEntry.ParseConfigParams(IniFile.ReadString('hosts', Entries[I], ''), IP, Netmask, Gateway) then begin Entry := TPxBOOTPEntry.Create(Entries[I], IP, Netmask, Gateway); if Assigned(Entry) then Add(Entry); end; finally IniFile.Free; end; finally Entries.Free; end; end; { TPxBOOTPServer } { Private declarations } { Protected declarations } function GetThisServerIP: String; function LookupHostAddr(const hn: string): String; var h: PHostEnt; begin Result := ''; if hn <> '' then begin if hn[1] in ['0'..'9'] then begin if inet_addr(pchar(hn)) <> INADDR_NONE then Result := hn; end else begin h := gethostbyname(pchar(hn)); if h <> nil then Result := format('%d.%d.%d.%d', [ord(h^.h_addr^[0]), ord(h^.h_addr^[1]), ord(h^.h_addr^[2]), ord(h^.h_addr^[3])]); end; end else Result := '0.0.0.0'; end; function LocalHostName: String; var name: array[0..255] of char; begin Result := ''; if gethostname(name, sizeof(name)) = 0 then Result := name; end; function LocalHostAddr: String; begin Result := LookupHostAddr(LocalHostName); end; begin Result := LocalHostAddr; end; function GetMACAddressFromBOOTPPacket(bootp_packet: TBOOTPData): String; begin Result := Format('%.2X:%.2X:%.2X:%.2X:%.2X:%.2X', [ bootp_packet.chaddr[0], bootp_packet.chaddr[1], bootp_packet.chaddr[2], bootp_packet.chaddr[3], bootp_packet.chaddr[4], bootp_packet.chaddr[5] ]); end; function TPxBOOTPServer.GetClientInfo(MAC: String; var IP, Netmask, Gateway: String): Boolean; var I: Integer; Entry: TPxBOOTPEntry; begin Entry := nil; for I := 0 to Entries.Count - 1 do begin Entry := Entries[I]; if Entry.MAC = MAC then Break else Entry := nil; end; if Assigned(Entry) then begin IP := Entry.IP; Netmask := Entry.IP; Gateway := Entry.IP; Result := IP <> ''; end else Result := False; end; procedure TPxBOOTPServer.Execute; var Addr: sockaddr_in; AddrLen, Count: Integer; FDRead: TFDSet; Time: TTimeVal; bootp_packet: TBOOTPData; LogMessage: String; ClientMAC, ClientIP, ClientNetmask, ClientGateway: String; begin Log('BOOTP server started successfully'); while not Terminated do begin AddrLen := SizeOf(Addr); FD_ZERO(FDRead); FD_SET(FServerSocket, FDRead); Time.tv_sec := 1; Time.tv_usec := 1000; case Select(0, @FDRead, nil, nil, @Time) of 1: begin FillChar(Addr, SizeOf(Addr), 0); Count := recvfrom(FServerSocket, bootp_packet, SizeOf(bootp_packet), 0, Addr, AddrLen); if Count > 0 then begin ClientMAC := GetMACAddressFromBOOTPPacket(bootp_packet); LogMessage := 'Received BOOTP request from ' + ClientMAC + '...'; if GetClientInfo(ClientMAC, ClientIP, ClientNetmask, ClientGateway) then begin LogMessage := LogMessage + 'Responding with IP=' + ClientIP + '...'; bootp_packet.op := BOOTP_REPLY; bootp_packet.yiaddr := inet_addr(PChar(ClientIP)); bootp_packet.subnet.op := BOOTP_OPTION_SUBNETMASK; bootp_packet.subnet.size := 4; bootp_packet.subnet.snmask := inet_addr(PChar(ClientNetmask)); bootp_packet.gateway.op := BOOTP_OPTION_DEFGW; bootp_packet.gateway.size := 4; bootp_packet.gateway.gw := inet_addr(PChar(ClientGateway)); bootp_packet.client.op := BOOTP_OPTION_CLIENT; bootp_packet.client.size := 4; bootp_packet.client.gw := GetLocalIPAddress; Addr.sin_addr.S_addr := INADDR_BROADCAST; sendto(FClientSocket, bootp_packet, SizeOf(bootp_packet), 0, Addr, AddrLen); LogMessage := LogMessage + 'OK'; end else LogMessage := LogMessage + 'Host not configured'; Log(LogMessage); end; end; end; Sleep(100); end; Log('BOOTP server terminated.'); end; { Public declarations } constructor TPxBOOTPServer.Create; var Addr: sockaddr_in; Opt : BOOL; ConfigFile: TIniFile; begin inherited Create(True); Log('BOOTP server is starting...'); FEntries := TPxBOOTPEntries.Create; ConfigFile := TIniFile.Create(ChangeFileExt(ParamStr(0), '.conf')); FServerPort := ConfigFile.ReadInteger('General', 'ServerPort', DEFAULT_SERVER_PORT); FClientPort := ConfigFile.ReadInteger('General', 'ClientPort', DEFAULT_CLIENT_PORT); ConfigFile.Free; // server socket FServerSocket := socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); if FServerSocket = INVALID_SOCKET then begin Log('Error creating server socket for BOOTP server.'); Fail; end; // bind the server socket so that it can receive packets on a specified port Addr.sin_family := AF_INET; Addr.sin_port := htons(ServerPort); Addr.sin_addr.S_addr := INADDR_ANY; if bind(FServerSocket, Addr, SizeOf(Addr)) = SOCKET_ERROR then begin Log('Error binding server socket for BOOTP server (another instance already running ?).'); Fail; end; // set the SOL_SOCKET -> SO_BROADCAST option to TRUE so that the socket can send/receive broadcast messages // client socket FClientSocket := socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); if FClientSocket = INVALID_SOCKET then begin Log('Error creating client socket for BOOTP server.'); Fail; end; // bind the server socket so that it can receive packets on a specified port Addr.sin_family := AF_INET; Addr.sin_port := htons(ClientPort); Addr.sin_addr.S_addr := INADDR_ANY; if bind(FClientSocket, Addr, SizeOf(Addr)) = SOCKET_ERROR then begin Log('Error binding client socket for BOOTP server (another instance already running ?).'); Fail; end; // set the SOL_SOCKET -> SO_BROADCAST option to TRUE so that the socket can send/receive broadcast messages Opt := True; if setsockopt(FClientSocket, SOL_SOCKET, SO_BROADCAST, @Opt, SizeOf(Opt)) = SOCKET_ERROR then begin Log('Error setting SO_BROADCAST flag for BOOTP client socket.'); Fail; end; Resume; end; destructor TPxBOOTPServer.Destroy; begin inherited Destroy; end; procedure TPxBOOTPServer.Terminate; begin inherited Terminate; // close socket (implies an error on server socket, but that is OK !) closesocket(FServerSocket); end; { *** } procedure Initialize; var WSAData: TWSAData; begin WSAStartup($202, WSAData); end; procedure Finalize; begin WSACleanup; end; initialization Initialize; finalization Finalize; end.
unit PingU; interface uses Windows, WinSock2, SysUtils, PingAPIU; function Ping(const Host: string; out ResultLine: String): Integer; implementation {$REGION 'Host + IP to Internal representation'} type TIPFormat = (UNSPEC, IPv4, IPv6); TLookupResult = record Format: TIPFormat; HumanReadable: string; addr4: sockaddr_in; addr6: sockaddr_in6; end; function LookupIP(const Hostname: String): TLookupResult; var Hints: ADDRINFOW; addrinfo: PAddrInfoW; begin // Lowest amount of hints possible... ZeroMemory(@Hints, sizeof(Hints)); Hints.ai_family := AF_UNSPEC; Hints.ai_socktype := 0; Hints.ai_protocol := IPPROTO_IP; Hints.ai_flags := 0; if (GetAddrInfoW(PChar(Hostname), nil, @Hints, addrinfo) <> 0) then begin RaiseLastOSError(); Exit; end; // Default format Result.Format := UNSPEC; // Only take the first one case addrinfo.ai_family of AF_UNSPEC: begin Result.Format := UNSPEC; end; AF_INET: begin Result.Format := IPv4; Result.HumanReadable := GetHumanAddress(PSockAddr(addrinfo.ai_addr), addrinfo.ai_addrlen); Result.addr4 := PSockAddrIn(addrinfo.ai_addr)^; end; AF_INET6: begin Result.Format := IPv6; Result.HumanReadable := GetHumanAddress(PSockAddr(addrinfo.ai_addr), addrinfo.ai_addrlen); Result.addr6 := PSockAddrIn6(addrinfo.ai_addr)^; end; end; // Clean up FreeAddrInfoW(addrinfo); end; {$ENDREGION} {$REGION 'Error Messages' } const IP_STATUS_BASE = 11000; IP_SUCCESS = 0; IP_BUF_TOO_SMALL = IP_STATUS_BASE + 1; IP_DEST_NET_UNREACHABLE = IP_STATUS_BASE + 2; IP_DEST_HOST_UNREACHABLE = IP_STATUS_BASE + 3; IP_DEST_PROT_UNREACHABLE = IP_STATUS_BASE + 4; IP_DEST_PORT_UNREACHABLE = IP_STATUS_BASE + 5; IP_NO_RESOURCES = IP_STATUS_BASE + 6; IP_BAD_OPTION = IP_STATUS_BASE + 7; IP_HW_ERROR = IP_STATUS_BASE + 8; IP_PACKET_TOO_BIG = IP_STATUS_BASE + 9; IP_REQ_TIMED_OUT = IP_STATUS_BASE + 10; IP_BAD_REQ = IP_STATUS_BASE + 11; IP_BAD_ROUTE = IP_STATUS_BASE + 12; IP_TTL_EXPIRED_TRANSIT = IP_STATUS_BASE + 13; IP_TTL_EXPIRED_REASSEM = IP_STATUS_BASE + 14; IP_PARAM_PROBLEM = IP_STATUS_BASE + 15; IP_SOURCE_QUENCH = IP_STATUS_BASE + 16; IP_OPTION_TOO_BIG = IP_STATUS_BASE + 17; IP_BAD_DESTINATION = IP_STATUS_BASE + 18; IP_GENERAL_FAILURE = IP_STATUS_BASE + 50; function ErrorToText(const ErrorCode: Integer): String; begin case ErrorCode of IP_BUF_TOO_SMALL: Result := 'IP_BUF_TOO_SMALL'; IP_DEST_NET_UNREACHABLE: Result := 'IP_DEST_NET_UNREACHABLE'; IP_DEST_HOST_UNREACHABLE: Result := 'IP_DEST_HOST_UNREACHABLE'; IP_DEST_PROT_UNREACHABLE: Result := 'IP_DEST_PROT_UNREACHABLE'; IP_DEST_PORT_UNREACHABLE: Result := 'IP_DEST_PORT_UNREACHABLE'; IP_NO_RESOURCES: Result := 'IP_NO_RESOURCES'; IP_BAD_OPTION: Result := 'IP_BAD_OPTION'; IP_HW_ERROR: Result := 'IP_HW_ERROR'; IP_PACKET_TOO_BIG: Result := 'IP_PACKET_TOO_BIG'; IP_REQ_TIMED_OUT: Result := 'IP_REQ_TIMED_OUT'; IP_BAD_REQ: Result := 'IP_BAD_REQ'; IP_BAD_ROUTE: Result := 'IP_BAD_ROUTE'; IP_TTL_EXPIRED_TRANSIT: Result := 'IP_TTL_EXPIRED_TRANSIT'; IP_TTL_EXPIRED_REASSEM: Result := 'IP_TTL_EXPIRED_REASSEM'; IP_PARAM_PROBLEM: Result := 'IP_PARAM_PROBLEM'; IP_SOURCE_QUENCH: Result := 'IP_SOURCE_QUENCH'; IP_OPTION_TOO_BIG: Result := 'IP_OPTION_TOO_BIG'; IP_BAD_DESTINATION: Result := 'IP_BAD_DESTINATION'; IP_GENERAL_FAILURE: Result := 'IP_GENERAL_FAILURE'; else Result := 'Unknown Error'; end; end; {$ENDREGION} /// <summary> /// Performs a ICMP Echo Request /// </summary> function PingV4(const ip: in_addr; const HumanReadable: String; out ResultLine: String): Integer; var ICMPFile: THandle; SendData: array [0 .. 31] of AnsiChar; ReplyBuffer: PICMP_ECHO_REPLY; ReplySize: DWORD; NumResponses: DWORD; begin Result := 3; SendData := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; ICMPFile := IcmpCreateFile; if ICMPFile <> INVALID_HANDLE_VALUE then try ReplySize := sizeof(ICMP_ECHO_REPLY) + sizeof(SendData); GetMem(ReplyBuffer, ReplySize); try NumResponses := IcmpSendEcho(ICMPFile, ip, @SendData, sizeof(SendData), nil, ReplyBuffer, ReplySize, 1000); if (NumResponses <> 0) then begin ResultLine := 'Received Response from ' + HumanReadable + ' in ' + IntToStr(ReplyBuffer.RoundTripTime) + ' ms'; Result := 0; end else begin ResultLine := 'Error: ' + ErrorToText(GetLastError()); Result := 1; end; finally FreeMem(ReplyBuffer); end; finally IcmpCloseHandle(ICMPFile); end else begin RaiseLastOSError(); end; end; /// <summary> /// Performs a ICMP6 Echo Request /// </summary> function PingV6(ip: sockaddr_in6; const HumanReadable: String; out ResultLine: String): Integer; var ICMPFile: THandle; SourceAddress: sockaddr_in6; SendData: array [0 .. 31] of AnsiChar; ReplyBuffer: PICMPV6_ECHO_REPLY; ReplySize: DWORD; NumResponses: DWORD; begin Result := 3; SendData := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; ip.sin6_scope_id := 0; ICMPFile := Icmp6CreateFile; if ICMPFile <> INVALID_HANDLE_VALUE then try // Source Address FillChar(SourceAddress, sizeof(SourceAddress), 0); // Reply ReplySize := 4000; // sizeof(ICMP_ECHO_REPLY) + sizeof(SendData); GetMem(ReplyBuffer, ReplySize); try // handle: Integer; Event: Pointer; ApcRoutine: Pointer; ApcContext: Pointer; SourceAddress: PSockAddrIn6; DestinationAddress: PSockAddrIn6; RequestData: Pointer; RequestSize: Integer; RequestOptions: PIP_OPTION_INFORMATION; ReplyBuffer: Pointer; ReplySize: Integer; Timeout: Integer): Integer; stdcall; external 'iphlpapi.dll'; NumResponses := Icmp6SendEcho2(ICMPFile, nil, nil, nil, @SourceAddress, @ip, @SendData, sizeof(SendData), nil, ReplyBuffer, ReplySize, 1000); if (NumResponses > 0) then begin if (ReplyBuffer.Status = 0) then begin ResultLine := 'Received Response from ' + HumanReadable + ' in ' + IntToStr(ReplyBuffer.RoundTripTime) + ' ms'; Result := 0; end else begin ResultLine := 'An Error occured: ' + IntToStr(ReplyBuffer.Status); Result := 1; end; end else begin ResultLine := 'Error: ' + ErrorToText(GetLastError()); Result := 1; end; finally FreeMem(ReplyBuffer); end; finally IcmpCloseHandle(ICMPFile); end else begin RaiseLastOSError(); end; end; function Ping(const Host: string; out ResultLine: String): Integer; var Lookup: TLookupResult; begin Lookup := LookupIP(Host); if Lookup.Format = IPv4 then begin Result := PingV4(Lookup.addr4.sin_addr, Lookup.HumanReadable, ResultLine); end else begin Result := PingV6(Lookup.addr6, Lookup.HumanReadable, ResultLine); end; end; end.
{*******************************************************} { } { NTS Aero UI Library } { Created by GooD-NTS ( good.nts@gmail.com ) } { http://ntscorp.ru/ Copyright(c) 2011 } { License: Mozilla Public License 1.1 } { } {*******************************************************} unit UI.Aero.black.GameButton; interface {$I '../../Common/CompilerVersion.Inc'} uses {$IFDEF HAS_UNITSCOPE} System.Classes, Winapi.Windows, Winapi.UxTheme, Vcl.Graphics, {$ELSE} Windows, Classes, Graphics, UxTheme, {$ENDIF} UI.Aero.Button.Custom, UI.Aero.Button.Theme, UI.Aero.Button; type TBlackGameButton = class(TAeroThemeButton) private subLeft: Integer; Protected function GetCaptionRect: TRect; override; function GetTextFormat: Cardinal; override; procedure DoClassicThemePaint(const Sender: TAeroCustomButton; PartID, StateID: Integer; Surface: TCanvas); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure AddSub(sText, sGameTag: String; iTag: integer; whenClick: TNotifyEvent; isEnabled: Boolean); end; implementation uses UI.Aero.Core; { TBlackGameButton } Constructor TBlackGameButton.Create(AOwner: TComponent); var osPartID: Integer; begin Inherited Create(AOwner); subLeft:= 0; ThemeClassName:= 'BUTTON'; Height:= 73; Width:= 305; if AeroCore.RunWindowsVista then osPartID:= BP_COMMANDLINK else osPartID:= BP_PUSHBUTTON; with State do begin PartNormal:= osPartID; PartHightLight:= osPartID; PartFocused:= osPartID; PartDown:= osPartID; PartDisabled:= osPartID; StateNormal:= 1; StateHightLight:= 2; StateFocused:= 5; StateDown:= 3; StateDisabled:= 4; end; with Image do begin PartHeight:= 64; PartWidth:= 64; end; end; destructor TBlackGameButton.Destroy; begin inherited Destroy; end; procedure TBlackGameButton.DoClassicThemePaint(const Sender: TAeroCustomButton; PartID, StateID: Integer; Surface: TCanvas); begin case StateID of 2: begin Surface.Brush.Color:= clHighlight; Surface.FillRect( Self.GetClientRect ); end; 3: begin Surface.Brush.Color:= clHotLight; Surface.FillRect( Self.GetClientRect ); end; end; Inherited DoClassicThemePaint(Sender,PartID,StateID,Surface); end; procedure TBlackGameButton.AddSub(sText, sGameTag: String; iTag: integer; whenClick: TNotifyEvent; isEnabled: Boolean); var AButton: TAeroButton; begin AButton := TAeroButton.Create(Self); AButton.Parent := Self; AButton.Caption := sText; AButton.sTag := sGameTag; AButton.Tag := iTag; AButton.FlatStyle := True; AButton.OnClick := whenClick; AButton.Top := 24; AButton.Left := 76 + subLeft; AButton.Enabled := isEnabled; subLeft := subLeft + AButton.Width + 4; end; function TBlackGameButton.GetCaptionRect: TRect; begin Result.Left := 76; Result.Top := 4; Result.Right := Width - 4; Result.Bottom := Height - 8; end; function TBlackGameButton.GetTextFormat: Cardinal; begin Result:= (DT_TOP OR DT_LEFT OR DT_SINGLELINE); end; end.
(*!------------------------------------------------------------ * Fano Web Framework Skeleton Application (https://fanoframework.github.io) * * @link https://github.com/fanoframework/fano-app-db * @copyright Copyright (c) 2018 Zamrony P. Juhara * @license https://github.com/fanoframework/fano-app-db/blob/master/LICENSE (GPL 3.0) *------------------------------------------------------------- *) unit UserListingView; interface {$MODE OBJFPC} {$H+} uses fano; type (*!----------------------------------------------- * View instance for user listing page * * @author Zamrony P. Juhara <zamronypj@yahoo.com> *------------------------------------------------*) TUserListingView = class(TInjectableObject, IView) private userModel : IModelReader; fBaseTpl : IViewPartial; fBaseTemplatePath : string; public constructor create( const usr : IModelReader; const baseTpl : IViewPartial ); destructor destroy(); override; (*!------------------------------------------------ * render view *------------------------------------------------ * @param viewParams view parameters * @param response response instance * @return response *-----------------------------------------------*) function render( const viewParams : IViewParameters; const response : IResponse ) : IResponse; end; implementation uses SysUtils; constructor TUserListingView.create( const usr : IModelReader; const baseTpl : IViewPartial ); begin userModel := usr; fBaseTpl := baseTpl; fBaseTemplatePath := getCurrentDir() + '/resources/Templates/base.template.html'; end; destructor TUserListingView.destroy(); begin fBaseTpl := nil; userModel := nil; inherited destroy(); end; (*!------------------------------------------------ * render view *------------------------------------------------ * @param viewParams view parameters * @param response response instance * @return response *-----------------------------------------------*) function TUserListingView.render( const viewParams : IViewParameters; const response : IResponse ) : IResponse; var userData : IModelResultSet; respBody : IResponseStream; mainContent : string; begin userData := userModel.data(); respBody := response.body(); mainContent := ''; if (userData.count() > 0) then begin mainContent := '<div class="container has-text-centered">' + '<div class="column">' + '<table class="table is-fullwidth is-hoverable">' + '<thead>' + '<tr>' + ' <th>No</th>' + ' <th>Name</th>' + ' <th>Email</th>' + '</tr>' + '</thead><tbody>'; while (not userData.eof()) do begin mainContent := mainContent + '<tr>' + '<td>' + userData.readString('id') + '</td>' + '<td>' + userData.readString('name') + '</td>' + '<td>' + userData.readString('email') + '</td>' + '</tr>'; userData.next(); end; mainContent := mainContent + '</tbody></table></div></div>'; end; viewParams['mainContent'] := mainContent; respBody.write( fBaseTpl.partial( fBaseTemplatePath, viewParams ) ); result := response; end; end.
unit MasterForm; { Copyright (c) 2017+, Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Layouts, FMX.ListBox, FMX.TabControl, FMX.Controls.Presentation, FMX.DialogService, IniFiles, SystemSupport, FHIRClient, ServerForm; type TMasterToolsForm = class(TForm) tbMain: TTabControl; Label2: TLabel; TabItem1: TTabItem; pnlToolbar: TPanel; Panel1: TPanel; lbServers: TListBox; btnConnect: TButton; btnAddServer: TButton; btnRemoveServer: TButton; Splitter1: TSplitter; Panel2: TPanel; Label1: TLabel; lbFiles: TListBox; btnReopen: TButton; btnRemoveFile: TButton; btnOpen: TButton; btnNew: TButton; ToolBar1: TToolBar; SpeedButton1: TSpeedButton; SpeedButton2: TSpeedButton; SpeedButton3: TSpeedButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure lbServersClick(Sender: TObject); procedure lbFilesClick(Sender: TObject); procedure btnRemoveServerClick(Sender: TObject); procedure btnAddServerClick(Sender: TObject); procedure btnConnectClick(Sender: TObject); private { Private declarations } FIni : TIniFile; procedure saveServers; procedure saveFiles; public { Public declarations } end; var MasterToolsForm: TMasterToolsForm; implementation {$R *.fmx} procedure TMasterToolsForm.btnAddServerClick(Sender: TObject); begin TDialogService.InputQuery('Server Address', ['URL'], [''], procedure(const AResult: TModalResult; const AValues: array of string) begin if (AResult = mrOK) and (aValues[0] <> '') then begin lbServers.Items.Insert(0, aValues[0]); end; end); end; procedure TMasterToolsForm.btnConnectClick(Sender: TObject); var client : TFhirHTTPClient; tab : TTabItem; serverForm : TServerFrameForm; begin client := TFhirHTTPClient.Create(nil, lbServers.Items[lbServers.ItemIndex], false); try tab := tbMain.Add(TTabItem); tbMain.ActiveTab := tab; tab.Text := lbServers.Items[lbServers.ItemIndex]; serverForm := TServerFrameForm.create(tab); serverForm.Parent := tab; serverForm.Align := TAlignLayout.Client; serverForm.Client := client.link; finally client.Free; end; end; procedure TMasterToolsForm.btnRemoveServerClick(Sender: TObject); var i : integer; begin i := lbServers.ItemIndex; lbServers.items.Delete(i); if i = lbServers.items.Count then dec(i); lbServers.ItemIndex := i; saveServers; lbServersClick(nil); end; procedure TMasterToolsForm.FormCreate(Sender: TObject); begin FIni := TIniFile.Create(IncludeTrailingPathDelimiter(SystemTemp) + 'settings.ini'); FIni.ReadSection('Servers', lbServers.Items); if lbServers.Items.count = 0 then lbServers.Items.add('http://test.fhir.org'); lbServers.ItemIndex := 0; lbServersClick(self); FIni.ReadSection('Files', lbFiles.Items); if lbFiles.Items.count > 0 then lbFiles.ItemIndex := 0; lbFilesClick(self); end; procedure TMasterToolsForm.FormDestroy(Sender: TObject); var s : String; begin saveServers; saveFiles; FIni.Free; end; procedure TMasterToolsForm.lbFilesClick(Sender: TObject); begin btnReopen.Enabled := lbFiles.ItemIndex >= 0; btnRemoveFile.Enabled := lbFiles.ItemIndex >= 0; end; procedure TMasterToolsForm.lbServersClick(Sender: TObject); begin btnConnect.Enabled := lbServers.ItemIndex >= 0; btnRemoveServer.Enabled := lbServers.ItemIndex >= 0; end; procedure TMasterToolsForm.saveFiles; var s : String; begin try FIni.EraseSection('Files'); for s in lbFiles.Items do FIni.WriteString('Files', s, ''); except // nothing we can do end; end; procedure TMasterToolsForm.saveServers; var s : String; begin try FIni.EraseSection('Servers'); for s in lbServers.Items do FIni.WriteString('Servers', s, ''); except // nothing we can do end; end; end.
unit BaseClass; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option, Data.DBXJSONCommon, System.JSON, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client; type TBaseSQL = class constructor Create(connection: TFDConnection); procedure SQLexecute(SQLtext: string); procedure SQLactivity(SQLtext: string); function GetValuesFieldString(fieldname: string): string; function GetValuesFieldBoolean(fieldname: string): Boolean; function GetValuesFieldInt(fieldname: string): Integer; function GetValuesFieldDouble(fieldname: string): Double; function GetDataSource: TDataSource; function EOF: Boolean; function RecordCount: Integer; procedure MoveNext; procedure setValues(field, values: string); procedure loadFromFile(filepath: string); procedure First; private function GetJsonRecord: TJSONObject; function GetJsonAllRecord: TJSONArray; protected Query: TFDQuery; DataSource: TDataSource; connectionBC: TFDConnection; function StrToBollMy(values: string): Boolean; function GetConnection: TFDConnection; function GetJsonQuery(IsNameArray: string): TJSONObject; end; implementation constructor TBaseSQL.Create(connection: TFDConnection); begin Query := TFDQuery.Create(Application); Query.Connection := connection; DataSource := TDataSource.Create(Application); DataSource.DataSet := Query; connectionBC := connection; end; procedure TBaseSQL.SQLexecute(SQLtext: string); begin try Query.SQL.Clear; Query.SQL.Text := SQLtext; Query.ExecSQL; except on e: Exception do ShowMessage(e.Message + ' ЗАПРОС ' + SQLtext); end; end; procedure TBaseSQL.SQLactivity(SQLtext: string); begin try Query.SQL.Clear; Query.SQL.Text := SQLtext; Query.Active := True; except on e: exception do ShowMessage(e.Message + ' ЗАПРОС ' + SQLtext); end; end; function TBaseSQL.getValuesFieldString(fieldname: string): string; begin try Result := Query.FieldByName(fieldname).AsString; except on e: Exception do Result := ''; end; end; function TBaseSQL.getValuesFieldBoolean(fieldname: string): Boolean; begin Result := Query.FieldByName(fieldname).AsBoolean; end; function TBaseSQL.getValuesFieldInt(fieldname: string): Integer; begin Result := Query.FieldByName(fieldname).AsInteger; end; function TBaseSQL.getValuesFieldDouble(fieldname: string): Double; begin Result := Query.FieldByName(fieldname).AsFloat; end; function TBaseSQL.getDataSource: TDataSource; begin Result := DataSource; end; function TBaseSQL.GetJsonRecord: TJSONObject; var i: Integer; begin Result := TJSONObject.Create; for i := 0 to Query.FieldCount - 1 do begin Result.AddPair(Query.Fields[i].fieldname, GetValuesFieldString(Query.Fields[i].fieldname)); end; end; function TBaseSQL.GetJsonAllRecord(): TJSONArray; begin result := TJSONArray.Create; while not EOF do begin result.AddElement(GetJsonRecord); MoveNext; end; end; function TBaseSQL.GetJsonQuery(IsNameArray: string): TJSONObject; begin result := TJSONObject.Create; result.AddPair(IsNameArray, GetJsonAllRecord()); end; function TBaseSQL.EOF: Boolean; begin Result := Query.Eof end; function TBaseSQL.RecordCount: Integer; begin Result := Query.RecordCount; end; procedure TBaseSQL.MoveNext; begin Query.Next; end; procedure TBaseSQL.setValues(field: string; values: string); begin try Query.Edit; Query.FieldByName(field).AsString := values; Query.Post except on e: Exception do ShowMessage('Не верный тип данных'); end; end; function TBaseSQL.StrToBollMy(values: string): Boolean; begin try if StrToInt(values) > 0 then Result := True else Result := False; except on e: Exception do ShowMessage(e.Message); end; end; function TBaseSQL.getConnection: TFDConnection; begin Result := connectionBC; end; procedure TBaseSQL.loadFromFile(filepath: string); begin Query.SQL.LoadFromFile(filepath); Query.ExecSQL; end; procedure TBaseSQL.First; begin Query.First; end; end.
unit gmAureliusDataset; interface {$REGION 'DatasetHelper'} { TDataSet helper classes to simplify access to TDataSet fields and make TDataSet work with a for-in-loop. Author: Uwe Raabe - ur@ipteam.de Techniques used: - class helpers - enumerators - invokable custom variants This unit implements some "Delphi Magic" to simplify the use of TDataSets and its fields. Just by USING this unit you can access the individual fields of a TDataSet like they were properties of a class. For example let's say a DataSet has fields First_Name and Last_Name. The normal approach to access the field value would be to write something like this: DataSet.FieldValues['First_Name'] or DataSet.FieldByName('First_Name'].Value With this unit you can simply write DataSet.CurrentRec.First_Name You can even assign DataSet.CurrentRec to a local variable of type variant to shorten the needed typing and clarify the meaning (let PersonDataSet be a TDataSet descendant with fields as stated above). var Person: Variant; FullName: string; begin Person := PersonDataSet.CurrentRec; ... FullName := Trim(Format('%s %s', [Person.First_Name, Person.Last_Name])); ... end; If you write to such a property, the underlying DatsSet is automatically set into Edit mode. Obviously you still have to know the field names of the dataset, but this is just the same as if you are using FieldByName. The second benefit of this unit shows up when you try to iterate over a DataSet. This reduces to simply write the following (let Lines be a TStrings decendant taking the full names of all persons): var Person: Variant; begin ... // Active state of PersonDataSet is saved during the for loop. // If PersonDataSet supports bookmarks, the position is also saved. for Person in PersonDataSet do begin Lines.Add(Trim(Format('%s %s', [Person.First_Name, Person.Last_Name]))); end; ... end; You can even set these "variant-field-properties" during the for loop as the DataSet will automatically Post your changes within the Next method. How it works: We use a class helper to add the CurrentRec property and the enumerator to the TDataSet class. The CurrentRec property is also used by the enumerator to return the current record when iterating. The TDataSetEnumerator does some housekeeping to restore the active state and position of the DataSet after the iteration, thus your code hasn't to do this each time. The tricky thing is making the variant to access the dataset fields as if they were properties. This is accomplished by introducing a custom variant type descending from TInvokeableVariantType. Besides the obligatory overwriting of Clear and Copy, which turn out to be quite simple, we implement the GetProperty and SetProperty methods to map the property names to field names. That's all! CAUTION! Don't do stupid things with the DataSet while there is some of these variants connected to it. Especially don't destroy it! The variant stuff is completely hidden in the implementation section, as for now I can see no need to expose it. } {$ENDREGION} uses Aurelius.Bind.Dataset, Aurelius.Criteria.Base, Aurelius.Criteria.Linq, Data.DB, Generics.Collections, Classes, System.SysUtils, cxGridDBTableView; type EValidationError = class(Exception) public FDataset: TDataset; Field: TField; end; TgmAureliusDataset = class; TDataSetEnumerator = class private FBookmark: TBookmark; FDataSet: TgmAureliusDataset; FMoveToFirst: Boolean; FWasActive: Boolean; function GetCurrent: Variant; public constructor Create(ADataSet: TgmAureliusDataset); destructor Destroy; override; function MoveNext: Boolean; property Current: Variant read GetCurrent; end; TgmAureliusOpenType = (tgmAFetchAll, tgmACursor, tgmAFetchPage); TgmAureliusDataset = class(TAureliusDataset) private FCriteria: TCriteria; FAppendList: TList<TObject>; FUpdateList: TList<TObject>; FDeleteList: TList<TObject>; FMasterDataSet: TgmAureliusDataset; FImmediatePost: boolean; FOpenType: TgmAureliusOpenType; FSeqName: string; FKeyFields: string; FxTableView: TcxGridDBTableView; FLastQuery: Variant; function GetPKKeyValue: Variant; // procedure ReadStrData(Reader: TReader); // procedure WriteStrData(Writer: TWriter); procedure AssegnaMasterKey; function GetCurrentRec: Variant; function GetgmDesignClass: string; protected procedure InternalObjectInsert(Obj: TObject); override; procedure InternalObjectUpdate(Obj: TObject); override; procedure InternalObjectRemove(Obj: TObject); override; procedure InternalRefresh; override; procedure DoAfterInsert; override; procedure DoAfterEdit; override; procedure DoBeforePost; override; function MyCreateObject: TObject; procedure SetPrimarykey(const pSeqName: string); // procedure DefineProperties(Filer: TFiler); override; function PSGetKeyFields: string; override; public class function gmVariantToObject(V: Variant): TObject; class function gmObjectToVariant(Obj: TObject): Variant; constructor Create(AOwner: TComponent); override; destructor Destroy; override; function MyLocateRecord(const KeyFields: string; const KeyValues: Variant; Options: TLocateOptions): Boolean; // procedure ClearAppendList; function IsInAppendList(pObj: TObject): boolean; // procedure SaveDetail(const nFK: string; vFK: TObject); procedure SaveDetail; procedure PulisciListe; procedure SistemaFields(pField: TField); procedure GetAll<T: class>; overload; // procedure GetAll<T: class>(pAlias: TArray<string>; pCond: TArray<TLinqExpression>); overload; procedure GetAll<T: class>(pCond: TLinqExpression; const pOrder: string = ''); overload; procedure RefreshRecord<T: class>; procedure CheckFields; procedure CheckFieldsBeforePost; procedure RaiseError(const msg: string; fField: TField = nil); procedure AbortError(const msg: string; fField: TField = nil); function GetEnumerator: TDataSetEnumerator; function ChangedFromLastQuery(pParam: Variant): boolean; property CurrentRec: Variant read GetCurrentRec; property PKKeyValue: Variant read GetPKKeyValue; // property gmClassName: string read FgmClassName write FgmClassName; property DesignClass; property gmDesignClass: string read GetgmDesignClass; property xTableView: TcxGridDBTableView read FxTableView write FxTableView; property OpenType: TgmAureliusOpenType read FOpenType write FOpenType default tgmAFetchAll; property LastQuery: Variant read FLastQuery write FLastQuery; published property SeqName: string read FSeqName write FSeqName; property MasterDataSet: TgmAureliusDataset read FMasterDataSet write FMasterDataSet; property ImmediatePost: boolean read FImmediatePost write FImmediatePost default false; end; const sgmValoreObbligatorio = 'Valore obbligatorio !'; implementation uses Aurelius.Commands.Inserter, gmAureliusDatasetHelpers,Bcl.Rtti.ObjectFactory, Aurelius.Mapping.Optimization, Aurelius.Mapping.Metadata, Vcl.Dialogs, System.UITypes, {$REGION 'DatasetHelper'} Variants; type { A custom variant type that implements the mapping from the property names to the DataSet fields. } TVarDataRecordType = class(TInvokeableVariantType) public procedure Clear(var V: TVarData); override; procedure Copy(var Dest: TVarData; const Source: TVarData; const Indirect: Boolean); override; function GetProperty(var Dest: TVarData; const V: TVarData; const Name: string): Boolean; override; function SetProperty(const V: TVarData; const Name: string; const Value: TVarData): Boolean; override; end; type { Our layout of the variants record data. We only hold a pointer to the DataSet. } TVarDataRecordData = packed record VType: TVarType; Reserved1, Reserved2, Reserved3: Word; DataSet: TDataSet; Reserved4: LongInt; end; var { The global instance of the custom variant type. The data of the custom variant is stored in a TVarData record, but the methods and properties are implemented in this class instance. } VarDataRecordType: TVarDataRecordType = nil; { A global function the get our custom VarType value. This may vary and thus is determined at runtime. } function VarDataRecord: TVarType; begin result := VarDataRecordType.VarType; end; { A global function that fills the VarData fields with the correct values. } function VarDataRecordCreate(ADataSet: TDataSet): Variant; begin VarClear(result); TVarDataRecordData(result).VType := VarDataRecord; TVarDataRecordData(result).DataSet := ADataSet; end; procedure TVarDataRecordType.Clear(var V: TVarData); begin { No fancy things to do here, we are only holding a pointer to a TDataSet and we are not supposed to destroy it here. } SimplisticClear(V); end; procedure TVarDataRecordType.Copy(var Dest: TVarData; const Source: TVarData; const Indirect: Boolean); begin { No fancy things to do here, we are only holding a pointer to a TDataSet and that can simply be copied here. } SimplisticCopy(Dest, Source, Indirect); end; function TVarDataRecordType.GetProperty(var Dest: TVarData; const V: TVarData; const Name: string): Boolean; var fld: TField; begin { Find a field with the property's name. If there is one, return its current value. } fld := TVarDataRecordData(V).DataSet.FindField(Name); result := (fld <> nil); if result then Variant(dest) := fld.Value; end; function TVarDataRecordType.SetProperty(const V: TVarData; const Name: string; const Value: TVarData): Boolean; var fld: TField; begin { Find a field with the property's name. If there is one, set its value. } fld := TVarDataRecordData(V).DataSet.FindField(Name); result := (fld <> nil); if result then begin { Well, we have to be in Edit mode to do this, don't we? } TVarDataRecordData(V).DataSet.Edit; fld.Value := Variant(Value); end; end; constructor TDataSetEnumerator.Create(ADataSet: TgmAureliusDataset); { The enumerator is automatically created and destroyed in the for-in loop. So we remember the active state and set a flag that the first MoveNext will not move to the next record, but stays on the first one instead. } begin inherited Create; FDataSet := ADataSet; Assert(FDataSet <> nil); { save the Active state } FWasActive := FDataSet.Active; { avoid flickering } FDataSet.DisableControls; if FWasActive then begin { get a bookmark of the current position - even if it is invalid } FBookmark := FDataSet.GetBookmark; FDataSet.First; end else begin { FBookmark is initialized to nil anyway, so no need to set it here } FDataSet.Active := true; end; FMoveToFirst := true; end; destructor TDataSetEnumerator.Destroy; { Restore the DataSet to its previous state. } begin if FWasActive then begin { if we have a valid bookmark, use it } if FDataSet.BookmarkValid(FBookmark) then FDataSet.GotoBookmark(FBookmark); { I'm not sure, if FreeBokmark can handle nil pointers - so to be safe } if FBookmark <> nil then FDataSet.FreeBookmark(FBookmark); end else FDataSet.Active := false; { don't forget this one! } FDataSet.EnableControls; inherited; end; function TDataSetEnumerator.GetCurrent: Variant; begin { We simply return the CurrentRec property of the DataSet, which is exposed due to the class helper. } Result := FDataSet.CurrentRec; end; function TDataSetEnumerator.MoveNext: Boolean; begin { Check if we have to move to the first record, which has been done already during Create. } if FMoveToFirst then FMoveToFirst := false else FDataSet.Next; Result := not FDataSet.EoF; end; {$ENDREGION} constructor TgmAureliusDataset.Create(AOwner: TComponent); begin inherited Create(AOwner); FAppendList := TList<TObject>.Create; FUpdateList := TList<TObject>.Create; FDeleteList := TList<TObject>.Create; FImmediatePost := false; FOpenType := tgmAFetchAll; FLastQuery := varNull; end; destructor TgmAureliusDataset.Destroy; begin FAppendList.Free; FUpdateList.Free; FDeleteList.Free; inherited; end; class function TgmAureliusDataset.gmVariantToObject(V: Variant): TObject; begin if VarIsNull(V) then Exit(nil); Result := TObject(IntPtr(V)); end; class function TgmAureliusDataset.gmObjectToVariant(Obj: TObject): Variant; begin Result := IntPtr(Obj); end; (* procedure TgmAureliusDataset.ReadStrData(Reader: TReader); begin FgmClassName := Reader.ReadString; if (DesignClass='') and (FgmClassName<>'') then begin DesignClass := 'Modelli.'+FgmClassName; FgmClassName := ''; end; end; procedure TgmAureliusDataset.WriteStrData(Writer: TWriter); begin Writer.WriteString(FgmClassName); end; procedure TgmAureliusDataset.DefineProperties(Filer: TFiler); function DoWrite: Boolean; begin // no inherited value -- check for default (nil) value Result := FgmClassName <> ''; end; begin inherited; { allow base classes to define properties } Filer.DefineProperty('gmClassName', ReadStrData, WriteStrData, DoWrite); end; *) function TgmAureliusDataset.GetPKKeyValue: Variant; begin result := FieldByName(PSGetKeyFields).Value; end; function TgmAureliusDataset.IsInAppendList(pObj: TObject): boolean; var // xKey: Variant; xKey: TObject; // sKey: Variant; begin result := false; // sKey := MyGetPropValue(PSGetKeyFields,pObj); for xKey in FAppendList do // if xKey=sKey then if xKey=pObj then Exit(true); end; procedure TgmAureliusDataset.InternalObjectInsert(Obj: TObject); begin if FImmediatePost then begin inherited; end; end; procedure TgmAureliusDataset.InternalObjectUpdate(Obj: TObject); begin if FImmediatePost then inherited; end; procedure TgmAureliusDataset.InternalObjectRemove(Obj: TObject); var sKey: Variant; del: boolean; i: integer; begin if FImmediatePost then inherited else begin del := false; sKey := MyGetPropValue(PSGetKeyFields,Obj); i:=0; while (i<FAppendList.Count) and not del do begin // if FAppendList[i]=sKey then if FAppendList[i]=Obj then begin FAppendList.Delete(i); del := true; end; i := i+1; end; if not del then FDeleteList.Add( Obj ); end; end; procedure TgmAureliusDataset.DoAfterInsert; begin // if (DataSetField=nil) then ??? a cosa serviva ? if (FSeqName<>'') then begin SetPrimaryKey(FSeqName); end; // if FImmediatePost then AssegnaMasterKey; // else // FAppendList.Add( EntityFieldByName('Self').AsObject ); FAppendList.Add( CurrentObj ); inherited; end; procedure TgmAureliusDataset.DoAfterEdit; var // xKey: Variant; xKey: TObject; // sKey: Variant; // KeyFields: string; found: boolean; // Pos: integer; // FieldName: string; // j: integer; begin if not FImmediatePost then begin found := false; (* KeyFields := PSGetKeyFields; if KeyFields<>'' then begin sKey := ''; Pos := 1; while Pos <= KeyFields.Length do begin FieldName := ExtractFieldName(KeyFields, Pos); for j := 0 to FieldCount - 1 do if AnsiCompareText(FieldName, Fields[J].FieldName) = 0 then begin if sKey='' then sKey := FieldByName(FieldName).AsString else sKey := sKey + ';' + FieldByName(FieldName).AsString; Break; end; end; *) for xKey in FAppendList do // if xKey=sKey then if xKey=EntityFieldByName('Self').AsObject then begin found := True; Break; end; if not found then // FUpdateList.Add( sKey ); FUpdateList.Add( EntityFieldByName('Self').AsObject ); // end; end; inherited; end; procedure TgmAureliusDataset.DoBeforePost; begin inherited; // sempre! if (FImmediatePost { ??? or (FMasterDataSet<>nil)}) {and not Assigned(BeforePost)} then CheckFieldsBeforePost; end; procedure TgmAureliusDataset.RefreshRecord<T>; begin if Manager<>nil then begin Manager.Refresh(self.Current<T>); end; end; procedure TgmAureliusDataset.InternalRefresh; begin inherited; // Togliere se si attiva davvero il refresh ! (* if (Manager<>nil) and (FCriteria<>nil) then begin DisableControls; Close; SetSourceCriteria(FCriteria); Open; EnableControls; end; *) end; function TgmAureliusDataset.PSGetKeyFields: string; begin if FKeyFields='' then begin FKeyFields := inherited; end; result := FKeyFields; end; procedure TgmAureliusDataset.CheckFields; var i: integer; // e: EValidationError; // msg: string; begin for i:=0 to FieldCount-1 do begin if Fields[i].Required and Fields[i].IsNull then begin RaiseError(sgmValoreObbligatorio,Fields[i]); end; end; end; procedure TgmAureliusDataset.CheckFieldsBeforePost; var gc: TcxGridDBColumn; begin try CheckFields; except on E: EValidationError do begin MessageDlg(E.Field.DisplayName + #13 + E.Message,mtWarning,[mbOk],0); if xTableView<>nil then begin gc := xTableView.GetColumnByFieldName(E.Field.FieldName); if gc<>nil then gc.FocusWithSelection; xTableView.Invalidate(True); end else E.Field.FocusControl; Abort; end; end; end; function TgmAureliusDataset.MyCreateObject: TObject; var FObjectFactory: IObjectFactory; begin FObjectFactory := TObjectFactory.Create; Result := DoCreateObject; if Result = nil then Result := FObjectFactory.CreateInstance(ObjectClass); end; procedure TgmAureliusDataset.SetPrimarykey(const pSeqName: string); var Inserter: TInserter; FObj: TObject; begin if Assigned(Manager) and (PSGetKeyFields<>'') and (FieldByName(PSGetKeyFields).IsNull) and not (FieldByName(PSGetKeyFields).AutoGenerateValue=arAutoInc) then begin FObj := MyCreateObject; Inserter := Manager.GetCommandFactory.GetCommand<TInserter>(FObj.ClassType); try Inserter.SetIdentifier(FObj, pSeqName); FieldByName(PSGetKeyFields).Value := MyGetPropValue(PSGetKeyFields,FObj); // FAppendList.Add( FieldByName(PSGetKeyFields).Value ); finally Inserter.Free; FObj.Free; end; end; end; function TgmAureliusDataset.MyLocateRecord(const KeyFields: string; const KeyValues: Variant; Options: TLocateOptions): Boolean; var ResultFields: string; SyncCursor: boolean; begin SyncCursor := true; result := LocateRecord(KeyFields, KeyValues, Options, SyncCursor, ResultFields); end; procedure TgmAureliusDataset.AssegnaMasterKey; var Associations: TList<TAssociation>; A: TAssociation; Clazz: TClass; mClass: TClass; mTable: TgmAureliusDataset; c: TComponent; oldState: TDatasetState; begin if FMasterDataset<>nil then begin Clazz := Explorer.Hierarchy.FindClassByName(gmDesignClass); Associations := Explorer.GetAssociations(Clazz, True, False); mClass := Explorer.Hierarchy.FindClassByName(FMasterDataset.gmDesignClass); mTable := nil; for c in self.Owner do if (c is TgmAureliusDataset) and (TgmAureliusDataset(c).Name=FMasterDataset.Name) then begin mTable := TgmAureliusDataset(c); Break; end; if mTable<>nil then for A in Associations do begin if (A.Kind = TAssociationKind.SingleValued) and (A.Target=mClass) then begin oldState := State; if not (oldState in dsEditModes) then Edit; EntityFieldByName(Copy(A.ClassMemberName,2)).AsObject := mTable.EntityFieldByName('Self').AsObject; if not (oldState in dsEditModes) then Post; Break; end; end; end; end; procedure TgmAureliusDataset.SaveDetail; var // sKey: Variant; sKey: TObject; xKey: TObject; begin if State in dsEditModes then Post; DisableControls; for xKey in FDeleteList do begin Manager.Remove(xKey); end; for sKey in FAppendList do begin (* // if MyLocateRecord(PSGetKeyFields, sKey, []) then if Locate(PSGetKeyFields, sKey, []) then begin AssegnaMasterKey; Manager.Save(EntityFieldByName('Self').AsObject); end; *) // Manager.Save(sKey); Manager.SaveOrUpdate(sKey); end; for sKey in FUpdateList do begin (* // if MyLocateRecord(PSGetKeyFields, sKey, []) then if Locate(PSGetKeyFields, sKey, []) then begin Manager.Update(EntityFieldByName('Self').AsObject); end; *) Manager.Update(sKey); end; EnableControls; end; procedure TgmAureliusDataset.PulisciListe; begin FAppendList.Clear; FUpdateList.Clear; FDeleteList.Clear; end; procedure TgmAureliusDataset.SistemaFields(pField: TField); var MetaId: TMetaId; IdentityColumn: TColumn; i: integer; Clazz: TClass; Associations: TList<TAssociation>; A: TAssociation; function AssociationIsManyValued(xClazz: TClass; const xClassMemberName: string): boolean; var xAss: TList<TAssociation>; q: TAssociation; begin result := false; xAss := Explorer.GetAssociations(xClazz, True, False); for q in xAss do begin if (q.Kind = TAssociationKind.ManyValued) and (q.MappedBy=xClassMemberName) then begin // pField.Required := false; Exit(True); end; end; end; begin // -- settaggio chiave primaria Clazz := Explorer.Hierarchy.FindClassByName(gmDesignClass); MetaId := Explorer.MyGetId(Clazz); // Assert(Length(MetaId.Columns) > 0); if (MetaId<>nil) and (Length(MetaId.Columns) > 0) then begin IdentityColumn := MetaId.Columns[0]; Assert(IdentityColumn <> nil); for i:=0 to FieldDefs.Count-1 do begin if pField.FieldName=IdentityColumn.Name then begin pField.ProviderFlags := pField.ProviderFlags + [pfInKey]; if MetaId.IsAutoGenerated then begin pField.AutoGenerateValue := arAutoInc; pField.Required := False; end; pField.ReadOnly := false; exit; end; end; end; // -- tolgo Required a Foreign-Key 1-n // il valore di master viene inserito automaticamente in fase di Save // ma altrimenti darebbe errore sul Post del dataset Associations := Explorer.GetAssociations(Clazz, True, False); for A in Associations do begin if (A.Kind = TAssociationKind.SingleValued) then begin if (Copy(A.ClassMemberName,2) = pField.FieldName) and AssociationIsManyValued(A.Target,A.ClassMemberName) then begin pField.Required := false; Break; end; end; end; end; procedure TgmAureliusDataset.GetAll<T>; begin Close; FCriteria := Manager.Find<T>; // FCriteria.AutoDestroy := false; // attivare quando sarÓ streamable // e si potrÓ attivare InternalRefresh... case FOpenType of // tgmAFetchAll: SetSourceList(Manager.FindAll<T>); tgmAFetchAll: SetSourceCriteria(FCriteria); tgmACursor: SetSourceCursor(FCriteria.Open); tgmAFetchPage: SetSourceCriteria(FCriteria, 50); end; Open; end; (* procedure TgmAureliusDataset.GetAll<T>(pAlias: TArray<string>; pCond: TArray<TLinqExpression>); var s: string; c: TLinqExpression; i: integer; begin Close; FCriteria := Manager.Find<T>; i := 0; if pAlias<>nil then for s in pAlias do begin FCriteria := FCriteria.CreateAlias(s, chr(i+65), TFetchMode.Eager); inc(i); end; if pCond<>nil then for c in pCond do FCriteria := FCriteria.Add( c ); case FOpenType of // tgmAFetchAll: SetSourceList( FCriteria.List<T> ); tgmAFetchAll: SetSourceCriteria(FCriteria); tgmACursor: SetSourceCursor(FCriteria.Open); tgmAFetchPage: SetSourceCriteria(FCriteria, 50); end; Open; end; *) procedure TgmAureliusDataset.GetAll<T>(pCond: TLinqExpression; const pOrder: string = ''); var s: string; i: integer; pAlias: TList<string>; alias,prec,temp: string; g: integer; o: integer; begin pAlias := TList<string>.Create; // DisableControls; try Close; FCriteria := Manager.Find<T>; for i:=0 to FieldCount-1 do begin temp := Fields[i].FieldName; g := Pos('.',temp); prec := ''; while g>0 do begin alias := Copy(temp,0,g-1); if alias<>'' then begin if pAlias.IndexOf(UpperCase(prec + alias))=-1 then begin pAlias.Add( UpperCase(prec + alias) ); end; prec := prec + alias + '.'; end; temp := Copy(temp,g+1); g := Pos('.',temp); end; end; o := 1; for s in pAlias do begin // FCriteria := FCriteria.CreateAlias(s, pAlias.Items[s], TFetchMode.Eager); FCriteria := FCriteria.CreateAlias(s, chr(o+64), TFetchMode.Eager); inc(o); end; FCriteria := FCriteria.Add( pCond ); if pOrder<>'' then FCriteria := FCriteria.OrderBy(pOrder, True); case FOpenType of // tgmAFetchAll: SetSourceList( FCriteria.List<T> ); tgmAFetchAll: SetSourceCriteria(FCriteria); tgmACursor: SetSourceCursor(FCriteria.Open); tgmAFetchPage: SetSourceCriteria(FCriteria, 50); end; Open; finally pAlias.Free; // EnableControls; end; end; procedure TgmAureliusDataset.RaiseError(const msg: string; fField: TField = nil); var e: EValidationError; begin e := EValidationError.Create(msg); e.FDataset := self; e.Field := fField; raise e; end; procedure TgmAureliusDataset.AbortError(const msg: string; fField: TField = nil); var MsgErr: string; begin try RaiseError(msg, fField); except on E: EValidationError do begin MsgErr := E.Message; if E.Field<>nil then MsgErr := E.Field.DisplayName + #13 + MsgErr; MessageDlg(MsgErr,mtWarning,[mbOk],0); if E.Field<>nil then E.Field.FocusControl; Abort; end; end; end; {$REGION 'DatasetHelper'} function TgmAureliusDataset.GetCurrentRec: Variant; begin { return one of our custom variants } Result := VarDataRecordCreate(Self); end; function TgmAureliusDataset.GetEnumerator: TDataSetEnumerator; begin { return a new enumerator } Result := TDataSetEnumerator.Create(Self); end; function TgmAureliusDataset.GetgmDesignClass: string; var pp: integer; begin pp := Pos('.',DesignClass); result := Copy(DesignClass,pp+1,Length(DesignClass)-pp); end; function TgmAureliusDataset.ChangedFromLastQuery(pParam: Variant): boolean; begin result := not Active or VarIsNull(FLastQuery) or (FLastQuery<>pParam); { if result then FLastQuery := pParam; } end; initialization { Create our custom variant type, which will be registered automatically. } VarDataRecordType := TVarDataRecordType.Create; finalization { Free our custom variant type. } FreeAndNil(VarDataRecordType); {$ENDREGION} end.
unit uServer; interface uses Iocp, iocp.Utils.Hash, iocp.Http, iocp.Http.Websocket, Windows, SysUtils, Classes, SyncObjs; type /// <summary> /// 日志信息类型 /// </summary> TXLogType = (log_Debug, {调试信息} log_Info {信息}, log_Warning {警告}, log_Error {错误}); type /// <summary> /// 日志写入处理 /// </summary> TOnWriteLog = procedure (Sender: TObject; AType: TXLogType; const Log: string) of object; /// <summary> /// 任务处理请求 /// </summary> TOnProcRequest = procedure (Request: TIocpHttpRequest; Response: TIocpHttpResponse) of object; /// <summary> /// HTTP服务系统 /// </summary> TPtService = class(TObject) private //FPtWebService: TIocpHttpServer; FPtWebService: TIocpWebSocketServer; FOnWriteLog: TOnWriteLog; HttpReqRef: Integer; FProcList: TStringHash; FHtmlFileExts: TStringHash; function GetWebService: TIocpHttpServer; protected function IsDestroying: Boolean; procedure Log(Sender: TObject; AType: TXLogType; const Msg: string); procedure LogD(Sender: TObject; const Msg: string); procedure LogE(Sender: TObject; const Title: string; E: Exception); procedure DoWriteLog(Sender: TObject; AType: TXLogType; const Msg: string); protected procedure DoRequest(Sender: TIocpHttpServer; Request: TIocpHttpRequest; Response: TIocpHttpResponse); procedure DoWebSocketRequest(Sender: TIocpWebSocketServer; Request: TIocpWebSocketRequest; Response: TIocpWebSocketResponse); procedure DoRegProc(); virtual; abstract; procedure DoFreeProcItem(Item: PHashItem); public constructor Create(Port: Word); reintroduce; destructor Destroy; override; procedure RegProc(const URI: string; const Proc: TOnProcRequest); procedure Start; procedure Stop; property WebService: TIocpHttpServer read GetWebService; end; type TPtHttpService = class(TPtService) protected procedure DoRegProc(); override; procedure RequestDemo03(Request: TIocpHttpRequest; Response: TIocpHttpResponse); procedure RequestHello(Request: TIocpHttpRequest; Response: TIocpHttpResponse); procedure RequestUpfile(Request: TIocpHttpRequest; Response: TIocpHttpResponse); end; implementation type PMethod = ^TMethod; { TPtService } constructor TPtService.Create(Port: Word); begin FOnWriteLog := DoWriteLog; //FPtWebService := TIocpHttpServer.Create(nil); FPtWebService := TIocpWebSocketServer.Create(nil); FPtWebService.ListenPort := Port; FPtWebService.UploadMaxDataSize := 1024 * 1024; FPtWebService.MaxTaskWorker := 64; FPtWebService.MaxContextPoolSize := 1; FPtWebService.OnHttpRequest := DoRequest; FPtWebService.OnWebSocketRequest := DoWebSocketRequest; FProcList := TStringHash.Create(); FProcList.OnFreeItem := DoFreeProcItem; FHtmlFileExts := TStringHash.Create(); FHtmlFileExts.Add('.html', 1); FHtmlFileExts.Add('.htm', 1); FHtmlFileExts.Add('.xml', 1); FHtmlFileExts.Add('.xmls', 1); FHtmlFileExts.Add('.json', 1); DoRegProc(); end; destructor TPtService.Destroy; begin try Stop; FreeAndNil(FPtWebService); FreeAndNil(FProcList); FreeAndNil(FHtmlFileExts); except LogE(Self, 'DoDestroy', Exception(ExceptObject)); end; inherited Destroy; end; procedure TPtService.DoFreeProcItem(Item: PHashItem); begin if Item <> nil then Dispose(Pointer(Item.Value)); end; procedure TPtService.DoRequest(Sender: TIocpHttpServer; Request: TIocpHttpRequest; Response: TIocpHttpResponse); var V: Number; begin InterlockedIncrement(HttpReqRef); V := FProcList.ValueOf(LowerCase(string(Request.URI))); if V <> -1 then begin TOnProcRequest(PMethod(Pointer(V))^)(Request, Response); end else Response.SendFileByURI(Request.URI, '', False, True); end; procedure TPtService.DoWebSocketRequest(Sender: TIocpWebSocketServer; Request: TIocpWebSocketRequest; Response: TIocpWebSocketResponse); var S: TMemoryStream; Data: string; begin //OutputDebugString(PChar(Request.DataString())); S := TMemoryStream.Create; try Data := Request.DataString(hct_UTF8); S.Write(Data[1], Length(Data) {$IFDEF UNICODE} shl 1{$ENDIF}); S.Position := 0; Response.Send(S, wso_Text); finally S.Free; end; Response.Send(Request.DataString()); end; procedure TPtService.DoWriteLog(Sender: TObject; AType: TXLogType; const Msg: string); begin end; function TPtService.GetWebService: TIocpHttpServer; begin Result := FPtWebService; end; function TPtService.IsDestroying: Boolean; begin Result := (not Assigned(Self)); end; procedure TPtService.Log(Sender: TObject; AType: TXLogType; const Msg: string); begin if Assigned(FOnWriteLog) and (not IsDestroying) then FOnWriteLog(Sender, AType, Msg); end; procedure TPtService.LogD(Sender: TObject; const Msg: string); begin if Assigned(FOnWriteLog) and (not IsDestroying) then FOnWriteLog(Sender, log_Debug, Msg); end; procedure TPtService.LogE(Sender: TObject; const Title: string; E: Exception); begin if Assigned(FOnWriteLog) and (not IsDestroying) then begin if E = nil then FOnWriteLog(Sender, log_Error, Format('[%s] %s', [Sender.ClassName, Title])) else FOnWriteLog(Sender, log_Error, Format('[%s] %s Error: %s', [Sender.ClassName, Title, E.Message])) end; end; procedure TPtService.RegProc(const URI: string; const Proc: TOnProcRequest); var P: PMethod; begin if Length(URI) = 0 then Exit; if Assigned(Proc) then begin New(P); P^ := TMethod(Proc); FProcList.Add(LowerCase(URI), Integer(P)); end; end; procedure TPtService.Start; begin FPtWebService.Open; end; procedure TPtService.Stop; begin FPtWebService.Close; end; { TPtHttpService } procedure TPtHttpService.DoRegProc; begin RegProc('/RequestDemo03.o', RequestDemo03); RegProc('/Hello', RequestHello); RegProc('/upfile', RequestUpfile); end; procedure TPtHttpService.RequestDemo03(Request: TIocpHttpRequest; Response: TIocpHttpResponse); var O: TIocpHttpWriter; begin O := Response.GetOutWriter(); O.Charset := hct_GB2312; O.Write('Data: ').Write(Request.GetDataString(string(Request.CharSet))).Write('<br>'); O.Write('编号: ').Write(Request.GetParam('userid')).Write('<br>'); O.Write('用户名: ').Write(Request.GetParam('username')).Write('<br>'); O.Write('密码: ').Write(Request.GetParam('userpass')).Write('<br>'); O.Write('性别: ').Write(Request.GetParam('sex')).Write('<br>'); O.Write('部门: ').Write(Request.GetParam('dept')).Write('<br>'); O.Write('兴趣: ').Write(Request.GetParamValues('inst')).Write('<br>'); O.Write('说明: ').Write(Request.GetParam('note')).Write('<br>'); O.Write('隐藏内容: ').Write(Request.GetParam('hiddenField')).Write('<br>'); O.Flush; end; procedure TPtHttpService.RequestHello(Request: TIocpHttpRequest; Response: TIocpHttpResponse); begin Response.Send('Hello'); end; // 上传文件处理 procedure TPtHttpService.RequestUpfile(Request: TIocpHttpRequest; Response: TIocpHttpResponse); const UpFileDir = 'files'; var S: TStream; F: TFileStream; FName, Path: string; begin if Request.IsPost and Request.IsFormData then begin // 判断是否为表单数据 F := nil; with Request.FormData['fname'] do begin // 表单中的文件数据字段 S := GetContentStream; // 内容流 if Assigned(S) then begin S.Position := 0; try // 得到文件保存位置 Path := Request.Owner.WebPath + UpFileDir + '\'; if not DirectoryExists(Path) then ForceDirectories(Path); // 生成一个文件名 FName := FileName; while FileExists(Path + FName) do begin FName := FormatDateTime('HHMMSSZZZ', Now) + FileName; end; // 写入文件 F := TFileStream.Create(Path + FName, fmCreate); F.CopyFrom(S, S.Size); finally FreeAndNil(F); S.Free; end; // 返回状态给浏览器 Response.Send( Format('{"result":"success.","ObjectFileName":"%s","SourceFileName":"%s"}', [UpFileDir + '/' + FName, FileName])); end else Response.Send('无效请求数据'); end; end else Response.ErrorRequest(); end; initialization finalization end.
{$MODE OBJFPC} { -*- delphi -*- } {$INCLUDE settings.inc} unit wires; // A mostly rigid string // This is a ShortString/UTF8String hybrid. // It uses a ShortString until you hit 255 characters, at which point it starts using a regular UTF8String. interface uses unicode, utf8; type TWire = record private const kSafeThreshold = High(ShortString) - High(TUTF8SequenceLength) + 1; var FShortString: ShortString; FLongString: UTF8String; function GetAsString(): UTF8String; inline; function GetIsEmpty(): Boolean; inline; public procedure Init(); inline; procedure Append(const Codepoint: TUnicodeCodepoint); inline; property AsString: UTF8String read GetAsString; property IsEmpty: Boolean read GetIsEmpty; end; operator = (const Op1: TWire; const Op2: UTF8String): Boolean; inline; implementation procedure TWire.Init(); begin FShortString := ''; FLongString := ''; end; procedure TWire.Append(const Codepoint: TUnicodeCodepoint); var AsUTF8: TUTF8Sequence; begin AsUTF8 := CodepointToUTF8(CodePoint); if (Length(FShortString) < kSafeThreshold) then begin {$PUSH} {$RANGECHECKS OFF} FShortString := FShortString + AsUTF8.AsString; {$POP} end else begin FLongString := FLongString + AsUTF8.AsString; end; end; function TWire.GetAsString(): UTF8String; begin Result := FShortString + FLongString; end; function TWire.GetIsEmpty(): Boolean; begin Result := FShortString[0] = #0; end; operator = (const Op1: TWire; const Op2: UTF8String): Boolean; inline; begin if (Length(Op2) < Length(Op1.FShortString)) then begin Result := False; end else if (Length(Op1.FShortString) < Op1.kSafeThreshold) then begin Result := Op1.FShortString = Op2; end else begin Result := (Op1.FShortString + Op1.FLongString) = Op2; end; end; end.
{*************************************************} { Базовая форма модального редактора *} {*************************************************} unit ItemEditUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, MaximizedUnit, ComCtrls, ImgList, ToolWin, ExtCtrls, DB, ExtraUnit; type TItemEditFormClass = class of TItemEditForm; TItemEditForm = class(TMaximizedForm) ToolPanel: TPanel; ToolBar: TToolBar; CloseBtn: TToolButton; ToolImages: TImageList; StatusBar: TStatusBar; Panel: TPanel; DataSource: TDataSource; procedure CloseBtnClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); protected FID: integer; FIDFieldName: string; FModified: boolean; procedure SetIDParam(ID: integer); virtual; function CheckBefPost: boolean; virtual; function CommonPost: boolean; virtual; function CommonEditState: boolean; virtual; procedure OtherRefresh; virtual; //обновить дополнительные наборы данных procedure FontChanged; override; public procedure StartAdd; virtual; procedure StartEdit(ID: integer); virtual; property ID: integer read FID; property Modified: boolean read FModified; end; var ItemEditForm: TItemEditForm; implementation {$R *.dfm} procedure TItemEditForm.StartAdd; begin FID := -1; SetIDParam(-1); DataSource.DataSet.Open; DataSource.DataSet.Append; OtherRefresh; end; procedure TItemEditForm.StartEdit(ID: integer); begin FID := ID; SetIDParam(ID); DataSource.DataSet.Open; OtherRefresh; end; procedure TItemEditForm.SetIDParam(ID: integer); begin end; procedure TItemEditForm.OtherRefresh; begin end; function TItemEditForm.CheckBefPost: boolean; begin Result := true; //чтобы можно было не перекрывать эту функцию, а выполнять проверку на BeforePost end; function TItemEditForm.CommonEditState: boolean; begin Result := false; if (DataSource.DataSet.State in dsEditModes) then begin DataSource.DataSet.UpdateRecord; Result := DataSource.DataSet.Modified; end; end; function TItemEditForm.CommonPost: boolean; begin Result := false; if (DataSource.DataSet.State in dsEditModes) then begin DataSource.DataSet.UpdateRecord; if CheckBefPost then begin try DataSource.DataSet.Post; if (FID = -1) then FID := DataSource.DataSet.FindField(FIDFieldName).AsInteger; FModified := true; Result := true; except raise; end; end; end; end; procedure TItemEditForm.CloseBtnClick(Sender: TObject); begin inherited; if CommonEditState then begin if CommonPost then Close; end else begin Close; end; end; procedure TItemEditForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if (Shift = []) then begin if (Key = VK_F2) then begin if CommonEditState then CommonPost; Key := 0; end; end; end; procedure TItemEditForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin inherited; if CommonEditState then begin if MessageDlg('Данные были отредактированы.' + #13#10 + 'Сохранить изменения?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin if CommonPost then CanClose := true else CanClose := false; end; end else CanClose := true; if CanClose then DataSource.DataSet.Close; end; procedure TItemEditForm.FontChanged; begin ToolPanel.Height := 41 + FontHeight(Font); end; end.
unit Names; { ******************************************************************************** ******* XLSReadWriteII V1.14 ******* ******* ******* ******* Copyright(C) 1999,2002 Lars Arvidsson, Axolot Data ******* ******* ******* ******* email: components@axolot.com ******* ******* URL: http://www.axolot.com ******* ******************************************************************************** ** Users of the XLSReadWriteII component must accept the following ** ** disclaimer of warranty: ** ** ** ** XLSReadWriteII is supplied as is. The author disclaims all warranties, ** ** expressed or implied, including, without limitation, the warranties of ** ** merchantability and of fitness for any purpose. The author assumes no ** ** liability for damages, direct or consequential, which may result from the ** ** use of XLSReadWriteII. ** ******************************************************************************** } {$B-} interface uses Classes, SysUtils, Dialogs, XLSUtils, BIFFRecsII, DecodeFormula, EncodeFormulaII, ExcelFuncII, XLSRWIIResourceStrings; const SUPBOOK_CURRFILE = #01#04; type TCustomName = class(TObject) private FNameDef: PByteArray; FNameDefLen: integer; FName: string; FOptions: word; procedure SetName(const Value: string); procedure SetOptions(const Value: word); public constructor Create; destructor Destroy; override; procedure SetNameDef(const Value: PByteArray; Len: integer); property Options: word read FOptions write SetOptions; property Name: string read FName write SetName; property NameDef: PByteArray read FNameDef; property NameDefLen: integer read FNameDefLen; end; type TWorkbookName = class(TCustomName) private FSheetIndex: word; FTabIndex: word; procedure SetSheetIndex(const Value: word); procedure SetTabIndex(const Value: word); public property SheetIndex: word read FSheetIndex write SetSheetIndex; property TabIndex: word read FTabIndex write SetTabIndex; end; type TExternName = class(TCustomName) private public end; type TExternSheet = class(TObject) private FSupBook: word; FFirstTab: word; FLastTab: word; public function Equal(ES: TExternSheet): boolean; property SupBook: word read FSupBook write FSupBook; property FirstTab: word read FFirstTab write FFirstTab; property LastTab: word read FLastTab write FLastTab; end; type TSupBookNameType = (sntUndefined,sntVolume,sntSameVolume,sntDownDir,sntUpDir,sntLongVolume,sntStartupDir,sntAltStartupDir,sntLibDir); type TSupBook = class(TObject) private FFileName: string; FNameType: TSupBookNameType; FSheetNames: TStringList; FExternNames: TList; function GetExternNames(Index: integer): TExternName; function GetExternNamesCount: integer; public constructor Create; destructor Destroy; override; function AddEXTERNNAME(N: TExternName): integer; procedure Clear; property Filename: string read FFilename write FFilename; property NameType: TSupBookNameType read FNameType write FNameType; property SheetNames: TStringList read FSheetNames; property ExternNames[Index: integer]: TExternName read GetExternNames; property ExternNamesCount: integer read GetExternNamesCount; end; type TNameDefs = class(TObject) private FWorkbookNames: TList; FExternSheets: TList; FSupBooks: TList; FExternCount: integer; function DecodeSUPBOOKName(S: string; IsDDE: boolean): string; function GetWorkbookNames(Index: integer): TWorkbookName; function GetWorkbookNamesCount: integer; function GetExternSheets(Index: integer): TExternSheet; function GetExternSheetsCount: integer; function GetSupBooks(Index: integer): TSupBook; function GetSupBooksCount: integer; public constructor Create; destructor Destroy; override; procedure Clear; function GetName(NameType: TNameType; SheetIndex,NameIndex: integer): string; function GetNameId(NameType: TNameType; Name: string): integer; function AddNAME(Options,SheetIndex,TabIndex: word; Name: string; NameDef: PByteArray; Len: integer): integer; procedure AddNAME_PrintColsRows(Index, Col1,Col2,Row1,Row2: integer); function AddEXTERNNAME_Read(Options: word; Name: string; NameDef: PByteArray; Len: integer): integer; function AddEXTERNSHEET(SupBook,FirstTab,LastTab: word; FromFile: boolean): integer; function AddSUPBOOK(Filename: string; SheetNames: TStrings): integer; function FindWorkbookName(WName: string): boolean; property WorkbookNames[Index: integer]: TWorkbookName read GetWorkbookNames; property WorkbookNamesCount: integer read GetWorkbookNamesCount; property ExternSheets[Index: integer]: TExternSheet read GetExternSheets; property ExternSheetsCount: integer read GetExternSheetsCount; property SupBooks[Index: integer]: TSupBook read GetSupBooks; property SupBooksCount: integer read GetSupBooksCount; property ExternCount: integer read FExternCount write FExternCount; end; type TAreaName = class(TCollectionItem) private FNameDef: PByteArray; FNameDefLen: integer; FAreaName: string; FOptions: word; FTabIndex: word; FWorkbookName: TWorkbookName; procedure SetAreaName(const Value: string); function GetNameDef: string; procedure SetNameDef(const Value: string); protected procedure DefineProperties(Filer: TFiler); override; function GetDisplayName: string; override; procedure ReadProp(Reader: TReader); procedure WriteProp(Writer: TWriter); public constructor Create(Collection: TCollection); override; destructor Destroy; override; // ********************************************** // *********** For internal use only. *********** // ********************************************** procedure AddRaw(Def: PByteArray; Len: integer); property AreaNameIgnoreDup: string read FAreaName write FAreaName; property RawNameDef: PByteArray read FNameDef; property NameDefLen: integer read FNameDefLen; property WorkbookName: TWorkbookName read FWorkbookName write FWorkbookName; // ********************************************** // *********** End internal use only. *********** // ********************************************** published property AreaName: string read FAreaName write SetAreaName; property NameDef: string read GetNameDef write SetNameDef stored False; property Options: word read FOptions write FOptions; property TabIndex: word read FTabIndex write FTabIndex; end; type TAreaNames = class(TCollection) private FEncoder: TEncodeFormula; function GetAreaName(Index: integer): TAreaName; protected FOwner: TPersistent; FGetNameMethod: TGetNameEvent; function GetOwner: TPersistent; override; public constructor Create(AOwner: TPersistent; GetNameMethod: TGetNameEvent; Encoder: TEncodeFormula); function Add: TAreaName; procedure AddFunction(Name: string); function FindName(AName: string): TAreaName; function GetNameId(AName: string): integer; property Items[Index: integer]: TAreaName read GetAreaName; default; end; implementation { TNameDefs } function TNameDefs.AddEXTERNNAME_Read(Options: word; Name: string; NameDef: PByteArray; Len: integer): integer; var N: TExternName; begin if FSupBooks.Count <= 0 then raise Exception.Create(ersNoSUPBOOKForEXTERNNAME); N := TExternName.Create; N.Options := Options; N.Name := Name; N.SetNameDef(NameDef,Len); Result := TSupBook(FSupBooks[FSupBooks.Count - 1]).AddEXTERNNAME(N); end; function TNameDefs.AddEXTERNSHEET(SupBook, FirstTab, LastTab: word; FromFile: boolean): integer; var N: TExternSheet; begin N := TExternSheet.Create; N.SupBook := SupBook; N.FirstTab := FirstTab; N.LastTab := LastTab; // A file may contain the same EXTERNSHEET more than once. if not FromFile then begin for Result := 0 to FExternSheets.Count - 1 do begin if TExternSheet(FExternSheets[Result]).Equal(N) then begin N.Free; Exit; end; end; end; FExternSheets.Add(N); Result := FExternSheets.Count - 1; end; function TNameDefs.AddNAME(Options,SheetIndex,TabIndex: word; Name: string; NameDef: PByteArray; Len: integer): integer; var N: TWorkbookName; begin N := TWorkbookName.Create; N.Options := Options; N.SheetIndex := SheetIndex; N.TabIndex := TabIndex; N.Name := Name; N.SetNameDef(NameDef,Len); Result := FWorkbookNames.Add(N); end; function TNameDefs.AddSUPBOOK(Filename: string; SheetNames: TStrings): integer; var SB: TSupBook; begin for Result := 0 to FSupBooks.Count - 1 do begin if (TSupBook(FSupBooks[Result]).SheetNames.Count <= 0) and (TSupBook(FSupBooks[Result]).Filename = Filename) then Exit; end; SB := TSupBook.Create; SB.Filename := Filename; if SheetNames <> Nil then SB.SheetNames.Assign(SheetNames); FSupBooks.Add(SB); Result := FSupBooks.Count - 1; end; procedure TNameDefs.Clear; var i: integer; begin for i := 0 to FWorkbookNames.Count - 1 do TObject(FWorkbookNames[i]).Free; FWorkbookNames.Clear; for i := 0 to FExternSheets.Count - 1 do TObject(FExternSheets[i]).Free; FExternSheets.Clear; for i := 0 to FSupBooks.Count - 1 do TObject(FSupBooks[i]).Free; FSupBooks.Clear; FExternCount := 0; end; constructor TNameDefs.Create; begin FWorkbookNames := TList.Create; FExternSheets := TList.Create; FSupBooks := TList.Create; end; destructor TNameDefs.Destroy; begin Clear; FWorkbookNames.Free; FExternSheets.Free; FSupBooks.Free; inherited; end; function TNameDefs.GetExternSheets(Index: integer): TExternSheet; begin Result := FExternSheets[Index]; end; function TNameDefs.GetExternSheetsCount: integer; begin Result := FExternSheets.Count; end; function TNameDefs.GetSupBooks(Index: integer): TSupBook; begin Result := FSupBooks[Index]; end; function TNameDefs.GetWorkbookNames(Index: integer): TWorkbookName; begin Result := FWorkbookNames[Index]; end; function TNameDefs.GetWorkbookNamesCount: integer; begin Result := FWorkbookNames.Count; end; function TNameDefs.GetSupBooksCount: integer; begin Result := FSupBooks.Count; end; function TNameDefs.GetName(NameType: TNameType; SheetIndex,NameIndex: integer): string; var i,j: integer; begin case NameType of ntName: begin if (SheetIndex >= FExternSheets.Count) or (NameIndex > FWorkbookNames.Count) then Result := '#NAME!' else Result := TWorkbookName(FWorkbookNames[NameIndex - 1]).Name; end; { ntExternName: if Index > FExternNames.Count then Result := '#NAME!' else Result := ExternNames[Index - 1].Name; } ntExternSheet: begin if SheetIndex >= FExternSheets.Count then Result := '#NAME!' else begin i := ExternSheets[SheetIndex].SupBook; j := ExternSheets[SheetIndex].FirstTab; if NameIndex > 0 then begin Dec(NameIndex); if (SupBooks[i].ExternNames[NameIndex].Options and $FFFE) = 0 then // Externname Result := SupBooks[i].ExternNames[NameIndex].Name else if (SupBooks[i].ExternNames[NameIndex].Options and $0010) <> 0 then // OLE Result := '[OLE]' else // DDE Result := DecodeSUPBOOKName(SupBooks[i].Filename,True) + '!''' + SupBooks[i].ExternNames[NameIndex].Name + '''' end else begin Result := SupBooks[i].Filename; if (Result <> '') { and (Result[1] = #1) } then Result := DecodeSUPBOOKName(Result,False); if j <= $00FF then Result := '[' + Result + ']' + SupBooks[i].SheetNames[j] + '!'; end; end; end; end; end; function TNameDefs.DecodeSUPBOOKName(S: string; IsDDE: boolean): string; var i: integer; begin if (S <> '') and (S[1] = #1) then S := Copy(S,2,MAXINT); i := 1; while i <= Length(S) do begin case Ord(S[i]) of 1: begin Result := Result + S[i + 1] + ':\'; Inc(i); end; 2: Result := Result + '\'; 3: if IsDDE then Result := Result + '|' else Result := Result + '\' ; 4: Result := Result + '..\'; 5: Result := Result + ''; 6: Result := Result + ''; 7: Result := Result + ''; 8: Result := Result + ''; else Result := Result + S[i]; end; Inc(i); end; end; function TNameDefs.FindWorkbookName(WName: string): boolean; var i: integer; begin for i := 0 to FWorkbookNames.Count - 1 do begin if AnsiCompareStr(WName,TWorkbookName(FWorkbookNames[i]).Name) = 0 then begin Result := True; Exit; end; end; Result := False; end; // There can only be one of these names per sheet. procedure TNameDefs.AddNAME_PrintColsRows(Index, Col1, Col2, Row1, Row2: integer); type TRowOrColRec8 = packed record opArea: byte; Area: TPTGArea3d8; end; type TRowAndColRec8 = packed record opMemFunc: byte; MemSize: word; opArea1: byte; Area1: TPTGArea3d8; opArea2: byte; Area2: TPTGArea3d8; opUnion: byte; end; var i: integer; RowAndCol8: TRowAndColRec8; RowOrCol8: TRowOrColRec8; begin for i := 0 to FWorkbookNames.Count - 1 do begin with TWorkbookName(FWorkbookNames[i]) do begin if (Options = $0020) and (Length(Name) = 1) and (Name[1] = #$07) and (TabIndex = (Index + 1)) then begin FWorkbookNames.Delete(i); Break; end; end; end; if (Col1 >= 0) and (Col2 >= 0) and (Row1 >= 0) and (Row2 >= 0) then begin RowAndCol8.opMemFunc := ptgMemFunc; RowAndCol8.MemSize := SizeOf(TRowAndColRec8) - 3; RowAndCol8.opArea1 := ptgArea3d; RowAndCol8.Area1.Index := Index; RowAndCol8.Area1.Col1 := Col1 + $C000; RowAndCol8.Area1.Col2 := Col2 + $C000; RowAndCol8.Area1.Row1 := 0; RowAndCol8.Area1.Row2 := 65535; RowAndCol8.opArea2 := ptgArea3d; RowAndCol8.Area2.Index := Index; RowAndCol8.Area2.Col1 := 0 + $C000; RowAndCol8.Area2.Col2 := 255 + $C000; RowAndCol8.Area2.Row1 := Row1; RowAndCol8.Area2.Row2 := Row2; RowAndCol8.opUnion := ptgUnion; AddNAME($0020,0,Index + 1,#07,@RowAndCol8,SizeOf(TRowAndColRec8)); end else if (Col1 >= 0) and (Col2 >= 0) then begin RowOrCol8.opArea := ptgArea3d; RowOrCol8.Area.Index := Index; RowOrCol8.Area.Col1 := Col1 + $C000; RowOrCol8.Area.Col2 := Col2 + $C000; RowOrCol8.Area.Row1 := 0; RowOrCol8.Area.Row2 := 65535; AddNAME($0020,0,Index + 1,#07,@RowOrCol8,SizeOf(TRowOrColRec8)); end else if (Row1 >= 0) and (Row2 >= 0) then begin RowOrCol8.opArea := ptgArea3d; RowOrCol8.Area.Index := Index; RowOrCol8.Area.Col1 := 0 + $C000; RowOrCol8.Area.Col2 := 255 + $C000; RowOrCol8.Area.Row1 := Row1; RowOrCol8.Area.Row2 := Row2; AddNAME($0020,0,Index + 1,#07,@RowOrCol8,SizeOf(TRowOrColRec8)); end; if ((Col1 >= 0) and (Col2 >= 0)) or ((Row1 >= 0) and (Row2 >= 0)) then AddEXTERNSHEET(AddSUPBOOK(SUPBOOK_CURRFILE,Nil),Index,Index,False); end; function TNameDefs.GetNameId(NameType: TNameType; Name: string): integer; begin for Result := 0 to FWorkbookNames.Count - 1 do begin if AnsiLowercase(Name) = AnsiLowercase(TWorkbookName(FWorkbookNames[Result]).Name) then Exit; end; Result := -1; end; { TCustomName } constructor TCustomName.Create; begin end; destructor TCustomName.Destroy; begin FreeMem(FNameDef); inherited; end; procedure TCustomName.SetName(const Value: string); begin FName := Value; end; procedure TCustomName.SetNameDef(const Value: PByteArray; Len: integer); begin FreeMem(FNameDef); GetMem(FNameDef,Len); Move(Value^,FNameDef^,Len); FNameDefLen := Len; end; procedure TCustomName.SetOptions(const Value: word); begin FOptions := Value; end; { TWorkbookName } procedure TWorkbookName.SetSheetIndex(const Value: word); begin FSheetIndex := Value; end; procedure TWorkbookName.SetTabIndex(const Value: word); begin FTabIndex := Value; end; { TSupBook } function TSupBook.AddEXTERNNAME(N: TExternName): integer; begin FExternNames.Add(N); Result := FExternNames.Count - 1; end; procedure TSupBook.Clear; var i: integer; begin for i := 0 to FExternNames.Count - 1 do TObject(FExternNames[i]).Free; FExternNames.Clear; end; constructor TSupBook.Create; begin FSheetNames := TStringList.Create; FExternNames := TList.Create; end; destructor TSupBook.Destroy; begin Clear; FExternNames.Free; FSheetNames.Free; inherited; end; function TSupBook.GetExternNames(Index: integer): TExternName; begin Result := FExternNames[Index]; end; function TSupBook.GetExternNamesCount: integer; begin Result := FExternNames.Count; end; { TExternSheet } function TExternSheet.Equal(ES: TExternSheet): boolean; begin Result := (ES.FSupBook = FSupBook) and (ES.FFirstTab = FFirstTab) and (ES.FLastTab = FLastTab); end; { TAreaName } constructor TAreaName.Create(Collection: TCollection); begin inherited Create(Collection); FAreaName := 'Area' + IntToStr(Id + 1); end; { function TAreaName.Exists(Value: string): boolean; var i: integer; begin Result := False; for i := 0 to Collection.Count - 1 do begin if (Collection.Items[i] <> Self) and (AnsiUppercase(TAreaName(Collection.Items[i]).AreaName) = AnsiUppercase(Value)) then begin Result := True; Exit; end; end; end; } procedure TAreaName.SetAreaName(const Value: string); var i: integer; begin if FOptions = 0 then begin if Value = '' then raise Exception.Create(ersNameIsMissing); for i := 0 to Collection.Count - 1 do begin if (Collection.Items[i] <> Self) and (AnsiUppercase(TAreaName(Collection.Items[i]).AreaName) = AnsiUppercase(Value)) then raise Exception.Create(ersThereIsAllreadyAnAreaNamed + ' "' + Value + '"'); end; end; FAreaName := Value; end; function TAreaName.GetNameDef: string; begin if (FNameDef <> Nil) and (FNameDefLen > 0) then Result := DecodeFmla(xvExcel97,FNameDef,FNameDefLen,0,0,TAreaNames(Collection).FGetNameMethod) else Result := ''; end; procedure TAreaName.SetNameDef(const Value: string); var P: PbyteArray; Sz: integer; begin GetMem(P,512); try Sz := TAreaNames(Collection).FEncoder.Encode(Value,P,512); AddRaw(P,Sz); finally FreeMem(P); end; end; procedure TAreaName.AddRaw(Def: PByteArray; Len: integer); begin FreeMem(FNameDef); FNameDef := Nil; FNameDefLen := Len; GetMem(FNameDef,FNameDefLen); Move(Def^,FNameDef^,FNameDefLen); if FWorkbookName <> Nil then FWorkbookName.SetNameDef(FNameDef,FNameDefLen); end; destructor TAreaName.Destroy; begin FreeMem(FNameDef); FNameDef := Nil; FNameDefLen := 0; inherited; end; function TAreaName.GetDisplayName: string; begin inherited GetDisplayName; Result := 'AreaName ' + IntToStr(ID); end; procedure TAreaName.DefineProperties(Filer: TFiler); begin inherited; Filer.DefineProperty('NameDefinition',ReadProp,WriteProp,True); end; procedure TAreaName.ReadProp(Reader: TReader); var S: string; begin FreeMem(FNameDef); FNameDef := Nil; FNameDefLen := 0; S := Reader.ReadString; FNameDefLen := HexStringToByteArray(S,FNameDef); end; procedure TAreaName.WriteProp(Writer: TWriter); var i: integer; S: string; begin S := ''; for i := 0 to FNameDefLen - 1 do S := S + Format('%.2X',[FNameDef[i]]); Writer.WriteString(S); end; { TAreaNames } function TAreaNames.Add: TAreaName; begin Result := TAreaName(inherited Add); end; procedure TAreaNames.AddFunction(Name: string); begin with Add do begin AreaName := Name; AddRaw(Nil,0); end; end; constructor TAreaNames.Create(AOwner: TPersistent; GetNameMethod: TGetNameEvent; Encoder: TEncodeFormula); begin inherited Create(TAreaName); FEncoder := Encoder; FGetNameMethod := GetNameMethod; FOwner := AOwner; end; function TAreaNames.FindName(AName: string): TAreaName; var i: integer; begin for i := 0 to Count - 1 do begin if AnsiLowercase(AName) = AnsiLowercase(TAreaName(Items[i]).AreaName) then begin Result := TAreaName(Items[i]); Exit; end; end; Result := Nil; end; function TAreaNames.GetAreaName(Index: integer): TAreaName; begin Result := TAreaName(inherited Items[Index]); end; function TAreaNames.GetNameId(AName: string): integer; begin for Result := 0 to Count - 1 do begin if AnsiLowercase(AName) = AnsiLowercase(TAreaName(Items[Result]).AreaName) then Exit; end; Result := -1; end; function TAreaNames.GetOwner: TPersistent; begin Result := FOwner; end; end.
unit uServerClasses; interface uses System.Classes, uModApp, uDBUtils, Rtti, Data.DB, SysUtils, StrUtils, uUser, System.JSON, uJSONUtils, uMR, uPNL, uEconomic; type TServerModAppHelper = class helper for TModApp public procedure CopyFrom(aModApp : TModApp); procedure Reload(LoadObjectList: Boolean = False); end; {$METHODINFO ON} TBaseServerClass = class(TComponent) public procedure AfterExecuteMethod; end; TUser = class(TComponent) public function GetLoginUser(aUserName, aPassword: String): TModUser; end; TCrud = class(TBaseServerClass) private function Retrieve(ModAppClass: TModAppClass; AID: String; LoadObjectList: Boolean = True): TModApp; overload; function ValidateCode(AOBject: TModApp): Boolean; protected function AfterSaveToDB(AObject: TModApp): Boolean; virtual; function BeforeSaveToDB(AObject: TModApp): Boolean; virtual; function StringToClass(ModClassName: string): TModAppClass; public function DeleteFromDB(AObject: TModApp): Boolean; function GenerateCustomNo(aTableName, aFieldName: string; aCountDigit: Integer = 11): String; overload; function GenerateID: String; function GenerateNo(aClassName: string): String; overload; function OpenQuery(S: string): TDataSet; function Retrieve(ModClassName, AID: string): TModApp; overload; function RetrieveByCode(ModClassName, aCode: string): TModApp; overload; function RetrieveJSON(AClassName, AID: String): TJSONObject; function RetrieveSingle(ModClassName, AID: string): TModApp; overload; function SaveToDB(AObject: TModApp): Boolean; function SaveToDBID(AObject: TModApp): String; function SaveToDBJSON(AJSON: TJSONObject): TJSONObject; function SaveToDBLog(AObject: TModApp): Boolean; function TestGenerateSQL(AObject: TModApp): TStrings; end; type TJSONCRUD = class(TBaseServerClass) private FCRUD: TCrud; protected function GetCRUD: TCrud; function StringToClass(ModClassName: string): TModAppClass; property CRUD: TCrud read GetCRUD write FCRUD; public function Retrieve(AClassName, AID: String): TJSONObject; function SaveToDB(AJSON: TJSONObject): TJSONObject; end; TCRUDMR = class(TCrud) public function GetMRByPeriod(AMRGroupID, AUnitID: String; AMonth, AYear: Integer): TModMR; function PrepareMR(AMRGroupID, AUnitID: String; AMonth, AYear: Integer): TJSONObject; end; type TCRUDPNLReport = class(TCrud) private function GetPNLReport(AUnitID: String; AMonth, AYear: Integer): TModPNLReport; function GetPNLSetting(AUnitID: String): TModPNLSetting; public function GetPNLPeriod(AUnitID: String; AMonth, AYear: Integer): TJSONObject; end; type TCRUDPNLSetting = class(TCrud) public function GetPNLSetting(AUnitID: String): TJSONObject; end; TCRUDEconomicSetting = class(TCrud) public function GetEconomicSetting(AUnitID: String): TJSONObject; end; type TCRUDEconomicReport = class(TCrud) private function GetEconomicReport(AUnitID: String; AMonth, AYear: Integer): TModEconomicReport; function GetEconomicSetting(AUnitID: String): TModEconomicSetting; public function GetEconomicPeriod(AUnitID: String; AMonth, AYear: Integer): TJSONObject; end; {$METHODINFO OFF} const CloseSession : Boolean = True; implementation uses System.Generics.Collections, Datasnap.DSSession, Data.DBXPlatform, uUnit, uMRGroupReport; function TUser.GetLoginUser(aUserName, aPassword: String): TModUser; var lCrud: TCrud; lDataset: TDataSet; S: string; sID: string; begin Result := nil; S := 'SELECT * from TUSER ' +' WHERE USERNAME = ' + QuotedStr(aUserName) +' AND PASSWORD = ' + QuotedStr(aPassword); lDataset := TDBUtils.OpenQuery(S); lCrud := TCrud.Create(Self); try if not lDataset.eof then begin sID := lDataset.FieldByname('ID').AsString; Result := lCrud.Retrieve(TModUser.ClassName, sID) as TModUser; end; finally lCrud.Free; lDataset.free; end; end; function TCrud.AfterSaveToDB(AObject: TModApp): Boolean; begin Result := True; end; function TCrud.BeforeSaveToDB(AObject: TModApp): Boolean; begin Result := True; end; function TCrud.DeleteFromDB(AObject: TModApp): Boolean; var lSS: TStrings; begin Result := False; lSS := TDBUtils.GenerateSQLDelete(AObject); Try Try TDBUtils.ExecuteSQL(lSS, False); TDBUtils.Commit; Result := True; except TDBUtils.RollBack; raise; End; Finally lSS.Free; AfterExecuteMethod; End; end; function TCrud.GenerateCustomNo(aTableName, aFieldName: string; aCountDigit: Integer = 11): String; var i: Integer; lNum: Integer; S: string; begin lNum := 0; S := 'select max(' + aFieldName + ') from ' + aTableName; with TDBUtils.OpenQuery(S) do begin Try if not eof then TryStrToInt( RightStr(Fields[0].AsString, aCountDigit), lNum); Finally free; End; end; inc(lNum); Result := IntToStr(lNum); for i := 0 to aCountDigit-1 do Result := '0' + Result; Result := RightStr(Result, aCountDigit); AfterExecuteMethod; end; function TCrud.GenerateID: String; begin Result := TDBUtils.GetNextIDGUIDToString(); end; function TCrud.GenerateNo(aClassName: string): String; var lClass: TModAppClass; lObj: TModApp; begin lClass := Self.StringToClass(aClassName); lObj := lClass.Create; Try Result := Self.GenerateCustomNo(lObj.GetTableName, lObj.GetCodeField, 11); Finally AfterExecuteMethod; lObj.Free; End; end; function TCrud.OpenQuery(S: string): TDataSet; begin Result := TDBUtils.OpenQuery(S); AfterExecuteMethod; end; function TCrud.Retrieve(ModClassName, AID: string): TModApp; var lClass: TModAppClass; begin lClass := Self.StringToClass(ModClassName); If not Assigned(lClass) then Raise Exception.Create('Class ' + ModClassName + ' not found'); Result := Self.Retrieve(lClass, AID); AfterExecuteMethod; end; function TCrud.Retrieve(ModAppClass: TModAppClass; AID: String; LoadObjectList: Boolean = True): TModApp; begin Result := ModAppClass.Create; TDBUtils.LoadFromDB(Result, AID, LoadObjectList); end; function TCrud.RetrieveByCode(ModClassName, aCode: string): TModApp; var lClass: TModAppClass; begin lClass := Self.StringToClass(ModClassName); If not Assigned(lClass) then Raise Exception.Create('Class ' + ModClassName + ' not found'); Result := lClass.Create; if aCode <> '' then TDBUtils.LoadByCode(Result, aCode); AfterExecuteMethod; end; function TCrud.RetrieveJSON(AClassName, AID: String): TJSONObject; var lModApp: TModApp; begin lModApp := Self.Retrieve(AClassName, AID); try Result := TJSONUtils.ModelToJSON(lModApp); finally lModApp.Free; end; end; function TCrud.RetrieveSingle(ModClassName, AID: string): TModApp; var lClass: TModAppClass; begin lClass := Self.StringToClass(ModClassName); If not Assigned(lClass) then Raise Exception.Create('Class ' + ModClassName + ' not found'); Result := Self.Retrieve(lClass, AID, False); AfterExecuteMethod; end; function TCrud.SaveToDB(AObject: TModApp): Boolean; var lSS: TStrings; begin Result := False; if not ValidateCode(AObject) then exit; if not BeforeSaveToDB(AObject) then exit; lSS := TDBUtils.GenerateSQL(AObject); Try Try TDBUtils.ExecuteSQL(lSS, False); if not AfterSaveToDB(AObject) then exit; TDBUtils.Commit; Result := True; except TDBUtils.RollBack; raise; End; Finally // AObject.Free; lSS.Free; AfterExecuteMethod; End; end; function TCrud.SaveToDBID(AObject: TModApp): String; // Result := ''; // If SaveToDB(AObject) then Result := AObject.ID; var lSS: TStrings; begin Result := ''; if not ValidateCode(AObject) then exit; if not BeforeSaveToDB(AObject) then exit; lSS := TDBUtils.GenerateSQL(AObject); Try Try TDBUtils.ExecuteSQL(lSS, False); if not AfterSaveToDB(AObject) then exit; TDBUtils.Commit; Result := AObject.ID; except TDBUtils.RollBack; raise; End; Finally // AObject.Free; lSS.Free; AfterExecuteMethod; End; end; function TCrud.SaveToDBJSON(AJSON: TJSONObject): TJSONObject; var AClassName: string; lClass: TModAppClass; LJSVal: TJSONValue; lModApp: TModApp; begin // LJSVal := AJSON.GetValue('ClassName'); lJSVal := TJSONUtils.GetValue(AJSON, 'ClassName'); if LJSVal = nil then Raise Exception.Create('ClassName can''t be found in JSON Body'); AClassName := LJSVal.Value; lClass := StringToClass(AClassName); lModApp := TJSONUtils.JSONToModel(AJSON, lClass); Self.SaveToDB(lModApp); try Result := TJSONUtils.ModelToJSON(lModApp); finally lModApp.Free; end; end; function TCrud.SaveToDBLog(AObject: TModApp): Boolean; var lSS: TStrings; begin Result := False; if not ValidateCode(AObject) then exit; lSS := TDBUtils.GenerateSQL(AObject); Try Try lSS.SaveToFile(ExtractFilePath(ParamStr(0)) + '\SaveToDB.log'); TDBUtils.ExecuteSQL(lSS, False); TDBUtils.Commit; Result := True; except TDBUtils.RollBack; raise; End; Finally lSS.Free; End; end; function TCrud.StringToClass(ModClassName: string): TModAppClass; var ctx: TRttiContext; typ: TRttiType; list: TArray<TRttiType>; begin Result := nil; ctx := TRttiContext.Create; list := ctx.GetTypes; for typ in list do begin if typ.IsInstance and (EndsText(ModClassName, typ.Name)) then begin Result := TModAppClass(typ.AsInstance.MetaClassType); break; end; end; ctx.Free; end; function TCrud.TestGenerateSQL(AObject: TModApp): TStrings; begin Result := TDBUtils.GenerateSQL(AObject); end; function TCrud.ValidateCode(AOBject: TModApp): Boolean; var S: string; sFilter: string; begin Result := True; if AObject.PropFromAttr(AttributeOfCode, False) = nil then exit; sFilter := AOBject.GetCodeField + ' = ' + QuotedStr(AObject.GetCodeValue); if AOBject.ID <> '' then sFilter := sFilter + ' And ' + AOBject.GetPrimaryField + ' <> ' + QuotedStr(AOBject.ID); S := Format(SQL_Select,['*', AOBject.GetTableName, sFilter]); with TDBUtils.OpenQuery(S) do begin Try Result := EOF; Finally Free; End; end; if not Result then raise Exception.Create(AOBject.GetTableName + '.' + AOBject.GetCodeField + ' : ' + AOBject.GetCodeValue + ' sudah ada di Database' ); end; procedure TBaseServerClass.AfterExecuteMethod; begin if CloseSession then GetInvocationMetaData.CloseSession := True; end; function TJSONCRUD.GetCRUD: TCrud; begin if not Assigned(FCRUD) then FCRUD := TCrud.Create(Self); Result := FCRUD; end; function TJSONCRUD.Retrieve(AClassName, AID: String): TJSONObject; var lModApp: TModApp; begin lModApp := Self.CRUD.Retrieve(AClassName, AID); try Result := TJSONUtils.ModelToJSON(lModApp); finally lModApp.Free; end; end; function TJSONCRUD.SaveToDB(AJSON: TJSONObject): TJSONObject; var AClassName: string; lClass: TModAppClass; LJSVal: TJSONValue; lModApp: TModApp; begin // LJSVal := AJSON.GetValue('ClassName'); lJSVal := TJSONUtils.GetValue(AJSON, 'ClassName'); if LJSVal = nil then Raise Exception.Create('ClassName can''t be found in JSON Body'); AClassName := LJSVal.Value; lClass := StringToClass(AClassName); lModApp := TJSONUtils.JSONToModel(AJSON, lClass); Self.CRUD.SaveToDB(lModApp); try Result := TJSONUtils.ModelToJSON(lModApp); finally lModApp.Free; end; end; function TJSONCRUD.StringToClass(ModClassName: string): TModAppClass; var ctx: TRttiContext; typ: TRttiType; list: TArray<TRttiType>; begin Result := nil; ctx := TRttiContext.Create; list := ctx.GetTypes; for typ in list do begin if typ.IsInstance and (EndsText(ModClassName, typ.Name)) then begin Result := TModAppClass(typ.AsInstance.MetaClassType); break; end; end; ctx.Free; end; function TCRUDMR.GetMRByPeriod(AMRGroupID, AUnitID: String; AMonth, AYear: Integer): TModMR; var lQ: TDataSet; S: string; begin Result := nil; S := 'SELECT * FROM MR A ' +' WHERE BULAN = ' + IntToStr(AMonth) +' AND A.TAHUN = ' + IntToStr(AYear) +' AND GROUPREPORT = ' + QuotedStr(AMRGroupID) +' AND UNITUSAHA = ' + QuotedStr(AUnitID); lQ := TDBUtils.OpenQuery(S); try if not lQ.Eof then Result := Self.Retrieve(TModMR, lQ.FieldByName('ID').AsString) as TModMR; finally lQ.Free; end; end; function TCRUDMR.PrepareMR(AMRGroupID, AUnitID: String; AMonth, AYear: Integer): TJSONObject; var lItem: TModMRItem; lLastYearMR: TModMR; lLYItem: TModMRItem; lMR: TModMR; lQ: TDataSet; S: string; procedure SetReportItem(aMR: TModMR; aItemID: string); var lFound: Boolean; lItem: TModMRItem; begin lFound := False; for lItem in aMR.MRItems do begin if lItem.MRItemReport.ID = aItemID then begin lFound := True; end; end; if not lFound then begin lItem := TModMRItem.Create; lItem.MRItemReport := TModMRItemReport.CreateID(aItemID); aMR.MRItems.Add(lItem); end; end; begin lMR := Self.GetMRByPeriod(AMRGroupID, AUnitID, AMonth, AYear); if lMR = nil then begin lMR := TModMR.Create; lMR.Bulan := AMonth; lMR.Tahun := AYear; lMR.GroupReport := TModMRGroupReport.CreateID(AMRGroupID); lMR.UnitUsaha := TModUnit.CreateID(AUnitID); end; lLastYearMR := Self.GetMRByPeriod(AMRGroupID, AUnitID, AMonth, AYear-1); S := 'select * from TMRItemReport ' + ' where GROUPREPORT = ' + QuotedStr(AMRGroupID) + ' and UNITUSAHA = ' + QuotedStr(AUnitID) + ' order by NAMA '; lQ := TDBUtils.OpenQuery(S); try while not lQ.Eof do begin SetReportItem(lMR, lQ.FieldByName('ID').AsString); lQ.Next; end; //set lastyear & reload mritemreport for lItem in lMR.MRItems do begin if lLastYearMR <> nil then for lLYItem in lLastYearMR.MRItems do begin if lItem.MRItemReport.ID = lLYItem.MRItemReport.ID then begin lItem.LastYear := lLYItem.Actual; end; end; lItem.MRItemReport.Reload; end; Result := TJSONUtils.ModelToJSON(lMR, [], True); finally lQ.Free; end; end; procedure TServerModAppHelper.CopyFrom(aModApp : TModApp); var ctx: TRttiContext; i: Integer; lAppClass: TModAppClass; lNewItem: TModApp; lNewObjList: TObject; lSrcItem: TModApp; lSrcObjList: TObject; meth: TRttiMethod; RttiType: TRttiType; Prop: TRttiProperty; rtItem: TRttiType; sGenericItemClassName: string; value: TValue; function SetPropertyFrom(AProp: TRttiProperty; ASource: TModApp): TModApp; var lSrcObj: TObject; begin Result := nil; lSrcObj := Prop.GetValue(ASource).AsObject; if not prop.PropertyType.AsInstance.MetaclassType.InheritsFrom(TModApp) then exit;; meth := prop.PropertyType.GetMethod('Create'); Result := TModApp(meth.Invoke(prop.PropertyType.AsInstance.MetaclassType, []).AsObject); if lSrcObj <> nil then TModApp(Result).CopyFrom(TModApp(lSrcObj)); end; begin RttiType := ctx.GetType(Self.ClassType); Try for Prop in RttiType.GetProperties do begin if not (Prop.IsReadable and Prop.IsWritable) then continue; // if prop.Visibility <> mvPublished then continue; If prop.PropertyType.TypeKind = tkClass then begin meth := prop.PropertyType.GetMethod('ToArray'); if Assigned(meth) then //object list begin lSrcObjList := prop.GetValue(aModApp).AsObject; lNewObjList := prop.GetValue(Self).AsObject; if lSrcObjList = nil then continue; value := meth.Invoke(prop.GetValue(aModApp), []); Assert(value.IsArray); sGenericItemClassName := StringReplace(lSrcObjList.ClassName, 'TOBJECTLIST<','', [rfIgnoreCase]); sGenericItemClassName := StringReplace(sGenericItemClassName, '>','', [rfIgnoreCase]); rtItem := ctx.FindType(sGenericItemClassName); meth := prop.PropertyType.GetMethod('Add'); if Assigned(meth) and Assigned(rtItem) then begin if not rtItem.AsInstance.MetaclassType.InheritsFrom(TModApp) then continue; lAppClass := TModAppClass( rtItem.AsInstance.MetaclassType ); for i := 0 to value.GetArrayLength - 1 do begin lSrcItem := TModApp(value.GetArrayElement(i).AsObject); lNewItem := lAppClass.Create; lNewItem.CopyFrom(lSrcItem); meth.Invoke(lNewObjList,[lNewItem]); end; end; prop.SetValue(Self, lNewObjList); end else begin prop.SetValue(Self, SetPropertyFrom(prop, aModApp)); end; end else Prop.SetValue(Self, Prop.GetValue(aModApp)); end; except raise; End; end; procedure TServerModAppHelper.Reload(LoadObjectList: Boolean = False); var lCRUD: TCRUD; lModApp: TModApp; begin If Self.ID = '' then exit; lCRUD := TCRUD.Create(nil); try if LoadObjectList then lModApp := lCRUD.Retrieve(Self.ClassName, Self.ID) else lModApp := lCRUD.RetrieveSingle(Self.ClassName, Self.ID); Try Self.CopyFrom(lModApp); Finally lModApp.Free; End; finally FreeAndNil(lCRUD); end; end; function TCRUDPNLReport.GetPNLPeriod(AUnitID: String; AMonth, AYear: Integer): TJSONObject; var LastYearPNL: TModPNLReport; lItem: TModPNLReportItem; lPNLItem: TModPNLReportItem; lPNLReport: TModPNLReport; lPNLSetting: TModPNLSetting; lSettingItem: TModPNLSettingItem; LYItem: TModPNLReportItem; begin lPNLReport := GetPNLReport(AUnitID, AMonth, AYear); Result := nil; if lPNLReport = nil then begin lPNLReport := TModPNLReport.Create; lPNLReport.Bulan := AMonth; lPNLReport.Tahun := AYear; lPNLReport.UnitUsaha := TModUnit.CreateID(AUnitID); end; lPNLSetting := GetPNLSetting(AUnitID); if lPNLSetting = nil then exit; //reload items Try for lSettingItem in lPNLSetting.Items do begin lItem := nil; for lPNLItem in lPNLReport.Items do begin if lPNLItem.PNLSettingItem.ID = lSettingItem.ID then begin lItem := lPNLItem; break; end; end; if lItem = nil then begin lItem := TModPNLReportItem.Create(); lItem.PNLSettingItem := TModPNLSettingItem.CreateID(lSettingItem.ID); lPNLReport.Items.Add(lItem); end; lItem.PNLSettingItem.Reload(); end; Finally lPNLSetting.Free; End; //lastyear LastYearPNL := Self.GetPNLReport(AUnitID, AMonth, AYear-1); if LastYearPNL <> nil then begin Try for LYItem in LastYearPNL.Items do begin for lPNLItem in lPNLReport.Items do begin if lPNLItem.PNLSettingItem.ID = LYItem.PNLSettingItem.ID then begin lPNLItem.LastYear := LYItem.Actual; lPNLItem.LastYearPercent := LYItem.ActualPercent; end; end; end; finally LastYearPNL.free; end; end; Result := TJSONUtils.ModelToJSON(lPNLReport, [], True); end; function TCRUDPNLReport.GetPNLReport(AUnitID: String; AMonth, AYear: Integer): TModPNLReport; var lQ: TDataSet; S: string; begin Result := nil; S := 'SELECT * FROM TPNLREPORT ' +' WHERE BULAN = ' + IntToStr(AMonth) +' AND TAHUN = ' + IntToStr(AYear) +' AND UNITUSAHA = ' + QuotedStr(AUnitID); lQ := TDBUtils.OpenQuery(S); try if not lQ.Eof then begin Result := Self.Retrieve(TModPNLReport, lQ.FieldByName('ID').AsString) as TModPNLReport; end; finally lQ.Free; end; end; function TCRUDPNLReport.GetPNLSetting(AUnitID: String): TModPNLSetting; var lQ: TDataSet; S: string; begin Result := nil; S := 'SELECT * FROM TPNLSetting ' +' WHERE UNITUSAHA = ' + QuotedStr(AUnitID); lQ := TDBUtils.OpenQuery(S); try if not lQ.Eof then Result := Self.Retrieve(TModPNLSetting, lQ.FieldByName('ID').AsString) as TModPNLSetting; finally lQ.Free; end; end; function TCRUDPNLSetting.GetPNLSetting(AUnitID: String): TJSONObject; var lPNLSetting: TModPNLSetting; lQ: TDataSet; S: string; begin Result := nil; S := 'SELECT * FROM TPNLSetting ' +' WHERE UNITUSAHA = ' + QuotedStr(AUnitID); lQ := TDBUtils.OpenQuery(S); try if not lQ.Eof then begin lPNLSetting := Self.Retrieve(TModPNLSetting, lQ.FieldByName('ID').AsString) as TModPNLSetting; Result := TJSONUtils.ModelToJSON(lPNLSetting, [], True); end; finally lQ.Free; end; end; function TCRUDEconomicSetting.GetEconomicSetting(AUnitID: String): TJSONObject; var lEconomicSetting: TModEconomicSetting; lQ: TDataSet; S: string; begin Result := nil; S := 'SELECT * FROM TEconomicSetting WHERE Unitusaha = ' + QuotedStr(AUnitID); lQ := TDBUtils.OpenQuery(S); try if not lQ.Eof then begin lEconomicSetting := Self.Retrieve(TModEconomicSetting, lQ.FieldByName('ID').AsString) as TModEconomicSetting; Result := TJSONUtils.ModelToJSON(lEconomicSetting, [], True); end; finally lQ.Free; end; end; function TCRUDEconomicReport.GetEconomicReport(AUnitID: String; AMonth, AYear: Integer): TModEconomicReport; var lQ: TDataSet; S: string; begin Result := nil; S := 'SELECT * FROM TECONOMICREPORT ' +' WHERE BULAN = ' + IntToStr(AMonth) +' AND TAHUN = ' + IntToStr(AYear) +' AND UNITUSAHA = ' + QuotedStr(AUnitID); lQ := TDBUtils.OpenQuery(S); try if not lQ.Eof then begin Result := Self.Retrieve(TModEconomicReport, lQ.FieldByName('ID').AsString) as TModEconomicReport; end; finally lQ.Free; end; end; function TCRUDEconomicReport.GetEconomicSetting(AUnitID: String): TModEconomicSetting; var lQ: TDataSet; S: string; begin Result := nil; S := 'SELECT * FROM TEconomicSetting ' +' WHERE UNITUSAHA = ' + QuotedStr(AUnitID); lQ := TDBUtils.OpenQuery(S); try if not lQ.Eof then Result := Self.Retrieve(TModEconomicSetting, lQ.FieldByName('ID').AsString) as TModEconomicSetting; finally lQ.Free; end; end; function TCRUDEconomicReport.GetEconomicPeriod(AUnitID: String; AMonth, AYear: Integer): TJSONObject; var lItem: TModEconomicReportItem; lEconomicItem: TModEconomicReportItem; lEconomicReport: TModEconomicReport; lEconomicSetting: TModEconomicSetting; lSettingItem: TModEconomicSettingItem; begin lEconomicReport := GetEconomicReport(AUnitID, AMonth, AYear); Result := nil; if lEconomicReport = nil then begin lEconomicReport := TModEconomicReport.Create; lEconomicReport.Bulan := AMonth; lEconomicReport.Tahun := AYear; lEconomicReport.UnitUsaha := TModUnit.CreateID(AUnitID); end; lEconomicSetting := GetEconomicSetting(AUnitID); if lEconomicSetting = nil then exit; //reload items Try for lSettingItem in lEconomicSetting.Items do begin lItem := nil; for lEconomicItem in lEconomicReport.Items do begin if lEconomicItem.EconomicSettingItem.ID = lSettingItem.ID then begin lItem := lEconomicItem; break; end; end; if lItem = nil then begin lItem := TModEconomicReportItem.Create(); lItem.EconomicSettingItem := TModEconomicSettingItem.CreateID(lSettingItem.ID); lEconomicReport.Items.Add(lItem); end; lItem.EconomicSettingItem.Reload(); end; Finally lEconomicSetting.Free; End; Result := TJSONUtils.ModelToJSON(lEconomicReport, [], True); end; end.
// WinRT.pas // Copyright 1998 BlueWater Systems // // Implementation of the tWinRT class. This class encapsulates some of the // functionality provided by the script commands to the WinRT preprocessor. // unit WinRT; {$H+} { must use huge strings } interface uses Windows, classes, sysutils, WinRTCtl, WinRTDriver, WinRTDimItem; type // the inp and outp methods require as a parameter a set // of tRTFlags. tRTFlags = set of ( rtfword, // the data is 16 bit rtflong, // or the data is 32 bit. // default is 8 bit when none of the above rtfabs, // port or memory address is absolute. Default is relative rtfdirect); // do a direct single call through DeviceIOControl // takes slightly less code but it's slower than // combining several operations in one DeviceIOControl call // type of buffer being passed to processlist tBufferType = ( btProcessBuffer, btWaitInterrupt, btSetInterrupt ); tWinRT = class private fhandle : cardinal; // handle returned by WinRTOpenDevice public constructor create(DeviceNumber : integer; sharing : boolean); destructor destroy; override; Procedure DeclEnd; Procedure inp(const aflags : tRTFlags; portaddr : integer; var addr); Procedure inm(const aflags : tRTFlags; memaddr : pointer; var addr); Procedure outp(const aflags : tRTFlags; portaddr, value : integer); Procedure outm(const aflags : tRTFlags; memaddr : pointer; value : integer); Procedure outpshadow(const aflags : tRTFlags; portaddr : integer; shadow : pointer); Procedure outmshadow(const aflags : tRTFlags; memaddr, shadow : pointer); Procedure Delay(wait : integer); Procedure Stall(wait : integer); Procedure SetEvent(handle : integer); Procedure DMAStart(TransferToDevice : boolean; NumberOfBytes : integer); Procedure DMAFlush; Procedure Trace(BitMask : integer; Str : string); Procedure TraceValue(BitMask : integer; Str : string; Value : integer); Procedure TraceShadow(Bitmask : integer; Str : string; shadow : pointer); Procedure BlockInterruptRoutine; Procedure ReleaseInterruptRoutine; Procedure InterruptSetup; Procedure InterruptService; Procedure InterruptDeferredProcessing; Procedure RejectInterrupt; Procedure ScheduleDeferredProcessing; Procedure StopInterrupts; Function AddItem(command, aport, avalue : integer) : integer; Procedure clear; Procedure ProcessBuffer; Procedure WaitInterrupt; Procedure SetInterrupt; Function SingleCall(command, aport, avalue : integer) : integer; Function Dim(wordsize, wordcount : integer; var data) : pointer; Function DimK(wordsize, value : integer) : pointer; Function DimStr(var S : string; size : integer) : pointer; Function GlobalDim(name:string;wordsize, wordcount : integer; var data) : pointer; Function ExternDim(name:string;wordsize, wordcount : integer; var data) : pointer; Procedure Math(operation : tWINRT_LOGIC_MATH; flags : integer; result, var1, var2 : pointer); Procedure ArrayMove(lvar : pointer; lvarindex : integer; rvar : pointer; rvarindex : integer); Procedure ArraySrcInd(lvar : pointer; lvarindex : integer; rvar, rvarindex : pointer); Procedure ArrayDstInd(lvar, lvarindex : pointer; rvar : pointer; rvarindex : integer); Procedure ArrayBothInd(lvar, lvarindex, rvar, rvarindex : pointer); Procedure _While(amath : tWINRT_LOGIC_MATH; mathflags : integer; var1, var2 : pointer); Procedure _Wend; Procedure _If(amath : tWINRT_LOGIC_MATH; mathflags : integer; var1, var2 : pointer); Procedure _Else; Procedure _Endif; Procedure _Goto(const alabel : string); Procedure _Label(const alabel : string); Procedure assign(dst, src : pointer); Property handle : cardinal read fhandle; private DimList, // list of dimmed variables fList : tlist; // list of WinRT commands buff : pWINRT_CONTROL_array; // a pointer to the array passed to DeviceIOControl whilestack, // a stack of pending _While's. _Wend closes. ifstack : tstack; // a stack of pending _IF's. _Endif closes. fDeviceNo, // WinRT device No. Used in error messages. lasterr, // last error. Read just befor raising an exception buffsize, // size of the buffer being passed to the driver undefgotos : integer; // number of _Goto's with _labels not yet defined fLabelList : tstringlist; // list of labels Function Flags2Ofs(const aflags : tRTFlags; var datasize : integer) : integer; Function Flags2Shf(const aflags : tRTFlags) : integer; Procedure Putdata; Procedure GetData; Procedure Push(value : integer; var stack : tStack); Function Pop(var stack : tStack) : integer; Function GetControlItems(index : integer) : pCONTROL_ITEM_ex; Procedure processlist(command : tBufferType); Procedure AddName(GlobalOrExtern: integer; const name: string); Property ControlItems[index : integer] : pCONTROL_ITEM_ex read GetControlItems; end; { of tWinRT declaration } // *********************************************************** // eWinRTError - exception class for tWinRT errors eWinRTError = class(exception); implementation // tWinRT.create - Open the Device and setup the object // Inputs: DeviceNumber - 0 - n (0 opens device WRTdev0) // sharing - TRUE opens device for sharing // FALSE opens device for exclusive use // Outputs: raises an exception if the device cannot be opened constructor tWinRT.create(DeviceNumber : integer; sharing : boolean); begin fhandle := cardinal(INVALID_HANDLE_VALUE); { get it ready for a possible early exception } inherited create; fDeviceNo := DeviceNumber; // open the device fhandle := WinRTOpenDevice(DeviceNumber, sharing); // make sure we got a valid handle to the device if fhandle = INVALID_HANDLE_VALUE then begin lasterr := GetLastError; raise eWinRTError.createfmt('Can''t open device %d Error %d', [DeviceNumber, lasterr]); end; //initialize the lists flist := tlist.create; DimList := tlist.create; fLabelList := tstringlist.create; with fLabelList do begin sorted := true; duplicates := dupAccept; end; end; { create } // tWinRT.destroy - frees memory and closes the WinRT device // if there is an error it raises eWinRTError showing // the last error destructor tWinRT.destroy; begin clear; flist.free; DimList.free; fLabelList.free; try if (fhandle <> INVALID_HANDLE_VALUE) and not CloseHandle(fhandle) then begin lasterr := GetLastError; raise eWinRTError.createfmt('Error when closing device %d Error %d', [fDeviceNo, Lasterr]); end; finally inherited destroy; end end; { destroy } // tWinRT.DeclEnd - called after all commands. Sets up the buffer passed to the // WinRT driver. // Inputs: none // Outputs: will raise exceptions if there are _While's without _Wend's // or _If's or _Else's without _Endifs's // or _Else's without matching _If's // or _Goto's to an undefined label Procedure tWinRT.DeclEnd; var ii, len, extraitems: integer; // loop counter p: pointer; // temporary place for string pointer begin if WhileStack.sp <> 0 then raise eWinRTError.create('Open _While calls'); if IfStack.sp <> 0 then raise eWinRTError.create('Open _If calls'); if undefgotos <> 0 then raise eWinrtError.create('_Goto''s with undefined labels'); // the labellist is no longer needed. Recover some memory fLabelList.clear; with flist do begin // allocate the buffer buffsize := count * sizeof(tWINRT_CONTROL_item); getmem(buff, buffsize); // fill the buffer with the control items ii := 0; while ii < count do begin buff^[ii] := pWINRT_CONTROL_item(flist[ii])^; with buff^[ii] do begin // replace the Dim Global and extern string pointer with the actual values if (WINRT_COMMAND = WINRT_GLOBAL) or (WINRT_COMMAND = WINRT_EXTERN) then begin // copy the content of the string {$IFDEF WIN32} len := length(string(value)); {$IFEND} extraitems := port; p := pointer(value); system.move(p^, value, len + 1); // decrement string refcount string(p) := ''; port := len; inc(ii, extraitems); end; inc(ii); end; end; end; end; { DeclEnd } // tWinRT.processlist - does the actual processing for ProcessBuffer, // WaitForInterrupt or SetInterrupt // Inputs: command - whether to use ProcessIoBuffer, WaitInterrupt, // or SetInterrupt // Outputs: none Procedure tWinRT.processlist(command : tBufferType); var Length, // length of data return from driver ii : integer; // loop counter begin // exit if there are no commands to send if flist.count = 0 then exit; with flist do begin // copy data from dimmed variables into the buffer putdata; // send the buffer down and wait for an interrupt if command = btWaitInterrupt then begin if not WinRTWaitInterrupt(fhandle, buff^, buffsize, Length) then begin lasterr := GetLastError; raise eWinRTError.createfmt('Error in WinRTWaitInterrupt Device %d Error %d', [fDeviceNo, LastErr]) end end // send the buffer down, set up the interrupt service routine else if command = btSetInterrupt then begin if not WinRTSetInterrupt(fhandle, buff^, buffsize, Length) then begin lasterr := GetLastError; raise eWinRTError.createfmt('Error in WinRTSetInterrupt Device %d Error %d', [fDeviceNo, LastErr]) end end // send the buffer down. else if not WinRTProcessIoBuffer(fhandle, buff^, buffsize, Length) then begin lasterr := GetLastError; raise eWinRTError.createfmt('Error in WinRTProcessBuffer Device %d Error %d', [fDeviceNo, LastErr]); end; // move data from the buffer to the dimmed variables for ii := 0 to count - 1 do with pCONTROL_ITEM_ex(flist[ii])^ do // values in the $0..$7fff range belong to DIM statements if (dsize > 0) and ((value < integer(NOVALUE)) or (value >= $8000)) then system.move(buff^[ii].value, pointer(value)^, dsize); // move data kept in WinRT variables to Pascal variables getdata; end; end; { processlist } // tWinRT.clear - clear all items // You call this function if you want to reuse a tWinRT object. // The handle to the Device remains valid, as the device will remain open. // All memory allocations inside the object are disposed. Procedure tWinRT.clear; var ii : integer; // loop counter begin if flist <> nil then with flist do begin for ii := 0 to count - 1 do begin // cancel the link to the heap dispose(CONTROLITEMs[ii]); end; clear end; if DimList <> nil then with DimList do begin for ii := 0 to count - 1 do tDimItem(items[ii]).free; clear end; if fLabelList <> nil then fLabelList.clear; WhileStack.sp := 0; IfStack.sp := 0; if buff <> nil then begin freemem(buff, buffsize); buff := nil end end; { clear } // tWinRT.inp - request a direct or buffered input from a port. // can be absolute or relative, and byte, word or long size // if the value addr is located under $8000 then it goes to // a shadow variable. // // Inputs // aFlags - can be one or more of // rtfword the data is 16 bit // rtflong or the data is 32 bit. // default is 8 bit when none of the above // rtfabs port address is absolute. Default is relative // rtfdirect do a single direct call through DeviceIOControl // example // [rtfabs, rtfdirect] use absolute addressing and // call direct. Data size is 8 bit // [] data size is 8 bit. Addressing is // relative and add it to the list for // future buffer processing. // the square brackets are needed because it's a pascal set. // // Portaddr - port address, relative. Absolute if rtfdirect set // Addr - reference to the variable that will receive the reading. // if the location of addr is under $8000 it's treated as a shadow. // In this case you must pass the shadow variable as shadowname^. Procedure tWinRT.inp(const aFlags : tRTFlags; Portaddr : integer; var Addr); var Datasize, Result, Command, Varpos : integer; begin Varpos := integer(@Addr); Command := INP_B + Flags2Ofs(aflags, datasize); if rtfdirect in aFlags then begin Result := SingleCall(Command, Portaddr, 0); if rtflong in aFlags then plong(@Addr)^ := result else if rtfword in aFlags then pword(@Addr)^ := Result else pbyte(@Addr)^ := Result; exit; end; if (Varpos >= $10000) or (Varpos < 0) then begin // goes to normal memory Result := AddItem(Command, Portaddr, integer(@Addr)); ControlItems[Result]^.dsize := Datasize; end else begin AddItem(Command, Portaddr, 0); Math(MOVE_TO, 0, @Addr, @Addr, pointer(MATH_MOVE_FROM_VALUE)); end end; { inp } // tWinRT.inm - request a direct or buffered input from physical memory. // can be absolute or relative, and byte, word or long size // if the value addr is located under $8000 then it goes to // a shadow variable. // // Inputs: // aFlags - can be one or more of // rtfword the data is 16 bit // rtflong or the data is 32 bit. // default is 8 bit when none of the above // rtfabs physical memory address is absolute. Default is relative // rtfdirect do a single direct call through DeviceIOControl // example // [rtfabs, rtfdirect] use absolute addressing and // call direct. Data size is 8 bit // [] data size is 8 bit. Addressing is // relative and add it to the list for // future buffer processing. // the square brackets are needed because it's a pascal set. // // Memaddr - physical memory address, relative. Absolute if rtfdirect set // Addr - reference to the variable that will receive the reading. // if the location of addr is under $8000 it's treated as a shadow. // In this case you must pass the shadow variable as shadowname^. Procedure tWinRT.inm(const aFlags : tRTFlags; Memaddr : pointer; var Addr); var Datasize, Result, Command, Varpos : integer; begin Command := INM_B + Flags2Ofs(aFlags, Datasize); if rtfdirect in aFlags then begin Result := SingleCall(Command, integer(Memaddr), 0); if rtflong in aFlags then plong(@Addr)^ := Result else if rtfword in aFlags then pword(@Addr)^ := Result else pbyte(@Addr)^ := Result; exit; end; Varpos := integer(@Addr); if (Varpos >= $10000) or (Varpos < integer(NOVALUE)) then begin // goes to normal memory Result := AddItem(Command, integer(Memaddr), integer(@Addr)); ControlItems[Result]^.dsize := Datasize; end else begin AddItem(Command, integer(Memaddr), 0); Math(MOVE_TO, 0, @Addr, @Addr, pointer(MATH_MOVE_FROM_VALUE)); end end; { inm } // tWinRT.outp - request a direct or buffered output to a port. // can be absolute or relative, and byte, word or long size // use outpshadow instead if you need to pass the value of // a shadow variable // // Inputs // aFlags - can be one or more of // rtfword the data is 16 bit // rtflong or the data is 32 bit. // default is 8 bit when none of the above // rtfabs port address is absolute. Default is relative // rtfdirect do a single direct call through DeviceIOControl // example // [rtfabs, rtfdirect] use absolute addressing and // call direct. Data size is 8 bit // [] data size is 8 bit. Addressing is // relative and add it to the list for // future buffer processing. // the square brackets are needed because it's a pascal set. // // Portaddr - port address, relative. Absolute if rtfdirect set // Value - value to be sent to the port Procedure tWinRT.outp(const aFlags : tRTFlags; Portaddr, Value : integer); var Datasize, Command : integer; begin Command := OUTP_B + Flags2Ofs(aFlags, Datasize); if rtfdirect in aFlags then SingleCall(Command, Portaddr, Value) else Additem(Command, Portaddr, Value) end; { outp } // tWinRT.outm - request a direct or buffered output to physical memory. // can be absolute or relative, and byte, word or long size // use outmshadow instead if you need to pass the value of // a shadow variable // // Inputs // aFlags - can be one or more of // rtfword the data is 16 bit // rtflong or the data is 32 bit. // default is 8 bit when none of the above // rtfabs physical memory address is absolute. Default is relative // rtfdirect do a single direct call through DeviceIOControl // example // [rtfabs, rtfdirect] use absolute addressing and // call direct. Data size is 8 bit // [] data size is 8 bit. Addressing is // relative and add it to the list for // future buffer processing. // the square brackets are needed because it's a pascal set. // // Memaddr - physical memory address, relative. Absolute if rtfdirect set // Value - value to be sent to physical memory Procedure tWinRT.outm(const aFlags : tRTFlags; Memaddr : pointer; Value : integer); var Datasize, Command : integer; begin Command := OUTM_B + Flags2Ofs(aFlags, Datasize); if rtfdirect in aflags then SingleCall(Command, integer(Memaddr), Value) else AddItem(Command, integer(Memaddr), Value) end; { outm } // tWinRT.outpshadow - request a direct or buffered output to a port // from a shadow variable. // can be absolute or relative, and byte, word or long size // // Inputs: // aFlags - can be one or more of // rtfword the data is 16 bit // rtflong or the data is 32 bit. // default is 8 bit when none of the above // rtfabs port address is absolute. Default is relative // rtfdirect no valid // example // [rtfabs, rtfdirect] use absolute addressing and // call direct. Data size is 8 bit // [] data size is 8 bit. Addressing is // relative and add it to the list for // future buffer processing. // the square brackets are needed because it's a pascal set. // // Portaddr - port address, relative. Absolute if rtfdirect set // Shadow - shadow variable holding the value to be sent to the port Procedure tWinRT.outpshadow(const aFlags : tRTFlags; Portaddr : integer; Shadow : pointer); var Datasize : integer; begin Math(MOVE_TO, 0, Shadow, Shadow, pointer(MATH_MOVE_TO_VALUE)); AddItem(OUTP_B + Flags2Ofs(aFlags, Datasize), Portaddr, 0) end; { outp } // tWinRT.outmshadow - request a direct or buffered output to physical // memory from a shadow variable. // can be absolute or relative, and byte, word or long size // // Inputs // aFlags - can be one or more of // rtfword the data is 16 bit // rtflong or the data is 32 bit. // default is 8 bit when none of the above // rtfabs port address is absolute. Default is relative // rtfdirect no valid // example // [rtfabs, rtfdirect] use absolute addressing and // call direct. Data size is 8 bit // [] data size is 8 bit. Addressing is // relative and add it to the list for // future buffer processing. // the square brackets are needed because it's a pascal set. // // Memaddr - physical memory address, relative. Absolute if rtfdirect set // Shadow - shadow variable holding the value to be sent to the port Procedure tWinRT.outmshadow(const aFlags : tRTFlags; Memaddr, Shadow : pointer); var Datasize : integer; begin Math(MOVE_TO, 0, Shadow, Shadow, pointer(MATH_MOVE_TO_VALUE)); additem(OUTM_B + Flags2Ofs(aFlags, Datasize), integer(Memaddr), 0) end; { outm } // tWinRT.Delay - allows timing delays between I/O commands. Delay is // implemented as a thread delay, and is used for relatively long // delays. Its accuracy is machine dependent and typically 10 or 15 // milliseconds on an Intel machine running Windows NT. This function // cannot by used during interrupt processing // Inputs: wait - wait time in milliseconds // Outputs: none Procedure tWinRT.Delay(wait : integer); begin AddItem(_DELAY, 0, wait); end; { Delay } // tWinRT.Stall - allows brief timing delays between I/O commands. Stall is // implemented as a spin loop type delay and is used for short delays. // Its accuracy is dependent on driver set up time. This function does // not allow other threads to operate during its delay and should // therefore be used as sparingly as possible. Setting stall times // greater than 50 microseconds can have very detrimental effects // to the system. // Inputs: wait - wait time in microseconds // Outputs: none Procedure tWinRT.Stall(wait : integer); begin AddItem(_STALL, 0, wait); end; // tWinRT.SetEvent - sets the state of a Win32 event to signaled. // Inputs: handle - handle to driver accessible event returned // from WinRTCreateEvent // Outputs: none Procedure tWinRT.SetEvent(handle : integer); begin AddItem(SET_EVENT, handle, 0); end; // tWinRT.DMAStart - Starts a DMA operation on a slave DMA device. This // command is not necessary for bus master DMA transfers. For slave // DMA devices, this command must be the last item in the list. // Inputs: TransferToDevice - true to transfer data from the host to the device // NumberOfBytes - number of bytes to transfer with this request. // This value MUST be less than or equal to the // size of the common buffer. // Outputs: none Procedure tWinRT.DMAStart(TransferToDevice : boolean; NumberOfBytes : integer); begin AddItem(DMA_START, integer(TransferToDevice), NumberOfBytes); end; // tWinRT.DMAFlush - Flushes the DMA buffers // Inputs: none // Outputs: none Procedure tWinRT.DMAFlush; begin AddItem(DMA_FLUSH, 0, 0); end; // tWinRT.Trace - used to places messages into the driver's internal debug // buffer, which can then be retrieved using the Debug Trace option // of the WinRT Console. // Inputs: BitMask - trace selection bitmask (16 bits). This value is // logically ANDed with the internally stored bitmask, // and if the result is non-zero, the trace message is placed // into the debug buffer. Otherwise, the message is discarded. // Str - the string to trace // Outputs: none Procedure tWinRT.Trace(BitMask : integer; Str : string); var Param1, Param2, Param3, ii : integer; Count : Double; Token : array[0..3] of ANSIchar; begin // add the trace command to the command list AddItem(WINRT_TRACE, 0, BitMask shl 16 or Length(Str)); Count := Length(Str); ii := 0; // add the string to trace to the command list while ii < Count do begin StrLCopy(PANSIChar(@Token[0]), PANSIChar(@Str[1+ii]), 4); Param1 := byte(Token[0]) or (byte(Token[1]) shl 8) or (byte(Token[2]) shl 16) or (byte(Token[3]) shl 24) ; Param1 := integer(Token); ii := ii + 4; if ii >= Count then begin AddItem(Param1, 0, 0); exit; end; StrLCopy(PANSIChar(@Token[0]), PANSIChar(@Str[1+ii]), 4); Param2 := byte(Token[0]) or (byte(Token[1]) shl 8) or (byte(Token[2]) shl 16) or (byte(Token[3]) shl 24) ; ii := ii + 4; if ii >= Count then begin AddItem(Param1, Param2, 0); exit; end; StrLCopy(PANSIChar(@Token[0]), PANSIChar(@Str[1+ii]), 4); Param3 := byte(Token[0]) or (byte(Token[1]) shl 8) or (byte(Token[2]) shl 16) or (byte(Token[3]) shl 24) ; ii := ii + 4; AddItem(Param1, Param2, Param3); end; end; // tWinRT.TraceValue - used to places messages into the driver's internal debug // buffer, which can then be retrieved using the Debug Trace option // of the WinRT Console. // Inputs: BitMask - trace selection bitmask (16 bits). This value is // logically ANDed with the internally stored bitmask, // and if the result is non-zero, the trace message is placed // into the debug buffer. Otherwise, the message is discarded. // Str - the string to trace // Value - number to be traced // Outputs: none Procedure tWinRT.TraceValue(BitMask : integer; Str : string; Value : integer); var Param1, Param2, Param3, ii : integer; Count : Double; Token : array[0..3] of ANSIchar; temp_const : pointer; begin // add the value to the command list temp_const := DimK(4, Value); ii := integer(MOVE_TO); AddItem(WinRTctl.MATH, ii shl 16 or integer(temp_const), integer(temp_const) shl 16 or DIMENSION_CONSTANT); // add the trace command to the command list AddItem(WINRT_TRACE, 0, BitMask shl 16 or Length(Str)); Count := Length(Str); ii := 0; // add the string to the command list while ii < Count do begin StrLCopy(PAnsiChar(@Token[0]), PAnsiChar(@Str[1+ii]), 4); Param1 := byte(Token[0]) or (byte(Token[1]) shl 8) or (byte(Token[2]) shl 16) or (byte(Token[3]) shl 24) ; ii := ii + 4; if ii >= Count then begin AddItem(Param1, 0, 0); exit; end; StrLCopy(PAnsiChar(@Token[0]), PAnsiChar(@Str[1+ii]), 4); Param2 := byte(Token[0]) or (byte(Token[1]) shl 8) or (byte(Token[2]) shl 16) or (byte(Token[3]) shl 24) ; ii := ii + 4; if ii >= Count then begin AddItem(Param1, Param2, 0); exit; end; StrLCopy(PAnsiChar(@Token[0]), PAnsiChar(@Str[1+ii]), 4); Param3 := byte(Token[0]) or (byte(Token[1]) shl 8) or (byte(Token[2]) shl 16) or (byte(Token[3]) shl 24) ; ii := ii + 4; AddItem(Param1, Param2, Param3); end; end; // tWinRT.TraceShadow - used to places messages into the driver's internal debug // buffer, which can then be retrieved using the Debug Trace option // of the WinRT Console. // Inputs: BitMask - trace selection bitmask (16 bits). This value is // logically ANDed with the internally stored bitmask, // and if the result is non-zero, the trace message is placed // into the debug buffer. Otherwise, the message is discarded. // Str - the string to trace // Shadow - shadow variable to be traced. // Outputs: none Procedure tWinRT.TraceShadow(Bitmask : integer; Str : string; Shadow : pointer); var Param1, Param2, Param3, ii : integer; Count : Double; Token : array[0..3] of char; begin // add the value to trace to the command list ii := integer(MOVE_TO); AddItem(WinRTctl.MATH, ii shl 16 or integer(Shadow), integer(Shadow) shl 16 or DIMENSION_CONSTANT); // add the trace command to the command list AddItem(WINRT_TRACE, integer(Shadow), BitMask shl 16 or Length(Str)); Count := Length(Str); ii := 0; // add the string to the command list while ii < Count do begin StrLCopy(PAnsiChar(@Token[0]), PAnsiChar(@Str[1+ii]), 4); Param1 := byte(Token[0]) or (byte(Token[1]) shl 8) or (byte(Token[2]) shl 16) or (byte(Token[3]) shl 24) ; ii := ii + 4; if ii >= Count then begin AddItem(Param1, 0, 0); exit; end; StrLCopy(PAnsiChar(@Token[0]), PAnsiChar(@Str[1+ii]), 4); Param2 := byte(Token[0]) or (byte(Token[1]) shl 8) or (byte(Token[2]) shl 16) or (byte(Token[3]) shl 24) ; ii := ii + 4; if ii >= Count then begin AddItem(Param1, Param2, 0); exit; end; StrLCopy(PAnsiChar(@Token[0]), PAnsiChar(@Str[1+ii]), 4); Param3 := byte(Token[0]) or (byte(Token[1]) shl 8) or (byte(Token[2]) shl 16) or (byte(Token[3]) shl 24) ; ii := ii + 4; AddItem(Param1, Param2, Param3); end; end; // tWinRT.BlockInterruptRoutine - Used to prevent the interrupt service routine // from interrupting a block of WinRT code. Any code in a block and release // section will not be interrupt by the interrupt service rotine. BlockInterruptRoutine // is not the same as CLI operation, as some other interrupts in the system // may still occur. Some (but not necessarily all) of the systm's interrupts // are blocked during a BlockInterruptRoutine block, so this command should be // used sparingly or it will have a detrimental impact on system performance. // This command is not valid in interrupt service routine blocks, but is valid // in deferred processing blocks. Procedure tWinRT.BlockInterruptRoutine; begin AddItem(WINRT_BLOCK_ISR, 0, 0); end; // tWinRT.ReleaseInterruptRoutine - Used following a BlockInterruptRoutine command // to allow the interrupt service routine to execute. ANy code in a block // and release section will not be interrupted by the interrupt service routine. // ReleaseInterruptRoutine is not the same as a STI operation. This command is // not valid in interrupt service blocks, but is valid in deferred processing blocks. Procedure tWinRT.ReleaseInterruptRoutine; begin AddItem(WINRT_RELEASE_ISR, 0, 0); end; // tWinRT.Interruptsetup - Used to process commands that will enable the // hardware device to interrupt. The driver first established the // interrupt service routine, then executes this block of code. // Commands in the buffer between this call and the InterruptService call // will be executed only once when the call to the driver is made. // // Must be located in a buffer with InterruptService and // InterruptDeferredProcessing. Must come before InterruptService and // InterruptDeferredProcessing. // Inputs: none // Outputs: none Procedure tWinRT.InterruptSetup; begin AddItem(ISR_SETUP, 0, 0); end; // tWinRT.InterruptService - Used to process commands at interrupt time. // The driver first establishes this code as the interrupt service routine. // Then it excutes the InterruptSetup block of code. Commands within // the interrupt service block will be executed each time an interrupt // occurs until a StopInterrupts command is encountered. // // Must be located in a buffer with InterruptSetup and InterruptDeferredProcessing. // Must be located between InterruptSetup and InterruptDeferredProcessing. // Delay, DMAStart and SetEvent are not allowed in the InterruptService block. // Inputs: none // Outputs: none Procedure tWinRT.InterruptService; begin AddItem(BEGIN_ISR, 0, 0); end; // tWinRT.InterruptDeferredProcessing - Used to process commands after an interrupt // occurs. The code in this block is executed after an interrupt occurs, // in response to one or more ScheduleDeferredProcessing commands. // Inputs: none // Outputs: none Procedure tWinRT.InterruptDeferredProcessing; begin AddItem(BEGIN_DPC, 0, 0); end; // tWinRT.RejectInterrupt - Used to indicate to the OS that the interrupt // that occurred did not belong to the device and exit from the interrupt // service routine. This command is necessary when using WinRT with a // PCI device that has interrupts. // Inputs: none // Outputs: none Procedure tWinRT.RejectInterrupt; begin AddItem(REJECT_INTERRUPT, 0, 0); end; // tWinRT.ScheduleDeferredProcessing - Indicates that the InterruptDeferredProcessing // block should be run when the interrupt service routine exits. // ScheduleDeferredProcessing must be called from the InterruptService // block and may be called once or more in the block. Multiple // InterruptService blocks may be executed before a single // InterruptDeferredProcessing finishes executing. // Input: none // Output: none Procedure tWinRT.ScheduleDeferredProcessing; begin AddItem(SCHEDULE_DPC, 0, 0); end; // tWinRT.StopInterrupts - Indicates that the InterruptService should no longer // be called when an interrupt occurs. The application must program // the device to disable the device from generating interruptsbefore the // application calls this command. Procedure tWinRT.StopInterrupts; begin AddItem(STOP_INTERRUPT, 0, 0); end; // tWinRT.AddItem - Add a control item to the list for buffered processing. // This low level method allows you to create entries in the // list that are not otherwise supported. // There is seldom need to call this method, as other higher // level methods are generally more suitable. // Inputs // Command The value that will go to WINRT_COMMAND // aPort The value that will go to port // aValue The value that will go to value in the tWINRT_CONTROL_ITEM // record // Outputs return the position of the item in the list Function tWinRT.AddItem(Command, aPort, aValue : integer) : integer; var iTemp : pCONTROL_ITEM_ex; begin new(iTemp); with iTemp^ do begin WINRT_COMMAND := command; port := aPort; value := aValue; dsize := 0; // used only to store data to pascal memory end; Result := flist.add(iTemp); end; { AddItem } // tWinRT.ProcessBuffer - Using the list already prepared, do the actual // processing. After a list has been prepared and completed with a call // to DeclEnd, ProcessBuffer can be called one or more times to // achieve the results programmed into the list. // ProcessBuffer does its work by calling processlist, // which then calls DeviceIOControl to communicate with the driver. // // Inputs: none // Outputs: none Procedure tWinRT.ProcessBuffer; begin ProcessList(btProcessBuffer) end; { ProcessBuffer } // tWinRT.WaitInterrupt - Using the list already prepared, do the actual // processing for a WaitInterrupt. // After a list has been prepared and completed with a call to // DeclEnd, WaitInterrupt can be called one or more times to // achieve the results programmed into the list // WaitInterrupt does its work by calling processlist // which then calls DeviceIOControl to communicate with the driver. // // The list previously supplied must have an InterruptSetup, // InterruptService, and InterruptDeferredProcessing. // // Inputs none // Outputs none Procedure tWinRT.WaitInterrupt; begin ProcessList(btWaitInterrupt) end; { WaitInterrupt } // tWinRT.SetInterrupt - Using the list already prepared, do the actual // processing for a SetInterrupt. // After a list has been prepared and completed with a call to // DeclEnd, SetInterrupt can be called to setup an ISR. // // The list previously supplied must have an InterruptSetup, // InterruptService, and InterruptDeferredProcessing. // // Inputs none // Outputs none Procedure tWinRT.SetInterrupt; begin ProcessList(btSetInterrupt) end; { SetInterrupt } // tWinRT.SingleCall - Perform an unbuffered call to the WinRT driver, // and Return value. Command is not checked. // Inputs // command The value that will go to WINRT_COMMAND // aport The value that will go to port // avalue The value that will go to value in the tWINRT_CONTROL_ITEM // record // Outputs returns whatever was stored in tWINRT_CONTROL_ITEM.value Function tWinRT.SingleCall(Command, aPort, aValue : integer) : integer; var Item : tWINRT_CONTROL_ITEM; Length : integer; begin with item do begin WINRT_COMMAND := Command; port := aPort; value := aValue; end; if not WinRTProcessIoBuffer(fhandle, pWINRT_CONTROL_array(@Item)^, sizeof(Item), Length) then begin LastErr := GetLastError; raise eWinRTError.createfmt('Error in WinRT SingleCall Device %d Error %d', [fDeviceNo, LastErr]); end; Result := Item.value; { return value to caller } end; { SingleCall } // tWinRT.Dim - dimensions a shadow variable or array. Returns a pseudo pointer // Inputs: // wordsize: 1 for byte or char, 2 for word, 4 for integer/longint // wordcount: 1 if single item, or the range if an array // data: a reference (not a pointer) to the Pascal variable shadows // Outputs: returns a pseudo pointer to the shadow variable created. This is // not a valid pascal pointer and should not be used as such Function tWinRT.Dim(wordsize, wordcount : integer; var data) : pointer; var i, flags, extrabytes, extraitems : integer; Dimitem : tDimItem; begin extrabytes := wordsize * wordcount - sizeof(longint); if extrabytes > 0 then extraitems := (extrabytes + sizeof(tWINRT_CONTROL_ITEM) - 1) div sizeof(tWINRT_CONTROL_ITEM) else extraitems := 0; if wordcount < 1 then wordcount := 1; if wordcount = 1 then flags := 0 else flags := DIMENSION_ARRAY; i := additem(WinRTCtl.DIM, (flags + wordsize) shl 16 + wordcount, 0); result := pointer(i); for i := 1 to extraitems do additem(NOP, 0, 0); // create an entry in the Dim list DimItem := tDimItem.create(result, data, WordSIze * WordCount); DimList.add(DimItem); end; { Dim } // tWinRT.DimStr - Declare a shadow variable to a huge string // This function is needed due to the special // way huge strings are processed in Delphi 2 // Inputs // S: The pascal huge string being shadowed // size: The maximum allowed size for S. Should include space // for an extra eos character which is #0, like an ASCIZ string // Sorry, no dynamic allocation possible here. // name: the name of the pascal variable shadowed. // Used in debug mode to list the shadow variable in the file Debug.fil // bConst: Is the string a constant, rather than a variable. // Outputs: returns a pseudo pointer to the shadow variable created. This is // not a valid pascal pointer and should not be used as such Function tWinRT.DimStr(var S : string; size : integer) : pointer; var index, extrabytes, extraitems : integer; DimStritem : tDimStrItem; begin extrabytes := size - sizeof(longint); if extrabytes > 0 then extraitems := (extrabytes + sizeof(tWINRT_CONTROL_ITEM) - 1) div sizeof(tWINRT_CONTROL_ITEM) else extraitems := 0; index := additem(WinRTCtl.DIM, (DIMENSION_ARRAY + 1) shl 16 + size, 0); result := pointer(index); for index := 1 to extraitems do additem(NOP, 0, 0); // create an entry in the Dim list DimStrItem := tDimStrItem.create(result, S, Size); DimList.add(DimStrItem); end; { DimStr } // tWinRT.DimK - Create a shadow helper constant. // Because it's a constant it actually does not // shadow any Pascal variable, but it's used // in math operations with other shadow variables } // Inputs: wordsize: 1 for byte or char, 2 for word, 4 for integer/longint // value: the value to assign to the constant Function tWinRT.DimK(wordsize, value : integer) : pointer; var index : integer; begin if (wordsize = 4) or (wordsize = 2) or (wordsize = 1) then index := additem(WinRTCtl.DIM, (DIMENSION_CONSTANT + wordsize) shl 16 + 1, Value) else raise eWinRTError.create('Invalid word size in constant creation'); result := pointer(index); end; { DimK } // tWinRT.Flags2Ofs - converts flag options for size and // absolute/relative to offsets to command value // Inputs: aFlags - flags to convert // Datasize - size of the data // Outputs: offset for command value Function tWinRT.Flags2Ofs(const aFlags : tRTFlags; var Datasize : integer) : integer; begin Result := Flags2Shf(aFlags); // get the size in bytes Datasize := 1 shl Result; if rtfabs in aFlags then inc(Result, 6) end; { Flags2Ofs } // tWinRT.Flags2Shf - converts flag options for size to offsets to command value // Inputs: aFlags - flags to convert // Outputs: offset for command value. // returns 0 for byte, 1 for word, 2 for long } Function tWinRT.Flags2Shf(const aflags : tRTFlags) : integer; begin // if rtfword and rtflong are set, rtfword takes precedence if rtfword in aflags then result := 1 else if rtflong in aflags then result := 2 else result := 0; end; { Flags2Shf } // tWinRT.Putdata - iterates over the Dim items and puts the data into the buff^ array // Inputs: none // Outputs: none Procedure tWinRT.Putdata; var i : integer; begin With Dimlist do For i := 0 to count - 1 do tDimItem(items[i]).put(buff^) end; { Putdata } // tWinRT.Getdata - iterates over the Dim items and gets the data from the buff^ array // Inputs: none // Outputs: none Procedure tWinRT.GetData; var i : integer; begin With Dimlist do For i := 0 to count - 1 do tDimItem(items[i]).get(buff^) end; { GetData } // tWinRT.Push - Helper function for while loops, and if statements. // Pushes value onto the whilestack and preincrements WhileStackPointer. // Inputs: Value - value to push onto the stack // Stack - the stack to push the value onto // Outputs: none Procedure tWinRT.Push(Value : integer; var Stack : tStack); begin with Stack do begin inc(sp); if sp > high(data) then raise eWinRTError.create('WinRT Declaration Stack overflow'); data[sp] := Value; end end; { WhilePush } // tWinRT.Pop - Helper function for while loops and if statements. // Pops value off the whilestack and decrements WhileStackPointer. // Inputs: Stack - the stack to pop from // Outputs: the value popped from the stack Function tWinRT.Pop(var Stack : tStack) : integer; begin with Stack do begin if sp < low(data) then raise eWinRTError.create('WinRT Declaration Stack underflow'); Result := data[sp]; dec(sp); end end; { WhilePop } // tWinRT._While - insert a _While statement in the list. All the list elements // will be processed later when the methods ProcessBuffer, // WaitInterrupt or SetInterrupt are called // // Inputs: // aMath The logical or bitwise command to be performed. It's listed in // the file WinRTCtl as an enumeration type tWINRT_LOGIC_MATH // Mathflags Optional flags that modify the operation. Also listed // in the interface section of file WinRTCtl // meaningful flags are LOGICAL_NOT_FLAG and MATH_SIGNED // Var1, Var2 pseudo pointers to the first and second operand. These // are pseudo pointers to dimmed variables // Outputs: none // // The _while statement continues until the next matching _Wend Procedure tWinRT._While(amath : tWINRT_LOGIC_MATH; mathflags : integer; var1, var2 : pointer); begin Push(additem(WinRTCtl._While, (ord(amath) or mathflags) shl 16, integer(var1) shl 16 + integer(var2)), WhileStack); end; { _While } // tWinRT._Wend - Inserts the statement that ends the _While. // An exception will be raised if there is no pending _While. // Inputs: none // Outputs: none Procedure tWinRT._Wend; var lastwhile : integer; whilep : pCONTROL_ITEM_ex; begin try lastwhile := Pop(WhileStack); except on eWinRTError do raise eWinRTError.create('A _Wend call without a corresponding _While'); end; // code the looping jump AddItem(JUMP_TO, lastwhile - flist.count, 0); whilep := flist[lastwhile]; with whilep^ do // store the while jump offset past the JUMP_TO port := port or (flist.count - lastwhile) end; { _Wend } // tWinRT._IF - insert an _IF statement in the list. All the list elements // will be processed later when the methods ProcessBuffer, // WaitInterrupt or SetInterrupt are called // // Inputs: // aMath The logical or bitwise command to be performed. It's listed in // the file WinRTCtl as an enumeration type tWINRT_LOGIC_MATH // Mathflags Optional flags that modify the operation. Also listed // in the interface section of file WinRTCtl // meaningful flags are LOGICAL_NOT_FLAG and MATH_SIGNED // Var1, Var2 pseudo pointers to the first and second operand // Outputs: none // // The _IF statement continues until the next matching _Else or _Endif Procedure tWinRT._If(aMath : tWINRT_LOGIC_MATH; Mathflags : integer; Var1, Var2 : pointer); begin Push(additem(LOGICAL_IF, (ord(aMath) or Mathflags) shl 16, integer(Var1) shl 16 + integer(Var2)), IfStack); end; { _If } // tWinRT._Else - Insert the statement that starts the code that will perform // if the _If condition does not succeed. // An exception will be raised if there is no pending _IF // Inputs: none // Outputs: none Procedure tWinRT._Else; var lastif : integer; ifp : pCONTROL_ITEM_ex; begin try lastif := Pop(IfStack); if lastif < 0 then raise eWinRTError.create(''); except on eWinRTError do raise eWinRTError.create('An _Else call without an _If'); end; // or it with $80000000 to flag it as an else Push(AddItem(JUMP_TO, 0, 0) or integer($80000000), ifstack); ifp := flist[lastif]; with ifp^ do port := port or (flist.count - lastif); end; { _Else } // tWinRT._Endif - Insert the statement that starts the code that will finish // the _If or _Else section // An exception will be raised if there is no pending _IF or _Else // Inputs: none // Outputs: none Procedure tWinRT._Endif; var LastIfElse : integer; Jumpp : pCONTROL_ITEM_ex; begin try LastIfElse := Pop(IfStack) and $7fffffff; { get the last _if or _else } except On eWinRTError do raise eWinRTError.create('An _Endif without a matching _If or _Else'); end; Jumpp := flist[LastIfElse]; { get the control item pointer } with Jumpp^ do port := port or (flist.count - LastIfElse); { fix the jump offset } end; { _Endif } // tWinRT.Math - insert a math item in the list. All the list elements // will be processed later when the methods ProcessBuffer, // WaitInterrupt or SetInterrupt are called. // // Inputs: // operation The math command to be performed. It's listed in // the file WinRTCtl as an enumeration type tWINRT_LOGIC_MATH // flags Optional flags that modify the operation. Also listed // in the interface section of file WinRTCtl // result pseudo pointer to the shadow variable that will receive the // result // var1, var2 pseudo pointers to the first and second operand // // Outputs: none Procedure tWinRT.Math(Operation : tWINRT_LOGIC_MATH; Flags : integer; Result, Var1, Var2 : pointer); begin AddItem(WinRTctl.MATH, (integer(Operation) + Flags) shl 16 + integer(Result), integer(Var1) shl 16 + integer(Var2)); end; { Math } // tWinRT.ArrayMove - move a value from a shadow array entry to another. // Either the source or the destination can be a non-array // shadow variable, in which case use an index of 0 // // Inputs // lvar: left side (destination) array pseudo pointer // lvarindex: destination index. Use 0 if not an array // rvar: right side (source) array pseudo pointer // lvarindex: source index. Use 0 if not an array Procedure tWinRT.ArrayMove(lvar : pointer; lvarindex : integer; rvar : pointer; rvarindex : integer); begin AddItem(ARRAY_MOVE, integer(lvar) + lvarindex shl 16, integer(rvar) + rvarindex shl 16) end; { ArrayMove } // tWinRT.ArraySrcInd - move a value from a shadow array entry to another. // The source index is indirect // The index in the source is actually another shadow // variable as in // lvar[lvarindex] := rvar[shadow variable] // The destination can be a non-array // shadow variable, in which case use an index of 0 // // Inputs // lvar: left side (destination) array pseudo pointer // lvarindex: destination index. Use 0 if not an array // rvar: right side (source) array pseudo pointer // rvarindex: source index shadow variable pseudo pointer. // This is an indirect index Procedure tWinRT.ArraySrcInd(lvar : pointer; lvarindex : integer; rvar, rvarindex : pointer); begin ArrayMove(lvar, lvarindex, rvar, integer(rvarindex) + ARRAY_MOVE_INDIRECT); end; { ArraySrcInd } // tWinRT.ArrayDstInd - move a value from a shadow array entry to another. // The destination index is indirect // The index in the destination is actually another shadow // variable as in // lvar[shadow variable] := rvar[rvarindex] // The source can be a non-array // shadow variable, in which case use an index of 0 // // Inputs // lvar: left side (destination) array pseudo pointer // lvarindex: destination index shadow variable pseudo pointer. // This is an indirect index // rvar: right side (source) array pseudo pointer // rvarindex: source index. Use 0 if not an array Procedure tWinRT.ArrayDstInd(lvar, lvarindex : pointer; rvar : pointer; rvarindex : integer); begin ArrayMove(lvar, integer(lvarindex) + ARRAY_MOVE_INDIRECT, rvar, rvarindex) end; { ArrayDstInd } // tWinRT.ArrayBothInd - move a value from a shadow array entry to another. // The destination and source indices are indirect // They are shadow variables as in // lvar[shadow variable] := rvar[shadow variable] // // Inputs // lvar: left side (destination) array pseudo pointer // lvarindex: destination index shadow variable pseudo pointer. // This is an indirect index // rvar: right side (source) array pseudo pointer // rvarindex: source index shadow variable pseudo pointer. // This is an indirect index Procedure tWinRT.ArrayBothInd(lvar, lvarindex, rvar, rvarindex : pointer); begin ArrayMove(lvar, integer(lvarindex) + ARRAY_MOVE_INDIRECT, rvar, integer(rvarindex) + ARRAY_MOVE_INDIRECT) end; { ArrayBothInd } // tWinRT._Goto - Yes, there is a goto statement! But you don't have // to use it if you don't like it! // _Goto is useful when there is a need to exit from // several levels of nested _if's or _While's // // Input aLabel: The label to jump to. The label can be declared before // or after the _goto statement // Any number of _goto statements can jump to the same // label Procedure tWinRT._Goto(const aLabel : string); var position, index, jumpofs : integer; begin position := -1; with fLabelList do begin if find(aLabel, index) then position := integer(objects[index]); if position >= 0 then jumpofs := position - fList.count else begin jumpofs := 0; addobject(aLabel, pointer(fList.count or integer($80000000))); inc(undefgotos) end; end; AddItem(JUMP_TO, jumpofs, 0); end; { _Goto } // tWinRT._Label - Create a label that allows _Goto Statements to jump // to it. // // Input // aLabel: The label name. The label can be declared before // or after the _goto statement // Any number of _goto statements can jump to the same label // Will raise an exception if a label with the same // name has been already declared Procedure tWinRT._Label(const aLabel : string); var controlitemindex, index : integer; Jumpp : pCONTROL_ITEM_ex; begin with fLabelList do begin repeat if not find(aLabel, index) then break; controlitemindex := integer(objects[index]); if controlitemindex < 0 then begin // a yet undefined goto controlitemindex := controlitemindex and $7fffffff; // reset the label unknown bit jumpp := fList[controlitemindex]; with jumpp^ do port := port or (fList.count - controlitemindex); { fix the jump offset } delete(index); // another one taken care dec(undefgotos) // one less to worry end else raise eWinRTError.createfmt('Duplicate Label "%s"', [aLabel]); until false; // add the label to the list addobject(aLabel, pointer(fList.count)); end; { with } end; { _Label } // tWinRT.assign - assign a shadow variable to another. They must not be // array variables // Inputs: dst - The destination pseudo pointer // src - The source pseudo pointer // Outputs; none Procedure tWinRT.assign(dst, src : pointer); begin Math(MOVE_TO, 0, dst, src, nil) end; { assign } // tWinRT.GetControlItems - gets a control item from the list // Inputs: index - index of the item to get // Outputs: the item Function tWinRT.GetControlItems(index : integer) : pCONTROL_ITEM_ex; begin result := flist[index] end; { GetControlItems } // tWinRT.ExternDim - dimensions a shadow variable or array. Returns a pseudo pointer // // Inputs: // name: the name of the extern variable // wordsize: 1 for byte or char, 2 for word, 4 for integer/longint // wordcount: 1 if single item, or the range if an array // data: a reference (not a pointer) to the Pascal variable shadows // Outputs: returns a pseudo pointer to the shadow variable created. This is // not a valid pascal pointer and should not be used as such function tWinRT.ExternDim(name: string; wordsize, wordcount: integer; var data): pointer; var i, flags, extrabytes, extraitems : integer; Dimitem : tDimItem; begin extrabytes := wordsize * wordcount - sizeof(longint); if extrabytes > 0 then extraitems := (extrabytes + sizeof(tWINRT_CONTROL_ITEM) - 1) div sizeof(tWINRT_CONTROL_ITEM) else extraitems := 0; if wordcount < 1 then wordcount := 1; if wordcount = 1 then flags := DIMENSION_EXTERN else flags := DIMENSION_ARRAY + DIMENSION_EXTERN; i := additem(WinRTCtl.DIM, (flags + wordsize) shl 16 + wordcount, 0); result := pointer(i); for i := 1 to extraitems do additem(NOP, 0, 0); // create an entry in the Dim list DimItem := tDimItem.create(result, data, WordSIze * WordCount); DimList.add(DimItem); AddName(WinRTCtl.WINRT_EXTERN, name); end; { Dim } // tWinRT.GlobalDim - dimensions a global shadow variable or array. Returns a pseudo pointer // Inputs: // name: the name of the global variable // wordsize: 1 for byte or char, 2 for word, 4 for integer/longint // wordcount: 1 if single item, or the range if an array // data: a reference (not a pointer) to the Pascal variable shadows // Outputs: returns a pseudo pointer to the shadow variable created. This is // not a valid pascal pointer and should not be used as such function tWinRT.GlobalDim(name: string; wordsize, wordcount: integer; var data): pointer; var i, flags, extrabytes, extraitems : integer; Dimitem : tDimItem; begin extrabytes := wordsize * wordcount - sizeof(longint); if extrabytes > 0 then extraitems := (extrabytes + sizeof(tWINRT_CONTROL_ITEM) - 1) div sizeof(tWINRT_CONTROL_ITEM) else extraitems := 0; if wordcount < 1 then wordcount := 1; if wordcount = 1 then flags := DIMENSION_GLOBAL else flags := DIMENSION_ARRAY + DIMENSION_GLOBAL; i := additem(WinRTCtl.DIM, (flags + wordsize) shl 16 + wordcount, 0); result := pointer(i); for i := 1 to extraitems do additem(NOP, 0, 0); // create an entry in the Dim list DimItem := tDimItem.create(result, data, WordSIze * WordCount); DimList.add(DimItem); AddName(WinRTCtl.WINRT_GLOBAL, name); end; { Dim } procedure tWinRT.AddName(GlobalOrExtern: integer; const name: string); var index, extrabytes, extraitems: integer; p: pointer; begin extrabytes := length(name) + 1 - sizeof(longint); if extrabytes > 0 then extraitems := (extrabytes + sizeof(tWINRT_CONTROL_ITEM) - 1) div sizeof(tWINRT_CONTROL_ITEM) else extraitems := 0; // increment name refcount p := nil; string(p) := name; additem(GlobalOrExtern, extraitems, integer(p)); for index := 1 to extraitems do additem(NOP, 0, 0); end; end.
uses crt, StrUtils; type RenderLine = record Content :string; Color :byte; end; procedure WriteLine(s :string; color :byte); begin TextColor(color); WriteLn(s); end; procedure DrawSmoke(frame :integer); const smoke :RenderLine = (Content: ' . . . . o o o o o o'; Color: White); var frameAnimation :string; begin frameAnimation := DupeString(' o', frame div 2); WriteLine(smoke.Content + frameAnimation, smoke.Color); end; procedure DrawTrain(frame :integer); const TrainRenderLines = 4; Train :array[1..TrainRenderLines] of RenderLine = ( (Content: ' _____ o'; Color: White), (Content: ' ____==== ]OO|_n_n__][.'; Color: LightCyan), (Content: ' [________]_|__|________)< '; Color: LightBlue), (Content: ' oo oo oo OOOO-| oo\\_'; Color: Blue) ); Rail :RenderLine = (Content: ' +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+'; Color: Magenta); var FrameAnimation :string; RenderLine :integer; begin FrameAnimation := PadLeft('', frame); for RenderLine := 1 to TrainRenderLines do WriteLine(FrameAnimation + Train[RenderLine].Content, Train[RenderLine].Color); WriteLine(Rail.Content, Rail.Color); end; procedure Animation; const MaxFrames = 40; FrameTime = 100; var frame :integer; begin for frame := 0 to MaxFrames do begin ClrScr; DrawSmoke(frame); DrawTrain(frame); Delay(FrameTime); end; end; begin Animation; NormVideo; end.
{----------------------------------------------------------------------------- The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/MPL-1.1.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is: JvDsgnIntf.PAS, released on 2002-07-04. The Initial Developers of the Original Code are: Andrei Prygounkov <a dott prygounkov att gmx dott de> Copyright (c) 1999, 2002 Andrei Prygounkov All Rights Reserved. Contributor(s): You may retrieve the latest version of this file at the Project JEDI's JVCL home page, located at http://jvcl.delphi-jedi.org description : interface to design-time routines Known Issues: -----------------------------------------------------------------------------} // $Id: JvDsgnIntf.pas 12461 2009-08-14 17:21:33Z obones $ unit JvDsgnIntf; {$I jvcl.inc} interface uses {$IFDEF UNITVERSIONING} JclUnitVersioning, {$ENDIF UNITVERSIONING} Windows, Classes, Graphics; { DrawDesignFrame draws frame on the rect, Rect. JVCL uses this function to drawing frame around controls at design-time } procedure DrawDesignFrame(Canvas: TCanvas; Rect: TRect); procedure DesignerNotify(ASelf, Item: TComponent; Operation: TOperation); procedure DesignerModified(ASelf: TComponent); procedure DesignerSelectComponent(ASelf: TComponent); var DrawDesignFrameProc: procedure(Canvas: TCanvas; Rect: TRect); DesignerNotifyProc: procedure(ASelf, Item: TComponent; Operation: TOperation); DesignerModifiedProc: procedure(ASelf: TComponent); DesignerSelectComponentProc: procedure(ASelf: TComponent); type TGetProjectNameProc = function: string; var GetProjectNameProc: TGetProjectNameProc = nil; {$IFDEF UNITVERSIONING} const UnitVersioning: TUnitVersionInfo = ( RCSfile: '$URL: https://jvcl.svn.sourceforge.net/svnroot/jvcl/branches/JVCL3_47_PREPARATION/run/JvDsgnIntf.pas $'; Revision: '$Revision: 12461 $'; Date: '$Date: 2009-08-14 19:21:33 +0200 (ven. 14 août 2009) $'; LogPath: 'JVCL\run' ); {$ENDIF UNITVERSIONING} implementation procedure DrawDesignFrame(Canvas: TCanvas; Rect: TRect); begin if Assigned(DrawDesignFrameProc) then DrawDesignFrameProc(Canvas, Rect); end; procedure DesignerNotify(ASelf, Item: TComponent; Operation: TOperation); begin if Assigned(DesignerNotifyProc) then DesignerNotifyProc(ASelf, Item, Operation); end; procedure DesignerModified(ASelf: TComponent); begin if Assigned(DesignerModifiedProc) then DesignerModifiedProc(ASelf); end; procedure DesignerSelectComponent(ASelf: TComponent); begin if Assigned(DesignerSelectComponentProc) then DesignerSelectComponentProc(ASelf); end; {$IFDEF UNITVERSIONING} initialization RegisterUnitVersion(HInstance, UnitVersioning); finalization UnregisterUnitVersion(HInstance); {$ENDIF UNITVERSIONING} end.
unit aOPCListBox; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, aOPCClass, aCustomOPCSource, aOPCConsts; type EDataLinkCollectionError = class(Exception); { TDataLinkCollectionItem } TDataLinkCollection = class; TDataLinkCollectionItem = class(THashCollectionItem) private FDataLink: TaOPCDataLink; FShowMoment: boolean; function GetDataLinkCollection: TDataLinkCollection; procedure SetDataLink(Value: TaOPCDataLink); function GetPhysID: TPhysID; function GetValue: string; procedure SetPhysID(const Value: TPhysID); procedure SetValue(const Value: string); function GetRepresentation: string; procedure SetShowMoment(const Value: boolean); protected procedure SetName(const Value: string);override; procedure ChangeData(Sender:TObject);virtual; public constructor Create(Collection: TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; property DataLinkCollection: TDataLinkCollection read GetDataLinkCollection; property DataLink: TaOPCDataLink read FDataLink write SetDataLink; property Representation: string read GetRepresentation; published property ShowMoment:boolean read FShowMoment write SetShowMoment default false; property PhysID:TPhysID read GetPhysID write SetPhysID; property Value:string read GetValue write SetValue; end; { TDataLinkCollection } TDataLinkCollection = class(THashCollection) private FOwner: TPersistent; function GetItem(Index: Integer): TDataLinkCollectionItem; protected function GetOwner: TPersistent; override; public constructor Create(AOwner: TPersistent); destructor Destroy; override; function Find(const Name: string): TDataLinkCollectionItem; // procedure LoadFromFile(const FileName: string); // procedure LoadFromStream(Stream: TStream); // procedure SaveToFile(const FileName: string); // procedure SaveToStream(Stream: TStream); property Items[Index: Integer]: TDataLinkCollectionItem read GetItem; default; end; TaOPCListBox = class(TListBox) private FDataLinkItems: TDataLinkCollection; FOPCSource : TaCustomMultiOPCSource; FOnChangeData: TNotifyEvent; procedure SetDataLinkItems(Value: TDataLinkCollection); protected procedure SetOPCSource(const Value: TaCustomMultiOPCSource);virtual; function GetOPCSource: TaCustomMultiOPCSource;virtual; procedure ChangeData(Sender:TObject);virtual; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOnwer: TComponent); override; destructor Destroy; override; published property OnChangeData:TNotifyEvent read FOnChangeData write FOnChangeData; property OPCSource: TaCustomMultiOPCSource read GetOPCsource write SetOPCSource; property DataLinkItems: TDataLinkCollection read FDataLinkItems write SetDataLinkItems; end; implementation uses StrUtils; { TaOPCListBox } procedure TaOPCListBox.ChangeData(Sender: TObject); var i:integer; dl:TDataLinkCollectionItem; // Index:integer; begin { if (Sender is TDataLinkCollectionItem) and not (csDestroying in ComponentState) then begin dl := TDataLinkCollectionItem(Sender); if dl.Name = '' then exit; Index := Items.IndexOf(dl.Representation); if dl.FDataLink.IsActive then begin if Index < 0 then Items.Add(dl.Representation); end else begin if Index >= 0 then Items.Delete(Index); end; if Assigned(FOnChangeData) then FOnChangeData(Self); end; } if (csDestroying in ComponentState) or (csLoading in ComponentState) or (csReading in ComponentState) then exit; Items.BeginUpdate; Items.Clear; for i:=0 to Pred(FDataLinkItems.Count) do begin dl := FDataLinkItems[i]; if not (dl.Name = '') and dl.DataLink.IsActive and (dl.DataLink.ErrorCode = 0) then Items.AddObject(dl.Representation, dl); end; Items.EndUpdate; if Assigned(FOnChangeData) then FOnChangeData(Sender); { for i:=FDataLinkItems.Count - 1 downto 0 do begin dl := FDataLinkItems[i]; if dl.Name = '' then Continue; Index := Items.IndexOf(dl.Name); if dl.FDataLink.IsActive then begin if Index < 0 then Items.Add(dl.Name); end else begin if Index >= 0 then Items.Delete(Index); end; end; } end; constructor TaOPCListBox.Create(AOnwer: TComponent); begin inherited Create(AOnwer); FDataLinkItems := TDataLinkCollection.Create(Self); end; destructor TaOPCListBox.Destroy; begin FDataLinkItems.Free; inherited Destroy; end; function TaOPCListBox.GetOPCSource: TaCustomMultiOPCSource; begin Result := FOPCSource; end; procedure TaOPCListBox.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = FOPCSource) then FOPCSource := nil; end; procedure TaOPCListBox.SetDataLinkItems(Value: TDataLinkCollection); begin FDataLinkItems.Assign(Value); end; procedure TaOPCListBox.SetOPCSource(const Value: TaCustomMultiOPCSource); var i:integer; begin if FOPCSource <> Value then begin FOPCSource := Value; for i:=0 to FDataLinkItems.Count - 1 do TDataLinkCollectionItem(FDataLinkItems[i]).DataLink.OPCSource := Value; end; end; { TDataLinkCollectionItem } procedure TDataLinkCollectionItem.Assign(Source: TPersistent); var s: TDataLinkCollectionItem; begin if Source is TDataLinkCollectionItem then begin s := TDataLinkCollectionItem(Source); Name := s.Name; FDataLink.PhysID := s.FDataLink.PhysID; end else inherited Assign(Source); end; procedure TDataLinkCollectionItem.ChangeData(Sender: TObject); begin if (Collection.Owner <> nil) and (Collection.Owner is TaOPCListBox) then TaOPCListBox(Collection.Owner).ChangeData(Self); end; constructor TDataLinkCollectionItem.Create(Collection: TCollection); begin inherited Create(Collection); FDataLink := TaOPCDataLink.Create(Collection.Owner); FDataLink.StairsOptions := []; if (Collection.Owner <> nil) and (Collection.Owner is TaOPCListBox) then begin FDataLink.OPCSource := TaOPCListBox(Collection.Owner).OPCSource; FDataLink.OnChangeData := ChangeData; end; FDataLink.Control := Self; end; destructor TDataLinkCollectionItem.Destroy; begin Value := ''; FDataLink.Free; inherited Destroy; end; function TDataLinkCollectionItem.GetDataLinkCollection: TDataLinkCollection; begin Result := Collection as TDataLinkCollection; end; function TDataLinkCollectionItem.GetPhysID: TPhysID; begin Result := FDataLink.PhysID; end; function TDataLinkCollectionItem.GetRepresentation: string; begin Result := IfThen((DataLink.Moment = 0) or not ShowMoment, '',DateTimeToStr(DataLink.Moment)+' : ')+ Name; end; function TDataLinkCollectionItem.GetValue: string; begin Result := FDataLink.Value; end; procedure TDataLinkCollectionItem.SetDataLink(Value: TaOPCDataLink); begin FDataLink.PhysID := Value.PhysID; end; procedure TDataLinkCollectionItem.SetName(const Value: string); {var index:integer; OldRepresentation,OldName:string; } begin { OldRepresentation := Representation; OldName := Name; inherited; if FDataLink.IsActive then begin if (OldName<>Value) then begin if OldName <> '' then begin index := TaOPCListBox(Collection.Owner).Items.IndexOf(OldRepresentation); if index >= 0 then begin if Value = '' then TaOPCListBox(Collection.Owner).Items.Delete(index) else TaOPCListBox(Collection.Owner).Items.Strings[index]:= Representation; end; end else TaOPCListBox(Collection.Owner).Items.Add(Representation); end; end; } inherited; ChangeData(nil); end; procedure TDataLinkCollectionItem.SetPhysID(const Value: TPhysID); begin FDataLink.PhysID := Value; end; procedure TDataLinkCollectionItem.SetShowMoment(const Value: boolean); begin FShowMoment := Value; end; procedure TDataLinkCollectionItem.SetValue(const Value: string); begin FDataLink.Value := Value; end; { TDataLinkCollection } constructor TDataLinkCollection.Create(AOwner: TPersistent); begin inherited Create(TDataLinkCollectionItem); FOwner := AOwner; end; destructor TDataLinkCollection.Destroy; begin inherited Destroy; end; function TDataLinkCollection.Find( const Name: string): TDataLinkCollectionItem; var i: Integer; begin i := IndexOf(Name); if i=-1 then raise EDataLinkCollectionError.CreateFmt(SDataLinkNotFound, [Name]); Result := Items[i]; end; function TDataLinkCollection.GetItem( Index: Integer): TDataLinkCollectionItem; begin Result := TDataLinkCollectionItem(inherited Items[Index]); end; function TDataLinkCollection.GetOwner: TPersistent; begin Result := FOwner; end; end.
unit BusStopController; interface uses BusStop, Generics.Collections, Aurelius.Engine.ObjectManager, ControllerInterfaces; type TBusStopController = class(TInterfacedObject, IController<TBusStop>) private FManager: TObjectManager; public constructor Create; destructor Destroy; procedure Delete(BusStop: TBusStop); function GetAll: TList<TBusStop>; end; implementation uses DBConnection; { TBeaconController } constructor TBusStopController.Create; begin FManager := TDBConnection.GetInstance.CreateObjectManager; end; procedure TBusStopController.Delete(BusStop: TBusStop); begin if not FManager.IsAttached(BusStop) then BusStop := FManager.Find<TBusStop>(BusStop.Id); FManager.Remove(BusStop); end; destructor TBusStopController.Destroy; begin FManager.Free; inherited; end; function TBusStopController.GetAll: TList<TBusStop>; begin FManager.Clear; Result := FManager.FindAll<TBusStop>; end; end.
unit MD.Editors; interface uses FMXVclUtils, FMX.Graphics, VCL.Graphics, DesignEditors, DesignIntf, System.Types, System.Classes, FMX.Forms, MD.ColorPalette, FMXEditors, VCLEditors, System.SysUtils, System.UITypes, FMX.Types, FMX.Ani, ToolsAPI, PropInspAPI; const FilmStripMargin: Integer = 2; FilmStripWidth: Integer = 12; FilmStripHeight: Integer = 13; SCreateNewColorAnimation = 'Create New TColorAnimation'; SCreateNewColorKeyAnimation = 'Create New TColorKeyAnimation'; type TMaterialColorProperty = class(TIntegerProperty, ICustomPropertyDrawing, ICustomPropertyListDrawing, ICustomPropertyDrawing80, IProperty160) private FPropertyPath: string; protected function IsAnimated: Boolean; virtual; procedure CreateNewAnimation(AnimationClass: TComponentClass); function TextToMaterialColor(const Value: string): TAlphaColor; virtual; public function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; procedure GetValues(Proc: TGetStrProc); override; procedure SetValue(const Value: string); override; procedure Edit; override; { ICustomPropertyListDrawing } procedure ListMeasureHeight(const Value: string; ACanvas: TCanvas; var AHeight: Integer); procedure ListMeasureWidth(const Value: string; ACanvas: TCanvas; var AWidth: Integer); procedure ListDrawValue(const Value: string; ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); { ICustomPropertyDrawing } procedure PropDrawName(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); procedure PropDrawValue(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); { ICustomPropertyDrawing80 } function PropDrawNameRect(const ARect: TRect): TRect; function PropDrawValueRect(const ARect: TRect): TRect; { IProperty160 } procedure SetPropertyPath(const Value: string); end; var VCLBitmap: VCL.Graphics.TBitmap = nil; FMXBitmap: FMX.Graphics.TBitmap = nil; implementation function GetPropertyName(const AnAnimation: TAnimation): string; begin Result := AnsiString(''); if AnAnimation is TFloatAnimation then begin Result := TFloatAnimation(AnAnimation).PropertyName; Exit; end; if AnAnimation is TFloatKeyAnimation then begin Result := TFloatKeyAnimation(AnAnimation).PropertyName; Exit; end; if AnAnimation is TGradientAnimation then begin Result := TGradientAnimation(AnAnimation).PropertyName; Exit; end; if AnAnimation is TColorAnimation then begin Result := TColorAnimation(AnAnimation).PropertyName; Exit; end; if AnAnimation is TColorKeyAnimation then begin Result := TColorKeyAnimation(AnAnimation).PropertyName; Exit; end; if AnAnimation is TRectAnimation then begin Result := TRectAnimation(AnAnimation).PropertyName; Exit; end; if AnAnimation is TBitmapAnimation then begin Result := TBitmapAnimation(AnAnimation).PropertyName; Exit; end; if AnAnimation is TBitmapListAnimation then begin Result := TBitmapListAnimation(AnAnimation).PropertyName; Exit; end; end; function ComponentOfPersistent(APersistent: TPersistent): TComponent; begin while Assigned(APersistent) do begin if APersistent is TOwnedCollection then APersistent := TOwnedCollection(APersistent).Owner else if APersistent is TCollectionItem then APersistent := TCollectionItem(APersistent).Collection else if APersistent is TComponent then Break else APersistent := nil; end; Result := TComponent(APersistent); end; function FMXObjectOfDesigner(const ADesigner: IDesigner; const AIndex: Integer = 0): TFmxObject; var LSelections: IDesignerSelections; LComp: TComponent; begin Result := nil; if Assigned(ADesigner) and (AIndex >= 0) then begin LSelections := TDesignerSelections.Create; ADesigner.GetSelections(LSelections); if Assigned(LSelections) and (AIndex < LSelections.Count) then begin LComp := ComponentOfPersistent(LSelections.Items[AIndex]); if LComp is TFmxObject then Result := TFmxObject(LComp); end; end; end; function IsAnimatedImpl(const APropertyPath: string; const ADesigner: IDesigner): Boolean; var BO, LChild: TFmxObject; I: Integer; begin Result := False; BO := FMXObjectOfDesigner(ADesigner); if Assigned(BO) then for I := 0 to BO.ChildrenCount - 1 do begin LChild := BO.Children[I]; if (LChild is TAnimation) and (APropertyPath = GetPropertyName(TAnimation(LChild))) then begin Result := True; Exit; end; end; end; function TMaterialColorProperty.TextToMaterialColor(const Value: string): TAlphaColor; begin Result := StringToMaterialColor(Value); end; function PaintColorBox(const Value: TAlphaColor; ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean): TRect; overload; const SquareSize = 3; var Right, Size: Integer; NewRect: TRect; OldPenColor, OldBrushColor: TColor; begin Right := (ARect.Bottom - ARect.Top) { * 2 } + ARect.Left; // save off things OldBrushColor := ACanvas.Brush.Color; OldPenColor := ACanvas.Pen.Color; try Size := ((ARect.Height - 4) div SquareSize) * SquareSize + 2; NewRect := TRect.Create(ARect.TopLeft, Size, Size); NewRect.Offset(FilmStripMargin, (ARect.Height - NewRect.Height + 1) div 2); if FMXBitmap = nil then FMXBitmap := FMX.Graphics.TBitmap.Create(Size - 2, Size - 2) else FMXBitmap.SetSize(Size - 2, Size - 2); FMXBitmap.Clear(Value); CreatePreview(FMXBitmap, VCLBitmap, TRect.Create(TPoint.Create(0, 0), FMXBitmap.Width, FMXBitmap.Height), clBlack, clWhite, SquareSize, True); ACanvas.Pen.Color := ACanvas.Brush.Color; ACanvas.Rectangle(ARect.Left, ARect.Top, Right, ARect.Bottom); if ASelected then ACanvas.Pen.Color := clHighlightText else ACanvas.Pen.Color := clWindowText; ACanvas.Rectangle(NewRect); ACanvas.Draw(NewRect.Left + 1, NewRect.Top + 1, VCLBitmap); finally // restore the things we twiddled with ACanvas.Pen.Color := OldPenColor; ACanvas.Brush.Color := OldBrushColor; Result := Rect(Right, ARect.Top, ARect.Right, ARect.Bottom); end; end; function PaintColorBox(const Value: string; ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean): TRect; overload; var LValue: TMaterialColor; begin LValue := StringToMaterialColor(Value); Result := PaintColorBox(LValue, ACanvas, ARect, ASelected); end; function PaintFilmStrip(const Value: string; ACanvas: TCanvas; const ARect: TRect; IsAnimated: Boolean): TRect; var I, Right, Left, Top: Integer; OldPenColor, OldBrushColor: TColor; BorderColor, CellColor: TColor; begin Left := ARect.Left + FilmStripMargin; Right := Left + FilmStripWidth; Top := ARect.Top + Round((ARect.Bottom - ARect.Top - FilmStripHeight) / 2); with ACanvas do begin // save off things OldPenColor := Pen.Color; OldBrushColor := Brush.Color; Pen.Color := ACanvas.Brush.Color; Rectangle(ARect.Left, ARect.Top, Right + FilmStripMargin, ARect.Bottom); // frame things if IsAnimated then begin BorderColor := TColors.Black; CellColor := TColors.LtGray; end else begin BorderColor := TColors.LtGray; CellColor := TColors.White; end; Pen.Color := BorderColor; Rectangle(Left, Top, Right, Top + FilmStripHeight); for I := 0 to 2 do begin Rectangle(Left, Top + 2 + (4 * I), Right, Top + 5 + (4 * I)); end; Rectangle(Left + 2, Top, Right - 2, Top + FilmStripHeight); Brush.Color := CellColor; Pen.Color := CellColor; Rectangle(Left + 3, Top, Right - 3, Top + FilmStripHeight); Pen.Color := BorderColor; Rectangle(Left + 2, Top + 3, Right - 2, Top + FilmStripHeight - 3); // restore the things we twiddled with Brush.Color := OldBrushColor; Pen.Color := OldPenColor; Result := Rect(Right + FilmStripMargin, ARect.Top, ARect.Right, ARect.Bottom); end; end; { TMaterialColorProperty } procedure TMaterialColorProperty.CreateNewAnimation(AnimationClass: TComponentClass); var BO: TFmxObject; LAni: TAnimation; LPropName: string; begin LPropName := (BorlandIDEServices as IOTAPropInspServices).Selection.GetActiveItem; BO := FMXObjectOfDesigner(Designer); if Assigned(BO) then begin LAni := TAnimation(Designer.CreateComponent(AnimationClass, BO, 0,0,0,0)); LAni.Parent := BO; if LAni is TColorAnimation then TColorAnimation(LAni).PropertyName := LPropName; if LAni is TColorKeyAnimation then TColorKeyAnimation(LAni).PropertyName := LPropName; end; end; procedure TMaterialColorProperty.Edit; begin inherited; end; function TMaterialColorProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paDialog, paValueList, paRevertable]; end; function TMaterialColorProperty.GetValue: string; begin try Result := MaterialColorToString(TMaterialColor(GetOrdValue)); except // on E: Exception do ShowMessage(E.Message); end; end; procedure TMaterialColorProperty.GetValues(Proc: TGetStrProc); begin GetMaterialColorValues(Proc); end; function TMaterialColorProperty.IsAnimated: Boolean; begin Result := IsAnimatedImpl(FPropertyPath, Designer); end; procedure TMaterialColorProperty.ListDrawValue(const Value: string; ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); var ValueRect: TRect; begin if (not SameText(Value, SCreateNewColorAnimation)) and (not SameText(Value, SCreateNewColorKeyAnimation)) then ValueRect := PaintColorBox(Value, ACanvas, ARect, ASelected) else ValueRect := PaintFilmStrip(Value, ACanvas, ARect, True); DefaultPropertyListDrawValue(Value, ACanvas, ValueRect, ASelected); end; procedure TMaterialColorProperty.ListMeasureHeight(const Value: string; ACanvas: TCanvas; var AHeight: Integer); begin AHeight := ((FilmStripHeight + 2 * FilmStripMargin) div 2 + 1) * 2; end; procedure TMaterialColorProperty.ListMeasureWidth(const Value: string; ACanvas: TCanvas; var AWidth: Integer); begin AWidth := AWidth + ACanvas.TextHeight('M') { * 2 }; end; procedure TMaterialColorProperty.PropDrawName(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); begin DefaultPropertyDrawName(Self, ACanvas, ARect); end; function TMaterialColorProperty.PropDrawNameRect(const ARect: TRect): TRect; begin Result := ARect; end; procedure TMaterialColorProperty.PropDrawValue(ACanvas: TCanvas; const ARect: TRect; ASelected: Boolean); var LRect: TRect; begin if GetVisualValue <> '' then begin LRect := PaintFilmStrip(GetVisualValue, ACanvas, ARect, IsAnimated); PaintColorBox(TextToMaterialColor(GetVisualValue), ACanvas, LRect, False); end else DefaultPropertyDrawValue(Self, ACanvas, ARect); end; function TMaterialColorProperty.PropDrawValueRect(const ARect: TRect): TRect; begin Result := Rect(ARect.Left, ARect.Top, FilmStripMargin * 2 + FilmStripWidth + (ARect.Bottom - ARect.Top) + ARect.Left, ARect.Bottom); end; procedure TMaterialColorProperty.SetPropertyPath(const Value: string); begin FPropertyPath := Value; end; procedure TMaterialColorProperty.SetValue(const Value: string); begin try SetOrdValue(Integer(StringToMaterialColor(Value))); Modified; except // on E: Exception do ShowMessage(E.Message); end; end; end.
type vertex = record adj:array of integer; end; graph = array of vertex; type node = record i: integer; next: ^node; end; pnode = ^node; queue = record head: ^node; tail: ^node; end; procedure init(var q: queue); begin q.head := nil; q.tail := nil; end; procedure enqueue(var q: queue; i: integer); var n: ^node; begin new(n); n^.i := i; n^.next := nil; if q.head = nil then begin q.head := n; q.tail := n; end else begin q.tail^.next := n; // append to tail q.tail := n; end; end; function dequeue(var q: queue): integer; var p: ^node; begin dequeue := q.head^.i; p := q.head; q.head := q.head^.next; dispose(p); if q.head = nil then q.tail := nil; end; function isEmpty(q: queue): boolean; begin exit(q.head = nil); end; function isConnected(const g: graph): boolean; //depth-first search var visited: array of boolean; b: boolean; procedure visit(i: integer); var j: integer; begin visited[i] := true; for j in g[i].adj do if not visited[j] then visit(j); end; begin visit(0); for end; begin setLength(visited, length(g)); // sets all array elements to false visit(0); for b in visited do writeln(b); for b in visited do if not b then exit(false); exit(true); end; function is_connected(g:graph; s,d:integer):boolean; var visited:array of boolean; procedure visit(i); var j:integer; begin visited[i]:=true; for j in g[i].adj do begin if not visited[j] do begin visit(j) end; end; end; begin end; function furthest(const g:graph; v:integer):integer; var visited:array of boolean; q:queue; begin setLength(visited, length(g)); init(q); enqueue(v); while not isEmpty(q) do begin i:= dequeue(q); for j in g[i].adj do begin if not visited[j] then begin enqueue(j); visited[j]:=true; end; end; end; end; var g:graph; i:integer; begin setLength(g, 2); setLength(g[0].adj, 1); g[0].adj[0]:=1; setLength(g[1].adj, 1); g[0].adj[0]:=0; { setLength(g[2].adj, 1); g[0].adj[0]:=3; setLength(g[3].adj, 1); g[0].adj[0]:=2; } { setLength(g[1].adj, 1); g[0].adj[0]:=0; g[0].adj[1]:=5; g[0].adj[2]:=2; setLength(g[2].adj, 3); g[0].adj[0]:=1; g[0].adj[1]:=8; g[0].adj[2]:=3; setLength(g[3].adj, 3); g[0].adj[0]:=2; g[0].adj[1]:=8; g[0].adj[2]:=4; setLength(g[4].adj, 1); g[0].adj[0]:=3; setLength(g[5].adj, 2); g[0].adj[0]:=1; g[0].adj[1]:=6; setLength(g[6].adj, 2); g[0].adj[0]:=7; g[0].adj[1]:=5; setLength(g[7].adj, 1); g[0].adj[0]:=6; setLength(g[8].adj, 2); g[0].adj[0]:=2; g[0].adj[1]:=3; } writeln(isConnected(g)); writeln('hel'); end.
program WolfSheepCabbage; uses SysUtils; type bank = (BLeft, BRight); eval = (EDone, ELegal, EIllegal); movable = (MWolf, MSheep, MCabbage, MFarmer); state = record wolf, sheep, cabbage, farmer: bank; end; moveptr = ^move; move = record orig, dest: bank; moved: movable; next: moveptr; end; stackptr = ^stack; stack = record gameState: state; next: stackptr; end; { Helper functions } function oppositeBank(b: bank) : bank; begin if (b = BRight) then oppositeBank := BLeft else oppositeBank := BRight; end; { Stringifying functions } function bank2str(s: state; b: bank) : string; begin bank2str := ''; if (s.wolf = b) then bank2str := bank2str + 'W'; if (s.sheep = b) then bank2str := bank2str + 'O'; if (s.cabbage = b) then bank2str := bank2str + 'K'; if (s.farmer = b) then bank2str := bank2str + 'F'; end; function state2str(s: state) : string; begin state2str := '[ ' + bank2str(s, BLeft) + ' || ' + bank2str(s, BRight) + ' ]'; end; function stack2str(stk: stackptr) : string; begin stack2str := state2str(stk^.gameState); while (stk^.next <> nil) do begin stk := stk^.next; stack2str := stack2str + ' -> ' + state2str(stk^.gameState); end; end; { Stack manipulation } function appendState(stk: stackptr; s: state) : stackptr; var stkptr: stackptr; begin appendState := stk; if (appendState = nil) then begin new(appendState); stkptr := appendState; end else begin stkptr := appendState; while(stkptr^.next <> nil) do stkptr := stkptr^.next; new(stkptr^.next); stkptr := stkptr^.next; end; stkptr^.next := nil; stkptr^.gameState := s; end; function popState(stk: stackptr) : stackptr; begin popState := stk; if ((stk <> nil) and (stk^.next = nil)) then begin dispose(stk); popState := nil; end else begin while((stk^.next <> nil) and (stk^.next^.next <> nil)) do stk := stk^.next; dispose(stk^.next); stk^.next := nil; end; end; procedure tearDownStack(stk: stackptr); begin if (stk <> nil) then begin if (stk^.next <> nil) then tearDownStack(stk^.next); dispose(stk); end; end; { Move list manipulation } function appendMove(list: moveptr; origin, destination: bank; moved: movable ) : moveptr; var mvptr: moveptr; begin appendMove := list; if (appendMove = nil) then begin new(appendMove); mvptr := appendMove; end else begin mvptr := appendMove; while(mvptr^.next <> nil) do mvptr := mvptr^.next; new(mvptr^.next); mvptr := mvptr^.next; end; mvptr^.next := nil; mvptr^.dest := destination; mvptr^.orig := origin; mvptr^.moved := moved; end; procedure tearDownMoveList(list: moveptr); begin if (list <> nil) then begin if (list^.next <> nil) then tearDownMoveList(list^.next); dispose(list); end; end; { Problem definition } function stateEval(s: state) : eval; begin stateEval := ELegal; if (((s.wolf = s.sheep) and (s.wolf <> s.farmer)) or ((s.sheep = s.cabbage) and (s.sheep <> s.farmer))) then stateEval := EIllegal; if ((s.wolf = BRight) and (s.sheep = BRight) and (s.cabbage = BRight) and (s.farmer = BRight)) then stateEval := EDone; end; function genStates(s: state) : moveptr; begin genStates := nil; genStates := appendMove(genStates, s.farmer, oppositeBank(s.farmer), MFarmer); if (s.wolf = s.farmer) then genStates := appendMove(genStates, s.wolf, oppositeBank(s.wolf), MWolf); if (s.sheep = s.farmer) then genStates := appendMove(genStates, s.sheep, oppositeBank(s.sheep), MSheep); if (s.cabbage = s.farmer) then genStates := appendMove(genStates, s.cabbage, oppositeBank(s.cabbage), MCabbage); end; function search(s: state; depth: byte; stk: stackptr; showFailed: boolean) : eval; var mvptr, x: moveptr; nextState: state; ev: eval; begin search := stateEval(s); if (search = EDone) then begin writeln(#10, '+ :do dna ', depth, ': ', stack2str(stk), #10); end else if((depth > 0) and (search <> EIllegal)) then begin mvptr := genStates(s); x := mvptr; while (mvptr <> nil) do begin nextState := s; nextState.farmer := oppositeBank(nextState.farmer); if (mvptr^.moved = MWolf) then nextState.wolf := oppositeBank(nextState.wolf) else if (mvptr^.moved = MSheep) then nextState.sheep := oppositeBank(nextState.sheep) else if (mvptr^.moved = MCabbage) then nextState.cabbage := oppositeBank(nextState.cabbage); stk := appendState(stk, nextState); ev := search(nextState, depth - 1, stk, showFailed); if (search <> EDone) then begin if (ev = EDone) then search := EDone else if ((ev = ELegal) and (search = EIllegal)) then search := ELegal; end; if (showFailed and (search = ELegal)) then begin writeln('- :do dna ', depth, ': ', stack2str(stk)); end; stk := popState(stk); mvptr := mvptr^.next; end; tearDownMoveList(x); end; end; function searchSolution(s: state; depth: byte; showFailed: boolean) : eval; var stk: stackptr; begin stk := appendState(nil, s); searchSolution := search(s, depth, stk, showFailed); tearDownStack(stk); end; { Main } var depth, argumentOffset: byte; showFailed: boolean; s: state; ev: eval; begin depth := 7; argumentOffset := 0; showFailed := true; if ((ParamCount <> 0) and (ParamCount <> 2) and (ParamCount <> 4)) then begin writeln('Dostepne opcje:'); writeln(#9'-h {"true", "false"}: ukryj nieudane przejscia'); writeln(#9'-d <byte>: glebokosc poszukiwania rozwiazania'); exit; end; while (argumentOffset <> ParamCount) do begin if ((ParamStr(argumentOffset+1) = '-h') and (ParamStr(argumentOffset+2) = 'true')) then showFailed := false; if (ParamStr(argumentOffset+1) = '-d') then depth := StrToInt(ParamStr(argumentOffset+2)); argumentOffset := argumentOffset + 2; end; writeln('Poszukuje rozwiazania z glebokoscia przeszukiwania ', depth); s.wolf := BLeft; s.sheep := BLeft; s.cabbage := BLeft; s.farmer := BLeft; ev := searchSolution(s, depth, showFailed); write('Wynik: '); if (ev = EDone) then begin write('znaleziono rozwiazania!'); end else begin write('nie znaleziono rozwiazan...'); end; write(#10); end.
{Nama : Firman Abdul Zaelani NPM : 18.14.1.046 Kelompok : Kelompok 1 Kode Soal : D} Program Konversi_suhu; uses crt; label menu; var pilihan : char; F,C,K,R : real; begin menu : clrscr; writeln('====================='); writeln('Program Konversi Suhu'); writeln('====================='); writeln; writeln('Pilihan Menu (1-4) : '); writeln('================================='); writeln('[1] Konversi Celcius - Fahrenheit'); writeln('[2] Konversi Celcius - Reamur'); writeln('[3] Konversi Celcius - Kelvin'); writeln('[4] Keluar Program'); writeln('================================='); writeln; write('Masukan pilihan anda : '); readln(pilihan); writeln; case pilihan of '1' : begin writeln('================================='); write('Masukan suhu dalam Celcius : '); readln(C); F:=(9/5)*C+32; writeln(C:0:2,' Celcius = ',F:0:2, ' Fahrenheit'); writeln('================================='); end; '2': begin writeln('================================='); write('Masukan suhu dalam Celcius : '); readln(C); R:=(4/5)*C; writeln(C:0:2,' Celcius = ',R:0:2,' Reamur'); writeln('================================='); end; '3': begin writeln('================================='); write('Masukan suhu dalam Celcius : '); readln(C); K:=C+273; writeln(C:0:2,' Celcius = ',K:0:2,' Kelvin'); writeln('================================='); end; '4' : begin halt(0); end; end; writeln; writeln('Tekan sembarang tombol untuk ke menu'); readln; goto menu; readln; end.
{ Copy CELL records from selected plugin(s) to a new file to preserve their settings. Can be used for lighting overhauls. Select lighting plugins with Ctrl+Click in TES5Edit and apply this script. Created new patch file must be loaded last and recreated every time you uninstall/reorder/update master plugins. } unit UserScript; var newfile: IInterface; cells: TStringList; recs: array [0..50000] of IInterface; function Initialize: integer; begin cells := TStringList.Create; AddMessage('Building cells list, please wait...'); end; function Process(e: IInterface): integer; var idx: integer; s: string; begin if Signature(e) <> 'CELL' then Exit; // only interior cells if GetElementNativeValues(e, 'DATA') and 1 = 0 then Exit; s := IntToHex(FormID(e), 8); idx := cells.IndexOf(s); if idx = -1 then begin recs[cells.Count] := e; cells.Add(s); end else recs[idx] := e; end; function Finalize: integer; var i: integer; r: IInterface; begin if cells.Count <> 0 then begin // create a new patch file newfile := AddNewFile; if not Assigned(newfile) then begin AddMessage('Patch file creation canceled'); Result := 1; Exit; end; for i := 0 to cells.Count - 1 do begin r := recs[i]; // add current plugin as a master AddRequiredElementMasters(GetFile(r), newfile, False); // copy CELL record to patch, parameters: record, file, AsNew, DeepCopy wbCopyElementToFile(r, newfile, False, True); end; AddMessage(Format('Patch file created with %d cell records.', [cells.Count])); end else AddMessage('No cell records found to copy.'); cells.Free; end; end.
unit proclib; { рев.от 070501 (+) Добавлена overload процедура DevideStringToToken, в которой возвращается размер получившегося массива (!) Исправлены эти же процедуры - массив заполнялся с 1-го элемента } interface uses SysUtils,rxStrUtils,uUtils,registry,StrUtils,classes; Type {слово в предложении} TToken = string; TTokenList = array of TToken; //*** {истина, если номер строки idx присутствует в списке обработанных MadeList} function InMadeList(idx:integer;MadeList:TStringList):boolean; //*** {проверяет дату на нули - 00.00.0000, если так, то выводит дату, указанную в newdate. По умолчанию 01.01.2000} function CheckDate(date:string;newdate:string='01.01.2000'):string; //*** //*** {истина если арабские символы уже в серии} function IsAlreadyArab(ser:string):boolean; //*** //*** {выдергивает num фамилию из двойной surname которые разделены delim } function DoubleSurname(surname:string;delim:string;num:integer):string; //*** //*** { возвращает цифровое значение месяца, заданный словом } function MonthToDig(month:string):string; //*** //*** { форматирует входную строку адреса в вид Страна,Область,город г,улица ул,дом,корпус,квартира Вход: г.Город, Область область, ул.Улица, дом-кв } function Z2Addr(addr:string):string; //*** //*** { разбивает строку по словам (токенам), заполняя переданный массив слов, который должен существовать. } procedure DevideStringToToken(str:string;delimiter:char;out TokenList:TTokenList);overload; procedure DevideStringToToken(str:string;delimiter:char;out TokenList:TTokenList; out TokenListSize:integer);overload; //*** //*** { меняет порядок слов в предложении } function InvertToken(str:string;delimiter:char):string; //*** //**** { удаляет возможные нецифры из строки } function DelCharFromDig(str:string):string; //**** //******* { восстанавливает параметр из реестра } procedure LoadParam(local,reg:integer); //******* //******* { сохраняет параметр в реестр } //procedure SaveParam(local,reg:integer); //******* //******* { если длина str1+str2 больше 25 симыолов, то выводится str1 } function Digit25(str1,str2:string):string;overload; //******* //******* { да - если входная строка содержит одни символы нет - если во введенной строке есть цмфры } function IsAlpha(str:string):boolean; //******* //******* { возвращает уд личн, собранное из двух полей doc_s и doc_n - серии и номера документа если серия док-та состоит из одних цифр, то код уд личности = 21 ПаРФ, если в серии содержатся буквы, то код уд. личности = 01 ПаСССР, и в этом случае цифры перед буквами переводятся в римские. } function MakeUdLichn(ser,num:string):string; //******* //******* { возращает kod=510 -> легковые kod=520 -> грузовые kod=561 -> мотоциклы kod=540 -> автобусы } function TypeTrans(kod:string):string; //******* //******* //возвращает 19?? если входной год= 2 знака, 200?, если входной год = 1 знак function God_V(god_from_table:string):string; //******* //******* // Создание имени файла для резервного хранения типа file.bak function MakeBackupFileName(OldFN:string;NewExt:string):string; //******* //******* // переводит арабское число в римское. // число должно быть <=39. function Arab2Rome(Arab:integer):string;overload; //function Arab2Rome(Arab:string):string;overload; //******* //******* { слева добавляет fill_ch к строке str для получения char_cnt символов возвращает строку. Например, padl('11',5,'0') вернет 00011; } function padl(str:string;char_cnt:integer;fill_ch:char):string; //******* //******* { возвращает 1, если отчество father_name мужчины, 0, если женщины, -1 если определить не удалось. } //******* //******* function mw(father_name:string):integer; { выдает М, если mw = 1 Ж, если mw = 0 -, если mw = -1; } //******* //******* function AnalyseMW(mw:integer):string;overload; function AnalyseMW(mw:string):string;overload; //******* //******* { если пункт пустой, то не выводится ничего, иначе - punct п } function GetPunct(punct:string):string; //******* //******* //Получает инициалы по полному ФИО - Фамилия И.О. function GetInitials(full_fio:string):string; //******* implementation //--------- procedure SaveIntParam(local:integer;param:string); var reg:TRegistry; begin reg:=TRegistry.Create; // reg.RootKey:=HKEY_LOCAL_MACHINE; try if reg.OpenKey('\IT\PVS',true) then begin reg.WriteInteger(param,local); reg.CloseKey; end except // ShowMessage('Ошибка сохранения параметров'); end; reg.Free; end; //--------- //---------- function ReadParam(param:string):integer; var reg:TRegistry; tmp:integer; begin tmp:=0; reg:=TRegistry.Create; // reg.RootKey:=HKEY_LOCAL_MACHINE; try if reg.OpenKey('\IT\PVS',false) then begin tmp:=reg.ReadInteger(param); reg.CloseKey; end; except end; reg.Free; result:=tmp; end; //------- //-------- function GetPunct(punct:string):string; var tmp:string; begin tmp:=''; if punct<>'' then begin if (Pos('п.',punct)>0) or (Pos('П.',punct)>0) then tmp:=copy(punct,3,Length(punct)-2)+ ' п' else tmp:=punct + ' п'; end; result:=tmp; end; //-------- //--- function IsAlreadyArab(ser:string):boolean; var tmp:boolean; begin if (Pos('I',ser)>0) or (Pos('V',ser)>0) or (Pos('X',ser)>0) then tmp:=true else tmp:=false; result:=tmp; end; //--- //-------- function IsAlpha(str:string):boolean; var tmp:boolean; i:integer; begin tmp:=false; for i:=1 to Length(str) do begin if str[i] in ['0'..'9'] then begin end else begin if str[i]=' ' then begin end else begin tmp:=true; break; end; end; end; result:=tmp; end; //--------- //----------- function MakeUdLichn(ser,num:string):string; var tmp:string; begin tmp:=''; if (ser='') and (num='') then begin result:='91,0'; exit; end; try if not IsAlpha(ser) then begin if Pos(' ',ser)=0 then tmp:='21,'+LeftStr(ser,length(ser)-2)+' '+RightStr(ser,2)+' '+padl(num,6,'0') else tmp:='21,'+ser+' '+padl(num,6,'0'); end else if not IsAlreadyArab(ser) then tmp:='01,'+Arab2Rome(StrToInt(LeftStr(ser,length(ser)-2)))+'-'+RightStr(ser,2)+' '+padl(num,6,'0') else tmp:='01,'+ser+' '+num; except tmp:='91,'+ser+' '+num; end; result:=tmp; end; //----------- //-------------- function TypeTrans(kod:string):string; var tmp:string; begin tmp:=''; if kod='510' then tmp:='легковые'; if kod='520' then tmp:='грузовые'; if kod='561' then tmp:='мотоциклы'; if kod='540' then tmp:='автобусы'; result:=tmp; end; //-------------- //----- function DelCharFromDig(str:string):string; var i:integer; tmp:string; begin tmp:=''; for i:=1 to Length(str) do begin if str[i] in ['0'..'9'] then tmp:=tmp+str[i]; end; result:=tmp; end; //----- //------------- function God_V(god_from_table:string):string; var tmp:string; god:string; begin god:=DelCharFromDig(god_from_table); tmp:=''; if Length(god)=1 then tmp:='200'+god else if Length(god)=2 then tmp:='19'+god else tmp:=god; result:=tmp; end; //-------------- //------------------------ function MakeBackupFileName(OldFN:string;NewExt:string):string; begin Result:=ReplaceStr(OldFN,ExtractFileExt(OldFN),NewExt); end; //------------------------- //------------------------- function Edin(ostatok:integer):string; // считает колво единиц var tmp:string; function Fill(povtor:integer):string; // заполняет единицы до нужного колва // 8 - VIII var j:integer; tmp:string; begin for j:=1 to povtor do tmp:=tmp+'I'; result:=tmp; end; begin if ostatok<5 then tmp:=Fill(ostatok) else if ostatok=5 then tmp:='V'; if ostatok>5 then tmp:='V'+Fill(ostatok-5); if ostatok=9 then tmp:='IX'; if ostatok=4 then tmp:='IV'; result:=tmp; end; //--------- function Arab2Rome(Arab:integer):string;overload; var des:integer; //кол-во десятков Rome:string; i:integer; begin des:=Arab div 10; for i:=1 to des do begin Rome:=Rome+'X'; end; Rome:=Rome+Edin(Arab mod 10); result:=Rome; end; //-------------------------- //--------- { function Arab2Rome(Arab:string):string;overload; var des:integer; //кол-во десятков Rome:string; i:integer; begin des:=Arab div 10; for i:=1 to des do begin Rome:=Rome+'X'; end; Rome:=Rome+Edin(Arab mod 10); result:=Rome; end; //-------------------------- } //-------------------------- function padl(str:string;char_cnt:integer;fill_ch:char):string; var i:integer; tmp:string; begin tmp:=''; for i:=0 to char_cnt-length(str)-1 do begin tmp:=tmp+fill_ch; end; result:=tmp+str; end; //--------------------------- //--------------------------- function mw(father_name:string):integer; var tmp:integer; okonch:string; begin okonch:=ansilowercase(copy(father_name,Length(father_name)-1,2)); tmp:=-1; if (okonch='ич') or (okonch='лы') then tmp:=1 else if (okonch='на') or (okonch='зы')then tmp:=2; result:=tmp; end; //--------------------------- //---------------------------- function AnalyseMW(mw:integer):string; var tmp:string; begin case mw of 1:tmp:='1'; 0:tmp:='2'; -1:tmp:='-'; end; result:=tmp; end; function AnalyseMW(mw:string):string;overload; var tmp:string; begin if (mw='М') or (mw = 'муж.') then tmp:='1'; if (mw='Ж') or (mw = 'жен.') then tmp:='2'; result:=tmp; end; //---------------------------- //************** function GetInitials(full_fio:string):string; var tmp:string; i:integer; begin tmp:=''; i:=Pos(' ',full_fio); tmp:=copy(full_fio,0,i)+ copy(full_fio,i,2)+'.'+ copy(full_fio,PosEx(' ',full_fio,i+1),2)+'.'; result:=tmp; end; //************** //--- function Digit25(str1,str2,str3:string):string;overload; var tmp:string; begin if Length(str1+'-'+str2+ '('+str3+')')>24 then tmp:=str1 else if str2<>'' then tmp:=str1+'-'+str2+'('+str3+')' else tmp:=str1; result:=tmp; end; //--- //--------- function Digit25(str1,str2:string):string; var tmp:string; begin if Length(str1+'-'+str2)>24 then tmp:=str1 else if str2<>'' then begin if Pos('ВАЗ',str1)=0 then tmp:=str1+'-'+str2 else tmp:=str1+' '+str2 end else tmp:=str1; result:=tmp; end; //--------- //--------- procedure LoadParam(local,reg:integer); var regs:TRegistry; begin regs:=TRegistry.Create; // regs.RootKey:=HKEY_CURRENT_MACHINE; if regs.OpenKey('IT\pvs',true) then begin // local:=regs.ReadInteger(regs); end end; //--------- //--- function InvertToken(str:string;delimiter:char):string; var tmp:string; token:TToken; i:integer; delim_cnt,curr_token:integer; TokenList:TTokenList; begin tmp:=''; token:=''; curr_token:=0; delim_cnt:=0; //избавились от оконечных пробелов str:=Trim(str); //подсчитали колво разделителей, -> слов колво_разд+1 for i := 0 to Length(str)-1 do begin if str[i]=delimiter then delim_cnt:=delim_cnt+1; end; SetLength(TokenList,delim_cnt+1); for i:=1 to Length(str) do begin if str[i]<>delimiter then token:=token+str[i] else begin curr_token:=curr_token+1; TokenList[delim_cnt+1-curr_token]:=token; token:=''; end end; //для последнего слова curr_token:=curr_token+1; TokenList[delim_cnt+1-curr_token]:=token; for i:=0 to delim_cnt do begin tmp:=tmp+TokenList[i]+delimiter; end; result:=tmp; end; //--- //--- function Z2Addr(addr:string):string; { var tmp:string; TokenList:TTokenList; _beg,_end:integer; strana,obl,gor,punct,dom,korpus,kv:string; } begin { DevideStringToToken(addr,' ',TokenList); _beg:=Pos('г.',addr); _end:=Pos(' ',addr); gor:=copy(addr,_beg,_end-_beg); _beg:=PosEx(' ',addr,Pos('gor',addr)+1); _end:=Pos('область',addr); obl:=copy(addr,_beg,_end-_beg); _beg:=Pos('ул.',addr); } end; //--- //--- procedure DevideStringToToken(str:string;delimiter:char;out TokenList:TTokenList;out TokenListSize:integer);overload; var tmp:string; token:TToken; i:integer; delim_cnt,curr_token:integer; begin tmp:=''; token:=''; curr_token:=0; delim_cnt:=0; //избавились от оконечных пробелов str:=Trim(str); //подсчитали колво разделителей, -> слов колво_разд+1 for i := 0 to Length(str) do begin if str[i]=delimiter then delim_cnt:=delim_cnt+1; end; SetLength(TokenList,delim_cnt+2); for i:=1 to Length(str) do begin if str[i]<>delimiter then token:=token+str[i] else begin // TokenList[delim_cnt+1-curr_token]:=token; TokenList[curr_token]:=token; curr_token:=curr_token+1; token:=''; end end; //для последнего слова // curr_token:=curr_token+1; // TokenList[delim_cnt+1-curr_token]:=token; TokenList[curr_token]:=token; TokenListSize:=delim_cnt+2; end; procedure DevideStringToToken(str:string;delimiter:char;out TokenList:TTokenList); var tmp:string; token:TToken; i:integer; delim_cnt,curr_token:integer; begin tmp:=''; token:=''; curr_token:=0; delim_cnt:=0; //избавились от оконечных пробелов str:=Trim(str); //подсчитали колво разделителей, -> слов колво_разд+1 for i := 0 to Length(str)-1 do begin if str[i]=delimiter then delim_cnt:=delim_cnt+1; end; SetLength(TokenList,delim_cnt+2); for i:=1 to Length(str) do begin if str[i]<>delimiter then token:=token+str[i] else begin // TokenList[delim_cnt+1-curr_token]:=token; TokenList[curr_token]:=token; curr_token:=curr_token+1; token:=''; end end; //для последнего слова // curr_token:=curr_token+1; // TokenList[delim_cnt+1-curr_token]:=token; TokenList[curr_token]:=token; end; //--- //--- function MonthToDig(month:string):string; var tmp:string; begin tmp:='-1'; if Pos('янв',month)>0 then tmp:='01'; if Pos('фев',month)>0 then tmp:='02'; if Pos('мар',month)>0 then tmp:='03'; if Pos('апр',month)>0 then tmp:='04'; if (Pos('май',month)>0) or (Pos('мая',month)>0) then tmp:='05'; if Pos('июн',month)>0 then tmp:='06'; if Pos('июл',month)>0 then tmp:='07'; if Pos('авг',month)>0 then tmp:='08'; if Pos('сен',month)>0 then tmp:='09'; if Pos('окт',month)>0 then tmp:='10'; if Pos('ноя',month)>0 then tmp:='11'; if Pos('дек',month)>0 then tmp:='12'; result:=tmp; end; //--- //--- function DoubleSurname(surname:string;delim:string;num:integer):string; var tmp:string; _start,_end:integer; begin if num>2 then begin tmp:=surname; result:=tmp; exit; end; if Pos(delim,surname)=1 then surname:=copy(surname,2,Length(surname)-1); if Pos(delim,surname)>0 then begin if num=1 then begin _start:=1; _end:=Pos(delim,surname)-1; end else begin _start:=Pos(delim,surname)+1; _end:=Length(surname)-_start+1; end; tmp:=trim(copy(surname,_start,_end)); end else tmp:=surname; result:=tmp; end; //--- //--- function CheckDate(date:string;newdate:string='01.01.2000'):string; var tmp:string; begin tmp:=date; if date='00.00.0000' then tmp:=newdate; result:=tmp; end; //--- function InMadeList(idx:integer;MadeList:TStringList):boolean; var tmp:boolean; i:integer; begin tmp:=false; for i:=0 to MadeList.Count-1 do begin if idx = StrToInt(copy(MadeList.Strings[i],1,Pos('=>>',MadeList.Strings[i])-1)) then begin tmp:=true; break; end; end; result:=tmp; end; //--- end.
unit DKey; (***************************************************************************** Prozessprogrammierung SS08 Aufgabe: Muehle Beinhaltet die Tastentask fuer den Anzeigerechner. Autor: Alexander Bertram (B_TInf 2616) *****************************************************************************) interface procedure KeyTask; implementation uses RTKernel, RTKeybrd, RTTextIO, Types, DTypes, Tools, Board, Logger, LoggerMB, ProcMB, DIPXSnd, Semas; procedure ShowKeySettings(var f: text); (***************************************************************************** Beschreibung: Zeigt die Tastenbelegung an. In: f: text: Textdateivariable fuer die Ausgabe Out: - *****************************************************************************) begin Write(f, FormFeed); WriteLn(f, '[S] Spiel starten'); WriteLn(f, '[B] Spiel beenden'); WriteLn(f, '[', #$1B#$1A#$18#$19'] Cursor bewegen'); WriteLn(f, '[Enter] Spielstein setzen, markieren, ziehen, schlagen'); WriteLn(f, '[Esc] Programm beenden', #$A#$D); end; {$F+} procedure KeyTask; (***************************************************************************** Beschreibung: Tastentask. In: - Out: - *****************************************************************************) var Key: char; BoardMessage: TBoardMessage; LoggerMessage: TLoggerMessage; KeyIn, KeyOut: text; ProcessMessage: TProcessMessage; Success: boolean; begin Debug('Wurde erzeugt'); { Fenster erzeugen } Debug('Erzeuge Fenster'); NewWindow(KeyIn, KeyOut, cKeyWindowFirstCol, cKeyWindowFirstRow, cKeyWindowLastCol, cKeyWindowLastRow, cKeyWindowColor, ' ' + cKeyTaskName + ' '); Debug('Fenster erzeugt'); { Tastenbelegung anzeigen } ShowKeySettings(KeyOut); while true do begin { Auf Tastendruck warten } Debug('Warte auf Tastendruck'); Key := RTKeybrd.ReadKey; Debug('Taste gedrueckt'); { Taste analaysieren } Debug('Analysiere Taste'); case UpCase(Key) of { Enter } #13: begin Debug('Enter gedrueckt'); { Positionswahl an Spielfeld melden } BoardMessage.Kind := bmkFieldPositionSelection; BoardMB.Put(Board.Mailbox, BoardMessage); end; { Escape } #27: begin Debug('Escape gedrueckt'); { Abfrage, ob Programm beendet werden soll } Write(KeyOut, 'Programm wirklich beenden? [J]/[N]'); repeat { Auf Tastendruck warten } Key := UpCase(RTKeybrd.ReadKey); if Key = 'J' then begin { Programmende an Prozessrechner senden } ProcessMessage.Kind := prmkExit; ProcMB.Put(DIPXSnd.Mailbox, ProcessMessage); {$IFDEF DEBUG} { Programmende dem Logger senden } LoggerMessage.Kind := lomkExit; LoggerMB.Put(Logger.Mailbox, LoggerMessage); {$ELSE} { Ereignis in der Exitsemaphore speichern } Signal(ExitSemaphore); {$ENDIF} end; until (Key = 'J') or (Key = 'N'); { Tastenbelegung anzeigen } ShowKeySettings(KeyOut); end; { Sondertaste } #0: begin Debug('Sondertaste gedrueckt'); { Sondertaste auswerten } Key := ReadKey; case Key of { Links } #75: begin Debug('Pfeiltaste nach links gedrueckt'); { Cursorbewegung nach links ans Spielfeld senden } BoardMessage.Kind := bmkCursorMove; BoardMessage.Direction := dLeft; BoardMB.Put(Board.Mailbox, BoardMessage); end; { Rechts } #77: begin Debug('Pfeiltaste nach rechts gedrueckt'); { Cursorbewegung nach rechts ans Spielfeld senden } BoardMessage.Kind := bmkCursorMove; BoardMessage.Direction := dRight; BoardMB.Put(Board.Mailbox, BoardMessage); end; { Hoch } #72: begin Debug('Pfeiltaste nach oben gedrueckt'); { Cursorbewegung nach oben ans Spielfeld senden } BoardMessage.Kind := bmkCursorMove; BoardMessage.Direction := dUp; BoardMB.Put(Board.Mailbox, BoardMessage); end; { Runter } #80: begin Debug('Pfeiltaste nach unten gedrueckt'); { Cursorbewegung nach unten ans Spielfeld senden } BoardMessage.Kind := bmkCursorMove; BoardMessage.Direction := dDown; BoardMB.Put(Board.Mailbox, BoardMessage); end; end; end; 'S': begin Debug('S gedrueckt'); { Spielstart an den Prozessrechner senden } ProcessMessage.Kind := prmkStartGame; ProcMB.PutCond(DIPXSnd.Mailbox, ProcessMessage, Success); end; 'B': begin Debug('B gedrueckt'); { Spielende an den Prozessrechner senden } ProcessMessage.Kind := prmkEndGame; ProcMB.PutCond(DIPXSnd.Mailbox, ProcessMessage, Success); end; end; { Taskwechsel } RTKernel.Delay(0); end; end; end.
unit frmExceptionInThread; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, uExceptionInThread; type TForm52 = class(TForm) Memo1: TMemo; Button1: TButton; procedure Button1Click(Sender: TObject); private { Private declarations } FThread: TExceptionThread; public { Public declarations } procedure HandleException(Sender: TObject); end; var Form52: TForm52; implementation {$R *.dfm} procedure TForm52.Button1Click(Sender: TObject); begin FThread := TExceptionThread.Create(Memo1); FThread.OnTerminate := HandleException; FThread.Start; end; procedure TForm52.HandleException(Sender: TObject); var LThread: TExceptionThread; begin if Sender is TExceptionThread then begin LThread := TExceptionThread(Sender); end else begin Memo1.Lines.Add('Sender is not a TExceptionThread'); Exit; end; if LThread.FatalException <> nil then begin if LThread.FatalException is Exception then begin // Cast to Exception needed because FatalException is a TObject Memo1.Lines.Add(Exception(LThread.FatalException).Message); end; end; end; end.
program ejer3; const valorAlto = 999; type producto = record codigo: integer; descripcion: string; precio: real; stock_actual: integer; stock_minimo: integer; end; pedido = record codigo: integer; cantidad: integer; end; arc_maestro = file of producto; arc_detalle = file of pedido; vector_detalle = array[1..4] of arc_detalle; vector_registro = array[1..4] of pedido; {----------------- LEER PRODUCTO MAESTRO ---------------} procedure leer_producto(var p: producto); begin write('Codigo: '); readln(p.codigo); if (p.codigo <> -1) then begin write('Descripcion: '); readln(p.descripcion); write('Precio: '); readln(p.precio); write('Stock actual: '); readln(p.stock_actual); write('Stock minimo: '); readln(p.stock_minimo); writeln('-------------'); end; end; {--------------------- CARGAR ARCHIVO MAESTRO ----------------------} procedure cargar_archivo_maestro(var arc: arc_maestro); var p: producto; begin rewrite(arc); leer_producto(p); while(p.codigo <> -1) do begin write(arc, p); leer_producto(p); end; close(arc); writeln('ARCHIVO MAESTRO CARGADO'); end; {-------------MOSTRAR EN PANTALLA EL ARCHIVO MAESTRO-----------------} procedure imprimir_arc_maestro(var arc_m: arc_maestro); var p: producto; begin reset(arc_m); writeln('ARCHIVO MAESTRO'); while(not eof(arc_m)) do begin read(arc_m, p); writeln(); writeln('Codigo: ', p.codigo ); writeln('Descripcion: ', p.descripcion); writeln('Precio: ', p.precio:2:2); writeln('Stock actual: ', p.stock_actual); writeln('Stock minimo: ', p.stock_minimo); writeln('-------------------------'); end; close(arc_m); end; {------------------ LEER PEDIDOS DETALLE --------------} procedure leer_detalle(var pd: pedido); begin write('Codigo: '); readln(pd.codigo); if (pd.codigo <> -1) then begin write('Cantidad: '); readln(pd.cantidad); writeln('-------------'); end; end; {-------------- CARGAR ARCHIVOS DETALLE DE LAS 4 SUCURSALES ---------} procedure cargar_archivo_detalle(var vec_d: vector_detalle); var i: integer; pd: pedido; begin for i:= 1 to 4 do begin rewrite(vec_d[i]); writeln('CARGAR SUCURSAL ', i); writeln(); leer_detalle(pd); while(pd.codigo <> -1) do begin write(vec_d[i], pd); leer_detalle(pd); end; writeln('SUCURSAL ', i, ' CARGADA'); end; writeln(); writeln('ARCHIVO DETALLE CARGADO'); end; {---------MOSTRAR EN PANTALLA EL ARCHIVO DETALLE----------} procedure imprimir_arc_detalle(var vec_d: vector_detalle); var pd: pedido; i: integer; begin writeln(); writeln('ARCHIVO DETALLE'); for i:= 1 to 4 do begin reset(vec_d[i]); writeln('SUCURSAL ', i); while(not eof(vec_d[i])) do begin read(vec_d[i], pd); writeln(); writeln('Codigo: ', pd.codigo); writeln('Cantidad: ', pd.cantidad); writeln('-------------------------'); end; close(vec_d[i]); end; end; {--------------- LEO EL REGISTRO SI NO LLEGO A SU FINAL -----------} procedure leer (var arc_d: arc_detalle; var pd: pedido); begin if (not eof(arc_d)) then begin read(arc_d, pd); end else pd.codigo:= valorAlto; end; {----------------- MINIMO --------------} procedure minimo (var vec_d:vector_detalle; var vec_r:vector_registro; var reg_min:pedido; var suc: integer); var reg: pedido; i, posMin, aux:integer; begin reg_min.codigo:= valorAlto; aux:= 9999; for i:= 1 to 4 do begin if (vec_r[i].codigo < aux) then begin aux:= vec_r[i].codigo; reg_min:= vec_r[i]; posMin:= i; end; end; if (reg_min.codigo <> valorAlto) then begin leer(vec_d[posMin], reg); vec_r[posMin]:= reg; suc:= posMin; end; end; {-------------- IMPRIMIR REGISTRO ----------------} procedure imprimir_registro(p: producto); begin writeln('Codigo: ', p.codigo); writeln('Descripcion: ', p.descripcion); writeln('Precio: ', p.precio:2:2); writeln('Stock actual: ', p.stock_actual); writeln('Stock minimo: ', p.stock_minimo); writeln('-------------'); end; {--------------- ACTUALIZAR MAESTRO -------------} procedure actualizar_maestro(var arc_m: arc_maestro; var vec_d: vector_detalle); var vec_r: vector_registro; prod: producto; reg_min: pedido; suc,i: integer; begin for i:= 1 to 4 do begin reset(vec_d[i]); leer(vec_d[i], vec_r[i]); // PONGO EN EL VECTOR REGISTRO EL PRIMER ELEMENTO DE CADA DETALLE end; reset(arc_m); minimo(vec_d, vec_r, reg_min, suc); //SACO EL MINIMO ENTRE LOS ELEMENTOS DEL VECTOR REGISTRO while(reg_min.codigo <> valorAlto) do begin read(arc_m, prod); while(prod.codigo <> reg_min.codigo) do read(arc_m, prod); while(prod.codigo = reg_min.codigo) do begin if (prod.stock_actual >= reg_min.cantidad) then //SI EL STOCK ACTUAL ES MAYOR O IGUAL A LA CANTIDAD HAGO EL PEDIDO Y RESTO EL STOCK prod.stock_actual:= prod.stock_actual - reg_min.cantidad else begin writeln('No se pudo satisfacer'); writeln('Sucursal ', suc ); imprimir_registro(prod); writeln('Cantidad que no pudo ser enviada: ', (reg_min.cantidad - prod.stock_actual)); prod.stock_actual:= 0; end; if (prod.stock_actual < prod.stock_minimo) then begin //PREGUNTO SI EL STOCK QUE QUEDO ES MENOR AL STOCK MINIMO writeln('Producto debajo del stock minimo'); imprimir_registro(prod); end; minimo(vec_d, vec_r, reg_min, suc); end; seek(arc_m,(filePos(arc_m)-1)); write(arc_m, prod); end; close(arc_m); end; var arc_m: arc_maestro; vec_d: vector_detalle; i: integer; j: string; begin assign(arc_m, 'ejer3_archivoMaestro'); writeln('CARGAR ARCHIVO MAESTRO'); cargar_archivo_maestro(arc_m); imprimir_arc_maestro(arc_m); for i:= 1 to 4 do begin str(i, j); assign(vec_d[i], 'detalle' + j); end; writeln('CARGAR ARCHIVOS DETALLES'); cargar_archivo_detalle(vec_d); imprimir_arc_detalle(vec_d); actualizar_maestro(arc_m, vec_d); imprimir_arc_maestro(arc_m); end.
unit FOwnership; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo, FBase, UBase, USampleClasses; type TFrameOwnership = class(TFrameBase) ButtonCreateObjectTree: TButton; ButtonDeleteFirstBranch: TButton; ButtonFreeObjectTree: TButton; procedure ButtonCreateObjectTreeClick(Sender: TObject); procedure ButtonDeleteFirstBranchClick(Sender: TObject); procedure ButtonFreeObjectTreeClick(Sender: TObject); private { Private declarations } FTree: TSampleNode; FBranch1: TSampleNode; public { Public declarations } end; implementation {$R *.fmx} procedure TFrameOwnership.ButtonCreateObjectTreeClick(Sender: TObject); var Branch2, SubBranch: TSampleNode; I: Integer; begin ButtonCreateObjectTree.Enabled := False; ButtonDeleteFirstBranch.Enabled := True; ButtonFreeObjectTree.Enabled := True; { Create the root without a parent. This is the only object we need to free at some point. } FTree := TSampleNode.Create(nil); { Create two branches and add them to the root } FBranch1 := TSampleNode.Create(FTree); Branch2 := TSampleNode.Create(FTree); { Create a reference cycle between these two branches. Since the Link property is implemented using a [weak] reference, this will NOT lead to a memory leak. } FBranch1.Link := Branch2; Branch2.Link := FBranch1; { Add 5 sub-branches to FBranch1. } for I := 0 to 4 do begin SubBranch := TSampleNode.Create(FBranch1); { Create a reference cycle between the sub-branch and its owner } SubBranch.Link := FBranch1; end; { We should have a total of 1 + 2 + 5 = 8 live objects now. } Log('----------------------------------------------------'); Log('Created Object Tree with two branches, where the first branch has ' + 'five sub-branches for a total of 1 + 2 + 5 = 8 objects.'); Log(' * TSampleNode.InstanceCount = %d', [TSampleNode.InstanceCount]); Log(''); end; procedure TFrameOwnership.ButtonDeleteFirstBranchClick(Sender: TObject); begin { Delete the first branch. We also need to set its reference to nil on ARC platforms, otherwise the branch will stay alive and not be released. } FBranch1.Delete; FBranch1 := nil; Log('Freed first branch with its 5 sub-branches. ' + 'So only 2 instances should remain (the root and the second branch).'); Log(' * TSampleNode.InstanceCount = %d', [TSampleNode.InstanceCount]); Log(''); ButtonDeleteFirstBranch.Enabled := False; end; procedure TFrameOwnership.ButtonFreeObjectTreeClick(Sender: TObject); begin ButtonCreateObjectTree.Enabled := True; ButtonDeleteFirstBranch.Enabled := False; ButtonFreeObjectTree.Enabled := False; { Free tree and all its branches and sub-branches. On ARC platforms, we need to set FTree to nil to release any references. } FTree.Free; FTree := nil; { There is another subtle but important difference between ARC and non-ARC platforms: * On ARC platforms, the FBranch1 field may keep a whole branch of the tree alive, so we need to set it to nil to free it and its sub-branches. * On non-ARC platforms, freeing the FTree also freed all its branches and sub-branches, so the FBranch1 field may be an invalid reference now (a dangling pointer). So we should also set it to nil. } FBranch1 := nil; Log('Freed entire Object Tree with all branches and sub-branches.'); Log(' * TSampleNode.InstanceCount = %d', [TSampleNode.InstanceCount]); Log(''); end; end.
{ hello -- print a friendly greeting Autor: Lorenzo Cabrini <lorenzo.cabrini@gmail.com> } program hello; begin writeln('Hello world!'); end.
{****************************************************************************} { @@Copyright:SUNTOGETHER } { @@Summary:框架部分常量和变量。 } { @@Description: } { @@Author: Suntogether } { @@Version:1.0 } { @@Create:2007-01-15 } { @@Remarks: } { @@Modify: } {****************************************************************************} unit FrameCommon; interface uses Classes,SysUtils,DebuggerImpl,DataAccessInt; const TabSeparator=#9; //LocalNetAccessTypeName='6A87A31D0E534F1881AB12CD780D0484'; //LocalNetAccessTypeName='C5CCEA1F-4C04-47F3-8F01-D1258019973B'; LocalNetAccessTypeName= '2E6B016E-8753-4506-87BE-0F76E2CA9A29'; DefaultGetKeyIdProcedureName='stp_GetNextSequence'; DefaultRollBackKeyIdProcedureName='stp_RollBackNextSequence'; DefaultResetKeyIdProcedureName='stp_ResetNextSequence'; DefaultDBScriptFileDirectory='DBScript\'; var //Summary: // 当前系统编号 CurrentSystemNumber:LongInt; //Summary: // 保存调试信息 Debugger:TDebugger; DataAccessFactory:IDataAccessFactoryInt ; implementation uses Forms; initialization Debugger:=TDebugger.Create(nil); finalization FreeAndNil(Debugger); end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [PONTO_MARCACAO] The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit PontoMarcacaoVO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils, PontoFechamentoJornadaVO; type [TEntity] [TTable('PONTO_MARCACAO')] TPontoMarcacaoVO = class(TVO) private FID: Integer; FID_COLABORADOR: Integer; FID_PONTO_RELOGIO: Integer; FNSR: Integer; FDATA_MARCACAO: TDateTime; FHORA_MARCACAO: String; FTIPO_MARCACAO: String; FTIPO_REGISTRO: String; FPAR_ENTRADA_SAIDA: String; FJUSTIFICATIVA: String; //Transientes FListaPontoMarcacao: TObjectList<TPontoMarcacaoVO>; FListaPontoFechamentoJornada: TObjectList<TPontoFechamentoJornadaVO>; public constructor Create; override; destructor Destroy; override; [TId('ID', [ldGrid, ldLookup, ldComboBox])] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_COLABORADOR', 'Id Colaborador', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdColaborador: Integer read FID_COLABORADOR write FID_COLABORADOR; [TColumn('ID_PONTO_RELOGIO', 'Id Ponto Relogio', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdPontoRelogio: Integer read FID_PONTO_RELOGIO write FID_PONTO_RELOGIO; [TColumn('NSR', 'Nsr', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property Nsr: Integer read FNSR write FNSR; [TColumn('DATA_MARCACAO', 'Data Marcacao', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataMarcacao: TDateTime read FDATA_MARCACAO write FDATA_MARCACAO; [TColumn('HORA_MARCACAO', 'Hora Marcacao', 64, [ldGrid, ldLookup, ldCombobox], False)] property HoraMarcacao: String read FHORA_MARCACAO write FHORA_MARCACAO; [TColumn('TIPO_MARCACAO', 'Tipo Marcacao', 8, [ldGrid, ldLookup, ldCombobox], False)] property TipoMarcacao: String read FTIPO_MARCACAO write FTIPO_MARCACAO; [TColumn('TIPO_REGISTRO', 'Tipo Registro', 8, [ldGrid, ldLookup, ldCombobox], False)] property TipoRegistro: String read FTIPO_REGISTRO write FTIPO_REGISTRO; [TColumn('PAR_ENTRADA_SAIDA', 'Par Entrada Saida', 16, [ldGrid, ldLookup, ldCombobox], False)] property ParEntradaSaida: String read FPAR_ENTRADA_SAIDA write FPAR_ENTRADA_SAIDA; [TColumn('JUSTIFICATIVA', 'Justificativa', 450, [ldGrid, ldLookup, ldCombobox], False)] property Justificativa: String read FJUSTIFICATIVA write FJUSTIFICATIVA; //Transientes /// OBS: essas listas só serão utilizadas para inserir dados no banco. são são "anotadas" para não realizar consultas no ORM property ListaPontoMarcacao: TObjectList<TPontoMarcacaoVO> read FListaPontoMarcacao write FListaPontoMarcacao; property ListaPontoFechamentoJornada: TObjectList<TPontoFechamentoJornadaVO> read FListaPontoFechamentoJornada write FListaPontoFechamentoJornada; end; implementation constructor TPontoMarcacaoVO.Create; begin inherited; FListaPontoMarcacao := TObjectList<TPontoMarcacaoVO>.Create; FListaPontoFechamentoJornada := TObjectList<TPontoFechamentoJornadaVO>.Create; end; destructor TPontoMarcacaoVO.Destroy; begin FreeAndNil(FListaPontoMarcacao); FreeAndNil(FListaPontoFechamentoJornada); inherited; end; initialization Classes.RegisterClass(TPontoMarcacaoVO); finalization Classes.UnRegisterClass(TPontoMarcacaoVO); end.
{ ******************************************************************************* Title: T2Ti ERP Description: Unit para armazenas as constantes do sistema The MIT License Copyright: Copyright (C) 2020 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> @author Albert Eije (T2Ti.COM) @version 3.0 ******************************************************************************* } unit Constantes; interface uses IniFiles; type TConstantes = class const {$WRITEABLECONST ON} MAXIMO_REGISTROS_RETORNADOS = 50; QUANTIDADE_POR_PAGINA = 50; DECIMAIS_QUANTIDADE: Integer = 3; DECIMAIS_VALOR: Integer = 2; // carregados do arquivo INI CHAVE: string = ''; VETOR: string = ''; ENDERECO_SERVIDOR: string = ''; PORTA_SERVIDOR: string = ''; ROTA_JWT: string = ''; BD_SERVER: string = ''; BD_PORTA: string = ''; BD_BANCO: string = ''; BD_USUARIO: string = ''; BD_SENHA: string = ''; {$WRITEABLECONST OFF} public constructor Create; end; implementation constructor TConstantes.Create; var IniFile: TIniFile; begin inherited; try IniFile := TIniFile.Create('c:\t2ti\ini\config-server.ini'); // servidor CHAVE := IniFile.ReadString('Servidor', 'chave', ''); VETOR := IniFile.ReadString('Servidor', 'vetor', ''); ENDERECO_SERVIDOR := IniFile.ReadString('Servidor', 'endereco', ''); PORTA_SERVIDOR := IniFile.ReadString('Servidor', 'porta', ''); ROTA_JWT := IniFile.ReadString('Servidor', 'rotajwt', ''); // banco de dados BD_SERVER := IniFile.ReadString('MySQL', 'servidor', ''); BD_PORTA := IniFile.ReadString('MySQL', 'porta', ''); BD_BANCO := IniFile.ReadString('MySQL', 'banco', ''); BD_USUARIO := IniFile.ReadString('MySQL', 'usuario', ''); BD_SENHA := IniFile.ReadString('MySQL', 'senha', ''); finally IniFile.Free; end; end; end.
unit JPL.Win.Processes; interface uses Windows, SysUtils, Classes, TlHelp32, PsAPI, ShellAPI; function GetProcessFileName(const pID: DWORD): string; function IsAppRunning(const FileName: string): Boolean; function GetThreadFileName(const tID: DWORD): string; procedure RunAsAdmin(hWnd: HWND; FileName, Parameters: string); implementation procedure RunAsAdmin(hWnd: HWND; FileName, Parameters: string); var sei: TShellExecuteInfo; begin FillChar(sei, SizeOf(sei), 0); sei.cbSize := sizeof(sei); sei.Wnd := hWnd; sei.fMask := SEE_MASK_FLAG_DDEWAIT or SEE_MASK_FLAG_NO_UI; sei.lpVerb := 'runas'; sei.lpFile := PChar(FileName); sei.lpParameters := PChar(Parameters); sei.nShow := SW_SHOWNORMAL; if not ShellExecuteEx(@sei) then RaiseLastOSError; end; function GetThreadFileName(const tID: DWORD): string; var snap: THandle; pe32: TProcessEntry32; te32: TThreadEntry32; arrProcesses: array of integer; i: integer; pID: DWORD; begin Result := ''; pID := 0; snap := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0); try pe32.dwSize := SizeOf(TProcessEntry32); if integer(Process32First(snap, pe32)) <> 0 then repeat SetLength(arrProcesses, Length(arrProcesses) + 1); arrProcesses[Length(arrProcesses) - 1] := integer(pe32.th32ProcessID); until integer(Process32Next(snap, pe32)) = 0; finally CloseHandle(snap); end; for i := 0 to Length(arrProcesses) - 1 do begin snap := CreateToolHelp32Snapshot(TH32CS_SNAPTHREAD, 0); try te32.dwSize := SizeOf(TThreadEntry32); if integer(Thread32First(snap, te32)) <> 0 then repeat if te32.th32ThreadID = tID then begin pID := te32.th32OwnerProcessID; Break; end; until integer(Thread32Next(snap, te32)) = 0; finally CloseHandle(snap); end; end; SetLength(arrProcesses, 0); if pID <> 0 then Result := GetProcessFileName(pID); end; function IsAppRunning(const FileName: string): Boolean; var snap: THandle; pe32: TProcessEntry32; begin Result := False; snap := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0); pe32.dwSize := SizeOf(TProcessEntry32); if integer(Process32First(snap, pe32)) <> 0 then repeat if UpperCase(FileName) = UpperCase(GetProcessFileName(pe32.th32ProcessID)) then begin Result := True; Break; end; until integer(Process32Next(snap, pe32)) = 0; CloseHandle(snap); end; function GetProcessFileName(const pID: DWORD): string; var hProc: HWND; buffer: array[0..1023] of Char; snap: THandle; pe32: TProcessEntry32; begin Result := ''; if (Win32Platform = VER_PLATFORM_WIN32_NT) and (Win32MajorVersion > 3) then begin hProc := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, pID); if hProc <> 0 then begin FillChar(buffer, SizeOf(buffer), 0); GetModuleFileNameEx(hProc, 0, buffer, SizeOf(buffer)); Result := buffer; end; CloseHandle(hProc); end else begin snap := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0); pe32.dwSize := SizeOf(TProcessEntry32); if integer(Process32First(snap, pe32)) <> 0 then repeat if integer(pID) = integer(pe32.th32ProcessID) then begin Result := pe32.szExeFile; Break; end; until integer(Process32Next(snap, pe32)) = 0; CloseHandle(snap); end; end; end.
// debugging services for KDBManager // backdoor unit KDBDebug; { Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface implementation uses Backdoor, KBase, KDBLogging, KDBManager, KDBHtmlSupport, KProcs, SysUtils; type TKDBBackdoor = class (TBaseObject) private function RunSQLQuery(AConnMan : TKDBManager; ACommand, AURL : String):String; procedure DbgDatabase(const ACommand, AURL: String; var VResult: String); procedure ConnListChange(AConnMan : TKDBManager; ABeingCreated : Boolean); public constructor create; destructor destroy; override; end; { TKDBBackdoor } constructor TKDBBackdoor.create; var i : integer; begin inherited; KDBManagers.RegisterHook('KDBDebug', ConnListChange); for i := 0 to KDBManagers.Count - 1 do begin ConnListChange(KDBManagers.ConnMan[i], true); end; end; destructor TKDBBackdoor.destroy; begin KDBManagers.UnRegisterHook('KDBDebug'); inherited; end; procedure TKDBBackdoor.ConnListChange(AConnMan : TKDBManager; ABeingCreated : Boolean); begin AConnMan.Tag := SysIDbg.RegisterCommand('KDBManager', AConnMan.Name, 'KDBManager: '+AConnMan.Name, DBG_SEC_ANONYMOUS, DbgDatabase); end; function TKDBBackdoor.RunSQLQuery(AConnMan : TKDBManager; ACommand, AURL : String):String; var LSql : String; LConn : TKDBConnection; begin split(ACommand, '=', ACommand, LSQL); LSQL := MimeDecode(LSql); // extract sql.... if LSql = '' then begin result := '<form action="'+AURL+'" method="get"><input type="text" size=80 name="sql"><br><input type="submit"></form>'; end else begin LConn := AConnMan.GetConnection('backdoor'); try result := DirectSQLInHTML(LConn, LSQL); LConn.Release; except on e:exception do begin LConn.Error(e); result := e.message; end; end; end; end; procedure TKDBBackdoor.DbgDatabase(const ACommand, AURL: String; var VResult: String); var LConnMan : TKDBManager; s, t : String; begin LConnMan := KDBManagers[GetStringCell(AURL, 2, '/')]; if ACommand = '' then begin VResult := 'KDBManager: '+LConnMan.DBDetails+':<br>'+ '<a href="'+AURL+'/use">Current Use</a><br>'+ '<a href="'+AURL+'/stats">Stats</a><br>'+ '<a href="'+AURL+'/sql">SQL</a><br>'; end else begin if SameText(ACommand, 'use') then begin VResult := LConnMan.GetConnSummary; end else if SameText(copy(ACommand, 1, 5), 'stats') then begin split(ACommand, '/', t, s); VResult := LConnMan.Logger.InteractiveReport(MimeDecode(s), AUrl+'/stats'); end else if SameText(copy(ACommand, 1, 3), 'sql') then begin VResult := RunSQLQuery(LConnMan, ACommand, AUrl); end else begin VResult := 'Unknown command '+ACommand; end; end; end; var GKDBBackdoor : TKDBBackdoor; initialization GKDBBackdoor := TKDBBackdoor.create; finalization FreeAndNil(GKDBBackdoor); end.
unit PageControlSimple; interface uses SysUtils, Classes, Controls, ComCtrls, Messages, CommCtrl, Windows; type TPageControlSimple = class(TPageControl) private function GetActivePageIndex: Integer; procedure HideTitle; procedure SetActivePageIndex(const Value: Integer); { Private declarations } protected procedure Loaded; override; { Protected declarations } procedure WndProc(var Message: TMessage); override; public constructor Create(AOwner: TComponent); override; property ActivePageIndex: Integer read GetActivePageIndex write SetActivePageIndex; Procedure AdjustClientRect(var Rect: TRect); override; { Public declarations } published { Published declarations } end; procedure Register; implementation procedure Register; begin RegisterComponents('KIV', [TPageControlSimple]); end; procedure TPageControlSimple.AdjustClientRect(var Rect: TRect); begin inherited; if (csDesigning in ComponentState) then Inherited AdjustClientRect(Rect) else Rect.Top:=0; end; constructor TPageControlSimple.Create(AOwner: TComponent); begin inherited Create(AOwner); Style:=tsFlatButtons; end; function TPageControlSimple.GetActivePageIndex: Integer; begin Result:=inherited ActivePageIndex; end; procedure TPageControlSimple.HideTitle; var i: Integer; begin for i:=0 to PageCount-1 do Pages[i].TabVisible:=False; end; procedure TPageControlSimple.Loaded; begin inherited Loaded; if not ((csDesigning in ComponentState) or (csReading in ComponentState)) then ActivePageIndex:=ActivePageIndex; end; procedure TPageControlSimple.SetActivePageIndex(const Value: Integer); begin HideTitle; inherited ActivePageIndex:=Value; end; procedure TPageControlSimple.WndProc(var Message: TMessage); begin inherited WndProc(Message); with Message do if (Msg = TCM_ADJUSTRECT) and (Message.WParam = 0) then InflateRect(PRect(LParam)^, 4, 4); end; end.
{ ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Framework.) @created(20 Jul 2016) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Skype : ispinheiro) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } unit ormbr.session.objectset; interface uses DB, Rtti, TypInfo, Classes, Variants, SysUtils, Generics.Collections, /// ORMBr ormbr.bind, ormbr.objects.manager, ormbr.session.abstract, dbebr.factory.interfaces; type // M - Sessão Abstract TSessionObjectSet<M: class, constructor> = class(TSessionAbstract<M>) protected FConnection: IDBConnection; public constructor Create(const AConnection: IDBConnection; const APageSize: Integer = -1); overload; destructor Destroy; override; procedure LoadLazy(const AOwner, AObject: TObject); override; procedure NextPacketList(const AObjectList: TObjectList<M>); overload; override; function NextPacketList: TObjectList<M>; overload; override; function NextPacketList(const APageSize, APageNext: Integer): TObjectList<M>; overload; override; function NextPacketList(const AWhere, AOrderBy: String; const APageSize, APageNext: Integer): TObjectList<M>; overload; override; end; implementation { TSessionObjectSet<M> } constructor TSessionObjectSet<M>.Create(const AConnection: IDBConnection; const APageSize: Integer); begin inherited Create(APageSize); FConnection := AConnection; FManager := TObjectManager<M>.Create(Self, AConnection, APageSize); end; procedure TSessionObjectSet<M>.LoadLazy(const AOwner, AObject: TObject); begin inherited; FManager.LoadLazy(AOwner, AObject); end; function TSessionObjectSet<M>.NextPacketList(const AWhere, AOrderBy: String; const APageSize, APageNext: Integer): TObjectList<M>; begin inherited; Result := nil; if FFetchingRecords then Exit; Result := FManager.NextPacketList(AWhere, AOrderBy, APageSize, APageNext); if Result = nil then Exit; if Result.Count > 0 then Exit; FFetchingRecords := True; end; function TSessionObjectSet<M>.NextPacketList(const APageSize, APageNext: Integer): TObjectList<M>; begin inherited; Result := nil; if FFetchingRecords then Exit; Result := FManager.NextPacketList(APageSize, APageNext); if Result = nil then Exit; if Result.Count > 0 then Exit; FFetchingRecords := True; end; destructor TSessionObjectSet<M>.Destroy; begin FManager.Free; inherited; end; procedure TSessionObjectSet<M>.NextPacketList(const AObjectList: TObjectList<M>); begin inherited; if FFetchingRecords then Exit; FPageNext := FPageNext + FPageSize; if FFindWhereUsed then FManager.NextPacketList(AObjectList, FWhere, FOrderBy, FPageSize, FPageNext) else FManager.NextPacketList(AObjectList, FPageSize, FPageNext); /// <summary> /// if AObjectList = nil then /// Exit; /// if AObjectList.RecordCount > 0 then /// Exit; /// FFetchingRecords := True; /// Esse código para definir a tag FFetchingRecords, está sendo feito no /// método NextPacketList() dentro do FManager. /// </summary> end; function TSessionObjectSet<M>.NextPacketList: TObjectList<M>; begin inherited; Result := nil; if FFetchingRecords then Exit; FPageNext := FPageNext + FPageSize; if FFindWhereUsed then Result := FManager.NextPacketList(FWhere, FOrderBy, FPageSize, FPageNext) else Result := FManager.NextPacketList(FPageSize, FPageNext); if Result = nil then Exit; if Result.Count > 0 then Exit; FFetchingRecords := True; end; end.
{*******************************************************} { } { Functions for VirtualTree Drag&Drop implementation } { } {*******************************************************} unit VSTDragDrop_win; interface uses VirtualTrees, vstUtils, ActiveX, ShellAPI, Classes, Types, Windows; type { Implements the drag&drop functions called by the files tree in frmMain VSTDragDrop is called on dropping a file (or any content), identifies the dropped content and calles AddItem ultimately GetFileListFromObj is a helper function to transfer an IDataObject into filepath strings, which will get added to a passed StringList } TDragEvent = class procedure VSTDragDrop(Sender: TBaseVirtualTree; Source: TObject; DataObject: IDataObject; Formats: TFormatArray; Shift: TShiftState; Pt: TPoint; var Effect: Integer; Mode: TDropMode); procedure GetFileListFromObj(const DataObj: IDataObject; FileList: TStringList); end; implementation uses ComObj; procedure TDragEvent.VSTDragDrop(Sender: TBaseVirtualTree; Source: TObject; DataObject: IDataObject; Formats: TFormatArray; Shift: TShiftState; Pt: TPoint; var Effect: Integer; Mode: TDropMode); var I, j: Integer; MyList: TStringList; begin MyList := TStringList.Create; Sender.BeginUpdate; try for i := 0 to High(formats) - 1 do begin if Formats[i] = CF_HDROP then // Explorer drop begin GetFileListFromObj(DataObject, MyList); //here we have all filenames for j:=0 to MyList.Count - 1 do begin if Mode = dmOnNode then begin AddItem(Sender,Sender.DropTargetNode,MyList.Strings[j]); end else begin AddItem(Sender,nil,MyList.Strings[j]); end; end; end else if Formats[i] = CF_VIRTUALTREE then // VirtualTree drop begin case Mode of dmNowhere: Sender.ProcessDrop(DataObject,nil,Effect,amAddChildLast); dmAbove: Sender.ProcessDrop(DataObject,Sender.DropTargetNode,Effect,amInsertBefore); dmOnNode: begin if not IsFile(Sender,Sender.DropTargetNode) then Sender.ProcessDrop(DataObject,Sender.DropTargetNode,Effect,amAddChildLast); end; dmBelow: Sender.ProcessDrop(DataObject,Sender.DropTargetNode,Effect,amInsertAfter); end; end; end; finally MyList.Free; Sender.SortTree(0,sdAscending,true); Sender.EndUpdate; end; end; procedure TDragEvent.GetFileListFromObj(const DataObj: IDataObject; FileList: TStringList); var FmtEtc: TFormatEtc; // specifies required data format Medium: TStgMedium; // storage medium containing file list DroppedFileCount: Integer; // number of dropped files I: Integer; // loops thru dropped files FileNameLength: Integer; // length of a dropped file name FileName: String; // name of a dropped file Buffer: Array [0..MAX_PATH] of Char; begin // Get required storage medium from data object FmtEtc.cfFormat := CF_HDROP; FmtEtc.ptd := nil; FmtEtc.dwAspect := DVASPECT_CONTENT; FmtEtc.lindex := -1; FmtEtc.tymed := TYMED_HGLOBAL; OleCheck(DataObj.GetData(FmtEtc, Medium)); try try // Get count of files dropped DroppedFileCount := DragQueryFile(Medium.hGlobal, $FFFFFFFF, nil, 0); // Get name of each file dropped and process it for I := 0 to Pred(DroppedFileCount) do begin // get length of file name, then name itself FileNameLength := DragQueryFile(Medium.hGlobal, I, @buffer, sizeof(buffer)); FileName := buffer; //SetLength(FileName, FileNameLength); //DragQueryFileW(Medium.hGlobal, I, PWideChar(FileName), FileNameLength + 1); // add file name to list FileList.Append(FileName); end; finally // Tidy up - release the drop handle // don't use DropH again after this DragFinish(Medium.hGlobal); end; finally ReleaseStgMedium(Medium); end; end; end.
unit UxlGrid; interface uses Windows, UxlClasses, UxlWinControl, UxlPanel, UxlListView, UxlEdit, UxlList, UxlComboBox, UxlMiscCtrls; type TGridStatus = (gsNormal, gsSizeCol, gsSizeRow, gsMoveCol, gsMoveRow); TFixedRowCol = (frcNone, frcAuto, frcUser); TDrawCellEvent = function (h_dc: HDC; const o_rect: TRect; row, col: integer): boolean of object; TxlGrid = class (TxlControl) private FEdit: TxlEdit; FComboBox: TxlComboBox; FColSlide: TxlVertSlide; FRowSlide: TxlHorzSlide; FCells: array of array of widestring; // 行,列 FColWidth, FRowHeight: array of integer; FFixedRow, FFixedCol: TFixedRowCol; FFixedColor: TColor; FFixedBrush: HBrush; FStatus: TGridStatus; FSizeRowCol: integer; FFirstRow, FFirstCol: integer; FReadOnly: boolean; FGridResizable: boolean; FOnDrawCell: TDrawCellEvent; function GetRowHeight (row: integer): integer; procedure SetRowHeight (row: integer; value: integer); function GetColWidth (col: integer): integer; procedure SetColWidth (col: integer; value: integer); function GetRowCount (): integer; procedure SetRowcount (value: integer); function GetColCount (): integer; procedure SetColCount (value: integer); procedure f_GetPageRowColCount (var i_rowcount, i_colcount: integer); function PageRowCount (): integer; function PageColCount (): integer; function GetCell (row, col: integer): widestring; procedure SetCell (row, col: integer; const value: widestring); procedure SetFirstRow (value: integer); procedure SetFirstCol (value: integer); procedure MoveRow (i_source, i_target: integer); procedure MoveCol (i_source, i_target: integer); procedure f_OnClick (o_point: TPoint); procedure f_OnMouseMove (o_point: TPoint); procedure f_Draw (); procedure f_SetCursor (o_status: TGridStatus); procedure f_DetermineStatus (); procedure f_DetermineScrollBar (); procedure f_OnVertScroll (i_request, i_thumbpos: word); procedure f_OnHorzScroll (i_request, i_thumbpos: word); procedure f_OnStartMove (Sender: TObject); procedure f_OnRowMove (Sender: TObject); procedure f_OncolMove (Sender: TObject); procedure f_ExitFromEditMode (); function TableRect (): TRect; function TableWidth (): integer; function TableHeight (): integer; function GridRect (i_row, i_col: integer): TRect; function GetGridByPoint (pt: TPoint; var i_row, i_col: integer): boolean; function NoGrid (): boolean; procedure SetFixedColor (i_color: TColor); protected function DoCreateControl (HParent: HWND): HWND; override; procedure OnCreateControl (); override; procedure OnDestroyControl (); override; function ProcessMessage (AMessage, wParam, lParam: DWORD): DWORD; override; procedure OnSize (clpos: TPos); override; function IsUserClass (): boolean; override; public property RowCount: integer read GetRowCount write SetRowCount; // 包括表头行 property ColCount: integer read GetColCount write SetColCount; property FixedRow: TFixedRowCol read FFixedRow write FFixedRow; property FixedCol: TFixedRowCol read FFixedCol write FFixedCol; property FirstRow: integer read FFirstRow write SetFirstRow; property FirstCol: integer read FFirstCol write SetFirstCol; procedure SaveGrid; function GridValid (row, col: integer): boolean; property Cells[row, col: integer]: widestring read GetCell write SetCell; default; property RowHeight[row: integer]: integer read GetRowHeight write SetRowHeight; property ColWidth[col: integer]: integer read GetColWidth write SetColWidth; property FixedColor: TColor read FFixedColor write SetFixedColor; property ReadOnly: boolean read FReadOnly write FReadOnly; property GridResizable: boolean read FGridResizable write FGridResizable; property OnDrawCell: TDrawCellEvent read FOnDrawCell write FOnDrawCell; end; implementation uses CommCtrl, Messages, UxlStrUtils, UxlFunctions, UxlMath, UxlCommDlgs; function TxlGrid.DoCreateControl (HParent: HWND): HWND; begin RegisterControlClass ('TxlGrid', GetStockObject(WHITE_BRUSH)); result := CreateWin32Control (HParent, 'TxlGrid', WS_VSCROLL or WS_HSCROLL); end; procedure TxlGrid.OnCreateControl (); begin inherited; // FGrayBrush := GetStockObject (LTGRAY_BRUSH); //GetSysColorBrush(COLOR_BTNFACE); // FixedColor := RGB (198, 195, 198); FStatus := gsNormal; FEdit := TxlEdit.create(self); with FEdit do begin Align := alNone; Border := false; // ParentColor := true; ParentFont := true; end; FComboBox := TxlComboBox.Create (self); with FComboBox do begin AllowEdit := true; Align := alNone; Border := false; parentColor := true; ParentFont := true; end; FColSlide := TxlVertSlide.Create (self); with FColSlide do begin Width := 8; Border := true; OnStartSlide := f_OnStartMove; OnEndSlide := f_OnColMove; end; FRowSlide := TxlHorzSlide.Create (self); with FRowSlide do begin Height := 8; Border := true; OnStartSlide := f_OnStartMove; OnEndSlide := f_OnRowMove; end; FFirstRow := 0; FFirstCol := 0; end; procedure TxlGrid.OnDestroyControl (); begin FEdit.Free; FComboBox.Free; FColSlide.Free; FRowSlide.Free; if FFixedBrush <> 0 then DeleteObject (FFixedBrush); inherited; end; function TxlGrid.IsUserClass (): boolean; begin result := true; end; procedure TxlGrid.SetFixedColor (i_color: TColor); begin FFixedColor := i_color; if FFixedBrush <> 0 then DeleteObject (FFixedBrush); FFixedBrush := CreateSolidBrush (i_color); end; function TxlGrid.ProcessMessage (AMessage, wParam, lParam: DWORD): DWORD; var b_processed: boolean; begin result := 0; b_processed := true; case AMessage of WM_PAINT: f_Draw (); WM_LBUTTONDOWN: f_OnClick (MakePoints(lParam)); WM_MOUSEMOVE: f_OnMouseMove (MakePoints(lParam)); WM_LBUTTONDBLCLK: SetWndStyle (WS_VSCROLL or WS_HSCROLL, true); WM_VSCROLL: f_OnVertScroll (LoWord(wparam), HiWord(wparam)); WM_HSCROLL: f_OnHorzScroll (LoWord(wparam), HiWord(wparam)); else b_processed := false; end; if not b_processed then result := inherited ProcessMessage (AMessage, wParam, lParam); end; procedure TxlGrid.OnSize (clpos: TPos); begin inherited OnSize (clpos); f_DetermineScrollBar; end; procedure TxlGrid.f_OnVertScroll (i_request, i_thumbpos: word); var i: integer; begin i := FirstRow; case i_request of SB_LINEDOWN: FirstRow := i + 1; SB_LINEUP: FirstRow := i - 1; SB_PAGERIGHT: FirstRow := i + PageRowCount; SB_PAGELEFT: FirstRow := i - PageRowCount; SB_THUMBTRACK: FirstRow := i_thumbpos; end; if FirstRow <> i then begin FEdit.Hide; FComboBox.Hide; f_DetermineScrollBar; Redraw; end; end; procedure TxlGrid.f_OnHorzScroll (i_request, i_thumbpos: word); var i: integer; begin i := FirstCol; case i_request of SB_LINERIGHT: FirstCol := FirstCol + 1; SB_LINELEFT: FirstCol := FirstCol - 1; SB_PAGERIGHT: FirstCol := FirstCol + PageColCount; SB_PAGELEFT: FirstCol := FirstCol - PageColCount; SB_THUMBTRACK: FirstCol := i_thumbpos; end; if FirstCol <> i then begin FEdit.Hide; FComboBox.Hide; f_DetermineScrollBar; Redraw; end; end; procedure TxlGrid.f_DetermineScrollBar (); var si: TScrollInfo; begin with si do begin cbSize := sizeof (si); fMask := SIF_RANGE or SIF_PAGE or SIF_POS; nMin := 0; nMax := ColCount - 1; nPos := FFirstCol; nPage := PageColCount; //Min (ClientRect.Right * ColCount div (TableRect.Right - TableRect.Left), ColCount); end; SetScrollInfo (Fhandle, SB_HORZ, si, true); ShowScrollBar (Fhandle, SB_HORZ, (FirstCol > 0) or (ClientPos.Width < TableWidth)); si.nMax := RowCount - 1; si.nPage := PageRowCount; //Min (ClientRect.Bottom * RowCount div (TableRect.Bottom - TableRect.Top), RowCount); si.nPos := FFirstRow; SetScrollInfo (Fhandle, SB_VERT, si, true); ShowScrollBar (Fhandle, SB_VERT, (FirstRow > 0) or (ClientPos.Height < TableHeight)); end; //------------------------ procedure TxlGrid.SaveGrid (); var i_oldrow, i_oldcol: integer; o_ctrl: TxlControl; begin if FEdit.Visible then o_ctrl := FEdit else if FComboBox.Visible then o_ctrl := FComboBox else exit; GetGridByPoint (RectToPoint(o_ctrl.Rect), i_oldrow, i_oldcol); if GridValid (i_oldrow, i_oldcol) then Cells[i_oldrow, i_oldcol] := o_ctrl.Text; end; procedure TxlGrid.f_OnClick (o_point: TPoint); var i, i_row, i_col: integer; o_rect: TRect; o_list: TxlStrList; begin if FStatus = gsNormal then // edit begin if ReadOnly then exit; SaveGrid; GetGridByPoint (o_point, i_row, i_col); if not GridValid (i_row, i_col) then exit; o_rect := GridRect (i_row, i_col); inc(o_rect.Left, 1); inc (o_rect.Top, 1); if ((i_row = 0) and (FixedRow = frcAuto)) or ((i_col=0) and (FixedCol = frcAuto)) then begin FEdit.Hide; FComboBox.Hide; end else if (FixedRow = frcUser) and (i_row > 0) and IsSubStr (':', Cells[0, i_col]) then begin o_list := TxlStrList.Create; o_list.Separator := ','; o_list.Text := Trim(MidStr (Cells[0, i_col], FirstPos(':', Cells[0, i_col]) + 1)); FComboBox.Items.Clear; for i := o_list.Low to o_list.High do FComboBox.Items.Add (o_list[i]); o_list.Free; FEdit.Hide; inc (o_rect.Bottom, 120); FComboBox.rect := o_rect; FComboBox.Show; FComboBox.Text := Cells[i_row, i_col]; FComboBox.SetFocus; end else begin if ((FixedRow <> frcNone) and (i_row = 0)) or ((FixedCol <> frcNone) and (i_col = 0)) then FEdit.Color := FixedColor else FEdit.Color := self.Color; FComboBox.Hide; FEdit.Show; FEdit.rect := o_rect; FEdit.Text := Cells[i_row, i_col]; FEdit.SelectAll; FEdit.SetFocus; end; end; // else if FStatus in [gsMoveRow, gsMoveCol] then // FDragButton.Show; f_SetCursor (FStatus); end; procedure TxlGrid.f_ExitFromEditMode (); begin if FEdit.Visible or FComboBox.Visible then begin SaveGrid; FEdit.Hide; FComboBox.Hide; end; end; procedure TxlGrid.f_OnMouseMove (o_point: TPoint); procedure f_SetNormalStatus (); begin FStatus := gsNormal; f_SetCursor (gsNormal); end; var n, m: integer; begin f_DetermineStatus; if (FStatus in [gsSizeCol, gsSizeRow]) and KeyPressed(VK_LBUTTON) then // size grid begin f_ExitFromEditMode; if FStatus = gsSizeCol then begin m := FColWidth [FSizeRowCol]; n := o_point.x - GridRect(0, FSizeRowCol).Left; if (m <> n) and InRange (n, 20, ClientRect.Right) then FColWidth [FSizeRowCol] := n else if ABS (n - m) > 6 then f_SetNormalStatus; end else if FStatus = gsSizeRow then begin m := FRowHeight [FSizeRowCol]; n := o_point.y - GridRect(FSizeRowCol, 0).Top; if (m <> n) and InRange (n, 20, ClientRect.Bottom) then FRowHeight [FSizeRowCol] := n else if ABS (n - m) > 6 then f_SetNormalStatus; end; Redraw; end; end; procedure TxlGrid.f_DetermineStatus (); function f_IsSizeRow (const o_point: TPoint; var i_row: integer): boolean; var i, i_half: integer; begin result := false; if not GridResizable then exit; i_half := (GridRect(0,0).Right - GridRect(0,0).Left) div 2 + GridRect(0,0).Left; if InRange (o_point.X, i_half, GridRect(0,0).Right) then begin for i := 0 to RowCount - 1 do if ABS(o_point.y - GridRect(i, 0).Bottom) <= 6 then begin i_row := i; result := true; exit; end; end; end; function f_IsMoveRow (const o_point: TPoint; var i_row: integer): boolean; var i, i_half: integer; begin result := false; if (RowCount = 1) or ((RowCount = 2) and (FixedRow <> frcNOne)) then exit; i_half := (GridRect(0,0).Right - GridRect(0,0).Left) div 2 + GridRect(0,0).Left; if InRange (o_point.X, GridRect(0,0).Left, i_half) then begin for i := 0 to RowCount - 1 do if InRange(GridRect(i, 0).Bottom - o_point.y, 0, FRowSlide.Height) then begin i_row := i; result := true; exit; end; end; end; function f_IsSizeCol (const o_point: TPoint; var i_col: integer): boolean; var i, i_half: integer; begin result := false; if not GridResizable then exit; i_half := (GridRect(0,0).Bottom - GridRect(0,0).Top) div 2 + GridRect(0,0).Top; if InRange (o_point.y, i_half, GridRect(0,0).Bottom) then begin for i := 0 to ColCount - 1 do if ABS(o_point.x - GridRect(0, i).Right) <= 6 then begin i_col := i; result := true; exit; end; end; end; function f_IsMoveCol (const o_point: TPoint; var i_col: integer): boolean; var i, i_half: integer; begin result := false; if (ColCount = 1) or ((ColCount = 2) and (FixedCol <> frcNOne)) then exit; i_half := (GridRect(0,0).Bottom - GridRect(0,0).Top) div 2 + GridRect(0,0).Top; if InRange (o_point.y, GridRect(0,0).Top, i_half) then begin for i := 0 to ColCount - 1 do if InRange (GridRect(0, i).Right - o_point.x, 0, FColSlide.Width) then begin i_col := i; result := true; exit; end; end; end; var pt: TPoint; o_rect: TRect; begin pt := CursorPos; if KeyPressed(VK_LBUTTON) then exit; if f_IsSizeRow (pt, FSizeRowCol) then FStatus := gsSizeRow else if f_IsMoveRow (pt, FSizeRowCol) then FStatus := gsMoveRow else if f_IsSizeCol (pt, FSizeRowCol) then FStatus := gsSizeCol else if f_IsMoveCol (pt, FSizeRowCol) then FStatus := gsMoveCol else FStatus := gsNormal; f_SetCursor (FStatus); FColSlide.Visible := FStatus = gsMoveCol; FRowSlide.Visible := FStatus = gsMoveRow; if FStatus = gsMoveRow then begin o_rect := GridRect (FSizeRowCol, 0); with FRowSlide do begin Left := o_rect.Left; Top := o_rect.Bottom - Height; Width := RectToPos(o_rect).Width div 2; // Height := 10; end; end else begin o_rect := GridRect (0, FSizeRowCol); with FColSlide do begin Top := o_rect.Top; Left := o_rect.Right - Width; // Width := 10; Height := RectToPos(o_rect).Height div 2; end; end; end; procedure TxlGrid.f_SetCursor (o_status: TGridStatus); procedure f_DoSetCursor (pc: pChar); begin SetCursor (LoadCursor(0, pc)); end; begin case o_status of gsNormal: f_DoSetCursor (IDC_ARROW); gsSizeCol: f_DoSetCursor (IDC_SIZEWE); gsSizeRow: f_DoSetCursor (IDC_SIZENS); gsMoveCol: f_DoSetCursor (IDC_HAND); gsMoveRow: f_DoSetCursor (IDC_HAND); end; end; procedure TxlGrid.f_OnStartMove (Sender: TObject); begin f_ExitFromEditMode; end; procedure TxlGrid.f_OnRowMove (Sender: TObject); var i_row, i_col: integer; begin GetGridByPoint (CursorPos, i_row, i_col); MoveRow (FSizeRowCol, i_row); FStatus := gsNormal; FRowSlide.Hide; f_SetCursor (FStatus); Redraw; end; procedure TxlGrid.f_OnColMove (Sender: TObject); var i_row, i_col: integer; begin GetGridByPoint (CursorPos, i_row, i_col); MoveCol (FSizeRowCol, i_col); FStatus := gsNormal; FColSlide.Hide; f_SetCursor (FStatus); Redraw; end; //--------------- function TxlGrid.GetRowCount (): integer; begin result := Length(FRowHeight); end; procedure TxlGrid.SetRowcount (value: integer); var i, j, n: integer; begin if value = RowCount then exit; n := RowCount; SetLength (FRowHeight, value); SetLength (FCells, value, ColCount); if value > n then for i := n to value - 1 do begin FRowHeight[i] := 25; for j := 0 to ColCount - 1 do FCells[i, j] := ''; end; f_DetermineScrollBar; end; function TxlGrid.GetColCount (): integer; begin result := Length(FColWidth); end; procedure TxlGrid.SetColCount (value: integer); var i, j, n: integer; begin if value = ColCount then exit; n := ColCount; SetLength (FColWidth, value); SetLength (FCells, RowCount, value); if value > n then for i := n to value - 1 do begin FColWidth[i] := 120; for j := 0 to rowCount - 1 do FCells[j, i] := ''; end; f_DetermineScrollBar; end; function TxlGrid.GetRowHeight (row: integer): integer; begin result := IfThen(InRange(row, 0, RowCount - 1), FRowHeight[row], 0); end; procedure TxlGrid.SetRowHeight (row: integer; value: integer); var rc: TRect; begin if row < 0 then exit; if row > RowCount - 1 then RowCount := row + 1; GetScreenRect (rc, false); FRowHeight[row] := ConfineRange (value, 0, rc.Bottom); end; function TxlGrid.GetColWidth (col: integer): integer; begin result := IfThen(InRange(col, 0, ColCount - 1), FColWidth[col], 0); end; procedure TxlGrid.SetColWidth (col: integer; value: integer); var rc: TRect; begin if col < 0 then exit; if col > ColCount - 1 then ColCount := col + 1; GetScreenRect (rc, false); FColWidth[col] := ConfineRange (value, 0, rc.Right); end; procedure TxlGrid.f_GetPageRowColCount (var i_rowcount, i_colcount: integer); var pt: TPoint; i_row, i_col: integer; begin pt.x := ClientRect.Right; pt.y := ClientRect.Bottom; GetGridByPoint (pt, i_row, i_col); i_rowcount := i_row - FirstRow + 1; if pt.Y < GridRect(i_row, i_col).Bottom then // 最后一行不完整,不计入内 dec(i_rowcount); i_colcount := i_col - FirstCol + 1; if pt.x < GridRect(i_row, i_col).Right then // 最后一列不完整,不计入内。 dec(i_colcount); end; function TxlGrid.PageRowCount (): integer; var i: integer; begin f_GetPageRowColCount (result, i); end; function TxlGrid.PageColCount (): integer; var i: integer; begin f_GetPageRowColCount (i, result); end; procedure TxlGrid.SetFirstRow (value: integer); var i, n: integer; begin n := 0; for i := RowCount - 1 downto 0 do begin inc (n, RowHeight[i]); if n > ClientPos.Height then break; end; FFirstRow := ConfineRange (value, 0, i + 1); ReDraw; end; procedure TxlGrid.SetFirstCol (value: integer); var i, n: integer; begin n := 0; for i := ColCount - 1 downto 0 do begin inc (n, ColWidth[i]); if n > ClientPos.Width then break; end; FFirstCol := ConfineRange (value, 0, i + 1); ReDraw; end; procedure TxlGrid.MoveRow (i_source, i_target: integer); var s: widestring; i, j, i_height: integer; begin if i_source = i_target then exit; if (FixedRow <> frcNOne) and ((i_source = 0) or (i_target = 0)) then exit; for i := 0 to ColCount - 1 do begin s := Cells[i_source, i]; if i_source < i_target then begin for j := i_source to i_target - 1 do Cells[j, i] := Cells[j + 1, i]; end else begin for j := i_source downto i_target + 1 do Cells[j, i] := Cells[j - 1, i]; end; Cells[i_target, i] := s; end; i_height := RowHeight[i_source]; if i_source < i_target then begin for j := i_source to i_target - 1 do RowHeight[j] := RowHeight[j + 1]; end else begin for j := i_source downto i_target + 1 do RowHeight[j] := RowHeight[j - 1]; end; RowHeight[i_target] := i_height; // parent.Text := InttoStr(i_source) + '-->' + IntToStr(i_target); end; procedure TxlGrid.MoveCol (i_source, i_target: integer); var s: widestring; i, j, i_width: integer; begin if i_source = i_target then exit; if (FixedCol <> frcNOne) and ((i_source = 0) or (i_target = 0)) then exit; for i := 0 to RowCount - 1 do begin s := Cells[i, i_source]; if i_source < i_target then begin for j := i_source to i_target - 1 do Cells[i, j] := Cells[i, j + 1]; end else begin for j := i_source downto i_target + 1 do Cells[i, j] := Cells[i, j - 1]; end; Cells[i, i_target] := s; end; i_width := ColWidth[i_source]; if i_source < i_target then begin for j := i_source to i_target - 1 do ColWidth[j] := ColWidth[j + 1]; end else begin for j := i_source downto i_target + 1 do ColWidth[j] := ColWidth[j - 1]; end; ColWidth[i_target] := i_width; // parent.Text := InttoStr(i_source) + '-->' + IntToStr(i_target); end; //--------------------- function TxlGrid.GridValid (row, col: integer): boolean; begin result := InRange (row, 0, RowCount - 1) and InRange (col, 0, ColCount - 1); end; function TxlGrid.NoGrid (): boolean; begin result := (RowCount = 0) or (ColCount = 0); end; function TxlGrid.GridRect (i_row, i_col: integer): TRect; var i: integer; begin if not GridValid (i_row, i_col) then exit; result.Top := 0; if i_row >= FirstRow then for i := FirstRow to i_row - 1 do inc (result.Top, FRowHeight[i]) else for i := FirstRow - 1 downto i_row do dec (result.Top, FRowHeight[i]); result.Bottom := result.Top + FRowHeight[i_row]; result.Left := 0; if i_col >= FirstCol then for i := FirstCol to i_col - 1 do inc (result.Left, FColWidth[i]) else for i := FirstCol - 1 downto i_col do dec (result.Right, FColWidth[i]); result.Right := result.Left + FColWidth[i_col]; end; function TxlGrid.TableRect (): TRect; begin result := GridRect (0, 0); result.Right := GridRect (RowCount - 1, ColCount - 1).Right; result.Bottom := GridRect (RowCount - 1, ColCount - 1).Bottom; end; function TxlGrid.TableWidth (): integer; begin result := TableRect.Right - TableRect.Left; end; function TxlGrid.TableHeight (): integer; begin result := TableRect.Bottom - TableRect.Top; end; function TxlGrid.GetGridByPoint (pt: TPoint; var i_row, i_col: integer): boolean; var i, n: integer; begin n := -1; for i := FirstRow to RowCount - 1 do begin if n >= pt.y then break; inc (n, FRowHeight[i]); end; i_row := i - 1; n := -1; for i := FirstCol to ColCount - 1 do begin if n >= pt.x then break; inc (n, FColWidth[i]); end; i_col := i - 1; result := GridValid (i_row, i_col); end; //--------------------- function TxlGrid.GetCell (row, col: integer): widestring; function f_GetLabel (i: integer; b_aschar: boolean): widestring; begin if i = 0 then result := '' else if not b_aschar then result := IntToStr(i) else begin result := ''; repeat result := WideChar((i - 1) mod 26 + 65) + result; i := i div 26; until i = 0; end; end; begin if (row = 0) and (FixedRow = frcAuto) then result := IfThen (FixedCol = frcNone, f_GetLabel(col + 1, true), f_GetLabel(col, true)) else if (col = 0) and (FixedCol = frcAuto) then result := IfThen (FixedRow = frcNone, f_GetLabel(row + 1, false), f_GetLabel(row, false)) else result := IfThen (GridValid (row, col), FCells[row, col], ''); end; procedure TxlGrid.SetCell (row, col: integer; const value: widestring); begin if row >= RowCount then RowCount := row + 1; if col >= ColCount then ColCount := col + 1; FCells[row, col] := value; end; //--------------- procedure TxlGrid.f_Draw (); var i, j, m, n: integer; h_dc: HDC; o_rect, o_rect2, o_tablerect: TRect; s: widestring; i_flag: dword; ps: PaintStruct; begin if NoGrid then exit; o_rect := ClientRect; o_tablerect := TableRect; h_dc := Beginpaint ( Fhandle, ps ); SetBkMode( h_dc, TRANSPARENT ); SelectObject (h_dc, Font.Handle ); SetTextColor (h_dc, Font.Color); f_SetCursor (FStatus); o_rect2.Left := 0; o_rect2.Top := 0; if (FixedRow <> frcNone) and (FirstRow = 0) then begin o_rect2.Right := Min(o_rect.right, o_tablerect.Right); o_rect2.Bottom := FRowHeight[0]; FillRect (h_dc, o_rect2, FFixedBrush); end; if (FixedCol <> frcNone) and (FirstCol = 0) then begin o_rect2.Right := FColWidth[0]; o_rect2.Bottom := Min (o_rect.Bottom, o_tablerect.Bottom); FillRect (h_dc, o_rect2, FFixedBrush); end; SelectObject (h_dc, GetStockObject(DC_PEN)); SetDCPenColor (h_dc, GetSysColor(COLOR_BTNSHADOW)); // SelectObject (h_dc, GetStockObject (DKGRAY_BRUSH)); n := 0; for i := FirstCol to ColCount - 1 do begin if (n >= o_rect.right) then break; inc (n, FColWidth[i]); // Rectangle (h_dc, n - 3, 0, n + 3, RowHeight[0] div 3); MoveToEx (h_dc, n, 0, nil); LineTo (h_dc, n, Min(o_rect.bottom, o_tablerect.bottom)); end; n := 0; for i := FirstRow to RowCount - 1 do begin if n >= o_rect.bottom then break; m := 0; for j := FirstCol to ColCount - 1 do begin if m >= o_rect.right then break; o_rect2.Left := m + 3; o_rect2.Top := n + 1; o_rect2.Right := m + FColWidth[j] - 6; o_rect2.Bottom := n + FRowHeight[i] - 2; if (not assigned (FOnDrawCell)) or (not FOnDrawCell (h_dc, o_rect2, i, j)) then begin s := Cells[i, j]; if (i = 0) and (FixedRow = frcUser) and IsSubStr(':', s) then s := LeftStr (s, FirstPos(':', s) - 1); if s <> '' then begin i_flag := IfThen ( ((FixedRow <> frcNone) and (i = 0)) or ((FixedCol <> frcNone) and (j = 0)), DT_CENTER, DT_LEFT); DrawTextW (h_dc, pwidechar(s), Length(s), o_rect2, i_flag or DT_SINGLELINE or DT_NOPREFIX); end; end; inc (m, FColWidth[j]); end; inc (n, Frowheight[i]); MoveToEx (h_dc, 0, n, nil); LineTo (h_dc, Min(o_rect.right, o_tablerect.right), n); end; EndPaint ( Fhandle, ps ); // ValidateRect (Fhandle, @o_Rect); end; end.
unit Benchmarks.Find.Glob; interface uses Core.Benchmark.Base, Motif; type TBenchmarkFindGlob = class(TBaseBenchmark) private fMotif: TMotif; public procedure runBenchmark; override; procedure setDown; override; procedure setUp; override; end; implementation uses System.SysUtils, System.Classes; { TBenchmarkFindGlob } procedure TBenchmarkFindGlob.runBenchmark; var num: integer; begin inherited; for num:=0 to 999 do fMotif.findByPattern('x: AZB, y: 500'); end; procedure TBenchmarkFindGlob.setDown; begin inherited; fMotif.Free; end; procedure TBenchmarkFindGlob.setUp; var num: integer; begin inherited; fMotif:=TMotif.Create; for num:=0 to 999 do fMotif.add('x: A*B, y: '+IntToStr(num), IntToStr(num)); end; end.
program UsingEnumerations; uses TerminalUserInput; type Genre = (Pop, Classic, Rock); procedure Main(); var g: Genre; selection: Integer; begin selection := ReadIntegerRange('Select a genre (1 - 3): ', 1, 3); // Now you need to tell the compiler that you want to treat this // integer as a thing of type Genre (not of type integer) so you // need to 'cast' it to the Genre type: // Also enumerations start at 0 - we asked above for a number from 1 - 3 // so we need to subtrat 1. g := Genre(selection -1); Writeln(' You selected: ', g); end; begin Main(); end.
unit Unit4; {$mode objfpc}{$H+} interface uses Classes, SysUtils, pqconnection; //function pgroles_add(pg: TPQConnection; userName: string): boolean; // cdecl; external 'libpgroles.so'; function pgroles_add(pg: TPQConnection; userName: string): boolean; //cdecl; external 'libproject2.so'; function pgroles_rename(pg: TPQConnection; userNameOld, userNameNew: string): boolean; //cdecl; external 'libproject2.so'; function pgroles_password(pg: TPQConnection; userName, password: string): boolean; //cdecl; external 'libproject2.so'; function pgroles_delete(pg: TPQConnection; userName: string): boolean; //cdecl; external 'libproject2.so'; implementation function pgroles_add(pg: TPQConnection; userName: string): boolean; begin if (userName <> '') then begin pg.ExecuteDirect('CREATE USER "' + userName + '";'); pg.Transaction.Commit(); Result := True; end else Result := False; end; function pgroles_rename(pg: TPQConnection; userNameOld, userNameNew: string): boolean; begin if (userNameOld <> '') and (userNameNew <> '') then begin pg.ExecuteDirect('ALTER ROLE "' + userNameOld + '" RENAME TO "' + userNameNew + '";'); pg.Transaction.Commit(); Result := True; end else Result := False; end; function pgroles_password(pg: TPQConnection; userName, password: string): boolean; begin if (userName <> '') and (password <> '') then begin pg.ExecuteDirect('ALTER ROLE "' + userName + '" PASSWORD ''' + password + ''';'); pg.Transaction.Commit(); Result := True; end else Result := False; end; function pgroles_delete(pg: TPQConnection; userName: string): boolean; begin if (userName <> '') then begin pg.ExecuteDirect('DROP ROLE "' + userName + '";'); pg.Transaction.Commit(); Result := True; end else Result := False; end; end.
unit DecisionFormUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons; type TImageAction=(iaDelete1,iaDelete2,iaNone); // Action choisie par l'utilisateur: supprimer la 1ère image, la seconde, ou ne rien faire TDecisionForm = class(TForm) Panel1: TPanel; GroupBox1: TGroupBox; StaticText1: TStaticText; ScrollBox1: TScrollBox; PaintBox1: TPaintBox; GroupBox2: TGroupBox; StaticText2: TStaticText; ScrollBox2: TScrollBox; PaintBox2: TPaintBox; RadioGroup1: TRadioGroup; CheckBox1: TCheckBox; BitBtn1: TBitBtn; BitBtn2: TBitBtn; BitBtn3: TBitBtn; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Panel1Resize(Sender: TObject); procedure RadioGroup1Click(Sender: TObject); procedure PaintBox1Paint(Sender: TObject); procedure PaintBox2Paint(Sender: TObject); private FPicture1,FPicture2:TPicture; public Canceled:Boolean; function Execute(FileName1,FileName2:string;Similiraty:Single):TImageAction; // Renvoie l'action choisie par l'utilisateur end; var DecisionForm: TDecisionForm; implementation uses MainFormUnit; {$R *.dfm} procedure TDecisionForm.FormCreate(Sender: TObject); begin FPicture1:=TPicture.Create; FPicture2:=TPicture.Create; end; procedure TDecisionForm.FormDestroy(Sender: TObject); begin FPicture1.Destroy; FPicture2.Destroy; end; procedure TDecisionForm.Panel1Resize(Sender: TObject); begin GroupBox1.Width:=Panel1.ClientWidth div 2; end; procedure TDecisionForm.RadioGroup1Click(Sender: TObject); begin BitBtn1.Enabled:=RadioGroup1.ItemIndex>-1; // Il faut déjà prendre une décision avant de pouvoir la confirmer end; procedure TDecisionForm.PaintBox1Paint(Sender: TObject); begin PaintBox1.Canvas.Draw(0,0,FPicture1.Graphic); // Affichage de l'image 1 end; procedure TDecisionForm.PaintBox2Paint(Sender: TObject); begin PaintBox2.Canvas.Draw(0,0,FPicture2.Graphic); // Affichage de l'image 2 end; function GetFileSize(FileName:string):Int64; // Donne la taille d'un fichier var f:TSearchRec; begin if FindFirst(FileName,faAnyFile,f)=0 then try {$WARNINGS OFF} Result:=Int64(f.FindData.nFileSizeHigh) shl 32+f.FindData.nFileSizeLow; {$WARNINGS ON} finally FindClose(f); end else Result:=0; end; function TDecisionForm.Execute(FileName1, FileName2: string; Similiraty: Single): TImageAction; var m:TModalResult; const T:array[False..True] of TImageAction=(iaDelete1,iaDelete2); begin Result:=iaNone; if CheckBox1.Checked then // Si l'utilisateur a décidé de toujours faire la même action m:=mrOk // on ne lui demande pas son avis de nouveau else begin Caption:=Format('Similarity: %f %%',[Similiraty]); StaticText1.Caption:='.\'+Copy(FileName1,Length(MainForm.Edit1.Text)+2,Length(FileName1)); StaticText2.Caption:='.\'+Copy(FileName2,Length(MainForm.Edit1.Text)+2,Length(FileName2)); FPicture1.LoadFromFile(FileName1); FPicture2.LoadFromFile(FileName2); with FPicture1 do PaintBox1.SetBounds(0,0,Width,Height); with FPicture2 do PaintBox2.SetBounds(0,0,Width,Height); m:=ShowModal; // on demande son avis à l'utilisateur end; case m of mrOk:begin case RadioGroup1.ItemIndex of 0,4:Result:=T[RadioGroup1.ItemIndex=4]; 1,5:Result:=T[(FPicture1.Width*FPicture1.Height<FPicture2.Width*FPicture2.Height) xor (RadioGroup1.ItemIndex=1)]; 2,6:Result:=T[(GetFileSize(FileName1)<GetFileSize(FileName2)) xor (RadioGroup1.ItemIndex=2)]; 3,7:Result:=T[(FileDateToDateTime(FileAge(FileName1))<FileDateToDateTime(FileAge(FileName2))) xor (RadioGroup1.ItemIndex=3)]; end; end; mrCancel:Canceled:=True; // Opération annulée else CheckBox1.Checked:=False; // Si l'utilisateur n'a pas pris de décision, alors on lui demandera son avis la prochaine fois end; end; end.
(* @created(2019-12-27) @author(J.Delauney (BeanzMaster)) Historique : @br @unorderedList( @item(27/12/2019 : Creation ) ) --------------------------------------------------------------------------------@br ------------------------------------------------------------------------------ Description : Simulation d'un shader GLSL Code source de référence de Wouter Van Nifterick ------------------------------------------------------------------------------ @bold(Notes :) Quelques liens : @unorderedList( @item(http://www.shadertoy.com) @item(http://glslsandbox.com) ) ------------------------------------------------------------------------------@br @bold(Credits :) @unorderedList( @item(J.Delauney (BeanzMaster)) @item(https://github.com/WouterVanNifterick/delphi-shader) ) ------------------------------------------------------------------------------@br LICENCE : GPL/MPL @br ------------------------------------------------------------------------------ *==============================================================================*) unit BZSoftwareShader_SymetryDisco; //============================================================================== {$mode objfpc}{$H+} {$i ..\..\..\bzscene_options.inc} //------------------------ {$ALIGN 16} {$CODEALIGN CONSTMIN=16} {$CODEALIGN LOCALMIN=16} {$CODEALIGN VARMIN=16} //------------------------ //============================================================================== interface uses Classes, SysUtils, Math, BZClasses, BZMath, BZVectorMath, BZVectorMathUtils, BZRayMarchMath, BZColors, BZGraphic, BZBitmap, BZCadencer, BZCustomShader; Type { TBZSoftShader_GroundAndDistortPhongSphere } TBZSoftShader_SymetryDisco = Class(TBZCustomSoftwareShader) protected Fax: array [0 .. 26] of double; Fay: array [0 .. 26] of double; FaTime : Double; procedure DoApply(var rci: Pointer; Sender: TObject); override; public Constructor Create; override; Destructor Destroy; override; function Clone : TBZCustomSoftwareShader; override; function ShadePixelFloat:TBZColorVector; override; end; implementation { TBZSoftShader_GroundAndDistortPhongSphere } Constructor TBZSoftShader_SymetryDisco.Create; begin inherited Create; end; Destructor TBZSoftShader_SymetryDisco.Destroy; begin inherited Destroy; end; function TBZSoftShader_SymetryDisco.Clone : TBZCustomSoftwareShader; begin Result := TBZSoftShader_SymetryDisco.Create; Result.Assign(Self); end; procedure TBZSoftShader_SymetryDisco.DoApply(var rci: Pointer; Sender: TObject); Var t : Double; begin inherited DoApply(rci,sender); t := FiTime * 0.5; FaTime := Sin(FiTime * 0.3) * 2.0 + 3.0 + Tan(FiTime / 12.2); Fax[0] := Tan(t * 3.3) * 0.3; Fay[0] := Tan(t * 2.9) * 0.3; Fax[1] := Tan(t * 1.9) * 0.4; Fay[1] := Tan(t * 2.0) * 0.4; Fax[2] := Tan(t * 0.8) * 0.4; Fay[2] := Tan(t * 0.7) * 0.5; Fax[3] := Tan(t * 2.3) * 0.6; Fay[3] := Tan(t * 0.1) * 0.3; Fax[4] := Tan(t * 0.8) * 0.5; Fay[4] := Tan(t * 1.7) * 0.4; Fax[5] := Tan(t * 0.3) * 0.4; Fay[5] := Tan(t * 1.0) * 0.4; Fax[6] := Tan(t * 1.4) * 0.4; Fay[6] := Tan(t * 1.7) * 0.5; Fax[7] := Tan(t * 1.3) * 0.6; Fay[7] := Tan(t * 2.1) * 0.3; Fax[8] := Tan(t * 1.8) * 0.5; Fay[8] := Tan(t * 1.7) * 0.4; Fax[9] := Tan(t * 1.2) * 0.3; Fay[9] := Tan(t * 1.9) * 0.3; Fax[10] := Tan(t * 0.7) * 0.4; Fay[10] := Tan(t * 2.7) * 0.4; Fax[11] := Tan(t * 1.4) * 0.4; Fay[11] := Tan(t * 0.6) * 0.5; Fax[12] := Tan(t * 2.6) * 0.6; Fay[12] := Tan(t * 0.4) * 0.3; Fax[13] := Tan(t * 0.7) * 0.5; Fay[13] := Tan(t * 1.4) * 0.4; Fax[14] := Tan(t * 0.7) * 0.4; Fay[14] := Tan(t * 1.7) * 0.4; Fax[15] := Tan(t * 0.8) * 0.4; Fay[15] := Tan(t * 0.5) * 0.5; Fax[16] := Tan(t * 1.4) * 0.6; Fay[16] := Tan(t * 0.9) * 0.3; Fax[17] := Tan(t * 0.7) * 0.5; Fay[17] := Tan(t * 1.3) * 0.4; Fax[18] := Tan(t * 3.7) * 0.3; Fay[18] := Tan(t * 0.3) * 0.3; Fax[19] := Tan(t * 1.9) * 0.4; Fay[19] := Tan(t * 1.3) * 0.4; Fax[20] := Tan(t * 0.8) * 0.4; Fay[20] := Tan(t * 0.9) * 0.5; Fax[21] := Tan(t * 1.2) * 0.6; Fay[21] := Tan(t * 1.7) * 0.3; Fax[22] := Tan(t * 0.3) * 0.5; Fay[22] := Tan(t * 0.6) * 0.4; Fax[23] := Tan(t * 0.3) * 0.4; Fay[23] := Tan(t * 0.3) * 0.4; Fax[24] := Tan(t * 1.4) * 0.4; Fay[24] := Tan(t * 0.8) * 0.5; Fax[25] := Tan(t * 0.2) * 0.6; Fay[25] := Tan(t * 0.6) * 0.3; Fax[26] := Tan(t * 1.3) * 0.5; Fay[26] := Tan(t * 0.5) * 0.4; end; function TBZSoftShader_SymetryDisco.ShadePixelFloat : TBZColorVector; const cZ=1/64; // By @paulofalcao // // Some blobs modifications with symmetries // nice stuff :) procedure makePoint(x, y: Single; i: Integer; var res:Single); var xx, yy: Single; begin xx := x + Fax[i]; // tan(t*fx)*sx yy := y - Fay[i]; // tan(t*fy)*sy Res := Res + (cZ*0.8 / Sqrt(System.abs(x * xx + yy * yy))); end; function sim(const p: TBZVector4f; s: Single): TBZVector4f; var sd : Single; begin sd := (s * 0.5); Result := p; Result := p + sd; Result := Result / s; Result := Result.Fract * s; Result := Result - sd; end; function rot(const p: TBZVector2f; r: Single): TBZVector2f; var sr,cr:Double; begin //Result := p.Rotate(r,cNullVector2f); sr := Sin(r); cr := Cos(r); Result.x := p.x * cr - p.y * sr; Result.y := p.x * sr + p.y * cr; end; function rotsim(const p: TBZVector2f; s: Single): TBZVector2f; begin Result := p; Result := rot(p, -cPI / (s + s)); Result := rot(p, floor(Math.arctan2(Result.x, Result.y) / cPI * s) * (cPI / s)); end; function makeSymmetry(const p: TBZVector2f): TBZVector2f; begin Result := p; Result := rotsim(Result, FaTime); Result.x := System.abs(Result.x); end; function ComputePixel(Coord:TBZVector2f; aTime:Single) : TBZColorVector; var {$CODEALIGN VARMIN=16} finalColor : TBZColorVector; d: TBZVector4f; p : TBZVector2f; {$CODEALIGN VARMIN=4} x: Single; y: Single; a, b, c: Single; begin //p := (gl_FragCoord.xy / resolution.x) * 2.0 - vec2.Create(1.0, resolution.y / resolution.x); //(2.0 * gl_FragCoord.xy - resolution) / resolution.y; //p := ((Coord * FInvResolution.x) * 2.0) - vec2(1.0,FResolution.y / FResolution.x); p := ((Coord * FInvResolution) * 2.0) - 1.0; p.x := p.x * 1.33333; // p := p*2.0; p := makeSymmetry(p); x := p.x; y := p.y; a := 0; makePoint(x, y, 0, a); makePoint(x, y, 1, a); makePoint(x, y, 2, a); makePoint(x, y, 3, a); makePoint(x, y, 4, a); makePoint(x, y, 5, a); makePoint(x, y, 6, a); makePoint(x, y, 7, a); makePoint(x, y, 8, a); b := -a; makePoint(x, y, 9, b); makePoint(x, y, 10, b); makePoint(x, y, 11, b); makePoint(x, y, 12, b); makePoint(x, y, 13, b); makePoint(x, y, 14, b); makePoint(x, y, 15, b); makePoint(x, y, 16, b); makePoint(x, y, 17, b); c := -b; makePoint(x, y, 18, c); makePoint(x, y, 19, c); makePoint(x, y, 20, c); makePoint(x, y, 21, c); makePoint(x, y, 22, c); makePoint(x, y, 23, c); makePoint(x, y, 24, c); makePoint(x, y, 25, c); makePoint(x, y, 26, c); Result.Create(a,b,c); end; begin Result := ComputePixel(FragCoords, iTime); end; end.
{ Subroutines for manipulating an ordered list of strings. A data structure * of type STRING_LIST_T is used to maintain state associated with * the list of strings. } module string_list; define string_list_copy; define string_list_init; define string_list_kill; define string_list_line_add; define string_list_str_add; define string_list_line_del; define string_list_pos_abs; define string_list_pos_last; define string_list_pos_rel; define string_list_pos_start; define string_list_trunc; define string_list_sort; %include 'string2.ins.pas'; { ******************************************************************************** * * Subroutine STRING_LIST_COPY (LIST1, LIST2, MEM) * * Copy all the data from strings list LIST1 to LIST2. Data is completely * copied instead of just referenced. This subroutine can be used to make a * local copy of a strings list so that it can be modified without effecting * the original. It is assumed that LIST2 has NOT been initialized. If it has * been, then STRING_LIST_KILL should be used to deallocate any resources tied * up by LIST2 before being used here. The previous contents of LIST2 is * completely lost. MEM is the parent memory context to use. A new memory * context will be created under MEM, and will be used to allocate any dynamic * memory needed. No state is altered in LIST1. LIST2 is left positioned at * line zero, which is just before the first line in the list. } procedure string_list_copy ( {make separate copy of a strings list} in list1: string_list_t; {handle to input strings list} out list2: string_list_t; {handle to output strings list} in out mem: util_mem_context_t); {parent memory context to use} var ent_p: string_chain_ent_p_t; {pointer to current source chain entry} begin string_list_init (list2, mem); {init output string lists handle} list2.deallocable := list1.deallocable; ent_p := list1.first_p; {point to first input chain entry} while ent_p <> nil do begin {once for each string to copy} list2.size := ent_p^.s.max; {set desired size of this string} string_list_line_add (list2); {create new empty line in output list} string_copy (ent_p^.s, list2.str_p^); {copy string from in list to out list} ent_p := ent_p^.next_p; {advance to next input chain entry} end; list2.size := list1.size; {set to default size from input list} end; { ******************************************************************************** * * Subroutine STRING_LIST_INIT (LIST, MEM) * * Initialize a strings list. This MUST be done before the strings list is * manipulated in any other way. LIST is the control data block for the * strings list. MEM is the parent memory context to use. A subordinate * memory context will be created internally, and any dynamic memory will be * allocated under it. This subordinate memory context is deleted when the * strings list is killed (using the STRING_LIST_KILL subroutine). * * The strings list will be initialized to empty, and the current line number * will be set to 0, meaning before the first line. } procedure string_list_init ( {init a STRING_LIST_T data structure} out list: string_list_t; {control block for string list to initialize} in out mem: util_mem_context_t); {parent memory context to use} begin list.size := 132; list.deallocable := true; list.n := 0; list.curr := 0; list.str_p := nil; list.first_p := nil; list.last_p := nil; list.ent_p := nil; util_mem_context_get (mem, list.mem_p); {create memory context for any new mem} end; { ******************************************************************************** * * Subroutine STRING_LIST_KILL (LIST) * * "Delete" a strings list and deallocate any resources it may have tied up. * The only valid operation on the strings list LIST after this call is INIT. } procedure string_list_kill ( {delete string, deallocate resources} in out list: string_list_t); {must be initialized before next use} begin list.n := 0; list.curr := 0; list.str_p := nil; list.first_p := nil; list.last_p := nil; list.ent_p := nil; util_mem_context_del (list.mem_p); {delete strings and our memory context} end; { ******************************************************************************** * * Subroutine STRING_LIST_LINE_ADD (LIST) * * Insert a new line to the strings list directly after the current line. The * new line will be made the current line. } procedure string_list_line_add ( {insert new line after curr and make it curr} in out list: string_list_t); {strings list control block} const max_msg_parms = 2; {max parameters we can pass to a message} var ent_p: string_chain_ent_p_t; {pointer to new chain entry} size: sys_int_adr_t; {amount of memory needed for new string} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; begin if list.curr > list.n then begin {on a virtual line past end of list ?} sys_msg_parm_int (msg_parm[1], list.curr); sys_msg_parm_int (msg_parm[2], list.n); sys_message_bomb ('string', 'list_add_past_end', msg_parm, 2); end; size := sizeof(ent_p^) - sizeof(ent_p^.s) + {amount of mem needed for new string} string_size(list.size); util_mem_grab (size, list.mem_p^, list.deallocable, ent_p); {grab mem for new line} ent_p^.s.max := list.size; {init new string to empty} ent_p^.s.len := 0; ent_p^.prev_p := list.ent_p; {point new entry to predecessor} if list.ent_p = nil then begin {there is no previous line ?} ent_p^.next_p := list.first_p; list.first_p := ent_p; end else begin {there is at least one previous line} ent_p^.next_p := list.ent_p^.next_p; {point new entry to successor} end ; if ent_p^.next_p <> nil then begin {there IS a successor line} ent_p^.next_p^.prev_p := ent_p; end else begin {there is NO successor line} list.last_p := ent_p; end ; if ent_p^.prev_p <> nil then begin {there IS a previous line} ent_p^.prev_p^.next_p := ent_p; end else begin {there is NOT a previous line} list.first_p := ent_p; end ; list.n := list.n + 1; {one more line in this list} list.curr := list.curr + 1; {indicate new line is current} list.ent_p := ent_p; {set pointer to new current line} list.str_p := univ_ptr(addr(list.ent_p^.s)); {set address of current line} end; { ******************************************************************************** * * Subroutine STRING_LIST_STR_ADD (LIST, STR) * * Add a complete string to the list LIST. A new line will be created after * the current line, then made current. The length of the new line will be the * length of STR, and its contents will be copied from STR. } procedure string_list_str_add ( {add new string after curr, make curr} in out list: string_list_t; {list to add entry to} in str: univ string_var_arg_t); {string to set entry to, will be this size} val_param; begin list.size := str.len; {set size to make new list entries} string_list_line_add (list); {create new list entry, make it current} string_copy (str, list.str_p^); {initialize the new line with the string STR} end; { ******************************************************************************** * * Subroutine STRING_LIST_LINE_DEL (LIST, FORWARD) * * Delete the current line in the strings list LIST. If FORWARD is TRUE, then * the new current line becomes the line after the one deleted, otherwise it * becomes the line before the one deleted. This routine has no effect if the * current line does not exist. * * The line is always removed from the list, but the memory is only released if * DEALLOCABLE is set to TRUE. } procedure string_list_line_del ( {delete curr line in strings list} in out list: string_list_t; {strings list control block} in forward: boolean); {TRUE makes next line curr, FALSE previous} val_param; var old_ent_p: string_chain_ent_p_t; {saved pointer to old list entry} fwd: boolean; {TRUE if really go forward} begin if list.ent_p = nil then return; {nothing to delete ?} old_ent_p := list.ent_p; {save pointer to entry that will be deleted} fwd := forward; {init direction for new current line} if list.ent_p^.prev_p = nil then begin {deleting first line in list} list.first_p := list.ent_p^.next_p; end else begin {there is a previous line} list.ent_p^.prev_p^.next_p := list.ent_p^.next_p; end ; if list.ent_p^.next_p = nil then begin {deleting last line in list} list.last_p := list.ent_p^.prev_p; fwd := false; {definately not making following line current} end else begin {there is a following line} list.ent_p^.next_p^.prev_p := list.ent_p^.prev_p; end ; if fwd then begin {following line is new current line} list.ent_p := list.ent_p^.next_p; end else begin {previous line is new current line} list.ent_p := list.ent_p^.prev_p; list.curr := list.curr - 1; {line number of new current line} end ; if list.ent_p = nil then begin {we are before first line} list.str_p := nil; {indicate no current line} end else begin {we are at a real line} list.str_p := univ_ptr(addr(list.ent_p^.s)); end ; list.n := list.n - 1; {one less line in list} if list.deallocable then begin {lines can be individually deallocated ?} util_mem_ungrab (old_ent_p, list.mem_p^); {deallocate mem for deleted line} end; end; { ******************************************************************************** * * Subroutine STRING_LIST_POS_ABS (LIST, N) * * Position to the absolute line number N in the strings list LIST. The first * line is numbered 1. It is possible to be at "line" 0. This is really the * position before the first line. It is permissible to position to a line * past the end of the list. In that case STR_P will be NIL, but CURR will * indicate the number of the line, if it existed. } procedure string_list_pos_abs ( {set new current line number in strings list} in out list: string_list_t; {strings list control block} in n: sys_int_machine_t); {number of new current line, first = 1} val_param; const max_msg_parms = 1; {max parameters we can pass to a message} var i: sys_int_machine_t; {loop counter} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; begin if n < 0 then begin {some idiot requested negative line number ?} sys_msg_parm_int (msg_parm[1], n); sys_message_bomb ('string', 'list_pos_negative', msg_parm, 1) end; if (n = 0) or (n > list.n) then begin {going to a non-existant line ?} list.curr := n; list.str_p := nil; list.ent_p := nil; return; end; list.ent_p := list.first_p; {init to being at first line} for i := 2 to n do begin {once for each time to advance one line} list.ent_p := list.ent_p^.next_p; {advance to next line} end; list.curr := n; {indicate number of new current line} list.str_p := univ_ptr(addr(list.ent_p^.s)); end; { ******************************************************************************** * * Subroutine STRING_LIST_POS_LAST (LIST) * * Set the current position in the strings list LIST to the last line. } procedure string_list_pos_last ( {position to last line, 0 if none there} in out list: string_list_t); {strings list control block} begin if list.last_p = nil then begin {no lines exist} list.ent_p := nil; list.curr := 0; list.str_p := nil; end else begin {at least one line exists} list.ent_p := list.last_p; {make last line current} list.curr := list.n; list.str_p := univ_ptr(addr(list.ent_p^.s)); end ; end; { ******************************************************************************** * * Subroutine STRING_LIST_POS_REL (LIST, N_FWD) * * Move a relative position in the strings list LIST. N_FWD is the number of * lines to move forward. It may be negative to indicate moving towards the * start of the list. If no line exists at the new position, then STR_P will * be NIL. CURR will be the line number, if the line existed, except that CURR * will never be less than zero. } procedure string_list_pos_rel ( {move forward/backward in strings list} in out list: string_list_t; {strings list control block} in n_fwd: sys_int_machine_t); {lines to move forwards, may be negative} val_param; var pos: sys_int_machine_t; {actual position to move to} fwd: sys_int_machine_t; {amount to really move} i: sys_int_machine_t; {loop counter} begin if list.first_p = nil then return; {no lines exist, no place to move to ?} pos := max(0, list.curr + n_fwd); {make number of new target line} if pos = 0 then begin {going to before first line ?} list.curr := 0; {indicate new current position} list.ent_p := nil; list.str_p := nil; return; end; if pos > list.n then begin {going to after last line ?} list.curr := pos; {indicate number of line if it existed} list.str_p := nil; {indicate no line here} list.ent_p := nil; return; end; { * The target line really does exist, although we may not currently be on * a real line. } fwd := pos - list.curr; {number of lines to really move} if fwd >= 0 then begin {moving forward} if list.ent_p = nil then begin {not currently at a line ?} list.ent_p := list.first_p; {start at first line} fwd := fwd - 1; {one less line to go} end; for i := 1 to fwd do begin {once for each line to move forward} list.ent_p := list.ent_p^.next_p; end; end else begin {moving backward} if list.ent_p = nil then begin {not currently at a real line ?} list.ent_p := list.last_p; {start at the last line} fwd := pos - list.n; {update how many lines need to move} end; for i := -1 downto fwd do begin {once for each line to move backward} list.ent_p := list.ent_p^.prev_p; end end ; list.curr := pos; {indicate number of new current line} list.str_p := univ_ptr(addr(list.ent_p^.s)); end; { ******************************************************************************** * * Subroutine STRING_LIST_POS_START (LIST) * * Position to before the first line in the string list LIST. } procedure string_list_pos_start ( {position to before first line in list} in out list: string_list_t); {strings list control block} begin list.curr := 0; list.str_p := nil; list.ent_p := nil; end; { ******************************************************************************** * * Subroutine STRING_LIST_TRUNC (LIST) * * Truncate the strings list LIST after the current line. Note that if the * current position is before the first line (such as after a call to * STRING_LIST_POS_START), then this deletes all lines in the strings list. * This routine has no effect if positioned after the last line in the list. } procedure string_list_trunc ( {truncate strings list after current line} in out list: string_list_t); {strings list control block} var ent_p: string_chain_ent_p_t; {pointer to current chain entry} next_p: string_chain_ent_p_t; {pointer to next chain entry after curr} begin if list.curr >= list.n then return; {no lines to delete ?} if list.ent_p = nil then begin {curr pos is before first line} ent_p := list.first_p; list.first_p := nil; {there will be no first line} end else begin {curr pos is at a real line} ent_p := list.ent_p^.next_p; end ; {ENT_P points to first entry to delete} if ent_p = nil then return; {nothing to delete ?} if ent_p^.prev_p <> nil then begin {there is a previous entry ?} ent_p^.prev_p^.next_p := nil; {previous entry is now end of chain} end; while ent_p <> nil do begin {once for each chain entry to delete} next_p := ent_p^.next_p; {save address of next entry in chain} util_mem_ungrab (ent_p, list.mem_p^); {delete current chain entry} ent_p := next_p; {advance to next entry in chain} end; {back and process this new entry} list.n := list.curr; {current line is now last line} list.last_p := list.ent_p; end; { ******************************************************************************** * * Subroutine STRING_LIST_SORT (LIST, OPTS) * * Sorts the strings in the strings list LIST. OPTS contains a set of option * flags that control the collating sequence. } procedure string_list_sort ( {sort strings in a strings list} in out list: string_list_t; {strings list control block} in opts: string_comp_t); {option flags for collating seqence, etc} val_param; var start_p: string_chain_ent_p_t; {pointer to current sort start entry} best_p: string_chain_ent_p_t; {pointer to current best value found} curr_p: string_chain_ent_p_t; {pointer to current entry being tested} label loop; begin start_p := list.first_p; {init to starting with first list entry} loop: {outer loop} if start_p = nil then return; {nothing left to sort ?} best_p := start_p; {init best found so far is first entry} curr_p := start_p^.next_p; {init pointer to entry to compare to} while curr_p <> nil do begin {once for each entry to compare to} if string_compare_opts (curr_p^.s, best_p^.s, opts) < 0 {found better entry ?} then begin best_p := curr_p; {update pointer to best entry so far} end; curr_p := curr_p^.next_p; {advance to next entry in list} end; {back to check out this new entry} { * START_P is pointing to the entry to set this time. BEST_P is pointing to the * entry that should be moved to just before START_P. } if best_p = start_p then begin {no need to move anything ?} start_p := start_p^.next_p; {advance to next entry to start at} goto loop; end; { * Remove the entry at BEST_P from the list. This is guaranteed to never be the * first entry. } best_p^.prev_p^.next_p := best_p^.next_p; if best_p^.next_p = nil then begin {removing last entry in the list} list.last_p := best_p^.prev_p; end else begin {removing not-last list entry} best_p^.next_p^.prev_p := best_p^.prev_p; end ; { * Insert the entry at BEST_P immediately before the entry at START_P. } best_p^.prev_p := start_p^.prev_p; best_p^.next_p := start_p; start_p^.prev_p := best_p; if best_p^.prev_p = nil then begin {inserting at start of list} list.first_p := best_p; end else begin {inserting at not-start of list} best_p^.prev_p^.next_p := best_p; end ; goto loop; {back for next pass thru remaining list} end;
unit uFileIO; interface uses uInterfaces,Variants, SysUtils, Windows, ComObj, OSMan_TLB, uModule; implementation const fileReaderClassGUID: TGUID = '{6917C025-0890-4754-BB71-25C16552E15D}'; fileWriterClassGUID: TGUID = '{1B3AE666-0897-44A4-BBE0-C0C87BC8A32B}'; type TFileReader = class(TOSManObject,IResourceInputStream) protected hFile: THandle; fEOS: WordBool; public constructor Create(); override; destructor Destroy(); override; function get_eos:WordBool; published //URL: String representation of resource address (web-address, local FS file name, etc). procedure open(const URL: WideString); function read(const maxBufSize: Integer): OleVariant; property eos: WordBool read get_eos; end; TFileWriter = class (TOSManObject,IResourceOutputStream) protected fEOS:boolean; hFile:THandle; constructor Create(); override; destructor Destroy(); override; published //URL: String representation of resource address (web-address, local FS file name, etc). procedure open(const URL: WideString); //Write data from zero-based one dimensional SafeArray of bytes (VT_ARRAY | VT_UI1) procedure write(const aBuf:OleVariant); procedure set_eos(const aEOS:WordBool); function get_eos:WordBool; //write "true" if all data stored and stream should to release system resources //once set to "true" no write oprerations allowed on stream property eos: WordBool read get_eos write set_eos; end; { TFileReader } procedure TFileReader.open(const URL: WideString); var hr:DWord; begin if (URL='') then begin if hFile<> INVALID_HANDLE_VALUE then begin CloseHandle(hFile); hFile:=INVALID_HANDLE_VALUE; fEOS:=true; end; exit; end; if (hFile <> INVALID_HANDLE_VALUE) then raise EInOutError.Create(toString() + ': Open must be called only once'); hFile := CreateFileW(pWideChar(URL), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL or FILE_FLAG_SEQUENTIAL_SCAN, 0); if hFile = INVALID_HANDLE_VALUE then begin hr:=GetLastError(); raise EInOutError.Create(toString() + ': ' + SysErrorMessage(hr)); end; fEOS := false; end; function TFileReader.read(const maxBufSize: Integer): OleVariant; var p: pointer; c: DWord; begin if hFile=INVALID_HANDLE_VALUE then begin raise EInOutError.Create(toString()+': file must be opened before read'); end; result := VarArrayCreate([0, maxBufSize - 1], varByte); p := VarArrayLock(result); c := 0; try if not ReadFile(hFile, p^, maxBufSize, c, nil) then raise EInOutError.Create(toString() + ' :' + SysErrorMessage(GetLastError())); finally VarArrayUnlock(result); end; if Integer(c) < maxBufSize then VarArrayRedim(result, Integer(c) - 1); if integer(c) < maxBufSize then fEOS := true; end; constructor TFileReader.Create; begin inherited; hFile := INVALID_HANDLE_VALUE; fEOS := true; end; destructor TFileReader.Destroy; begin if hFile <> INVALID_HANDLE_VALUE then CloseHandle(hFile); hFile := INVALID_HANDLE_VALUE; fEOS:=true; inherited; end; function TFileReader.get_eos: WordBool; begin result:=fEOS; end; { TFileWriter } constructor TFileWriter.Create; begin inherited; hFile:=INVALID_HANDLE_VALUE; fEOS:=true; end; destructor TFileWriter.Destroy; begin if not eos then eos:=true; inherited; end; function TFileWriter.get_eos: WordBool; begin result:=fEOS; end; procedure TFileWriter.open(const URL: WideString); var hr:DWord; begin if (URL='') then begin eos:=true; exit; end; if hFile <> INVALID_HANDLE_VALUE then raise EInOutError.Create(toString() + ': Open must be called only once'); hFile := CreateFileW(pWideChar(URL), GENERIC_WRITE, FILE_SHARE_READ, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL or FILE_FLAG_SEQUENTIAL_SCAN, 0); if hFile = INVALID_HANDLE_VALUE then begin hr:=GetLastError(); raise EInOutError.Create(toString() + ': ' + SysErrorMessage(hr)); end; fEOS := false; end; procedure TFileWriter.set_eos(const aEOS: WordBool); begin if aEOS and (hFile<>INVALID_HANDLE_VALUE) then begin CloseHandle(hFile); hFile:=INVALID_HANDLE_VALUE; fEOS:=true; end; fEOS:=fEOS or aEOS; end; procedure TFileWriter.write(const aBuf: OleVariant); var pb:pByte; pv:PVariant; cnt:integer; hr,wrtn:DWord; begin pv:=@aBuf; while(VarIsByRef(pv^){(PVarData(pv).VType and varByRef)<>0}) do pv:=pVarData(pv)^.VPointer; if ((VarType(pv^) and VarTypeMask)<>varByte) or (VarArrayDimCount(pv^)<>1) then raise EInOutError.Create(toString()+'.write: array of bytes expected'); if hFile=INVALID_HANDLE_VALUE then raise EInOutError.Create(toString()+'.write: file must be opened before write'); cnt:=VarArrayHighBound(pv^,1)-VarArrayLowBound(pv^,1)+1; if cnt<=0 then exit; pb:=VarArrayLock(pv^); try if not WriteFile(hFile,pb^,cnt,wrtn,nil) or (wrtn<>DWord(cnt)) then begin hr:=GetLastError(); raise EInOutError.Create(toString()+'.write: '+SysErrorMessage(hr)); end; finally VarArrayUnlock(pv^); end; end; initialization uModule.OSManRegister(TFileReader, fileReaderClassGUID); uModule.OSManRegister(TFileWriter, fileWriterClassGUID); end.
unit TextEditor.Marks; interface uses System.Classes, System.Contnrs, System.UITypes, Vcl.Controls; type TTextEditorMark = class protected FBackground: TColor; FChar: Integer; FData: Pointer; FEditor: TCustomControl; FImageIndex: Integer; FIndex: Integer; FLine: Integer; FVisible: Boolean; public constructor Create(AOwner: TCustomControl); property Background: TColor read FBackground write FBackground default TColors.SysNone; property Char: Integer read FChar write FChar; property Data: Pointer read FData write FData; property ImageIndex: Integer read FImageIndex write FImageIndex; property Index: Integer read FIndex write FIndex; property Line: Integer read FLine write FLine; property Visible: Boolean read FVisible write FVisible; end; TTextEditorMarkEvent = procedure(ASender: TObject; var AMark: TTextEditorMark) of object; TTextEditorMarks = array of TTextEditorMark; TTextEditorMarkList = class(TObjectList) protected FEditor: TCustomControl; FOnChange: TNotifyEvent; function GetItem(AIndex: Integer): TTextEditorMark; procedure Notify(Ptr: Pointer; Action: TListNotification); override; procedure SetItem(AIndex: Integer; AItem: TTextEditorMark); property OwnsObjects; public constructor Create(AOwner: TCustomControl); function Extract(AItem: TTextEditorMark): TTextEditorMark; function Find(const AIndex: Integer): TTextEditorMark; function First: TTextEditorMark; function Last: TTextEditorMark; procedure ClearLine(ALine: Integer); procedure GetMarksForLine(ALine: Integer; var AMarks: TTextEditorMarks); procedure Place(AMark: TTextEditorMark); property Items[AIndex: Integer]: TTextEditorMark read GetItem write SetItem; default; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; implementation uses System.Types, TextEditor; constructor TTextEditorMark.Create(AOwner: TCustomControl); begin inherited Create; FBackground := TColors.SysNone; FIndex := -1; FEditor := AOwner; end; { TTextEditorBookmarkList } procedure TTextEditorMarkList.Notify(Ptr: Pointer; Action: TListNotification); begin inherited; if Assigned(FOnChange) then FOnChange(Self); end; function TTextEditorMarkList.GetItem(AIndex: Integer): TTextEditorMark; begin Result := TTextEditorMark(inherited GetItem(AIndex)); end; procedure TTextEditorMarkList.SetItem(AIndex: Integer; AItem: TTextEditorMark); begin inherited SetItem(AIndex, AItem); end; constructor TTextEditorMarkList.Create(AOwner: TCustomControl); begin inherited Create; FEditor := AOwner; end; function TTextEditorMarkList.Find(const AIndex: Integer): TTextEditorMark; var LIndex: Integer; LMark: TTextEditorMark; begin Result := nil; for LIndex := Count - 1 downto 0 do begin LMark := Items[LIndex]; if LMark.Index = AIndex then Exit(LMark); end; end; function TTextEditorMarkList.First: TTextEditorMark; begin Result := TTextEditorMark(inherited First); end; function TTextEditorMarkList.Last: TTextEditorMark; begin Result := TTextEditorMark(inherited Last); end; function TTextEditorMarkList.Extract(AItem: TTextEditorMark): TTextEditorMark; begin Result := TTextEditorMark(inherited Extract(AItem)); end; procedure TTextEditorMarkList.ClearLine(ALine: Integer); var LIndex: Integer; begin for LIndex := Count - 1 downto 0 do if Items[LIndex].Line = ALine then Delete(LIndex); end; procedure TTextEditorMarkList.GetMarksForLine(ALine: Integer; var AMarks: TTextEditorMarks); var LIndex, LIndex2: Integer; LMark: TTextEditorMark; begin SetLength(AMarks, Count); LIndex2 := 0; for LIndex := 0 to Count - 1 do begin LMark := Items[LIndex]; if LMark.Line = ALine then begin AMarks[LIndex2] := LMark; Inc(LIndex2); end; end; SetLength(AMarks, LIndex2); end; procedure TTextEditorMarkList.Place(AMark: TTextEditorMark); var LEditor: TCustomTextEditor; begin LEditor := nil; if Assigned(FEditor) and (FEditor is TCustomTextEditor) then LEditor := FEditor as TCustomTextEditor; if Assigned(LEditor) then if Assigned(LEditor.OnBeforeMarkPlaced) then LEditor.OnBeforeMarkPlaced(FEditor, AMark); if Assigned(AMark) then Add(AMark); if Assigned(LEditor) then if Assigned(LEditor.OnAfterMarkPlaced) then LEditor.OnAfterMarkPlaced(FEditor); end; end.
{Implementación de Listas con Arreglos (Implementación en Memoria Continua).} {Maximiliano Sosa; Ricardo Quesada; Gonzalo J. García} program Listas; uses Crt, Udatos, Upilas, Ucolas1, Ulistas1; var C: TipoCola; A, L: TipoLista; procedure IniLista(var L: TipoLista); {Comentario: }{Los elementos de las pilas son enteros positivos. Si alguna de las pilas se encuentra vacía, este estado será puesto de manifiesto poniendo un cero en la cola resultante. Para el caso dado a continuación la respuesta es: 0, 5, 6.} var P: TipoPila; begin CrearPila(P); PonerEnPila(P, 6); PonerEnPila(P, 2); PonerEnPila(P, 3); InserFin(L, P); CrearPila(P); InserFin(L, P); PonerEnPila(P, 4); PonerEnPila(P, 5); PonerEnPila(P, 1); PonerEnPila(P, 5); InserFin(L, P); end; function MaxEnPila(P: TipoPila): TipoDato; {Precondición: }{La pila P no puede estar vacía.} var x, max: TipoDato; begin SacarDePila(P, x); max := x; while not PilaVacia(P) do begin SacarDePila(P, x); if x > max then max := x; end; MaxEnPila := max; end; procedure GenListaAux(L: TipoLista; var A: TipoLista); var P, X: TipoPila; begin if not ListaVacia(L) then begin Primero(L); while not FinLista(L) do begin CrearPila(X); Info(L, P); if not PilaVacia(P) then begin PonerEnPila(X, MaxEnPila(P)); InserOrden(A, X, 'a'); end else begin PonerEnPila(X, Nulo); InserOrden(A, X, 'a'); end; Siguiente(L); end; end; end; procedure GenCola(A: TipoLista; var C: TipoCola); var X: TipoPila; begin if not ListaVacia(A) then begin Primero(A); while not FinLista(A) do begin Info(A, X); PonerEnCola(C, Top(X)); Siguiente(A); end; end; end; procedure MostCola(C: TipoCola); var x: TipoDato; begin while not ColaVacia(C) do begin SacarDeCola(C, x); write(x); write(' '); end; end; procedure Titulo; begin writeln; write('Algoritmos y Estructuras de Datos I - Universidad CAECE'); writeln; writeln; write('[1999] Maximiliano Sosa; Ricardo Quesada; Gonzalo J. García'); writeln; writeln; writeln; write('IMPLEMENTACION DE LISTAS BASADA EN ARREGLOS'); writeln; writeln; write('Parcial 2, Tema 3, Ejercicio 1: Se muestra la solución de un caso.'); writeln; writeln; writeln; writeln; end; begin clrscr; Titulo; CrearCola(C); CrearLista(L); CrearLista(A); IniLista(L); if not ListaVacia(L) then begin GenListaAux(L, A); GenCola(A, C); MostCola(C); end; end.
unit uImpostoController; interface uses uImposto, DBClient; type TImpostoController = class public function Inserir(oImposto: TImposto; var sError: string): Boolean; function Atualizar(oImposto: TImposto; var sError: string): Boolean; function Excluir(oImposto: TImposto; var sError: string): Boolean; function Consultar(oImposto: TImposto; pFiltro: string; var sError: string): TClientDataSet; procedure ConsultarId(oImposto: TImposto; pFiltro: string; var sError: string); function CarregaCombo(pObjeto: TObject; pCampo: string): TClientDataSet; end; implementation uses uPersistencia, SysUtils; { TImpostoController } function TImpostoController.Atualizar(oImposto: TImposto; var sError: string): Boolean; begin Result := TPersistencia.Atualizar(oImposto, sError); end; function TImpostoController.CarregaCombo(pObjeto: TObject; pCampo: string): TClientDataSet; begin Result := TPersistencia.CarregaLookupChaveEstrangeira(pObjeto, pCampo); end; function TImpostoController.Consultar(oImposto: TImposto; pFiltro: string; var sError: string): TClientDataSet; begin Result := TPersistencia.Consultar(oImposto, 'NOME', pFiltro, sError); end; procedure TImpostoController.ConsultarId(oImposto: TImposto; pFiltro: string; var sError: string); var ds: TClientDataSet; begin ds := TPersistencia.Consultar(oImposto, 'ID', pFiltro, sError); oImposto.Nome := ds.FieldByName('NOME').AsString; oImposto.Aliquota := ds.FieldByName('ALIQUOTA').AsInteger; end; function TImpostoController.Excluir(oImposto: TImposto; var sError: string): Boolean; begin Result := TPersistencia.Excluir(oImposto, sError); end; function TImpostoController.Inserir(oImposto: TImposto; var sError: string): Boolean; begin Result := TPersistencia.Inserir(oImposto, sError); end; end.
{ *************************************************************************** * * * This file is part of Lazarus DBF Designer * * * * Copyright (C) 2012 Vadim Vitomsky * * * * This source is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This code is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * General Public License for more details. * * * * A copy of the GNU General Public License is available on the World * * Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also * * obtain it by writing to the Free Software Foundation, * * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * * ***************************************************************************} unit umain; {$mode objfpc}{$H+} interface uses SysUtils, FileUtil, SynHighlighterPas, SynMemo, SynHighlighterSQL, LResources, Forms, Controls, Graphics, Dialogs, Menus, ComCtrls, ExtCtrls, ActnList, DBGrids, Buttons, db, dbf, dbf_fields, StdCtrls, Grids, DbCtrls, inifiles, Classes, urstrrings, LConvEncoding, Translations, DefaultTranslator, GetText, LazUTF8; type { TFormMain } TFormMain = class(TForm) actFileOpen: TAction; actFileExit: TAction; actCreateDBF: TAction; acrRestructureDBF: TAction; actEditData: TAction; actCSVExport: TAction; actCloseDbf: TAction; Action1: TAction; Action2: TAction; actSearch: TAction; actSQLExport: TAction; actPasExport: TAction; actMemoAssign: TAction; ImageList1: TImageList; MenuItem14: TMenuItem; ShowDeletedCheckBox: TCheckBox; MenuItem10: TMenuItem; MenuItem11: TMenuItem; MenuItem12: TMenuItem; MenuItem13: TMenuItem; ShowSourceCheckBox: TCheckBox; DbfDBGrid: TDBGrid; DbfLocaleComboBox: TComboBox; DBMemo1: TDBMemo; MenuItem7: TMenuItem; MenuItem8: TMenuItem; MenuItem9: TMenuItem; SearchLabel: TLabel; SearchEdit: TEdit; LocaleLabel: TLabel; DbGridPopupMenu: TPopupMenu; MenuItem3: TMenuItem; MenuItem4: TMenuItem; MenuItem5: TMenuItem; MenuItem6: TMenuItem; SearchPanel: TPanel; ExportDialog: TSaveDialog; SearchSpeedButton: TSpeedButton; sbFilterButton: TSpeedButton; CloseSpeedButton: TSpeedButton; SQLMenuExport: TMenuItem; PascalMenuExport: TMenuItem; sbCreateBitBtn: TSpeedButton; DbfTable: TDbf; DbfDatasource: TDatasource; MainActionList: TActionList; MainMenu1: TMainMenu; FileMenuItem: TMenuItem; FileOpenMenuItem: TMenuItem; FileCreateMenuItem: TMenuItem; FileExportMenuItem: TMenuItem; FileExitMenuItem: TMenuItem; EditMenuItem: TMenuItem; EditFieldListMenuItem: TMenuItem; HelpMenuItem: TMenuItem; HelpManualMenuItem: TMenuItem; HelpAboutMenuItem: TMenuItem; MenuItem1: TMenuItem; MenuItem2: TMenuItem; EditSettingsMenuItem: TMenuItem; EditDataEditMenuItem: TMenuItem; sbOpenSpeedButton: TSpeedButton; sbEditDataSpeedButton: TSpeedButton; SynFreePascalSyn1: TSynFreePascalSyn; SynMemo1: TSynMemo; SynPasSyn1: TSynPasSyn; SynSQLSyn1: TSynSQLSyn; TableOpenDialog: TOpenDialog; MainStatusBar: TStatusBar; ToolPanel: TPanel; ToolsJoinMenuItem: TMenuItem; ToolsSortMenuItem: TMenuItem; ToolsCompareMenuItem: TMenuItem; ToolsEmptyMenuItem: TMenuItem; ToolsPackMenuItem: TMenuItem; ToolsRecodeMenuItem: TMenuItem; ToolsMenuItem: TMenuItem; procedure acrRestructureDBFExecute(Sender: TObject); procedure actCloseDbfExecute(Sender: TObject); procedure actCreateDBFExecute(Sender: TObject); procedure actCSVExportExecute(Sender: TObject); procedure actEditDataExecute(Sender: TObject); procedure actFileExitExecute(Sender: TObject); procedure actFileOpenExecute(Sender: TObject); procedure Action2Execute(Sender: TObject); procedure actPascalMenuExportClick(Sender: TObject); procedure actSearchExecute(Sender: TObject); procedure actSQLExportExecute(Sender: TObject); procedure DbfTableAfterClose(DataSet: TDataSet); procedure DbfTableAfterOpen(DataSet: TDataSet); procedure DbfTableIndexMissing(var DeleteLink: Boolean); procedure MenuItem13Click(Sender: TObject); procedure ShowDeletedCheckBoxClick(Sender: TObject); procedure DbfDBGridDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); procedure MenuItem11Click(Sender: TObject); procedure MenuItem12Click(Sender: TObject); procedure ShowSourceCheckBoxClick(Sender: TObject); procedure DbfDBGridColEnter(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDropFiles(Sender: TObject; const FileNames: array of String); procedure FormKeyPress(Sender: TObject; var Key: char); procedure HelpAboutMenuItemClick(Sender: TObject); procedure LocaleComboBoxExit(Sender: TObject); procedure SearchEditChange(Sender: TObject); procedure SearchEditKeyPress(Sender: TObject; var Key: char); procedure ToolsEmptyMenuItemClick(Sender: TObject); procedure ToolsPackMenuItemClick(Sender: TObject); procedure DbFieldGetText(Sender : TField; var aText : String; DisplayText : Boolean); procedure DbFieldSetText(Sender : TField; const aText : String); procedure DbAfterOpen(Dataset : TDataset); procedure SetStatusBarInfo; private { private declarations } public { public declarations } end; var FormMain: TFormMain; settingsini : TINIFile; langfile : TINIFile; defaultlang : TINIFile; settingspath: String; implementation uses useltype, ustruct, uabout; var DbfSearchBookmark: TBookmark; procedure TFormMain.SetStatusBarInfo; var tl : String; begin //Adding information about opened table in main statusbar Caption := rsDBDesigner+DbfTable.TableName; MainStatusBar.Panels.Add; MainStatusBar.Panels[0].Width := 200; MainStatusBar.Panels[0].Text := rsTable+DbfTable.TableName; MainStatusBar.Panels.Add; MainStatusBar.Panels[1].Width := 200; case DbfTable.TableLevel of 3: tl := rsDBaseIII; 4: tl := rsDBaseIV; 7: tl := rsVisualDBaseV; 25: tl := rsFoxPro else tl := rsUnknown; //is this really needed? end;//case MainStatusBar.Panels[1].Text := rsTableLevel+IntToStr(DbfTable.TableLevel)+ ' ('+tl+')'; MainStatusBar.Panels.Add; MainStatusBar.Panels[2].Width := 150; MainStatusBar.Panels[2].Text := rsRecords+IntToStr(DbfTable.RecordCount); MainStatusBar.Panels.Add; MainStatusBar.Panels[3].Width := 160; MainStatusBar.Panels[3].Text := rsCodepage+IntToStr(DbfTable.CodePage); MainStatusBar.Panels.Add; MainStatusBar.Panels[4].Width := 120; MainStatusBar.Panels[4].Text := rsWaiting; case DbfTable.CodePage of 866: DbfLocaleComboBox.ItemIndex:=0; 1251,1252: DbfLocaleComboBox.ItemIndex:=1; else DbfLocaleComboBox.ItemIndex:=2; end;//case if DbfTable.TableLevel=3 then begin DbfLocaleComboBox.ItemIndex:=0; //for DBase III+ cp866 MainStatusBar.Panels[3].Text := rsCodepage866; end; end; { TFormMain } procedure TFormMain.FormKeyPress(Sender: TObject; var Key: char); begin case Key of #27:if not SearchPanel.Visible then actFileExitExecute(nil); #6:actSearchExecute(nil); end; end; procedure TFormMain.HelpAboutMenuItemClick(Sender: TObject); begin AboutForm.ShowModal; end; procedure TFormMain.LocaleComboBoxExit(Sender: TObject); begin DbfDBGrid.Refresh; end; procedure TFormMain.SearchEditChange(Sender: TObject); begin case DbfLocaleComboBox.ItemIndex of 0:DbfTable.Locate(DbfDBGrid.SelectedColumn.FieldName,UTF8ToConsole(SearchEdit.Text),[loCaseInsensitive,loPartialKey]); 1:DbfTable.Locate(DbfDBGrid.SelectedColumn.FieldName,Utf8ToAnsi(SearchEdit.Text),[loCaseInsensitive,loPartialKey]); 2:DbfTable.Locate(DbfDBGrid.SelectedColumn.FieldName,SearchEdit.Text,[loCaseInsensitive,loPartialKey]); end; end; procedure TFormMain.SearchEditKeyPress(Sender: TObject; var Key: char); begin if SearchEdit.Text='' then exit; case Key of #13:Begin case DbfLocaleComboBox.ItemIndex of 0:DbfTable.Locate(DbfDBGrid.SelectedColumn.FieldName,UTF8ToConsole(SearchEdit.Text),[loCaseInsensitive,loPartialKey]); 1:DbfTable.Locate(DbfDBGrid.SelectedColumn.FieldName,Utf8ToAnsi(SearchEdit.Text),[loCaseInsensitive,loPartialKey]); 2:DbfTable.Locate(DbfDBGrid.SelectedColumn.FieldName,SearchEdit.Text,[loCaseInsensitive,loPartialKey]); end; DbfTable.FreeBookmark(DbfSearchBookmark); SearchPanel.Visible:=false; end; #27: begin DbfTable.GotoBookmark(DbfSearchBookmark); DbfTable.FreeBookmark(DbfSearchBookmark); SearchEdit.Clear; SearchPanel.Visible:=false; end else begin case DbfLocaleComboBox.ItemIndex of 0:DbfTable.Locate(DbfDBGrid.SelectedColumn.FieldName,UTF8ToConsole(SearchEdit.Text),[loCaseInsensitive,loPartialKey]); 1:DbfTable.Locate(DbfDBGrid.SelectedColumn.FieldName,Utf8ToAnsi(SearchEdit.Text),[loCaseInsensitive,loPartialKey]); 2:DbfTable.Locate(DbfDBGrid.SelectedColumn.FieldName,SearchEdit.Text,[loCaseInsensitive,loPartialKey]); end; end; end; end; procedure TFormMain.actPascalMenuExportClick(Sender: TObject); var i : Integer; _rcnt : Integer; paslist : TStringList; begin ExportDialog.Filter:=rsPascalInclud; ExportDialog.DefaultExt:='.inc'; ExportDialog.InitialDir:=''; ExportDialog.FileName:=LowerCase(Copy(DbfTable.TableName,1,Pos('.',DbfTable.TableName)-1)); if not ExportDialog.Execute then exit; paslist:=TStringList.Create; //export as Pascal source SynMemo1.Visible:=true; SynMemo1.Clear; SynMemo1.Lines.Add('procedure CreateDbf(var _fname: String);'); SynMemo1.Lines.Add('var Dbf1 : Tdbf;'); SynMemo1.Lines.Add('Begin'); SynMemo1.Lines.Add(' Dbf1:=Tdbf.Create(nil);'); SynMemo1.Lines.Add(' Dbf1.FilePathFull:='''';'); SynMemo1.Lines.Add(' Dbf1.Tablename:=_fname;'); SynMemo1.Lines.Add(' Dbf1.TableLevel:='+IntToStr(DbfTable.TableLevel)+';'); SynMemo1.Lines.Add(' Dbf1.LanguageId:='+IntToStr(DbfTable.LanguageID)+';//test this'); for i := 0 to DbfTable.FieldCount-1 do begin case DbfTable.DbfFieldDefs.Items[i].FieldType of ftString:SynMemo1.Lines.Add(' Dbf1.FieldDefs.Add('''+DbfTable.DbfFieldDefs.Items[i].FieldName+''',ftString,'+IntToStr(DbfTable.DbfFieldDefs.Items[i].Size)+');'); ftSmallint:SynMemo1.Lines.Add(' Dbf1.FieldDefs.Add('''+DbfTable.DbfFieldDefs.Items[i].FieldName+''',ftSmallint,'+IntToStr(DbfTable.DbfFieldDefs.Items[i].Size)+');'); ftAutoInc:SynMemo1.Lines.Add(' Dbf1.FieldDefs.Add('''+DbfTable.DbfFieldDefs.Items[i].FieldName+''',ftAutoInc);'); ftInteger:SynMemo1.Lines.Add(' Dbf1.FieldDefs.Add('''+DbfTable.DbfFieldDefs.Items[i].FieldName+''',ftInteger,'+IntToStr(DbfTable.DbfFieldDefs.Items[i].Size)+');'); ftBoolean:SynMemo1.Lines.Add(' Dbf1.FieldDefs.Add('''+DbfTable.DbfFieldDefs.Items[i].FieldName+''',ftBoolean);'); ftDate:SynMemo1.Lines.Add(' Dbf1.FieldDefs.Add('''+DbfTable.DbfFieldDefs.Items[i].FieldName+''',ftDate);'); ftFloat:SynMemo1.Lines.Add(' Dbf1.FieldDefs.Add('''+DbfTable.DbfFieldDefs.Items[i].FieldName+''',ftFloat,'+IntToStr(DbfTable.DbfFieldDefs.Items[i].Size)+','+IntToStr(DbfTable.DbfFieldDefs.Items[i].Precision)+');'); end;//case end; SynMemo1.Lines.Add(' Dbf1.CreateTable;'); //data export SynMemo1.Lines.Add(' //export all data as text fields'); DbfTable.First; for _rcnt:=1 to DbfTable.ExactRecordCount do begin SynMemo1.Lines.Add(' Dbf1.Append;'); MainStatusBar.Panels[4].Text := Format(rsExportingRec, [IntToStr(_rcnt), IntToStr(DbfTable.ExactRecordCount)]); for i:=0 to DbfTable.Fields.Count-1 do begin case DbfLocaleComboBox.ItemIndex of 0:SynMemo1.Lines.Add(' Dbf1.FieldByName('''+DbfTable.Fields[i].FieldName+''').AsString:='''+ConsoleToUtf8(DbfTable.Fields[i].AsString)+''';'); 1:SynMemo1.Lines.Add(' Dbf1.FieldByName('''+DbfTable.Fields[i].FieldName+''').AsString:='''+AnsiToUtf8(DbfTable.Fields[i].AsString)+''';'); 2:SynMemo1.Lines.Add(' Dbf1.FieldByName('''+DbfTable.Fields[i].FieldName+''').AsString:='''+DbfTable.Fields[i].AsString+''';'); end; Application.ProcessMessages; end; SynMemo1.Lines.Add(' Dbf1.Post;'); DbfTable.Next; end; SynMemo1.Lines.Add('End;'); paslist.Assign(SynMemo1.Lines); paslist.SaveToFile(ExportDialog.FileName); paslist.Free; ShowMessage(Format(rsSavedAs, [ExportDialog.FileName])); ShowSourceCheckBox.Enabled:=true; ShowSourceCheckBox.Checked:=false; ShowSourceCheckBoxClick(self); MainStatusBar.Panels[4].Text := rsWaiting; end; procedure TFormMain.actSearchExecute(Sender: TObject); begin //show search dialog if not DbfTable.Active then Exit; DbfSearchBookmark:=DbfTable.GetBookmark; SearchPanel.Parent:=DbfDBGrid as TWinControl; SearchPanel.Left:=DbfDBGrid.SelectedFieldRect.Left+20; SearchPanel.Top:=DbfDBGrid.SelectedFieldRect.Top+20; // SearchEdit.Clear; SearchPanel.Visible:=true; SearchEdit.SetFocus; end; procedure TFormMain.actSQLExportExecute(Sender: TObject); var i,j : Integer; _s_,_ss_: String; sqllist : TStringList; begin ExportDialog.Filter:=rsSQLQueryFile; ExportDialog.DefaultExt:='.sql'; ExportDialog.InitialDir:=''; ExportDialog.FileName:=LowerCase(Copy(DbfTable.TableName,1,Pos('.',DbfTable.TableName)-1)); if not ExportDialog.Execute then exit; DbfTable.DisableControls; sqllist:=TStringList.Create; ShowSourceCheckBox.Enabled:=true; ShowSourceCheckBox.Checked:=true; SynMemo1.Visible:=true; SynMemo1.Highlighter:=SynSQLSyn1; SynMemo1.Clear; _s_:='CREATE TABLE '+UpperCase(Copy(DbfTable.TableName,1,Pos('.',DbfTable.TableName)-1))+' ('; for i := 0 to DbfTable.DbfFieldDefs.Count-1 do begin _s_:=_s_+DbfTable.DbfFieldDefs.Items[i].FieldName; case DbfTable.DbfFieldDefs.Items[i].FieldType of ftString,ftDate:_s_:=_s_+' VARCHAR, '; ftSmallint,ftInteger,ftLargeint:_s_:=_s_+' NUMERIC, '; ftFloat:_s_:=_s_+' FLOAT, '; ftBoolean:_s_:=_s_+' BOOLEAN, '; ftMemo:_s_:=_s_+' BLOB, ' else _s_:=_s_+' VARCHAR, '; END;//case end; Delete(_s_,Length(_s_)-1,2); sqllist.Add(_s_+');'); DbfTable.First; for j:=1 to DbfTable.ExactRecordCount do begin _s_:='INSERT INTO '+UpperCase(Copy(DbfTable.TableName,1,Pos('.',DbfTable.TableName)-1))+' VALUES('; _ss_:=''; for i:=0 to DbfTable.FieldCount-1 do begin case DbfLocaleComboBox.ItemIndex of 0:if DbfTable.Fields[i].AsString='' then _ss_:=_ss_+'NULL,' else _ss_:=_ss_+StringReplace(QuotedStr(Cp866ToUTF8(DbfTable.Fields[i].AsString)),',','.',[rfReplaceAll])+','; 1:if DbfTable.Fields[i].AsString='' then _ss_:=_ss_+'NULL,' else _ss_:=_ss_+StringReplace(QuotedStr(CP1251ToUtf8(DbfTable.Fields[i].AsString)),',','.',[rfReplaceAll])+','; 2:if DbfTable.Fields[i].AsString='' then _ss_:=_ss_+'NULL,' else _ss_:=_ss_+StringReplace(QuotedStr(KOI8ToUTF8(DbfTable.Fields[i].AsString)),',','.',[rfReplaceAll])+','; 3:if DbfTable.Fields[i].AsString='' then _ss_:=_ss_+'NULL,' else _ss_:=_ss_+StringReplace(QuotedStr(ISO_8859_15ToUTF8(DbfTable.Fields[i].AsString)),',','.',[rfReplaceAll])+','; 4:if DbfTable.Fields[i].AsString='' then _ss_:=_ss_+'NULL,' else _ss_:=_ss_+StringReplace(QuotedStr(DbfTable.Fields[i].AsString),',','.',[rfReplaceAll])+','; end; end; _s_:=_s_+_ss_; Delete(_s_,Length(_s_),1); sqllist.Add(_s_+');'); MainStatusBar.Panels[4].Text := Format(rsExportingRec, [IntToStr(j), IntToStr(DbfTable.ExactRecordCount)]); DbfTable.Next; Application.ProcessMessages; end; DbfTable.EnableControls; SynMemo1.Visible:=true; sqllist.SaveToFile(ExportDialog.FileName); SynMemo1.Lines.Assign(sqllist); ShowMessage(Format(rsSavedAs, [ExportDialog.FileName])); MainStatusBar.Panels[4].Text := rsWaiting; sqllist.Free; end; procedure TFormMain.DbfTableAfterClose(DataSet: TDataSet); begin actSearch.Enabled:=False; actEditData.Enabled:=False; actSQLExport.Enabled:=False; actCSVExport.Enabled:=False; actPasExport.Enabled:=False; acrRestructureDBF.Enabled:=False; actCloseDbf.Enabled:=True; end; procedure TFormMain.DbfTableAfterOpen(DataSet: TDataSet); var i,j : Integer; mask : String; begin actSearch.Enabled:=True; actEditData.Enabled:=True; actSQLExport.Enabled:=True; actCSVExport.Enabled:=True; actPasExport.Enabled:=True; acrRestructureDBF.Enabled:=True; actCloseDbf.Enabled:=false; //fields display format settings for i:=0 to DataSet.FieldCount-1 do begin if DataSet.FieldDefs.Items[i].Precision <>0 then begin mask:='#0.'; for j:=0 to DataSet.FieldDefs.Items[i].Precision-1 do mask:=mask+'0'; DbfDBGrid.Columns.Items[i].DisplayFormat:=mask; end; end; end; procedure TFormMain.DbfTableIndexMissing(var DeleteLink: Boolean); begin ShowMessage(rsIndexMissing); end; procedure TFormMain.MenuItem13Click(Sender: TObject); begin DbfTable.ClearFields; end; procedure TFormMain.ShowDeletedCheckBoxClick(Sender: TObject); begin DbfTable.ShowDeleted:=ShowDeletedCheckBox.Checked; MenuItem12.Enabled:=ShowDeletedCheckBox.Checked; end; procedure TFormMain.DbfDBGridDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); begin if not DbfTable.ShowDeleted then begin DbfDBGrid.DefaultDrawColumnCell(Rect,DataCol, Column, State); exit; end; if DbfTable.IsDeleted then begin DbfDBGrid.Canvas.Font.Color:=clRed; DbfDBGrid.DefaultDrawColumnCell(Rect,DataCol, Column, State); end; end; procedure TFormMain.MenuItem11Click(Sender: TObject); begin DbfTable.Delete; end; procedure TFormMain.MenuItem12Click(Sender: TObject); begin DbfTable.Undelete; end; procedure TFormMain.ToolsEmptyMenuItemClick(Sender: TObject); begin DbfTable.Active:=false; DbfTable.Exclusive:=true; DbfTable.Active:=true; DbfTable.EmptyTable; DbfTable.Active:=false; DbfTable.Exclusive:=false; DbfTable.Active:=true; end; procedure TFormMain.ToolsPackMenuItemClick(Sender: TObject); begin DbfTable.Active:=false; DbfTable.Exclusive:=true; DbfTable.Active:=true; DbfTable.PackTable; ShowMessage(rsTablePacked); end; procedure TFormMain.DbFieldGetText(Sender: TField; var aText: String; DisplayText: Boolean); begin if not DisplayText then Exit; case DbfLocaleComboBox.ItemIndex of 0: aText:=CP866ToUTF8(Sender.AsString);// DOS 1: aText:=CP1251ToUTF8(Sender.AsString); // Win1251 2: aText:=KOI8ToUTF8(Sender.AsString); // Koi8 3: aText:=ISO_8859_2ToUTF8(Sender.AsString);// ISO eastern europe // UTF16 // MAC else aText:=Sender.AsString; end; end; procedure TFormMain.DbFieldSetText(Sender: TField; const aText: String); begin case DbfLocaleComboBox.ItemIndex of 0: Sender.AsString:=UTF8ToCP866(aText);// DOS 1: Sender.AsString:=UTF8ToCP1251(aText); // Win1251 2: Sender.AsString:=UTF8ToKOI8U(aText); // Koi8 3: Sender.AsString:=UTF8ToISO_8859_2(aText);// ISO eastern europe // UTF16 // MAC else Sender.AsString:=aText; end; end; procedure TFormMain.DbAfterOpen(Dataset: TDataset); var i : Integer; begin for i := 0 to Dataset.FieldCount-1 do if Dataset.Fields[i].DataType in [ftWideString, ftString,ftMemo,ftBlob,ftFixedChar] then begin Dataset.Fields[i].OnGetText:=@DbFieldGetText; Dataset.Fields[i].OnSetText:=@DbFieldSetText; end; end; procedure TFormMain.actFileOpenExecute(Sender: TObject); var i : Integer; begin for i:= 0 to ComponentCount-1 do if (Components[i] is TDataSet) then begin (Components[i] as TDataSet).AfterOpen :=@DbAfterOpen; if (Components[i] as TDataSet).Active then DbAfterOpen(Components[i] as TDataSet); end; //Close opened before table and hide dbgrid DbfDBGrid.Visible := false; DBMemo1.DataField:=''; DbfTable.Active := False; //clear all panels on main statusbar MainStatusBar.Panels.Clear; Caption := 'DBDesigner'; if TableOpenDialog.Execute then begin DbfTable.FilePathFull := ExtractFilePath(TableOpenDialog.FileName); DbfTable.TableName := ExtractFileName(TableOpenDialog.FileName); DbfTable.Active := true; DbfDBGrid.Visible := true; DbfDBGridColEnter(self); SetStatusBarInfo; DbfTableAfterOpen(DbfTable); end; end; procedure TFormMain.Action2Execute(Sender: TObject); begin //TODO: show non-modal filter dialog with full field list and additional options if not DbfTable.Active then Exit; end; procedure TFormMain.ShowSourceCheckBoxClick(Sender: TObject); begin SynMemo1.Visible:=ShowSourceCheckBox.Checked; end; procedure TFormMain.DbfDBGridColEnter(Sender: TObject); begin DBMemo1.DataField:=DbfDBGrid.SelectedColumn.FieldName; end; procedure TFormMain.actFileExitExecute(Sender: TObject); begin Application.Terminate; end; procedure TFormMain.actCreateDBFExecute(Sender: TObject); begin FormSelectDbType.ShowModal; end; procedure TFormMain.actCSVExportExecute(Sender: TObject); var i,j : Integer; _s_: String; csvseparator : String; csvlist : TStringList; begin ExportDialog.Filter:=rsCSVFilesCsvA; ExportDialog.DefaultExt:='.csv'; ExportDialog.InitialDir:=''; ExportDialog.FileName:=LowerCase(Copy(DbfTable.TableName,1,Pos('.',DbfTable.TableName)-1)); if not ExportDialog.Execute then exit; csvlist:=TStringList.Create; csvseparator:=';';//TODO: settingsini.ReadString('EXPORT','CSVSEPARATOR',';'); SynMemo1.Clear; _s_:=''; for i := 0 to DbfTable.DbfFieldDefs.Count-1 do _s_:=_s_+DbfTable.DbfFieldDefs.Items[i].FieldName+csvseparator; Delete(_s_,Length(_s_),1); csvlist.Add(_s_); DbfTable.First; j:=0; while not DbfTable.EOF do begin _s_:=''; Inc(j); for i := 0 to DbfTable.FieldCount-1 do case DbfLocaleComboBox.ItemIndex of 0:_s_:=_s_+QuotedStr(ConsoleToUTF8(DbfTable.Fields[i].AsString))+csvseparator; 1:_s_:=_s_+QuotedStr(AnsiToUtf8(DbfTable.Fields[i].AsString))+csvseparator; 2:_s_:=_s_+QuotedStr(DbfTable.Fields[i].AsString)+csvseparator; end; Delete(_s_,Length(_s_),1); csvlist.Add(_s_); MainStatusBar.Panels[4].Text := Format(rsExportingRec, [IntToStr(j), IntToStr(DbfTable.ExactRecordCount)]); DbfTable.Next; Application.ProcessMessages; end; csvlist.SaveToFile(ExportDialog.FileName); SynMemo1.Lines.Assign(csvlist); ShowMessage(Format(rsSavedAs, [ExportDialog.FileName])); SynMemo1.Clear; MainStatusBar.Panels[4].Text := rsWaiting; csvlist.Free; end; procedure TFormMain.actEditDataExecute(Sender: TObject); begin if not DbfTable.Active then Exit; if DbfTable.State in dsEditModes then DbfTable.Post; DbfDatasource.AutoEdit := not DbfDatasource.AutoEdit; sbEditDataSpeedButton.Flat := DbfDatasource.AutoEdit; case DbfDatasource.AutoEdit of false: ImageList1.GetBitmap(1,sbEditDataSpeedButton.Glyph); true : ImageList1.GetBitmap(0,sbEditDataSpeedButton.Glyph); end; end; procedure TFormMain.acrRestructureDBFExecute(Sender: TObject); var I : Integer; flddefs : TDbfFieldDefs; begin if not DbfTable.Active then exit; tl := DbfTable.TableLevel; //try open index files FormDBSructureDesigner.IndexComboBox.Items.Clear; if FileExists(DbfTable.FilePathFull+ChangeFileExt(DbfTable.TableName,'.IDX')) then begin FormDBSructureDesigner.IndexComboBox.Items.Add(ChangeFileExt(DbfTable.TableName,'.IDX')); end else DbfTable.GetIndexNames(FormDBSructureDesigner.IndexComboBox.Items); isNew := false; flddefs:=DbfTable.DbfFieldDefs; with FormDBSructureDesigner do begin StructureStringGrid.RowCount := flddefs.Count+1; for i := 0 to flddefs.Count-1 do begin StructureStringGrid.Cells[0,i+1]:= IntToStr(i+1); StructureStringGrid.Cells[1,i+1]:= flddefs.Items[i].FieldName; if flddefs.Items[i].FieldType=ftString then begin StructureStringGrid.Cells[2, i+1]:=rsCharacter; StructureStringGrid.Cells[3,i+1]:= IntToStr(flddefs.Items[i].Size); end; if flddefs.Items[i].FieldType= ftSmallint then begin StructureStringGrid.Cells[2, i+1]:=rsNumber; StructureStringGrid.Cells[3,i+1]:= IntToStr(flddefs.Items[i].Size); end; if flddefs.Items[i].FieldType=ftInteger then begin StructureStringGrid.Cells[2, i+1]:=rsNumber; StructureStringGrid.Cells[3,i+1]:= IntToStr(flddefs.Items[i].Size); end; if FldDefs.Items[i].FieldType=ftWord then begin StructureStringGrid.Cells[2, i+1]:=rsNumber; StructureStringGrid.Cells[3,i+1]:= IntToStr(flddefs.Items[i].Size); end; if FldDefs.Items[i].FieldType=ftBoolean then StructureStringGrid.Cells[2, i +1]:=rsLogical; if FldDefs.Items[i].FieldType=ftFloat then begin StructureStringGrid.Cells[2, i+1]:=rsFloat; StructureStringGrid.Cells[3,i+1]:= IntToStr(FldDefs.Items[i].Size); StructureStringGrid.Cells[4,i+1]:= IntToStr(FldDefs.Items[i].Precision); end; if FldDefs.Items[i].FieldType=ftCurrency then StructureStringGrid.Cells[2,i+1]:=rsFloat; if FldDefs.Items[i].FieldType=ftBCD then StructureStringGrid.Cells[2, i+1]:=rsBinary; if FldDefs.Items[i].FieldType=ftDate then StructureStringGrid.Cells[2, i+1]:=rsDate; if FldDefs.Items[i].FieldType=ftDateTime then StructureStringGrid.Cells[2,i+1]:=rsDate; if FldDefs.Items[i].FieldType=ftBytes then StructureStringGrid.Cells[2, i+1]:=rsBinary; if FldDefs.Items[i].FieldType=ftAutoInc then StructureStringGrid.Cells[2, i+1]:=rsAutoinc; if flddefs.Items[i].FieldType=ftBlob then StructureStringGrid.Cells[2, i+1]:=rsFtBlob; if flddefs.Items[i].FieldType=ftMemo then StructureStringGrid.Cells[2, i+1]:=rsFtMemo; if flddefs.Items[i].FieldType=ftDBaseOle then StructureStringGrid.Cells[2,i+1]:=rsFtDBaseOle; if flddefs.Items[i].FieldType=ftFixedChar then StructureStringGrid.Cells[2, i+1]:=rsFtFixedChar; if flddefs.Items[i].FieldType=ftWideString then StructureStringGrid.Cells[2, i+1]:=rsFtWideString; if flddefs.Items[i].FieldType=ftLargeint then StructureStringGrid.Cells[2,i+1]:=rsFtLargeint; end;//for i end;//with FormDBSructureDesigner.ShowModal; end; procedure TFormMain.actCloseDbfExecute(Sender: TObject); begin DbfTable.Active:=false; DbfDBGrid.Visible := false; end; procedure TFormMain.FormCreate(Sender: TObject); var i : Integer; begin DbfDBGrid.Visible := false; actCloseDbf.Enabled:=DbfDBGrid.Visible; DbfTableAfterClose(DbfTable); WindowState := wsMaximized; {$IFDEF MSWINDOWS} DbfLocaleComboBox.ItemIndex:=1; {$ENDIF} //clear all panels on main statusbar MainStatusBar.Panels.Clear; Caption := rsDBDesigner; LocaleLabel.Caption:=rsDBFLocale; ShowSourceCheckBox.Caption:=rsShowSource; ShowDeletedCheckBox.Caption:=rsShowDeleted; SearchLabel.Caption:=rsSearch; if Paramcount>0 then begin for i:= 0 to ComponentCount-1 do if (Components[i] is TDataSet) then begin (Components[i] as TDataSet).AfterOpen :=@DbAfterOpen; if (Components[i] as TDataSet).Active then DbAfterOpen(Components[i] as TDataSet); end; //Close opened before table and hide dbgrid DbfDBGrid.Visible := false; DBMemo1.DataField:=''; DbfTable.Active := False; //check if no error open file DbfTable.FilePathFull := ExtractFilePath(ParamStr(1)); DbfTable.TableName := ExtractFileName(ParamStr(1)); try DbfTable.Active := true; //TODO: onError handler finally DbfDBGrid.Visible := true; DbfDBGridColEnter(self); SetStatusBarInfo; DbfTableAfterOpen(DbfTable); end; end; end; procedure TFormMain.FormDropFiles(Sender: TObject; const FileNames: array of String); var i : Integer; begin for i:= 0 to ComponentCount-1 do if (Components[i] is TDataSet) then begin (Components[i] as TDataSet).AfterOpen :=@DbAfterOpen; if (Components[i] as TDataSet).Active then DbAfterOpen(Components[i] as TDataSet); end; //Close opened before table and hide dbgrid DbfDBGrid.Visible := false; DBMemo1.DataField:=''; DbfTable.Active := False; //clear all panels on main statusbar MainStatusBar.Panels.Clear; Caption := rsDBDesigner; //TODO: check if no error open file DbfTable.FilePathFull := ExtractFilePath(FileNames[0]); DbfTable.TableName := ExtractFileName(FileNames[0]); DbfTable.Active := true; DbfDBGrid.Visible := true; DbfDBGridColEnter(self); SetStatusBarInfo; DbfTableAfterOpen(DbfTable); end; initialization {$I umain.lrs} end.
unit uFieldItemImpl; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs,DBClient,KeyPairDictionary, StdCtrls, Buttons, ExtCtrls; type TDataType=(dtBoolean,dtInteger,dtCurrency,dtDouble,dtString,dtWideString,dtMemo,dtDate,dtTime,dtDateTime,dtSmallint,dtBlob); TFieldItem=class(TPersistent) private FFieldName: string; FDisplayLabel: string; FIsKey:Boolean ; FIsShow: Boolean; FIsBrowseShow : Boolean; FShowWidth:integer; FDataType:TDataType; public procedure Assign(Source: TPersistent); override; function GetFieldSql:string; property FieldName:string read FFieldName write FFieldName; property DisplayLabel:string read FDisplayLabel write FDisplayLabel; property IsKey:Boolean read FIsKey write FIsKey; property IsShow:Boolean read FIsShow write FIsShow; property IsBrowseShow:Boolean read FIsBrowseShow write FIsBrowseShow; property ShowWidth:integer read FShowWidth write FShowWidth; property DataType:TDataType read FDataType write FDataType; end; TFieldItems=class(TKeyStringDictionary) private function GetFields(Index: Integer): TFieldItem; public constructor Create(AOwner:TComponent);override; procedure Clear;override; procedure Assign(Source: TKeyStringDictionary); property Fields[Index:Integer]:TFieldItem read GetFields;default; end; TFieldsImpl=class(TObject) public class procedure AddField(AFieldItems:TFieldItems ; AFieldName: string; ADisplayLabel: string; AIsKey:Boolean ; AIsShow: Boolean; AIsBrowseShow : Boolean; AShowWidth:integer ) ; end; implementation { TFieldsImpl } class procedure TFieldsImpl.AddField(AFieldItems: TFieldItems; AFieldName, ADisplayLabel: string;AIsKey, AIsShow, AIsBrowseShow: Boolean; AShowWidth: integer); var AFieldItem:TFieldItem ; begin AFieldItem:=TFieldItem.Create ; AFieldItem.FieldName:=AFieldName ; AFieldItem.DisplayLabel:=ADisplayLabel; AFieldItem.IsKey := AIsKey ; AFieldItem.IsShow:=AIsShow; AFieldItem.IsBrowseShow:=AIsBrowseShow ; AFieldItem.ShowWidth :=AShowWidth ; AFieldItem.DataType:=dtString ; try AFieldItems.Add(AFieldItem.FieldName,AFieldItem.DisplayLabel,AFieldItem) ; except on e:exception do begin end ; end; end; { TFieldItem } procedure TFieldItem.Assign(Source: TPersistent); begin if(Source is TFieldItem)then begin FIsShow:=TFieldItem(Source).IsShow; FFieldName:= TFieldItem(Source).FieldName; FDisplayLabel:= TFieldItem(Source).DisplayLabel; FIsKey:= TFieldItem(Source).IsKey; FIsBrowseShow:= TFieldItem(Source).IsBrowseShow; FShowWidth:= TFieldItem(Source).ShowWidth; end; end; function TFieldItem.GetFieldSql: string; begin Result:=EmptyStr; end; { TFieldItems } procedure TFieldItems.Clear; var Index:Integer; Obj:TObject; begin for Index:=0 to inherited Count -1 do begin Obj:=inherited Objects[Index]; if Obj<>nil then FreeAndNIl(Obj); end; inherited; end; procedure TFieldItems.Assign(Source: TKeyStringDictionary); var Item:TFieldItem; i:integer ; begin if not (Source is TFieldItems)then exit ; Clear ; for i:=0 to TFieldItems(Source).Count -1 do begin Item:=TFieldItem.Create; Item.Assign(TFieldItems(Source).Fields[i]) ; Add(Item.FieldName,Item.DisplayLabel,Item); end ; end; constructor TFieldItems.Create(AOwner: TComponent); begin inherited Create(AOwner); end; function TFieldItems.GetFields(Index: Integer): TFieldItem; begin Result:=(inherited Objects[Index])as TFieldItem; end; end.
// ---------------------------------------------------------------------------- // Unit : PxClassesTest.pas - a part of PxLib test suite // Author : Matthias Hryniszak // Date : 2006-02-13 // Version : 1.0 // Description : // Changes log : 2006-02-13 - initial version // ---------------------------------------------------------------------------- unit PxClassesTest; {$I ..\PxDefines.inc} interface uses Classes, SysUtils, TestFramework, PxClasses; type TPxCircularBufferTest = class(TTestCase) private FCircularBuffer: TPxCircularBuffer; public procedure Setup; override; procedure TearDown; override; published procedure TestClear; procedure TestReadWrite; end; implementation { TPxCircularBufferTest } { Private declarations } { Public declarations } procedure TPxCircularBufferTest.Setup; begin FCircularBuffer := TPxCircularBuffer.Create(1024); end; procedure TPxCircularBufferTest.TearDown; begin FreeAndNil(FCircularBuffer); end; { Published declarations } procedure TPxCircularBufferTest.TestClear; var S: String; begin // test write-clear S := 'TEST DATA'; FCircularBuffer.Write(S[1], Length(S)); FCircularBuffer.Clear; Check(FCircularBuffer.Size = 0, 'Error: buffer is not empty'); end; procedure TPxCircularBufferTest.TestReadWrite; const TEST_DATA = 'TEST DATA TEST DATA TEST DATA TEST DATA TEST DATA TEST DATA TEST DATA'; var S: String; begin // test write S := TEST_DATA; FCircularBuffer.Write(S[1], Length(S)); Check(FCircularBuffer.Size = Length(TEST_DATA), 'Error: expected data length doesn''t match'); // test read SetLength(S, 1024); SetLength(S, FCircularBuffer.Read(S[1], Length(S))); Check(S = TEST_DATA, 'Error: read data doesn''t match'); Abort; end; initialization RegisterTests([TPxCircularBufferTest.Suite]); end.
unit Settings; interface uses SysUtils, IniFiles; var LMinDepth, LMaxDepth: integer; LBook: string; implementation const CSection = 'settings'; var LFileName: TFileName; procedure ReadIniFile; const CDefaultMinDepth = 3; CDefaultMaxDepth = 7; CDefaultBook = 'gm2001.bin'; var LFile: TIniFile; begin LFile := TIniFile.Create(LFileName); try LMinDepth := LFile.ReadInteger(CSection, 'mindepth', CDefaultMinDepth); LMaxDepth := LFile.ReadInteger(CSection, 'maxdepth', CDefaultMaxDepth); LBook := LFile.ReadString(CSection, 'book', CDefaultBook); finally LFile.Free; end; end; procedure WriteIniFile; var LFile: TIniFile; begin LFile := TIniFile.Create(LFileName); try LFile.WriteInteger(CSection, 'mindepth', LMinDepth); LFile.WriteInteger(CSection, 'maxdepth', LMaxDepth); LFile.WriteString(CSection, 'book', LBook); finally LFile.Free; end; end; initialization LFileName := ChangeFileExt(ParamStr(0), '.ini'); ReadIniFile; finalization if not FileExists(LFileName) then WriteIniFile; end.
{ Copyright (C) 2013-2018 Tim Sinaeve tim.sinaeve@gmail.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. } unit DataGrabber.DataView.KGrid; { Issues: - column moving does not move its content, so it is disabled and not supported. } interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Menus, Vcl.Dialogs, Data.DB, KControls, KGrids, KDBGrids, DataGrabber.Interfaces, DataGrabber.DataView.Base; type TfrmKGrid = class(TBaseDataView, IDataView) grdMain : TKDBGrid; procedure grdMainDrawCell( Sender : TObject; ACol : Integer; ARow : Integer; R : TRect; State : TKGridDrawState ); procedure grdMainCustomSortRows( Sender : TObject; ByIndex : Integer; SortMode : TKGridSortMode; var Sorted : Boolean ); protected procedure NormalizeRect(var SR: TKGridRect); function GetGridType: string; override; procedure SetPopupMenu(const Value: TPopupMenu); override; public procedure AfterConstruction; override; function SelectionToCommaText( AQuoteItems: Boolean = True ): string; override; function SelectionToTextTable( AIncludeHeader: Boolean = False ): string; override; function SelectionToWikiTable( AIncludeHeader: Boolean = False ): string; override; function SelectionToFields( AQuoteItems: Boolean = True ): string; override; function SelectionToDelimitedTable( ADelimiter : string = #9; AIncludeHeader : Boolean = True ): string; override; procedure ApplyGridSettings; override; procedure AutoSizeColumns; override; procedure Copy; override; procedure HideSelectedColumns; override; procedure MergeAllColumnCells(AActive: Boolean); procedure UpdateView; override; procedure BeginUpdate; override; procedure EndUpdate; override; procedure Inspect; override; end; implementation {$R *.dfm} uses System.StrUtils, System.Math, System.UITypes, Vcl.Clipbrd, DDuce.ObjectInspector.zObjectInspector, KFunctions, DataGrabber.Utils; {$REGION 'construction and destruction'} procedure TfrmKGrid.AfterConstruction; begin inherited AfterConstruction; grdMain.MinRowHeight := 17; grdMain.DefaultRowHeight := 17; grdMain.Colors.FocusedRangeBkGnd := clGray; UpdateView; end; {$ENDREGION} {$REGION 'property access methods'} function TfrmKGrid.GetGridType: string; begin Result := 'KGrid'; end; procedure TfrmKGrid.SetPopupMenu(const Value: TPopupMenu); begin grdMain.PopupMenu := Value; end; {$ENDREGION} {$REGION 'event handlers'} {$REGION 'grdMain'} procedure TfrmKGrid.grdMainCustomSortRows(Sender: TObject; ByIndex: Integer; SortMode: TKGridSortMode; var Sorted: Boolean); var Field : TField; begin Field := DataSet.FieldByName(TKDBGridCol(grdMain.Columns[ByIndex]).FieldName); if Assigned(Field) and (Field.FieldKind = fkData) then begin case SortMode of smNone, smDown: Data.Sort(DataSet, Field.FieldName, False); smUp: begin Data.Sort(DataSet, Field.FieldName, True); end; end; Sorted := True; DataSet.First; end end; procedure TfrmKGrid.grdMainDrawCell(Sender: TObject; ACol, ARow: Integer; R: TRect; State: TKGridDrawState); var C : TCanvas; F : TField; D : Double; begin C := grdMain.CellPainter.Canvas; if ARow = 0 then begin C.Font.Style := C.Font.Style + [fsBold]; end; grdMain.Cell[ACol, ARow].ApplyDrawProperties; if Settings.GridCellColoring and (State = []) then begin F := DataSet.FindField(TKDBGridCol(grdMain.Cols[ACol]).FieldName); if Assigned(F) then begin if F is TNumericField then begin D := F.AsFloat; if IsZero(D) then C.Font.Color := clBlue else if D < 0 then C.Font.Color := clRed; end; if grdMain.CellPainter.Text = '' then begin C.Brush.Color := $00EFEFEF; end else begin C.Brush.Color := Settings.FieldTypeColors[F.DataType]; end; end; end; C.FillRect(R); grdMain.CellPainter.DefaultDraw; end; {$ENDREGION} {$ENDREGION} {$REGION 'private methods'} procedure TfrmKGrid.NormalizeRect(var SR: TKGridRect); var T: Integer; begin if SR.Row1 > SR.Row2 then begin T := SR.Row1; SR.Row1 := SR.Row2; SR.Row2 := T; end; if SR.Col1 > SR.Col2 then begin T := SR.Col1; SR.Col1 := SR.Col2; SR.Col2 := T; end; end; {$ENDREGION} {$REGION 'public methods'} procedure TfrmKGrid.ApplyGridSettings; begin if Settings.ShowHorizontalGridLines then grdMain.Options := grdMain.Options + [goHorzLine] else grdMain.Options := grdMain.Options - [goHorzLine]; if Settings.ShowVerticalGridLines then grdMain.Options := grdMain.Options + [goVertLine] else grdMain.Options := grdMain.Options - [goVertLine]; grdMain.Font.Assign(Settings.GridFont); end; procedure TfrmKGrid.AutoSizeColumns; var C : TKDBGridCol; I : Integer; CF: TKCurrencyFormat; begin BeginUpdate; try CF.CurrencyFormat := FormatSettings.CurrencyFormat; CF.CurrencyDecimals := FormatSettings.CurrencyDecimals; CF.CurrencyString := ''; CF.DecimalSep := FormatSettings.DecimalSeparator; CF.ThousandSep := FormatSettings.ThousandSeparator; CF.UseThousandSep := True; grdMain.AutoSizeGrid(mpColWidth); for I := 0 to grdMain.ColCount - 1 do begin grdMain.ColWidths[I] := grdMain.ColWidths[I] + 12; C := TKDBGridCol(grdMain.Cols[I]); C.CurrencyFormat := CF; C.Font.Assign(grdMain.Font); C.TitleFont.Assign(grdMain.Font); end; finally EndUpdate; end; end; procedure TfrmKGrid.Copy; begin Clipboard.AsText := Trim(SelectionToDelimitedTable(#9, False)); end; procedure TfrmKGrid.HideSelectedColumns; var I : Integer; SR : TKGridRect; begin SR := grdMain.Selection; NormalizeRect(SR); BeginUpdate; try for I := SR.Col1 to SR.Col2 do begin Data.HideField(DataSet, TKDBGridCol(grdMain.Cols[I]).FieldName); end; finally EndUpdate; end; end; procedure TfrmKGrid.Inspect; begin InspectComponent(grdMain); end; procedure TfrmKGrid.MergeAllColumnCells(AActive: Boolean); begin // TODO end; function TfrmKGrid.SelectionToCommaText(AQuoteItems: Boolean): string; var X, Y : Integer; S, T : string; SR : TKGridRect; CCount : Integer; begin S := ''; SR := grdMain.Selection; NormalizeRect(SR); CCount := SR.Col2 - SR.Col1; for Y := SR.Row1 to SR.Row2 do begin for X := SR.Col1 to SR.Col2 do begin T := grdMain.Cells[X, Y]; if AQuoteItems then T := QuotedStr(T); S := S + T; if X < SR.Col2 then S := S + ', '; end; if (CCount = 1) and (Y < SR.Row2) then S := S + ', ' else if Y < SR.Row2 then S := S + #13#10 end; Result := S; end; function TfrmKGrid.SelectionToDelimitedTable(ADelimiter: string; AIncludeHeader: Boolean): string; var X, Y : Integer; S, T : string; SL : TStringList; SR : TKGridRect; begin SL := TStringList.Create; try S := ''; SR := grdMain.Selection; NormalizeRect(SR); if AIncludeHeader then begin for X := SR.Col1 to SR.Col2 do begin S := S + grdMain.Cells[X, 0]; if X < SR.Col2 then S := S + ADelimiter; end; SL.Add(S); end; for Y := SR.Row1 to SR.Row2 do begin S := ''; for X := SR.Col1 to SR.Col2 do begin T := grdMain.Cells[X, Y]; S := S + T; if X < SR.Col2 then S := S + ADelimiter; end; SL.Add(S); end; Result := SL.Text; finally FreeAndNil(SL); end; end; function TfrmKGrid.SelectionToFields(AQuoteItems: Boolean): string; begin // TODO end; { does not take hidden columns into account! } function TfrmKGrid.SelectionToTextTable(AIncludeHeader: Boolean): string; var X, Y : Integer; S : string; N : Integer; sTxt : string; sLine : string; sFmt : string; Widths : array of Integer; SL : TStringList; SR : TKGridRect; begin BeginUpdate; try sLine := ''; sTxt := ''; SR := grdMain.Selection; NormalizeRect(SR); SetLength(Widths, SR.Col2 - SR.Col1); try SL := TStringList.Create; try for X := SR.Col1 to SR.Col2 do begin SL.Clear; if AIncludeHeader then begin SL.Add(TKDBGridCol(grdMain.Cols[X]).FieldName); end; for Y := SR.Row1 to SR.Row2 do begin S := grdMain.Cells[X, Y]; SL.Add(S); end; Widths[X] := GetMaxTextWidth(SL); end; finally FreeAndNil(SL); end; if AIncludeHeader then begin for X := SR.Col1 to SR.Col2 do begin N := Widths[X]; sFmt := '%-' + IntToStr(N) + 's'; sLine := sLine + '+' + Format(sFmt, [DupeString('-', N)]); sTxt := sTxt + '|' + Format(sFmt, [TKDBGridCol(grdMain.Cols[X]).FieldName]); end; sTxt := sTxt + '|'; sLine := sLine + '+'; Result := sLine + #13#10 + sTxt + #13#10 + sLine; end; for Y := SR.Row1 to SR.Row2 do begin sTxt := ''; for X := SR.Col1 to SR.Col2 do begin S := grdMain.Cells[X, Y]; N := Widths[X]; sFmt := '%-' + IntToStr(N) + 's'; sTxt := sTxt + '|' + Format(sFmt, [S]); end; sTxt := sTxt + '|'; Result := Result + #13#10 + sTxt; sTxt := ''; end; Result := Result + #13#10 + sLine; finally Finalize(Widths); end; finally EndUpdate; end; end; function TfrmKGrid.SelectionToWikiTable(AIncludeHeader: Boolean): string; begin // TODO end; procedure TfrmKGrid.UpdateView; begin BeginUpdate; try if Assigned(DataSet) and DataSet.Active then begin ApplyGridSettings; AutoSizeColumns; end; finally EndUpdate; end; end; procedure TfrmKGrid.EndUpdate; begin grdMain.UnlockSortMode; grdMain.UnlockUpdate; end; procedure TfrmKGrid.BeginUpdate; begin grdMain.LockSortMode; grdMain.LockUpdate; end; {$ENDREGION} end.
unit tpDbg; (* Permission is hereby granted, on 1-Nov-2003, free of charge, to any person obtaining a copy of this file (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. Author of original version of this file: Michael Ax *) (* Set compiler directive TPDEBUGLOG to activate use of the DebugLog within TtpAction.DoExecute in tpaction.pas, and elsewhere. *) interface uses SysUtils, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, Toolbar, ExtCtrls, Windows, utForm; type TDebugDlg = class(TtpFitForm) FontDialog: TFontDialog; Panel1: TPanel; Memo: TMemo; pnlFooter: TPanel; pnlButtons: TPanel; btOK: TButton; btCancel: TButton; Panel2: TPanel; ToolButton2: TtpToolButton; tpToolButton1: TtpToolButton; procedure ToolButton1Click(Sender: TObject); procedure ToolButton2Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure tpToolButton1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; TDebugExtendedComponentOptions = (decEnabled, decDesign, decYield, decLogFile , decCreate, decDestroy, decLoaded, decUpdate , decRefresh, decExecute, decInsert, decRemove ); TDebugExtendedComponentStates = (decActive,decFormError,decDestroying ,decPrintSet,decPrinting,decPrintError ,decFiling,decFileError ); TDebugExtendedComponentFlags = set of TDebugExtendedComponentOptions; TDebugExtendedComponentState = set of TDebugExtendedComponentStates; {using the flags and log procedure other parts of the app can use debugging services.} procedure DebugOn; export; procedure DebugOff; export; procedure DebugLog(Instance:TObject;const Text:String); export; procedure AdjustDebugFlags(Value:TDebugExtendedComponentFlags); export; var DebugDlg: TDebugDlg; DebugFlags:TDebugExtendedComponentFlags; DebugState:TDebugExtendedComponentState; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ implementation uses Restorer, UpdateOk, IniLink, uclogfil, ucwinapi, ucString; var FormRestorer:TFormRestorer; const { DebugLogName= 'c:\debuglog.ini';} MaxDebugLines= 300; MinDebugLines= MaxDebugLines div 2; {$R *.DFM} var Count:Longint; indent:Byte; procedure DebugLog(Instance:TObject;const Text:String); const BufSize=144; var offset:byte; txt:string; b:boolean; procedure tOut(const aText:String); begin with DebugDlg.Memo do with Lines do begin if Count>MaxDebugLines then begin Visible:=False; while Count>MinDebugLines do Delete(0); Visible:=True; end; try add(aText); except {ignore?} end; end; if decLogFile in DebugFlags then //uclogfil ucwinapi AppendToLog(WinTempPath+'DebugLog.txt',Text); if decYield in DebugFlags then Application.ProcessMessages; end; begin if not (decEnabled in DebugFlags) or (decDestroying in DebugState) then exit; if Text='CLOSE' then begin if DebugDlg<>nil then begin DebugDlg.Close; DebugDlg:=nil; end; exit; end; if not ((decFormError in DebugState) or (decActive in DebugState)) then if not (decFormError in DebugState) then begin if DebugDlg=nil then begin b:=(decCreate in DebugFlags); DebugFlags:=DebugFlags-[decCreate]; DebugDlg:= TDebugDlg.Create(nil); if b then DebugFlags:=DebugFlags+[decCreate]; end else {take our chances on the form really really being there already!} ; try with DebugDlg do begin with Memo.Lines do begin Clear; Add('Opened '+datetimetostr(now)); end; OnClose:=FormClose; Show; end; except DebugState:=DebugState+[decFormError]; raise; end; DebugState:=DebugState+[decActive] end; if (Instance<>nil) and (Instance is TComponent) then if csDesigning in TComponent(Instance).ComponentState then if not (decDesign in DebugFlags) then exit; { GetModuleFileName(hInstance,p,80); Result:=(Pos('.DCL',UpperCase(StrPas(p)))>0) or ((Pos('.DPL',UpperCase(StrPas(p)))>0) and (uppercase(copy(paramstr(0),1,5))='DELPHI') ); } { if (pos('.DCL',paramstr(0))>0) then {do nothing inside library!} { if (pos('Create',Text)>0) then exit;} if Text='CLOSE' then begin DebugDlg.Close; exit; end; case Text[1] of '[', '+', '-': offset:=2; '^': begin DebugDlg.Caption:=copy(text,2,255); FormRestorer.Load; exit; end; else offset:=1; end; case Text[1] of '[': indent:=indent+2; '-': indent:=indent-2; end; if Instance<>nil then if Instance is tComponent then with tComponent(Instance) do begin if Name<>'' then Txt:=Name+'.'+ClassName else Txt:=ClassName; if csAncestor in ComponentState then Txt:=Txt+'(csAncestor)'; //classes if csFixups in ComponentState then Txt:=Txt+'(csFixups)'; //classes if csUpdating in ComponentState then Txt:=Txt+'(csUpdating)'; //classes if csReading in ComponentState then Txt:=Txt+'(csReading)'; //classes if csWriting in ComponentState then Txt:=Txt+'(csWriting)'; //classes if Owner<>nil then with Owner do begin if Name<>'' then Txt:=Name+'.'+ClassName else Txt:=ClassName; if csAncestor in ComponentState then Txt:=Txt+'(csAncestor)'; //classes if csFixups in ComponentState then Txt:=Txt+'(csFixups)'; //classes if csUpdating in ComponentState then Txt:=Txt+'(csUpdating)'; //classes if csReading in ComponentState then Txt:=Txt+'(csReading)'; //classes if csWriting in ComponentState then Txt:=Txt+'(csWriting)'; //classes end; end else Txt:=Instance.Classname else Txt:=''; if Txt<>'' then Txt:=#9' ['+Txt; Txt:=copy(Text,offset,255)+Txt; Count:=Count+1; tOut(inttostr(Count)+'. '+Spaces(Indent)+txt); //SendToLog(inttostr(Count)+'. '+Spaces(Indent)+txt); case Text[1] of '[': indent:=indent-2; '+': indent:=indent+2; end; end; {} procedure DebugOn; begin AdjustDebugFlags([decEnabled]); end; procedure DebugOff; begin AdjustDebugFlags([]); end; procedure AdjustDebugFlags(Value:TDebugExtendedComponentFlags); begin if not (decEnabled in Value) and (decEnabled in DebugFlags) then begin{turn all off} Value:=Value-[decCreate,decDesign,decDestroy,decLoaded,decUpdate,decInsert,decRemove]; end; if (decEnabled in Value) and not (decEnabled in DebugFlags) then begin{turn all on} Value:=Value+[decCreate,decDesign,decDestroy,decLoaded,decUpdate,decInsert,decRemove]; end; DebugFlags:=Value; end; {-----------------------------------------------------------------------------------------} { } {-----------------------------------------------------------------------------------------} procedure TDebugDlg.FormCreate(Sender: TObject); begin Tag:= (Top shl 16) + Left; Top:= -1000; end; procedure TDebugDlg.FormActivate(Sender: TObject); begin if FormRestorer=nil then begin OnClose:=nil; FormRestorer:= TFormRestorer.Create(Self); with FormRestorer do begin Flags:= [resDefaultIni, resUseCaption]; Load; end; OnClose:=FormClose; if Top=-1000 then begin Top:=tag shr 16; Left:=tag and $FFFF; end; end; end; procedure TDebugDlg.ToolButton2Click(Sender: TObject); begin with TtpToolButton(Sender) do if down then begin Caption:='On'; AdjustDebugFlags([decEnabled]); end else begin Caption:='Off'; AdjustDebugFlags([]); end; end; procedure TDebugDlg.FormClose(Sender: TObject; var Action: TCloseAction); var TempFlags:TDebugExtendedComponentFlags; begin Action:=caFree; DebugState:=DebugState-[decActive]; DebugDlg:=nil; if FormRestorer<>nil then begin TempFlags:=DebugFlags; DebugFlags:=[]; FormRestorer.Save; FormRestorer.IniFileLink.Free; FormRestorer.Free; FormRestorer:=nil; DebugFlags:=TempFlags; end; end; procedure TDebugDlg.ToolButton1Click(Sender: TObject); begin Close; end; {-----------------------------------------------------------------------------------------} { INITIALIZATION AND EXIT PROCEDURES } {-----------------------------------------------------------------------------------------} procedure InitializeThisUnit; var i:integer; a:string; begin DebugDlg:=nil; FormRestorer:=nil; DebugFlags:=[ decEnabled, decDesign, decYield {, decLogFile} , decCreate, decDestroy, decLoaded, decUpdate , decRefresh, decExecute, decInsert, decRemove ]; DebugFlags:= []; DebugState:= []; // DebugFlags:= []; // DebugState:= []; { if csDesigning in ComponentState then exit;} {process the commandline to set the unit's globals to the desired DEBUG state.} for i:=1 to ParamCount do begin a:=uppercase(ParamStr(i)); if copy(a,1,4)='/Dbg' then begin DebugFlags:=DebugFlags+[decEnabled]; if Length(a)=4 then DebugFlags:=DebugFlags+[decCreate,decDesign,decDestroy,decLoaded,decUpdate,decInsert,decRemove] else begin delete(a,1,4); if pos('C',a)>0 then DebugFlags:=DebugFlags+[decCreate]; if pos('D',a)>0 then DebugFlags:=DebugFlags+[decDesign]; if pos('L',a)>0 then DebugFlags:=DebugFlags+[decLoaded]; if pos('U',a)>0 then DebugFlags:=DebugFlags+[decUpdate]; if pos('I',a)>0 then DebugFlags:=DebugFlags+[decInsert]; if pos('R',a)>0 then DebugFlags:=DebugFlags+[decRemove]; if pos('E',a)>0 then DebugFlags:=DebugFlags+[decExecute]; if pos('F',a)>0 then DebugFlags:=DebugFlags+[decRefresh]; end; exit; end; end; end; {-----------------------------------------------------------------------------------------} procedure FinalizeUnit; begin { if (decPrint in DebugFlags) or (decFile in DebugFlags) then {turn off} AdjustDebugFlags([]); {stores back into global} end; {-----------------------------------------------------------------------------------------} {-----------------------------------------------------------------------------------------} var Initialized: boolean; { SaveExit: Pointer =nil; { Saves the old ExitProc } procedure Finalize; far; begin { ExitProc := SaveExit;} FinalizeUnit; end; procedure Initialize; begin if not Initialized then begin AddExitProc(Finalize); Initialized:=True; DebugFlags:= []; DebugState:= []; Count:=0; Indent:=0; InitializeThisUnit; end; end; procedure TDebugDlg.tpToolButton1Click(Sender: TObject); begin with FontDialog do begin font.assign(memo.font); if execute then memo.font.assign(font); end; end; initialization Initialized := False; end.
unit PACCInstance; {$i PACC.inc} interface uses SysUtils,Classes,Math,PUCU,PACCTypes,PACCGlobals,PACCRawByteStringHashMap,PACCTarget, PACCPreprocessor,PACCLexer,PACCParser,PACCAnalyzer,PACCHighLevelOptimizer, PACCLinker,PACCAbstractSyntaxTree,PACCIntermediateRepresentationCode; type EPACCError=class(Exception) public SourceLocation:TPACCSourceLocation; end; TPACCInstance=class public Target:TPACCTarget; Options:TPACCOptions; SourceLocation:TPACCSourceLocation; Preprocessor:TPACCPreprocessor; Lexer:TPACCLexer; Parser:TPACCParser; Analyzer:TPACCAnalyzer; HighLevelOptimizer:TPACCHighLevelOptimizer; Linker:TPACCLinker; IntermediateRepresentationCode:TPACCIntermediateRepresentationCode; TokenSymbols:TPACCTokenSymbols; CountTokenSymbols:TPACCInt; TokenSymbolStringHashMap:TPACCRawByteStringHashMap; FirstType:PPACCType; LastType:PPACCType; TypeVOID:PPACCType; TypeBOOL:PPACCType; TypeCHAR:PPACCType; TypeSHORT:PPACCType; TypeINT:PPACCType; TypeLONG:PPACCType; TypeLLONG:PPACCType; TypeUCHAR:PPACCType; TypeUSHORT:PPACCType; TypeUINT:PPACCType; TypeULONG:PPACCType; TypeULLONG:PPACCType; TypeFLOAT:PPACCType; TypeDOUBLE:PPACCType; TypeLDOUBLE:PPACCType; TypeENUM:PPACCType; Nodes:TList; AllocatedObjects:TList; Errors:TStringList; Warnings:TStringList; HasErrors:boolean; HasWarnings:boolean; constructor Create(const ATarget:TPACCTargetClass;const AOptions:TPACCOptions); destructor Destroy; override; procedure AddError(const Msg:TPUCUUTF8String;const AtSourceLocation:PPACCSourceLocation=nil;const DoAbort:boolean=false); procedure AddWarning(const Msg:TPUCUUTF8String;const AtSourceLocation:PPACCSourceLocation=nil); function NewType:PPACCType; function CopyType(const FromType:PPACCType):PPACCType; function CopyIncompleteType(const FromType:PPACCType):PPACCType; function CopyFromTypeToType(const FromType,ToType:PPACCType):PPACCType; function NewBuiltinType(const Kind:TPACCTypeKind;const Size,Alignment:TPACCInt;const Unsigned:boolean):PPACCType; function NewNumbericType(const Kind:TPACCTypeKind;const Unsigned:boolean):PPACCType; function NewPointerType(const PointerToType:PPACCType):PPACCType; function NewArrayType(const ItemType:PPACCType;const ArrayLength:int64):PPACCType; function NewStructType(const IsStruct:boolean):PPACCType; function NewFunctionType(const ReturnType:PPACCType;const ParameterTypes:TPPACCTypes;const HasVarArgs,OldStyle:boolean):PPACCType; function NewStubType:PPACCType; function IsIntType(const Type_:PPACCType):boolean; function IsFloatType(const Type_:PPACCType):boolean; function IsArithmeticType(const Type_:PPACCType):boolean; function IsStringType(const Type_:PPACCType):boolean; function SameArithmeticType(const t,u:PPACCType):boolean; function UsualArithmeticConversion(t,u:PPACCType):PPACCType; function IsSameStruct(const a,b:PPACCType):boolean; function AreTypesCompatible(const a,b:PPACCType):boolean; function AreTypesEqual(const a,b:PPACCType):boolean; function TypeConversion(const Node:TPACCAbstractSyntaxTreeNode):TPACCAbstractSyntaxTreeNode; function GetPromotionType(const Type_:PPACCType):PPACCType; function EvaluateIntegerExpression(const Node:TPACCAbstractSyntaxTreeNode;const Address:PPACCAbstractSyntaxTreeNode):TPACCInt64; function EvaluateFloatExpression(const Node:TPACCAbstractSyntaxTreeNode;const Kind:TPACCTypeKind):TPACCLongDouble; end; implementation constructor TPACCInstance.Create(const ATarget:TPACCTargetClass;const AOptions:TPACCOptions); begin inherited Create; Options:=AOptions; Target:=ATarget.Create(self); SourceLocation.Source:=-1; SourceLocation.Line:=0; TokenSymbols:=nil; CountTokenSymbols:=0; TokenSymbolStringHashMap:=TPACCRawByteStringHashMap.Create; FirstType:=nil; LastType:=nil; Nodes:=TList.Create; AllocatedObjects:=TList.Create; Errors:=TStringList.Create; Warnings:=TStringList.Create; HasErrors:=false; HasWarnings:=false; TypeVOID:=NewBuiltinType(tkVOID,0,0,false); TypeBOOL:=NewBuiltinType(tkBOOL,Target.SizeOfBool,Target.AlignmentOfBool,true); TypeCHAR:=NewBuiltinType(tkCHAR,Target.SizeOfChar,Target.AlignmentOfChar,false); TypeSHORT:=NewBuiltinType(tkSHORT,Target.SizeOfShort,Target.AlignmentOfShort,false); TypeINT:=NewBuiltinType(tkINT,Target.SizeOfInt,Target.AlignmentOfInt,false); TypeLONG:=NewBuiltinType(tkLONG,Target.SizeOfLong,Target.AlignmentOfLong,false); TypeLLONG:=NewBuiltinType(tkLLONG,Target.SizeOfLongLong,Target.AlignmentOfLongLong,false); TypeUCHAR:=NewBuiltinType(tkCHAR,Target.SizeOfChar,Target.AlignmentOfChar,true); TypeUSHORT:=NewBuiltinType(tkSHORT,Target.SizeOfShort,Target.AlignmentOfShort,true); TypeUINT:=NewBuiltinType(tkINT,Target.SizeOfInt,Target.AlignmentOfInt,true); TypeULONG:=NewBuiltinType(tkLONG,Target.SizeOfLong,Target.AlignmentOfLong,true); TypeULLONG:=NewBuiltinType(tkLLONG,Target.SizeOfLongLong,Target.AlignmentOfLongLong,true); TypeFLOAT:=NewBuiltinType(tkFLOAT,Target.SizeOfFloat,Target.AlignmentOfFloat,false); TypeDOUBLE:=NewBuiltinType(tkDOUBLE,Target.SizeOfDouble,Target.AlignmentOfDouble,false); TypeLDOUBLE:=NewBuiltinType(tkLDOUBLE,Target.SizeOfLongDouble,Target.AlignmentOfLongDouble,false); TypeENUM:=NewBuiltinType(tkENUM,Target.SizeOfEnum,Target.AlignmentOfEnum,false); Preprocessor:=TPACCPreprocessor.Create(self); Lexer:=TPACCLexer.Create(self); Parser:=TPACCParser.Create(self); Analyzer:=TPACCAnalyzer.Create(self); HighLevelOptimizer:=TPACCHighLevelOptimizer.Create(self); Linker:=TPACCLinkerClass(Target.LinkerClass).Create(self); IntermediateRepresentationCode:=TPACCIntermediateRepresentationCode.Create(self); end; destructor TPACCInstance.Destroy; var CurrentType,NextType:PPACCType; i:TPACCInt; begin SetLength(TokenSymbols,0); TokenSymbolStringHashMap.Free; IntermediateRepresentationCode.Free; Linker.Free; HighLevelOptimizer.Free; Analyzer.Free; Parser.Free; Lexer.Free; Preprocessor.Free; for i:=Nodes.Count-1 downto 0 do begin TObject(Nodes[i]).Free; end; Nodes.Free; for i:=AllocatedObjects.Count-1 downto 0 do begin TObject(AllocatedObjects[i]).Free; end; AllocatedObjects.Free; CurrentType:=FirstType; while assigned(CurrentType) do begin NextType:=CurrentType^.Next; Finalize(CurrentType^); FreeMem(CurrentType); CurrentType:=NextType; end; FirstType:=nil; LastType:=nil; Errors.Free; Warnings.Free; Target.Free; inherited Destroy; end; procedure TPACCInstance.AddError(const Msg:TPUCUUTF8String;const AtSourceLocation:PPACCSourceLocation=nil;const DoAbort:boolean=false); var CurrentSourceLocation:PPACCSourceLocation; e:EPACCError; begin if assigned(AtSourceLocation) then begin CurrentSourceLocation:=AtSourceLocation; end else begin CurrentSourceLocation:=@SourceLocation; end; if CurrentSourceLocation^.Source>=0 then begin Errors.Add(Preprocessor.SourceFiles[CurrentSourceLocation^.Source]+':'+IntToStr(CurrentSourceLocation^.Line+1)+':'+IntToStr(CurrentSourceLocation^.Column+1)+': error: '+Msg); end else begin Errors.Add('?:'+IntToStr(CurrentSourceLocation^.Line+1)+':'+IntToStr(CurrentSourceLocation^.Column+1)+': error: '+Msg); end; HasErrors:=true; if DoAbort then begin e:=EPACCError.Create(Msg); if assigned(AtSourceLocation) then begin e.SourceLocation:=AtSourceLocation^; end else begin e.SourceLocation:=SourceLocation; end; raise e; end; end; procedure TPACCInstance.AddWarning(const Msg:TPUCUUTF8String;const AtSourceLocation:PPACCSourceLocation=nil); var CurrentSourceLocation:PPACCSourceLocation; begin if Options.EnableWarnings then begin if Options.WarningsAreErrors then begin AddError(Msg,AtSourceLocation); end else begin if assigned(AtSourceLocation) then begin CurrentSourceLocation:=AtSourceLocation; end else begin CurrentSourceLocation:=@SourceLocation; end; if CurrentSourceLocation^.Source>=0 then begin Warnings.Add(Preprocessor.SourceFiles[CurrentSourceLocation^.Source]+':'+IntToStr(CurrentSourceLocation^.Line+1)+':'+IntToStr(CurrentSourceLocation^.Column+1)+': warning: '+Msg); end else begin Warnings.Add('?:'+IntToStr(CurrentSourceLocation^.Line+1)+':'+IntToStr(CurrentSourceLocation^.Column+1)+': warning: '+Msg); end; HasWarnings:=true; end; end; end; function TPACCInstance.NewType:PPACCType; begin GetMem(result,SizeOf(TPACCType)); FillChar(result^,SizeOf(TPACCType),#0); result^.Previous:=LastType; if assigned(LastType) then begin LastType^.Next:=result; end else begin FirstType:=result; end; LastType:=result; result^.Attribute:=PACCEmptyAttribute; end; function TPACCInstance.CopyType(const FromType:PPACCType):PPACCType; begin GetMem(result,SizeOf(TPACCType)); FillChar(result^,SizeOf(TPACCType),#0); result^:=FromType^; result^.Fields:=copy(FromType^.Fields); result^.Previous:=LastType; result^.Next:=nil; if assigned(LastType) then begin LastType^.Next:=result; end else begin FirstType:=result; end; LastType:=result; end; function TPACCInstance.CopyIncompleteType(const FromType:PPACCType):PPACCType; begin if not assigned(FromType) then begin result:=nil; end else if FromType^.ArrayLength<0 then begin result:=CopyType(FromType); end else begin result:=FromType; end; end; function TPACCInstance.CopyFromTypeToType(const FromType,ToType:PPACCType):PPACCType; begin result:=ToType; if assigned(FromType) then begin result^.Kind:=FromType^.Kind; result^.Size:=FromType^.Size; result^.Alignment:=FromType^.Alignment; result^.Flags:=FromType^.Flags; result^.ChildType:=FromType^.ChildType; result^.ArrayLength:=FromType^.ArrayLength; result^.Fields:=copy(FromType^.Fields); result^.Offset:=FromType^.Offset; result^.MinValue:=FromType^.MinValue; result^.MaxValue:=FromType^.MaxValue; result^.BitOffset:=FromType^.BitOffset; result^.BitSize:=FromType^.BitSize; result^.ReturnType:=FromType^.ReturnType; result^.Parameters:=FromType^.Parameters; result^.Attribute:=FromType^.Attribute; end; end; function TPACCInstance.NewBuiltinType(const Kind:TPACCTypeKind;const Size,Alignment:TPACCInt;const Unsigned:boolean):PPACCType; begin result:=NewType; result^.Kind:=Kind; if Unsigned then begin Include(result^.Flags,tfUnsigned); end else begin Exclude(result^.Flags,tfUnsigned); end; result^.Size:=Size; result^.Alignment:=Alignment; end; function TPACCInstance.NewNumbericType(const Kind:TPACCTypeKind;const Unsigned:boolean):PPACCType; begin result:=NewType; result^.Kind:=Kind; if Unsigned then begin Include(result^.Flags,tfUnsigned); end else begin Exclude(result^.Flags,tfUnsigned); end; case Kind of tkVOID:begin result^.Size:=0; result^.Alignment:=0; end; tkBOOL:begin result^.Size:=Target.SizeOfBool; result^.Alignment:=Target.AlignmentOfBool; end; tkCHAR:begin result^.Size:=Target.SizeOfChar; result^.Alignment:=Target.AlignmentOfChar; end; tkSHORT:begin result^.Size:=Target.SizeOfShort; result^.Alignment:=Target.AlignmentOfShort; end; tkINT:begin result^.Size:=Target.SizeOfInt; result^.Alignment:=Target.AlignmentOfInt; end; tkLONG:begin result^.Size:=Target.SizeOfLong; result^.Alignment:=Target.AlignmentOfLong; end; tkLLONG:begin result^.Size:=Target.SizeOfLongLong; result^.Alignment:=Target.AlignmentOfLongLong; end; tkFLOAT:begin result^.Size:=Target.SizeOfFloat; result^.Alignment:=Target.AlignmentOfFloat; end; tkDOUBLE:begin result^.Size:=Target.SizeOfDouble; result^.Alignment:=Target.AlignmentOfDouble; end; tkLDOUBLE:begin result^.Size:=Target.SizeOfLongDouble; result^.Alignment:=Target.AlignmentOfLongDouble; end; else begin AddError('Internal error 2016-12-30-23-11-0000'); end; end; end; function TPACCInstance.NewPointerType(const PointerToType:PPACCType):PPACCType; begin result:=NewType; result^.Kind:=tkPOINTER; result^.Size:=Target.SizeOfPointer; result^.Alignment:=Target.SizeOfPointer; result^.ChildType:=PointerToType; end; function TPACCInstance.NewArrayType(const ItemType:PPACCType;const ArrayLength:int64):PPACCType; var Size:int64; begin if ArrayLength<0 then begin Size:=-1; end else begin Size:=ArrayLength*ItemType^.Size; end; result:=NewType; result^.Kind:=tkARRAY; result^.ChildType:=ItemType; result^.ArrayLength:=ArrayLength; result^.Size:=Size; result^.Alignment:=ItemType^.Alignment; end; function TPACCInstance.NewStructType(const IsStruct:boolean):PPACCType; begin result:=NewType; result^.Kind:=tkSTRUCT; if IsStruct then begin Include(result^.Flags,tfStruct); end else begin Exclude(result^.Flags,tfStruct); end; end; function TPACCInstance.NewFunctionType(const ReturnType:PPACCType;const ParameterTypes:TPPACCTypes;const HasVarArgs,OldStyle:boolean):PPACCType; begin result:=NewType; result^.Kind:=tkFUNCTION; if HasVarArgs then begin Include(result^.Flags,tfVarArgs); end else begin Exclude(result^.Flags,tfVarArgs); end; if OldStyle then begin Include(result^.Flags,tfOldStyle); end else begin Exclude(result^.Flags,tfOldStyle); end; result^.ReturnType:=ReturnType; end; function TPACCInstance.NewStubType:PPACCType; begin result:=NewType; result^.Kind:=tkSTUB; end; function TPACCInstance.IsIntType(const Type_:PPACCType):boolean; begin result:=Type_^.Kind in [tkBOOL,tkCHAR,tkSHORT,tkINT,tkLONG,tkLLONG]; end; function TPACCInstance.IsFloatType(const Type_:PPACCType):boolean; begin result:=Type_^.Kind in [tkFLOAT,tkDOUBLE,tkLDOUBLE]; end; function TPACCInstance.IsArithmeticType(const Type_:PPACCType):boolean; begin result:=Type_^.Kind in [tkBOOL,tkCHAR,tkSHORT,tkINT,tkLONG,tkLLONG,tkFLOAT,tkDOUBLE,tkLDOUBLE]; end; function TPACCInstance.IsStringType(const Type_:PPACCType):boolean; begin result:=(Type_^.Kind=tkARRAY) and assigned(Type_^.ChildType) and (Type_^.ChildType^.Kind=tkCHAR); end; function TPACCInstance.SameArithmeticType(const t,u:PPACCType):boolean; begin result:=(t^.Kind=u^.Kind) and ((tfUnsigned in t^.Flags)=(tfUnsigned in u^.Flags)); end; function TPACCInstance.UsualArithmeticConversion(t,u:PPACCType):PPACCType; var z:PPACCType; begin if not IsArithmeticType(t) then begin AddError('Internal error 2017-01-01-20-17-0000'); end; if not IsArithmeticType(u) then begin AddError('Internal error 2017-01-01-20-17-0001'); end; if t^.Kind<u^.Kind then begin z:=t; t:=u; u:=z; end; if IsFloatType(t) then begin result:=t; end else begin if not (IsIntType(t) and (t^.Size>=TypeINT^.Size)) then begin AddError('Internal error 2017-01-01-20-17-0002'); end; if not (IsIntType(u) and (u^.Size>=TypeINT^.Size)) then begin AddError('Internal error 2017-01-01-20-18-0000'); end; if t^.Size>u^.Size then begin result:=t; end else if t^.Size<u^.Size then begin AddError('Internal error 2017-01-01-20-19-0000'); end else if (tfUnsigned in t^.Flags)=(tfUnsigned in u^.Flags) then begin result:=t; end else begin result:=CopyType(t); Include(result^.Flags,tfUnsigned); end; end; end; function TPACCInstance.IsSameStruct(const a,b:PPACCType):boolean; var Index:TPACCInt; begin if a^.Kind=b^.Kind then begin case a^.Kind of tkARRAY:begin result:=(a^.ArrayLength=b^.ArrayLength) and IsSameStruct(a^.ChildType,b^.ChildType); end; tkPOINTER:begin result:=IsSameStruct(a^.ChildType,b^.ChildType); end; tkSTRUCT:begin if ((tfStruct in a^.Flags)=(tfStruct in b^.Flags)) and (length(a^.Fields)=length(b^.Fields)) then begin result:=true; for Index:=0 to length(a^.Fields)-1 do begin if not IsSameStruct(a^.Fields[Index].Type_,b^.Fields[Index].Type_) then begin result:=false; break; end; end; end else begin result:=false; end; end; else begin result:=true; end; end; end else begin result:=false; end; end; function TPACCInstance.AreTypesCompatible(const a,b:PPACCType):boolean; begin if a^.Kind=tkSTRUCT then begin result:=IsSameStruct(a,b); end else if a^.Kind=b^.Kind then begin if assigned(a^.ChildType) and assigned(b^.ChildType) then begin result:=AreTypesCompatible(a^.ChildType,b^.ChildType); end else if IsArithmeticType(a) and IsArithmeticType(b) then begin result:=SameArithmeticType(a,b); end else begin result:=true; end; end else begin result:=false; end; end; function TPACCInstance.AreTypesEqual(const a,b:PPACCType):boolean; begin if a^.Kind=tkSTRUCT then begin result:=IsSameStruct(a,b); end else if a^.Kind=b^.Kind then begin if assigned(a^.ChildType) and assigned(b^.ChildType) then begin result:=AreTypesEqual(a^.ChildType,b^.ChildType); end else if IsArithmeticType(a) and IsArithmeticType(b) then begin result:=SameArithmeticType(a,b); end else if (a^.Size=b^.Size) and ((tfUnsigned in a^.Flags)=(tfUnsigned in b^.Flags)) then begin result:=true; end else begin result:=false; end; end else begin result:=false; end; end; function TPACCInstance.TypeConversion(const Node:TPACCAbstractSyntaxTreeNode):TPACCAbstractSyntaxTreeNode; var Type_:PPACCType; begin if assigned(Node) then begin Type_:=Node.Type_; case Type_^.Kind of tkARRAY:begin // C11 6.3.2.1p3: An array of T is converted to a pointer to T. result:=TPACCAbstractSyntaxTreeNodeUnaryOperator.Create(self,astnkCONV,NewPointerType(Type_^.ChildType),Node.SourceLocation,Node); end; tkFUNCTION:begin // C11 6.3.2.1p4: A function designator is converted to a pointer to the function. result:=TPACCAbstractSyntaxTreeNodeUnaryOperator.Create(self,astnkADDR,NewPointerType(Type_),Node.SourceLocation,Node); end; tkSHORT,tkCHAR,tkBOOL:begin // C11 6.3.1.1p2: The integer promotions result:=TPACCAbstractSyntaxTreeNodeUnaryOperator.Create(self,astnkCONV,TypeINT,Node.SourceLocation,Node); end; tkINT:begin if Type_^.BitSize>0 then begin result:=TPACCAbstractSyntaxTreeNodeUnaryOperator.Create(self,astnkCONV,TypeINT,Node.SourceLocation,Node); end else begin result:=Node; end; end; else begin result:=Node; end; end; end else begin result:=nil; end; end; function TPACCInstance.GetPromotionType(const Type_:PPACCType):PPACCType; begin if assigned(Type_) then begin case Type_^.Kind of tkARRAY:begin // C11 6.3.2.1p3: An array of T is converted to a pointer to T. result:=NewPointerType(Type_^.ChildType); end; tkFUNCTION:begin // C11 6.3.2.1p4: A function designator is converted to a pointer to the function. result:=NewPointerType(Type_); end; tkSHORT,tkCHAR,tkBOOL:begin // C11 6.3.1.1p2: The integer promotions result:=TypeINT; end; tkINT:begin result:=TypeINT; end; tkLONG,tkLLONG:begin result:=TypeLONG; end; tkFLOAT:begin result:=TypeFLOAT; end; tkDOUBLE,tkLDOUBLE:begin result:=TypeDOUBLE; end; else begin result:=nil; end; end; end else begin result:=nil; end; end; function TPACCInstance.EvaluateIntegerExpression(const Node:TPACCAbstractSyntaxTreeNode;const Address:PPACCAbstractSyntaxTreeNode):TPACCInt64; function EvaluateStructReference(const Node:TPACCAbstractSyntaxTreeNode;const Offset:TPACCInt64):TPACCInt64; begin if Node.Kind=astnkSTRUCT_REF then begin result:=EvaluateStructReference(TPACCAbstractSyntaxTreeNodeStructReference(Node).Struct,Node.Type_^.Offset+Offset); end else begin result:=EvaluateIntegerExpression(Node,nil)+Offset; end; end; begin case Node.Kind of astnkINTEGER:begin if IsIntType(Node.Type_) then begin result:=TPACCAbstractSyntaxTreeNodeIntegerValue(Node).Value; end else begin result:=0; AddError('Integer expression expected',@Node.SourceLocation,false); end; end; astnkFLOAT:begin result:=0; AddError('Integer expression expected',@Node.SourceLocation,false); end; astnkSTRING:begin result:=0; AddError('Integer expression expected',@Node.SourceLocation,false); end; astnkOP_LOG_NOT:begin if EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeUnaryOperator(Node).Operand,Address)<>0 then begin result:=0; end else begin result:=1; end; end; astnkOP_NOT:begin result:=not EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeUnaryOperator(Node).Operand,Address); end; astnkOP_NEG:begin result:=-EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeUnaryOperator(Node).Operand,Address); end; astnkOP_CAST:begin result:=EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeUnaryOperator(Node).Operand,Address); end; astnkCONV:begin result:=EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeUnaryOperator(Node).Operand,Address); end; astnkADDR:begin if TPACCAbstractSyntaxTreeNodeUnaryOperator(Node).Operand.Kind=astnkSTRUCT_REF then begin result:=EvaluateStructReference(TPACCAbstractSyntaxTreeNodeUnaryOperator(Node).Operand,0); end else begin if assigned(Address) then begin Address^:=TypeConversion(Node); result:=0; end else begin result:=0; AddError('Integer expression expected',@Node.SourceLocation,false); end; end; end; astnkGVAR:begin if assigned(Address) then begin Address^:=TypeConversion(Node); result:=0; end else begin result:=0; AddError('Integer expression expected',@Node.SourceLocation,false); end; end; astnkDEREF:begin if TPACCAbstractSyntaxTreeNodeUnaryOperator(Node).Operand.Type_.Kind=tKPOINTER then begin result:=EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeUnaryOperator(Node).Operand,Address); end else begin result:=0; AddError('Integer expression expected',@Node.SourceLocation,false); end; end; astnkTERNARY:begin result:=EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeIFStatementOrTernaryOperator(Node).Condition,Address); if result<>0 then begin if assigned(TPACCAbstractSyntaxTreeNodeIFStatementOrTernaryOperator(Node).Then_) then begin result:=EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeIFStatementOrTernaryOperator(Node).Then_,Address); end; end else begin result:=EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeIFStatementOrTernaryOperator(Node).Else_,Address); end; end; astnkOP_ADD:begin result:=EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Left,Address)+EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Right,Address); end; astnkOP_SUB:begin result:=EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Left,Address)-EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Right,Address); end; astnkOP_MUL:begin result:=EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Left,Address)*EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Right,Address); end; astnkOP_DIV:begin result:=EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Left,Address) div EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Right,Address); end; astnkOP_AND:begin result:=EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Left,Address) and EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Right,Address); end; astnkOP_OR:begin result:=EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Left,Address) or EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Right,Address); end; astnkOP_XOR:begin result:=EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Left,Address) xor EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Right,Address); end; astnkOP_EQ:begin if EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Left,Address)=EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Right,Address) then begin result:=1; end else begin result:=0; end; end; astnkOP_LE:begin if EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Left,Address)<=EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Right,Address) then begin result:=1; end else begin result:=0; end; end; astnkOP_NE:begin if EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Left,Address)<>EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Right,Address) then begin result:=1; end else begin result:=0; end; end; astnkOP_GE:begin if EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Left,Address)>=EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Right,Address) then begin result:=1; end else begin result:=0; end; end; astnkOP_LT:begin if EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Left,Address)<EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Right,Address) then begin result:=1; end else begin result:=0; end; end; astnkOP_GT:begin if EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Left,Address)>EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Right,Address) then begin result:=1; end else begin result:=0; end; end; astnkOP_SHL:begin result:=EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Left,Address) shl EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Right,Address); end; astnkOP_SHR:begin result:=EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Left,Address) shr EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Right,Address); end; astnkOP_SAR:begin result:=SARcint64(EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Left,Address),EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Right,Address)); end; astnkOP_LOG_AND:begin if (EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Left,Address)<>0) and (EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Right,Address)<>0) then begin result:=1; end else begin result:=0; end; end; astnkOP_LOG_OR:begin if (EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Left,Address)<>0) or (EvaluateIntegerExpression(TPACCAbstractSyntaxTreeNodeBinaryOperator(Node).Right,Address)<>0) then begin result:=1; end else begin result:=0; end; end; else begin result:=0; AddError('Integer expression expected',@Node.SourceLocation,false); end; end; end; function TPACCInstance.EvaluateFloatExpression(const Node:TPACCAbstractSyntaxTreeNode;const Kind:TPACCTypeKind):TPACCLongDouble; begin case Node.Kind of astnkINTEGER:begin if IsIntType(Node.Type_) then begin result:=TPACCAbstractSyntaxTreeNodeIntegerValue(Node).Value; end else begin result:=0; AddError('Float expression expected',@Node.SourceLocation,false); end; end; astnkFLOAT:begin if IsFloatType(Node.Type_) then begin result:=TPACCAbstractSyntaxTreeNodeFloatValue(Node).Value; end else begin result:=0; AddError('Float expression expected',@Node.SourceLocation,false); end; end; astnkSTRING:begin result:=0; AddError('Float expression expected',@Node.SourceLocation,false); end; astnkOP_CAST:begin result:=EvaluateFloatExpression(TPACCAbstractSyntaxTreeNodeUnaryOperator(Node).Operand,Kind); end; astnkCONV:begin result:=EvaluateFloatExpression(TPACCAbstractSyntaxTreeNodeUnaryOperator(Node).Operand,Kind); end; else begin result:=0; AddError('Float expression expected',nil,false); end; end; end; end.
{$R+ <- this enables range checking, this can be also enabled by passing an option to the command line compiler: fpc -Cr. the next option, sadly, doesn't have a commandline switch: } {$B+ <- this enables complete boolean evaluation, see the test below using isEvaluated it won't be called if this $B+ is missing} (* Author: k-stz *) {Style guide: must have: - Identifiers _must_ be written in CamelCase (think Java), - CONSTANT identifiers _must_ be written in uppercase - tType identifiers must start with a 't' (tWeek, tWeekend) - begin between Begin and End we indent by 2 or 4 spaces, but consistently end - In if-then-else control structures, the begin/end share the same column: if <predicate> then begin <consequence> end else begin <alternative> end; - program indent (input, output); const UPPERCASE = 'SAME COLUMN AS const!'; // same for type and var declaration/definition blocks begin end. /* indent */ <- seems like we write the name of procedure/ function at the end - comments: in the program headline you must write down what the program does (not how it does it). Usually you _must_ comment the input and output data. TODO: what about procedures and functions? } { Pascal ist eine typisierte Programmiersprache, da jede Variable, vor der Benutzung, einem eindeutigen Datentyp zugeordnet werden muss. } {Program: <program heading> + <block> + . } program HiProgram; {<- this is the whole "program heading". What follows, all the way to the 'End.' at the very end is the <block> } { The point of this program is its implementation, a collection of concepts and idea of the programming language Pascal } var x : integer; procedure IsOdd (input : integer); begin write(input); if (odd(input)) then writeln(' is odd') {<- careful, no semicolon here!} else writeln(' is even'); end { IsOdd }; procedure Test1; {declaration part: <constant definition part> + <type definition part> + <variable declaration part> } { It seems between Begin and End variable definition is forbidden } const PI2 = sqr(pi); {constants should be written in _uppercase_! (style guide)} { type definition part, comes aptly before the variable one, as those will be used for variables! } (* these also have an inner order such that we can compare them and yield ORD(<tWeek var>) from them *) type tWeek = (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday); { dt. Ausschnittstyp, en. /subrange type/ } tWeekend = Saturday .. Sunday; { "variable declaration part" } var age, money : integer; {age and money both get the type integer here} day : tWeek; weekend : tWeekend; {/declaration part } {statement part: 'Begin'-label + <statement part> + 'End'-label} begin { writeln('pi2:'); } { Writeln(pi2); } { Writeln('How old are you'); } { readln(age); } { writeln('That''s funny, I''m also', age); } { writeln('years old! And I have twice as much money:'); } { money := age * 2; {<- assignment statement } } { writeln(money); } { writeln( day ); } writeln('own type definitions tests: '); writeln(tWeek(ord(succ (day)))); (* like with standard types, the type identifier is also a function! *) weekend := tWeekend(5); {!! careful, we can now only use tWeekend(5) and tWeekend(6) !!} writeln(weekend); weekend := Sunday; {we can use the enumerator elements explicitly though!} writeln(weekend); end { Test1 }; {/statement part } function isEvaluated () : boolean; begin writeln('isEvaluated invoked!'); isEvaluated := true; end; { isEvaluated} begin writeln('maxinteger:'); {<- 'strings'} writeln(succ(3) - pred(1)); writeln(exp(ln(10))); {==> 1.0} writeln('Char:'); writeln(succ('a')); {SUCC and PRED are also defined for CHARs} {ORD returns the ordinals for the char, CHAR returns char denoted by the ordinal} writeln(char(ord('t'))); {Boolean: } writeln('Boolean:'); writeln(true and false or not false ); {1 ∧ 0 ∨ ¬0} writeln('1=1 and true != false:',(1 = 1) and true <> false); writeln('1 <= 12:',1 <= 12,1 <> 1); x := 10; writeln(x); begin (* not a new name space or lexical scope *) x := 22; writeln(x); end; (* x is still 22 here *) Test1; IsOdd(10); writeln('Complete Boolean Evaluation test:'); if (true or isEvaluated()) then writeln('done'); end { HiProgram }.
{*************************************************************************} { } { XML Data Binding } { } { Generated on: 2015-03-18 21:24:13 } { Generated from: D:\xiewei\Code\国信电脑设备管理系统\DBField.xml } { Settings stored in: D:\xiewei\Code\国信电脑设备管理系统\DBField.xdb } { } {*************************************************************************} unit uDBFieldData; interface uses xmldom, XMLDoc, XMLIntf; type { Forward Decls } IXMLGuoSenDeviceSystemType = interface; IXMLDBDataType = interface; IXMLColDataType = interface; IXMLColItemType = interface; IXMLRowDataType = interface; IXMLRowItemType = interface; IXMLFieldType = interface; { IXMLGuoSenDeviceSystemType } IXMLGuoSenDeviceSystemType = interface(IXMLNode) ['{29A25CF6-9FDE-4344-980C-5D8D71FBE536}'] { Property Accessors } function Get_DBData: IXMLDBDataType; { Methods & Properties } property DBData: IXMLDBDataType read Get_DBData; end; { IXMLDBDataType } IXMLDBDataType = interface(IXMLNode) ['{E754DA20-3D28-48C7-84C2-CD80BED6823A}'] { Property Accessors } function Get_OperaterType: WideString; function Get_DBTable: WideString; function Get_SQL: WideString; function Get_ColData: IXMLColDataType; function Get_RowData: IXMLRowDataType; procedure Set_OperaterType(Value: WideString); procedure Set_DBTable(Value: WideString); procedure Set_SQL(Value: WideString); { Methods & Properties } property OperaterType: WideString read Get_OperaterType write Set_OperaterType; property DBTable: WideString read Get_DBTable write Set_DBTable; property SQL: WideString read Get_SQL write Set_SQL; property ColData: IXMLColDataType read Get_ColData; property RowData: IXMLRowDataType read Get_RowData; end; { IXMLColDataType } IXMLColDataType = interface(IXMLNodeCollection) ['{77098D5E-58B3-41D2-AB13-5FF84C0AB4AC}'] { Property Accessors } function Get_ColItem(Index: Integer): IXMLColItemType; { Methods & Properties } function Add: IXMLColItemType; function Insert(const Index: Integer): IXMLColItemType; property ColItem[Index: Integer]: IXMLColItemType read Get_ColItem; default; end; { IXMLColItemType } IXMLColItemType = interface(IXMLNode) ['{BA36DD8F-E518-427E-A9A3-AA572FC70550}'] { Property Accessors } function Get_Name: WideString; function Get_DisplayName: WideString; procedure Set_Name(Value: WideString); procedure Set_DisplayName(Value: WideString); { Methods & Properties } property Name: WideString read Get_Name write Set_Name; property DisplayName: WideString read Get_DisplayName write Set_DisplayName; end; { IXMLRowDataType } IXMLRowDataType = interface(IXMLNodeCollection) ['{6A227762-63EA-4FB7-A889-8BB8376014DD}'] { Property Accessors } function Get_RowItem(Index: Integer): IXMLRowItemType; { Methods & Properties } function Add: IXMLRowItemType; function Insert(const Index: Integer): IXMLRowItemType; property RowItem[Index: Integer]: IXMLRowItemType read Get_RowItem; default; end; { IXMLRowItemType } IXMLRowItemType = interface(IXMLNodeCollection) ['{C068FBEA-C297-4391-BFA0-08ADFB5A7880}'] { Property Accessors } function Get_ID: Integer; function Get_Field(Index: Integer): IXMLFieldType; procedure Set_ID(Value: Integer); { Methods & Properties } function Add: IXMLFieldType; function Insert(const Index: Integer): IXMLFieldType; property ID: Integer read Get_ID write Set_ID; property Field[Index: Integer]: IXMLFieldType read Get_Field; default; end; { IXMLFieldType } IXMLFieldType = interface(IXMLNode) ['{B86720CA-09B4-42E0-9511-70CB7A49B3F4}'] { Property Accessors } function Get_Name: WideString; function Get_Value: Integer; procedure Set_Name(Value: WideString); procedure Set_Value(Value: Integer); { Methods & Properties } property Name: WideString read Get_Name write Set_Name; property Value: Integer read Get_Value write Set_Value; end; { Forward Decls } TXMLGuoSenDeviceSystemType = class; TXMLDBDataType = class; TXMLColDataType = class; TXMLColItemType = class; TXMLRowDataType = class; TXMLRowItemType = class; TXMLFieldType = class; { TXMLGuoSenDeviceSystemType } TXMLGuoSenDeviceSystemType = class(TXMLNode, IXMLGuoSenDeviceSystemType) protected { IXMLGuoSenDeviceSystemType } function Get_DBData: IXMLDBDataType; public procedure AfterConstruction; override; end; { TXMLDBDataType } TXMLDBDataType = class(TXMLNode, IXMLDBDataType) protected { IXMLDBDataType } function Get_OperaterType: WideString; function Get_DBTable: WideString; function Get_SQL: WideString; function Get_ColData: IXMLColDataType; function Get_RowData: IXMLRowDataType; procedure Set_OperaterType(Value: WideString); procedure Set_DBTable(Value: WideString); procedure Set_SQL(Value: WideString); public procedure AfterConstruction; override; end; { TXMLColDataType } TXMLColDataType = class(TXMLNodeCollection, IXMLColDataType) protected { IXMLColDataType } function Get_ColItem(Index: Integer): IXMLColItemType; function Add: IXMLColItemType; function Insert(const Index: Integer): IXMLColItemType; public procedure AfterConstruction; override; end; { TXMLColItemType } TXMLColItemType = class(TXMLNode, IXMLColItemType) protected { IXMLColItemType } function Get_Name: WideString; function Get_DisplayName: WideString; procedure Set_Name(Value: WideString); procedure Set_DisplayName(Value: WideString); end; { TXMLRowDataType } TXMLRowDataType = class(TXMLNodeCollection, IXMLRowDataType) protected { IXMLRowDataType } function Get_RowItem(Index: Integer): IXMLRowItemType; function Add: IXMLRowItemType; function Insert(const Index: Integer): IXMLRowItemType; public procedure AfterConstruction; override; end; { TXMLRowItemType } TXMLRowItemType = class(TXMLNodeCollection, IXMLRowItemType) protected { IXMLRowItemType } function Get_ID: Integer; function Get_Field(Index: Integer): IXMLFieldType; procedure Set_ID(Value: Integer); function Add: IXMLFieldType; function Insert(const Index: Integer): IXMLFieldType; public procedure AfterConstruction; override; end; { TXMLFieldType } TXMLFieldType = class(TXMLNode, IXMLFieldType) protected { IXMLFieldType } function Get_Name: WideString; function Get_Value: Integer; procedure Set_Name(Value: WideString); procedure Set_Value(Value: Integer); end; { Global Functions } function GetGuoSenDeviceSystem(Doc: IXMLDocument): IXMLGuoSenDeviceSystemType; function LoadGuoSenDeviceSystem(const FileName: WideString): IXMLGuoSenDeviceSystemType; function NewGuoSenDeviceSystem: IXMLGuoSenDeviceSystemType; const TargetNamespace = ''; implementation { Global Functions } function GetGuoSenDeviceSystem(Doc: IXMLDocument): IXMLGuoSenDeviceSystemType; begin Result := Doc.GetDocBinding('GuoSenDeviceSystem', TXMLGuoSenDeviceSystemType, TargetNamespace) as IXMLGuoSenDeviceSystemType; end; function LoadGuoSenDeviceSystem(const FileName: WideString): IXMLGuoSenDeviceSystemType; begin Result := LoadXMLDocument(FileName).GetDocBinding('GuoSenDeviceSystem', TXMLGuoSenDeviceSystemType, TargetNamespace) as IXMLGuoSenDeviceSystemType; end; function NewGuoSenDeviceSystem: IXMLGuoSenDeviceSystemType; begin Result := NewXMLDocument.GetDocBinding('GuoSenDeviceSystem', TXMLGuoSenDeviceSystemType, TargetNamespace) as IXMLGuoSenDeviceSystemType; end; { TXMLGuoSenDeviceSystemType } procedure TXMLGuoSenDeviceSystemType.AfterConstruction; begin RegisterChildNode('DBData', TXMLDBDataType); inherited; end; function TXMLGuoSenDeviceSystemType.Get_DBData: IXMLDBDataType; begin Result := ChildNodes['DBData'] as IXMLDBDataType; end; { TXMLDBDataType } procedure TXMLDBDataType.AfterConstruction; begin RegisterChildNode('ColData', TXMLColDataType); RegisterChildNode('RowData', TXMLRowDataType); inherited; end; function TXMLDBDataType.Get_OperaterType: WideString; begin Result := AttributeNodes['OperaterType'].Text; end; procedure TXMLDBDataType.Set_OperaterType(Value: WideString); begin SetAttribute('OperaterType', Value); end; function TXMLDBDataType.Get_DBTable: WideString; begin Result := AttributeNodes['DBTable'].Text; end; procedure TXMLDBDataType.Set_DBTable(Value: WideString); begin SetAttribute('DBTable', Value); end; function TXMLDBDataType.Get_SQL: WideString; begin Result := AttributeNodes['SQL'].Text; end; procedure TXMLDBDataType.Set_SQL(Value: WideString); begin SetAttribute('SQL', Value); end; function TXMLDBDataType.Get_ColData: IXMLColDataType; begin Result := ChildNodes['ColData'] as IXMLColDataType; end; function TXMLDBDataType.Get_RowData: IXMLRowDataType; begin Result := ChildNodes['RowData'] as IXMLRowDataType; end; { TXMLColDataType } procedure TXMLColDataType.AfterConstruction; begin RegisterChildNode('ColItem', TXMLColItemType); ItemTag := 'ColItem'; ItemInterface := IXMLColItemType; inherited; end; function TXMLColDataType.Get_ColItem(Index: Integer): IXMLColItemType; begin Result := List[Index] as IXMLColItemType; end; function TXMLColDataType.Add: IXMLColItemType; begin Result := AddItem(-1) as IXMLColItemType; end; function TXMLColDataType.Insert(const Index: Integer): IXMLColItemType; begin Result := AddItem(Index) as IXMLColItemType; end; { TXMLColItemType } function TXMLColItemType.Get_Name: WideString; begin Result := AttributeNodes['Name'].Text; end; procedure TXMLColItemType.Set_Name(Value: WideString); begin SetAttribute('Name', Value); end; function TXMLColItemType.Get_DisplayName: WideString; begin Result := AttributeNodes['DisplayName'].Text; end; procedure TXMLColItemType.Set_DisplayName(Value: WideString); begin SetAttribute('DisplayName', Value); end; { TXMLRowDataType } procedure TXMLRowDataType.AfterConstruction; begin RegisterChildNode('RowItem', TXMLRowItemType); ItemTag := 'RowItem'; ItemInterface := IXMLRowItemType; inherited; end; function TXMLRowDataType.Get_RowItem(Index: Integer): IXMLRowItemType; begin Result := List[Index] as IXMLRowItemType; end; function TXMLRowDataType.Add: IXMLRowItemType; begin Result := AddItem(-1) as IXMLRowItemType; end; function TXMLRowDataType.Insert(const Index: Integer): IXMLRowItemType; begin Result := AddItem(Index) as IXMLRowItemType; end; { TXMLRowItemType } procedure TXMLRowItemType.AfterConstruction; begin RegisterChildNode('Field', TXMLFieldType); ItemTag := 'Field'; ItemInterface := IXMLFieldType; inherited; end; function TXMLRowItemType.Get_ID: Integer; begin Result := AttributeNodes['ID'].NodeValue; end; procedure TXMLRowItemType.Set_ID(Value: Integer); begin SetAttribute('ID', Value); end; function TXMLRowItemType.Get_Field(Index: Integer): IXMLFieldType; begin Result := List[Index] as IXMLFieldType; end; function TXMLRowItemType.Add: IXMLFieldType; begin Result := AddItem(-1) as IXMLFieldType; end; function TXMLRowItemType.Insert(const Index: Integer): IXMLFieldType; begin Result := AddItem(Index) as IXMLFieldType; end; { TXMLFieldType } function TXMLFieldType.Get_Name: WideString; begin Result := AttributeNodes['Name'].Text; end; procedure TXMLFieldType.Set_Name(Value: WideString); begin SetAttribute('Name', Value); end; function TXMLFieldType.Get_Value: Integer; begin Result := AttributeNodes['Value'].NodeValue; end; procedure TXMLFieldType.Set_Value(Value: Integer); begin SetAttribute('Value', Value); end; end.
object ExportFrm: TExportFrm Left = 453 Top = 181 BorderStyle = bsDialog Caption = ' Export File' ClientHeight = 390 ClientWidth = 539 Color = clBtnFace Font.Charset = ANSI_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Arial' Font.Style = [] OldCreateOrder = True Position = poDesigned OnShow = FormShow PixelsPerInch = 96 TextHeight = 14 object GroupBox8: TGroupBox Left = 8 Top = 108 Width = 158 Height = 85 Caption = ' Record Range ' TabOrder = 0 object rbAllRecords: TRadioButton Left = 8 Top = 16 Width = 81 Height = 18 Hint = 'Export all record in the data file' Caption = 'Whole file' Checked = True Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -11 Font.Name = 'Arial' Font.Style = [fsBold] ParentFont = False ParentShowHint = False ShowHint = True TabOrder = 0 TabStop = True end object rbRange: TRadioButton Left = 8 Top = 32 Width = 57 Height = 17 Hint = 'Export a limited range of records within the data file' Caption = 'Range' Font.Charset = DEFAULT_CHARSET Font.Color = clBlack Font.Height = -11 Font.Name = 'Arial' Font.Style = [fsBold] ParentFont = False ParentShowHint = False ShowHint = True TabOrder = 1 end object edRange: TRangeEdit Left = 26 Top = 50 Width = 119 Height = 20 AutoSize = False Text = ' 1 - 1.00000001504746622E30 ' LoValue = 1.000000000000000000 HiValue = 1.000000015047466E30 LoLimit = 1.000000000000000000 HiLimit = 1.000000015047466E30 Scale = 1.000000000000000000 NumberFormat = '%.0f - %.0f ' end end object ChannelsGrp: TGroupBox Left = 8 Top = 199 Width = 523 Height = 153 Hint = 'Select channels to be exported' Caption = ' Channels ' ParentShowHint = False ShowHint = True TabOrder = 1 object ckCh0: TCheckBox Left = 8 Top = 16 Width = 70 Height = 17 Caption = 'ckCh0' TabOrder = 0 end object ckCh1: TCheckBox Left = 8 Top = 32 Width = 70 Height = 17 Caption = 'CheckBox1' TabOrder = 1 end object ckCh2: TCheckBox Left = 8 Top = 48 Width = 70 Height = 17 Caption = 'CheckBox1' TabOrder = 2 end object ckCh3: TCheckBox Left = 8 Top = 64 Width = 70 Height = 17 Caption = 'CheckBox1' TabOrder = 3 end object ckCh4: TCheckBox Left = 8 Top = 81 Width = 70 Height = 17 Caption = 'CheckBox1' TabOrder = 4 end object ckCh5: TCheckBox Left = 8 Top = 97 Width = 70 Height = 17 Caption = 'CheckBox1' TabOrder = 5 end object ckCh6: TCheckBox Left = 8 Top = 112 Width = 70 Height = 17 Caption = 'CheckBox1' TabOrder = 6 end object ckCh7: TCheckBox Left = 8 Top = 128 Width = 70 Height = 17 Caption = 'CheckBox1' TabOrder = 7 end object ckCh8: TCheckBox Left = 88 Top = 16 Width = 70 Height = 17 Caption = 'ckCh0' TabOrder = 8 end object ckCh9: TCheckBox Left = 88 Top = 32 Width = 70 Height = 17 Caption = 'CheckBox1' TabOrder = 9 end object ckCh10: TCheckBox Left = 88 Top = 48 Width = 70 Height = 17 Caption = 'CheckBox1' TabOrder = 10 end object ckCh11: TCheckBox Left = 88 Top = 64 Width = 70 Height = 17 Caption = 'CheckBox1' TabOrder = 11 end object ckCh12: TCheckBox Left = 88 Top = 81 Width = 70 Height = 17 Caption = 'CheckBox1' TabOrder = 12 end object ckCh13: TCheckBox Left = 88 Top = 97 Width = 70 Height = 17 Caption = 'CheckBox1' TabOrder = 13 end object ckCh14: TCheckBox Left = 88 Top = 112 Width = 70 Height = 17 Caption = 'CheckBox1' TabOrder = 14 end object ckCh15: TCheckBox Left = 88 Top = 128 Width = 70 Height = 17 Caption = 'CheckBox1' TabOrder = 15 end object ckCh16: TCheckBox Left = 168 Top = 16 Width = 70 Height = 17 Caption = 'ckCh0' TabOrder = 16 end object ckCh17: TCheckBox Left = 168 Top = 32 Width = 70 Height = 17 Caption = 'CheckBox1' TabOrder = 17 end object ckCh18: TCheckBox Left = 168 Top = 48 Width = 70 Height = 17 Caption = 'CheckBox1' TabOrder = 18 end object ckCh19: TCheckBox Left = 168 Top = 64 Width = 70 Height = 17 Caption = 'CheckBox1' TabOrder = 19 end object ckCh20: TCheckBox Left = 168 Top = 81 Width = 70 Height = 17 Caption = 'CheckBox1' TabOrder = 20 end object ckCh21: TCheckBox Left = 168 Top = 97 Width = 70 Height = 17 Caption = 'CheckBox1' TabOrder = 21 end object ckCh22: TCheckBox Left = 168 Top = 112 Width = 70 Height = 17 Caption = 'CheckBox1' TabOrder = 22 end object ckCh23: TCheckBox Left = 168 Top = 128 Width = 70 Height = 17 Caption = 'CheckBox1' TabOrder = 23 end object ckCh24: TCheckBox Left = 248 Top = 16 Width = 70 Height = 17 Caption = 'ckCh0' TabOrder = 24 end object ckCh25: TCheckBox Left = 248 Top = 32 Width = 70 Height = 17 Caption = 'CheckBox1' TabOrder = 25 end object ckCh26: TCheckBox Left = 248 Top = 48 Width = 70 Height = 17 Caption = 'CheckBox1' TabOrder = 26 end object ckCh27: TCheckBox Left = 248 Top = 64 Width = 70 Height = 17 Caption = 'CheckBox1' TabOrder = 27 end object ckCh28: TCheckBox Left = 248 Top = 81 Width = 70 Height = 17 Caption = 'CheckBox1' TabOrder = 28 end object ckCh29: TCheckBox Left = 248 Top = 97 Width = 70 Height = 17 Caption = 'CheckBox1' TabOrder = 29 end object ckCh30: TCheckBox Left = 248 Top = 112 Width = 70 Height = 17 Caption = 'CheckBox1' TabOrder = 30 end object ckCh31: TCheckBox Left = 248 Top = 128 Width = 70 Height = 17 Caption = 'CheckBox1' TabOrder = 31 end end object GroupBox3: TGroupBox Left = 8 Top = -4 Width = 523 Height = 106 Caption = ' Files ' Font.Charset = ANSI_CHARSET Font.Color = clWindowText Font.Height = -12 Font.Name = 'Arial' Font.Style = [] ParentFont = False TabOrder = 2 object bChangeName: TButton Left = 8 Top = 82 Width = 121 Height = 17 Caption = 'Select Files' Font.Charset = ANSI_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Arial' Font.Style = [fsBold] ParentFont = False TabOrder = 0 OnClick = bChangeNameClick end object meFileList: TMemo Left = 3 Top = 17 Width = 510 Height = 59 Lines.Strings = ( 'meFileList') TabOrder = 1 WordWrap = False end end object GroupBox2: TGroupBox Left = 172 Top = 108 Width = 359 Height = 85 Caption = ' Output Format ' TabOrder = 3 object ckCombineRecords: TCheckBox Left = 8 Top = 38 Width = 146 Height = 25 Caption = 'Combine Records' TabOrder = 0 WordWrap = True end object cbExportFormat: TComboBox Left = 8 Top = 16 Width = 153 Height = 22 Hint = 'Select export file data format' Style = csDropDownList ParentShowHint = False ShowHint = True TabOrder = 1 OnChange = cbExportFormatChange end object ckASCIIRecordsInColumns: TCheckBox Left = 8 Top = 57 Width = 161 Height = 25 Caption = 'Save Records as Columns' TabOrder = 2 WordWrap = True end end object bOK: TButton Left = 8 Top = 358 Width = 50 Height = 20 Caption = 'OK' Font.Charset = ANSI_CHARSET Font.Color = clWindowText Font.Height = -12 Font.Name = 'Arial' Font.Style = [fsBold] ModalResult = 1 ParentFont = False TabOrder = 4 OnClick = bOKClick end object bCancel: TButton Left = 64 Top = 358 Width = 50 Height = 17 Caption = 'Cancel' Font.Charset = ANSI_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Arial' Font.Style = [fsBold] ModalResult = 2 ParentFont = False TabOrder = 5 end object ExportFile: TADCDataFile NumChannelsPerScan = 1 NumBytesPerSample = 2 NumScansPerRecord = 512 FloatingPointSamples = False MaxADCValue = 2047 MinADCValue = -2048 RecordNum = 0 NumFileHeaderBytes = 0 WCPNumZeroAvg = 0 WCPRecordAccepted = False ABFAcquisitionMode = ftGapFree EDREventDetectorChannel = 0 EDREventDetectorRecordSize = 0 EDRVarianceRecordSize = 0 EDRVarianceRecordOverlap = 0 EDRBackedUp = False ASCIISeparator = #9 ASCIITimeDataInCol0 = False ASCIITimeUnits = 's' ASCIITitleLines = 2 ASCIIFixedRecordSize = False ASCIISaveRecordsinColumns = False Left = 128 Top = 356 end object OpenDialog: TOpenDialog Left = 208 Top = 352 end end
// Copyright 2018 by John Kouraklis and Contributors. All Rights Reserved. // // 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 Casbin.Policy.Types; interface uses Casbin.Core.Base.Types, Casbin.Model.Sections.Types, System.Generics.Collections, System.Rtti, System.Types, Casbin.Watcher.Types, Casbin.Adapter.Types, Casbin.Adapter.Policy.Types; const DefaultDomain = 'default'; type TRoleNode = class private fDomain: string; fID: string; fValue: string; public constructor Create(const aValue: String; const aDomain: string = DefaultDomain); property Domain: string read fDomain; property Value: string read fValue; property ID: string read fID write fID; end; TRoleMode = ( {$REGION 'Returns all the roles and those inferred by the policies'} /// <summary> /// Returns all the roles and those inferred by the policies /// </summary> {$ENDREGION} rmImplicit, {$REGION 'Returns only the roles'} /// <summary> /// Returns only the roles /// </summary> {$ENDREGION} rmNonImplicit); IPolicyManager = interface (IBaseInterface) ['{B983A830-6107-4283-A45D-D74CDBB5E2EA}'] function section (const aSlim: Boolean = true): string; function toOutputString: string; function getAdapter: IPolicyAdapter; // Policies function policies: TList<string>; procedure addPolicy (const aSection: TSectionType; const aTag: string; const aAssertion: string); overload; procedure addPolicy (const aSection: TSectionType; const aAssertion: string); overload; procedure load (const aFilter: TFilterArray = []); function policy (const aFilter: TFilterArray = []): string; procedure clear; function policyExists (const aFilter: TFilterArray = []): Boolean; {$REGION ''} /// <param name="aRoleMode"> /// <para> /// rmImplicit: Deletes all roles from both 'g' and 'p' sections /// </para> /// <para> /// rmNonImplicit: Deletes roles only in 'g' sections /// </para> /// </param> {$ENDREGION} procedure removePolicy (const aFilter: TFilterArray = []; const aRoleMode: TRoleMode = rmImplicit); // Roles procedure clearRoles; function roles: TList<string>; function domains: TList<string>; function roleExists (const aFilter: TFilterArray = []): Boolean; {$REGION 'Adds the inheritance link between two roles'} /// <summary> /// Adds the inheritance link between two roles /// </summary> /// <example> /// addLink(name1, name2) adds a link between role:name 1 and role: name2 /// </example> {$ENDREGION} procedure addLink(const aBottom: string; const aTop: string); overload; procedure addLink(const aBottom: string; const aTopDomain: string; const aTop: string); overload; {$REGION 'Adds the inheritance link between two roles by passign domains'} /// <summary> /// Adds the inheritance link between two roles by passing domains /// </summary> /// <example> /// addLink(domain1, name1, domain2, name2) adds a link between role:name /// 1 in domain1 and role: name2 in domain 2 /// </example> {$ENDREGION} procedure addLink(const aBottomDomain: string; const aBottom: string; const aTopDomain: string; const aTop: string); overload; procedure removeLink(const aLeft: string; const aRight: string); overload; procedure removeLink(const aLeft: string; const aRightDomain: string; const aRight: string); overload; procedure removeLink(const aLeftDomain: string; const aLeft: string; const aRightDomain: string; const aRight: string); overload; function linkExists(const aLeft: string; const aRight: string):boolean; overload; function linkExists(const aLeft: string; const aRightDomain: string; const aRight: string):boolean; overload; function linkExists(const aLeftDomain: string; const aLeft: string; const aRightDomain: string; const aRight: string):boolean; overload; function rolesForEntity(const aEntity: string; const aDomain: string = ''; const aRoleMode: TRoleMode = rmNonImplicit): TStringDynArray; function entitiesForRole (const aEntity: string; const aDomain: string =''):TStringDynArray; // Watchers procedure registerWatcher (const aWatcher: IWatcher); procedure unregisterWatcher (const aWatcher: IWatcher); procedure notifyWatchers; // Permissions {$REGION ''} /// <remarks> /// Assumes the last part of a policy (assertion) statement indicates the /// permission /// </remarks> {$ENDREGION} function permissionsForEntity (const aEntity: string): TStringDynArray; function permissionExists (const aEntity: string; const aPermission: string): Boolean; // Adapter property Adapter: IPolicyAdapter read getAdapter; end; implementation uses System.SysUtils; constructor TRoleNode.Create(const aValue: String; const aDomain: string = DefaultDomain); var guid: TGUID; begin inherited Create; fValue:=Trim(aValue); fDomain:=Trim(aDomain); if CreateGUID(guid) <> 0 then fID:=GUIDToString(TGUID.Empty) else fID:=GUIDToString(guid); end; end.
unit UTabNavigator; interface uses Windows, UxlWinControl, UxlClasses, UxlDragControl, UNavigatorSuper, UxlTabControl, UxlExtClasses, UGlobalObj, UPageSuper, UTypeDef; type TTabNavigator = class (TNavigatorSuper, IOptionObserver, ISizeObserver) private FTab: TxlTabControl; FWndParent: TxlWinControl; FPage: TPageSuper; procedure f_OnTabSelChanged (newindex: integer); procedure f_OnTabDblClick (index: integer); procedure f_OnTabContextMenu (index: integer); procedure f_OnTabDropEvent (o_dragsource: IDragSource; hidxTarget: integer; b_copy: boolean); function f_FindItem (value: TPageSuper): integer; function f_GetTabItem (value: TPageSuper): TTabItem; function f_ProcessMessage (AMessage, wParam, lParam: DWORD; var b_processed: boolean): DWORD; procedure f_ExecutePageOperation(pb: TPageBehavior); function Page (index: integer): TPageSuper; protected procedure LoadIndex (); override; procedure SelectPage (value: TPageSuper); override; procedure AddPage (value: TPageSuper); override; procedure ResetPage (value: TPageSuper); override; procedure DeletePage (value: TPageSuper); override; procedure RenamePage (value: TPageSuper); override; public constructor Create (WndParent: TxlWinContainer); destructor Destroy (); override; function Control (): TxlDragControl; override; procedure OptionChanged (); procedure AdjustAppearance (); end; implementation uses MESSAGES, UxlExtDlgs, UxlList, Resource, UxlCommDlgs, UxlFunctions, UxlMath, UxlStrUtils, UPageStore, UOptionManager, UPageFactory, ULangManager; constructor TTabNavigator.Create (WndParent: TxlWinContainer); begin FWndParent := WndParent; FTab := TxlTabControl.create (WndParent); with FTab do begin Images := PageImageList.Images; Items.OnSelChanged := f_OnTabSelChanged; OnDblClick := f_OnTabDblClick; OnContextMenu := f_OnTabContextMenu; OnDropEvent := f_OnTabDropEvent; MessageHandler := f_ProcessMessage; end; OptionMan.AddObserver (self); SizeMan.AddObserver (self); end; destructor TTabNavigator.Destroy (); begin OptionMan.RemoveObserver (self); SizeMan.RemoveObserver (self); FTab.free; inherited; end; function TTabNavigator.Control (): TxlDragControl; begin result := FTab; end; function TTabNavigator.Page (index: integer): TPageSuper; begin result := PageStore[FTab.Items[index].data]; end; procedure TTabNavigator.OptionChanged (); begin with FTab do begin CanDrag := true; CanDrop := true; Font := OptionMan.Options.tabfont; end; if FTab.ShowImages <> OptionMan.Options.ShowTabImages then begin FTab.ShowImages := OptionMan.Options.ShowTabImages; if Active then begin LoadIndex (); SelectPage (FPage); end; end; AdjustAppearance; if Active and (FTab.Items.SelIndex >= 0) then FTab.Items.ItemHighlight [FTab.Items.SelIndex] := OptionMan.Options.HighlightCurrentTab; end; procedure TTabNavigator.AdjustAppearance (); var tcs: TTabStyle; begin tcs := FTab.Style; with tcs do begin multiline := OptionMan.Options.MultiLineTab and SizeMan.MultiLineTab; if OptionMan.Options.tabwidth <= 0 then tabwidth := 0 else tabwidth := 4 + 2 * OptionMan.Options.tabwidth; end; FTab.Style := tcs; end; //---------------------- procedure TTabNavigator.LoadIndex (); begin FTab.Items.Clear; end; procedure TTabNavigator.SelectPage (value: TPageSuper); var o_list: TxlIntList; i: integer; o_item: TTabItem; begin if value = nil then exit; if (FTab.Items.Count = 0) or (value.Owner <> FPage.Owner) then begin o_list := TxlIntList.Create; if value.Owner <> nil then value.Owner.GetChildList (o_list) else o_list.Add (value.id); FTab.Items.Clear; for i := o_list.Low to o_list.High do begin o_item := f_GetTabItem (PageStore[o_list[i]]); FTab.Items.Add (o_item); end; o_list.free; AdjustAppearance; end; FPage := value; for i := FTab.Items.Low to FTab.Items.High do if FTab.Items[i].data = value.id then begin FTab.Items.SelIndex := i; FTab.Items.ItemHighlight [i] := OptionMan.Options.HighlightCurrentTab; end else FTab.Items.ItemHighlight [i] := false; end; procedure TTabNavigator.AddPage (value: TPageSuper); var o_item: TTabItem; i: integer; begin if value.Owner <> FPage.Owner then exit; o_item := f_GetTabItem (value); i := FPage.Owner.Childs.FindChild (value.id); if i <= FTab.Items.High then FTab.Items.Insert (i, o_item) else FTab.Items.Add (o_item); FTab.Update; end; function TTabNavigator.f_GetTabItem (value: TPageSuper): TTabItem; begin with result do begin if FTab.ShowImages then text := value.name else text := f_NameToLabel (value); data := value.id; image := value.ImageIndex; highlight := false; end; end; procedure TTabNavigator.ResetPage (value: TPageSuper); var i: integer; begin i := f_FindItem (value); if i >= 0 then FTab.Items[i] := f_GetTabItem (value); end; procedure TTabNavigator.RenamePage (value: TPageSuper); var s_name: widestring; begin s_name := value.name; if InputBox (LangMan.GetItem(sr_rename, '重命名'), LangMan.GetItem(sr_inputpagename, '请输入标签页名称:'), s_name, m_rename, LangMan.GetItem(IDOK), LangMan.GetItem(IDCancel)) then begin value.Name := MultiLineToSingleLine (s_name, true); Eventman.EventNotify (e_PageNameChanged, value.id); end; end; procedure TTabNavigator.DeletePage (value: TPageSuper); var i_index: integer; begin i_index := f_FindItem (value); if i_index >= 0 then FTab.Items.Delete (i_index, false); end; function TTabNavigator.f_FindItem (value: TPageSuper): integer; var i: integer; begin result := -1; for i := FTab.Items.Low to FTab.Items.High do if FTab.Items[i].data = value.id then begin result := i; exit; end; end; //--------------------- procedure TTabNavigator.f_OnTabSelChanged (newindex: integer); begin PageCenter.ActivePage := Page(newindex); end; procedure TTabNavigator.f_ExecutePageOperation(pb: TPageBehavior); var m: integer; begin case pb of pbRename: m := m_rename; pbSwitchProperty: m := m_switchLock; else m := m_deletepage; end; CommandMan.ExecuteCommand (m); end; procedure TTabNavigator.f_OnTabContextMenu (index: integer); var p: TPageSuper; begin if index < 0 then exit; p := Page(index); if p <> PageCenter.ActivePage then PageCenter.ActivePage := p; EventMan.EventNotify (e_ContextMenuDemand, PageContext); end; procedure TTabNavigator.f_OnTabDropEvent (o_dragsource: IDragSource; hidxTarget: integer; b_copy: boolean); var o_page: TPageSuper; begin if (hidxTarget >= 0) and assigned (OnDropItems) then begin o_page := Page(hidxTarget); OnDropItems (o_dragsource, o_page.id, o_Page.Owner.id, b_copy); // FTab.Update; end; end; procedure TTabNavigator.f_OnTabDblClick (index: integer); begin f_ExecutePageOperation (OptionMan.Options.PageDblClick); end; function TTabNavigator.f_ProcessMessage (AMessage, wParam, lParam: DWORD; var b_processed: boolean): DWORD; var i_newpage: integer; w: smallint; begin result := 0; b_processed := true; case AMessage of WM_MBUTTONDOWN: f_ExecutePageOperation (OptionMan.Options.PageMButtonClick); WM_MOUSEWHEEL: begin w := wParam shr 16; i_newpage := ConfineRange (FTab.Items.SelIndex + -1 * sign(w), FTab.Items.Low, FTab.Items.High); if i_newpage <> FTab.Items.SelIndex then f_OnTabSelChanged (i_newpage); end; else b_processed := false; end; end; end.
unit CatRes; { Catarinka - Catarinka Resources Library Useful functions for reading or saving resources Copyright (c) 2003-2014 Felipe Daragon License: 3-clause BSD See https://github.com/felipedaragon/catarinka/ for details } interface {$I Catarinka.inc} uses {$IFDEF DXE2_OR_UP} System.SysUtils, Winapi.Windows, vcl.imaging.Jpeg, System.Classes; {$ELSE} SysUtils, Windows, Jpeg, Classes; {$ENDIF} type MyPWideChar = {$IFDEF UNICODE}PWideChar{$ELSE}PChar{$ENDIF}; function GetResourceAsPointer(const ResName, ResType: MyPWideChar; out Size: longword): pointer; function GetResourceAsString(const ResName, ResType: MyPWideChar): string; function GetResourceAsJpeg(const ResName: string): TJPEGImage; procedure SaveResourceAsFile(const ResName: string; const ResType: MyPWideChar; const FileName: string); function SaveResourceAsTempFile(const ResName: string; const ResType: MyPWideChar): string; implementation uses CatFiles; // Usage Example: // Jpg := GetResourceAsJpeg('sample_jpg'); // Image1.Picture.Bitmap.Assign(Jpg); function GetResourceAsJpeg(const ResName: string): TJPEGImage; var rs: TResourceStream; begin rs := TResourceStream.Create(hInstance, ResName, 'JPEG'); try Result := TJPEGImage.Create; Result.LoadFromStream(rs); finally rs.Free; end; end; // Example: Memo1.Lines.Text := GetResourceAsString('sample_txt', 'text'); function GetResourceAsString(const ResName, ResType: MyPWideChar): string; var rd: pansichar; // resource data sz: longword; // resource size begin rd := GetResourceAsPointer(ResName, ResType, sz); SetString(Result, rd, sz); end; procedure SaveResourceAsFile(const ResName: string; const ResType: MyPWideChar; const FileName: string); begin with TResourceStream.Create(hInstance, ResName, ResType) do try SaveToFile(FileName); finally Free; end; end; { Usage Example: procedure TForm1.FormCreate(Sender: TObject); var size: longword; sample_wav: pointer; begin sample_wav := GetResourceAsPointer('sample_wav', 'wave', size); sndPlaySound(sample_wav, SND_MEMORY or SND_NODEFAULT or SND_ASYNC); end; } // Based on an example from the Pascal Newsletter #25 function GetResourceAsPointer(const ResName, ResType: MyPWideChar; out Size: longword): pointer; var ib: HRSRC; // InfoBlock gmb: HGLOBAL; // GlobalMemoryBlock begin ib := FindResource(hInstance, ResName, ResType); if ib = 0 then raise Exception.Create(SysErrorMessage(GetLastError)); Size := SizeofResource(hInstance, ib); if Size = 0 then raise Exception.Create(SysErrorMessage(GetLastError)); gmb := LoadResource(hInstance, ib); if gmb = 0 then raise Exception.Create(SysErrorMessage(GetLastError)); Result := LockResource(gmb); if Result = nil then raise Exception.Create(SysErrorMessage(GetLastError)); end; function SaveResourceAsTempFile(const ResName: string; const ResType: MyPWideChar): string; begin Result := GetWindowsTempDir + 'temp_' + ResName; SaveResourceAsFile(ResName, ResType, Result); end; // ------------------------------------------------------------------------// end.
unit TextEditor.CodeFolding.Hint.Colors; interface uses System.Classes, Vcl.Graphics; type TTextEditorCodeFoldingHintColors = class(TPersistent) strict private FBackground: TColor; FBorder: TColor; public constructor Create; procedure Assign(ASource: TPersistent); override; published property Background: TColor read FBackground write FBackground default clWindow; property Border: TColor read FBorder write FBorder default clBtnFace; end; implementation constructor TTextEditorCodeFoldingHintColors.Create; begin inherited; FBackground := clWindow; FBorder := clBtnFace; end; procedure TTextEditorCodeFoldingHintColors.Assign(ASource: TPersistent); begin if Assigned(ASource) and (ASource is TTextEditorCodeFoldingHintColors) then with ASource as TTextEditorCodeFoldingHintColors do begin Self.FBackground := FBackground; Self.FBorder := FBorder; end else inherited Assign(ASource); end; end.
{ Copyright (c) 2013 Jeroen Wiert Pluimers for BeSharp.net and Coding In Delphi. Full BSD License is available at http://BeSharp.codeplex.com/license } unit LocomotionInterfacesUnit; // after http://en.wikipedia.org/wiki/Animal_locomotion // running, swimming, jumping, flying // not all animals can do all, but some can do more than one. // Note this is a model of the real world. Models are always a simplification. interface type IRunning = interface(IInterface) ['{8459D191-5301-4850-809B-606A9060239D}'] procedure Run; end; ISwimming = interface(IInterface) ['{EB521F97-48A1-45DA-815B-DFCC8E4E39F1}'] procedure Swim; end; IJumping = interface(IInterface) ['{0D38D12C-8AD7-4347-A90D-F8F3444AF9A2}'] procedure Jump; end; IFlying = interface(IInterface) ['{CD70991B-10AE-4F78-9993-3EAB75BA8B15}'] procedure Fly; end; implementation end.
unit TextEditor.Caret.NonBlinking; interface uses System.Classes, TextEditor.Caret.NonBlinking.Colors; type TTextEditorCaretNonBlinking = class(TPersistent) strict private FActive: Boolean; FColors: TTextEditorCaretNonBlinkingColors; FOnChange: TNotifyEvent; procedure DoChange; procedure SetActive(const AValue: Boolean); procedure SetColors(const AValue: TTextEditorCaretNonBlinkingColors); public constructor Create; destructor Destroy; override; procedure Assign(ASource: TPersistent); override; property OnChange: TNotifyEvent read FOnChange write FOnChange; published property Active: Boolean read FActive write SetActive default False; property Colors: TTextEditorCaretNonBlinkingColors read FColors write SetColors; end; implementation constructor TTextEditorCaretNonBlinking.Create; begin inherited; FColors := TTextEditorCaretNonBlinkingColors.Create; FActive := False; end; destructor TTextEditorCaretNonBlinking.Destroy; begin FColors.Free; inherited; end; procedure TTextEditorCaretNonBlinking.Assign(ASource: TPersistent); begin if Assigned(ASource) and (ASource is TTextEditorCaretNonBlinking) then with ASource as TTextEditorCaretNonBlinking do begin Self.FColors.Assign(FColors); Self.FActive := FActive; Self.DoChange; end else inherited Assign(ASource); end; procedure TTextEditorCaretNonBlinking.DoChange; begin if Assigned(FOnChange) then FOnChange(Self); end; procedure TTextEditorCaretNonBlinking.SetActive(const AValue: Boolean); begin if FActive <> AValue then begin FActive := AValue; DoChange; end; end; procedure TTextEditorCaretNonBlinking.SetColors(const AValue: TTextEditorCaretNonBlinkingColors); begin FColors.Assign(AValue); end; end.
unit notesmodel; {$MODE objfpc}{$H+} interface uses SysUtils, Classes, strutils, fgl; type TNote = record date : TDateTime; topic : string; text : string; end; PNote = ^TNote; TNotes = class private _notes : TFPList; _topics : TStringList; public constructor Create(); destructor Destroy; override; function addNote(text: string):PNote; overload; function addNote(date: TDateTime; text: string) : PNote; overload; function addNote(topic: string; text: string) : PNote; overload; function addNote(topic: string; date: TDateTime; text: string) : PNote; overload; function getCount : integer; function getNote(idx : integer) : PNote; function getTopic(idx : integer) : string; function getTopicNotes(topic: string) : TFPList; function hasTopic(topic: string) : boolean; property notes[idx : integer] : PNote read getNote; default; property topicNotes[topic : string] : TFPList read getTopicNotes; published property count : integer read getCount; property allNotes : TFPList read _notes; property topics : TStringList read _topics; end; TNotesFile = class private _directory : string; _filename : string; function getFilename : string; public constructor Create(); overload; constructor Create(directory, filename : string); overload; destructor Destroy(); override; procedure save(notes : TNotes); procedure load(notes : TNotes); end; implementation constructor TNotes.Create(); begin _notes := TFPList.create(); _topics := TStringList.create(); _topics.sorted := true; end; destructor TNotes.Destroy; begin freeAndNil(_notes); freeAndNil(_topics); end; function TNotes.addNote(text: string):PNote; begin result := addNote(date, text); end; function TNotes.addNote(date: TDateTime; text: string) : PNote; begin result := addNote('', date, text); end; function TNotes.addNote(topic, text: string):PNote; begin result := addNote(topic, date, text); end; function TNotes.addNote(topic: string; date: TDateTime; text: string) : PNote; var note : PNote; begin note := new(PNote); note^.topic := topic; note^.date := date; note^.text := text; _notes.add(note); if not hasTopic(topic) then _topics.add(topic); result := note; end; function TNotes.getCount() : integer; begin result := _notes.count; end; function TNotes.getNote(idx : integer) : PNote; begin result := _notes[idx]; end; function TNotes.hasTopic(topic: string) : boolean; var counter : integer; begin topic := lowercase(topic); result := false; for counter := 0 to _topics.count - 1 do begin if topic = lowercase(_topics[counter]) then begin result := true; break; end; end; end; function TNotes.getTopic(idx: integer) : string; begin result := _topics[idx]; end; function TNotes.getTopicNotes(topic: string) : TFPList; var counter : integer; note : PNote; begin result := TFPList.create(); for counter := 0 to _notes.count - 1 do begin note := _notes[counter]; if note^.topic = topic then result.add(note); end; end; constructor TNotesFile.Create(); begin _directory := getUserDir + '.quicknotes/'; _filename := 'notes.quicknotes'; end; constructor TNotesFile.Create(directory, filename : string); begin _directory := directory; _filename := filename; end; destructor TNotesFile.Destroy(); begin end; function TNotesFile.getFilename : string; begin result := _directory + _filename; end; procedure TNotesFile.save(notes : TNotes); var counter, topicCounter : integer; note : PNote; topicNotes : TFPList; topic : string; outputFile : text; begin if not directoryExists(_directory) then createDir(_directory); assign(outputFile, getFilename()); rewrite(outputFile); for topicCounter := 0 to notes.topics.count - 1 do begin topic := notes.topics[topicCounter]; topicNotes := notes.topicNotes[topic]; if topic <> '' then writeln(outputFile, '[', topic, ']'); for counter := 0 to topicNotes.count - 1 do begin note := topicNotes[counter]; writeln(outputFile, dateToStr(note^.date), #9, note^.text); end; end; close(outputFile); end; procedure TNotesFile.load(notes : TNotes); var inputFile : text; line : string; tabPos : integer; topic, dateStr, text : string; begin if fileExists(getFilename()) then begin assign(inputFile, getFilename()); reset(inputFile); while not eof(inputFile) do begin readln(inputFile, line); if line = '' then continue; if line[1] = '[' then begin // reading a topic topic := trimSet(line, ['[',']']); end else begin tabPos := npos(#9, line, 1); dateStr := midStr(line, 1, tabPos); text := midStr(line, tabPos + 1, length(line) - tabPos); notes.addNote(topic, strToDate(dateStr), text); end; end; close(inputFile); end; end; begin end.
(* Б) Напишите булеву функцию Test и программу для её демонстрации. Функция должна проверять, делится ли без остатка первое число на второе. *) function Test(n1, n2: integer): boolean; begin Test := (n1 mod n2) = 0; end; begin Writeln(Test(20, 4)); Writeln(Test(21, 5)); end.
unit Dwarf; {>Some utilities for extracting line number information from DWARF debug sections in a MACH-O file (like the .dSYM files generated by the Intel MacOS64 compiler for Delphi). For an introduction to the DWARD Debugging Format: * https://dwarfstd.org/doc/Debugging%20using%20DWARF-2012.pdf And the official specification: * https://dwarfstd.org/doc/DWARF5.pdf } {$SCOPEDENUMS ON} interface uses System.Classes, System.SysUtils, System.Generics.Collections; const DW_TAG_array_type = $01; DW_TAG_class_type = $02; DW_TAG_entry_point = $03; DW_TAG_enumeration_type = $04; DW_TAG_formal_parameter = $05; DW_TAG_imported_declaration = $08; DW_TAG_label = $0a; DW_TAG_lexical_block = $0b; DW_TAG_member = $0d; DW_TAG_pointer_type = $0f; DW_TAG_reference_type = $10; DW_TAG_compile_unit = $11; DW_TAG_string_type = $12; DW_TAG_structure_type = $13; DW_TAG_subroutine_type = $15; DW_TAG_typedef = $16; DW_TAG_union_type = $17; DW_TAG_unspecified_parameters = $18; DW_TAG_variant = $19; DW_TAG_common_block = $1a; DW_TAG_common_inclusion = $1b; DW_TAG_inheritance = $1c; DW_TAG_inlined_subroutine = $1d; DW_TAG_module = $1e; DW_TAG_ptr_to_member_type = $1f; DW_TAG_set_type = $20; DW_TAG_subrange_type = $21; DW_TAG_with_stmt = $22; DW_TAG_access_declaration = $23; DW_TAG_base_type = $24; DW_TAG_catch_block = $25; DW_TAG_const_type = $26; DW_TAG_constant = $27; DW_TAG_enumerator = $28; DW_TAG_file_type = $29; DW_TAG_friend = $2a; DW_TAG_namelist = $2b; DW_TAG_namelist_item = $2c; DW_TAG_packed_type = $2d; DW_TAG_subprogram = $2e; DW_TAG_template_type_param = $2f; DW_TAG_template_value_param = $30; DW_TAG_thrown_type = $31; DW_TAG_try_block = $32; DW_TAG_variant_part = $33; DW_TAG_variable = $34; DW_TAG_volatile_type = $35; DW_TAG_lo_user = $4080; DW_TAG_hi_user = $ffff; const DW_CHILDREN_no = 0; DW_CHILDREN_yes = 1; const DW_AT_sibling = $01; // reference DW_AT_location = $02; // block, constant DW_AT_name = $03; // string DW_AT_ordering = $09; // constant DW_AT_byte_size = $0b; // constant DW_AT_bit_offset = $0c; // constant DW_AT_bit_size = $0d; // constant DW_AT_stmt_list = $10; // constant DW_AT_low_pc = $11; // address DW_AT_high_pc = $12; // address DW_AT_language = $13; // constant DW_AT_discr = $15; // reference DW_AT_discr_value = $16; // constant DW_AT_visibility = $17; // constant DW_AT_import = $18; // reference DW_AT_string_length = $19; // block, constant DW_AT_common_reference = $1a; // reference DW_AT_comp_dir = $1b; // string DW_AT_const_value = $1c; // string, constant, block DW_AT_containing_type = $1d; // reference DW_AT_default_value = $1e; // reference DW_AT_inline = $20; // constant DW_AT_is_optional = $21; // flag DW_AT_lower_bound = $22; // constant, reference DW_AT_producer = $25; // string DW_AT_prototyped = $27; // flag DW_AT_return_addr = $2a; // block, constant DW_AT_start_scope = $2c; // constant DW_AT_stride_size = $2e; // constant DW_AT_upper_bound = $2f; // constant, reference DW_AT_abstract_origin = $31; // reference DW_AT_accessibility = $32; // constant DW_AT_address_class = $33; // constant DW_AT_artificial = $34; // flag DW_AT_base_types = $35; // reference DW_AT_calling_convention = $36; // constant DW_AT_count = $37; // constant, reference DW_AT_data_member_location = $38; // block, reference DW_AT_decl_column = $39; // constant DW_AT_decl_file = $3a; // constant DW_AT_decl_line = $3b; // constant DW_AT_declaration = $3c; // flag DW_AT_discr_list = $3d; // block DW_AT_encoding = $3e; // constant DW_AT_external = $3f; // flag DW_AT_frame_base = $40; // block, constant DW_AT_friend = $41; // reference DW_AT_identifier_case = $42; // constant DW_AT_macro_info = $43; // constant DW_AT_namelist_item = $44; // block DW_AT_priority = $45; // reference DW_AT_segment = $46; // block, constant DW_AT_specification = $47; // reference DW_AT_static_link = $48; // block, constant DW_AT_type = $49; // reference DW_AT_use_location = $4a; // block, constant DW_AT_variable_parameter = $4b; // flag DW_AT_virtuality = $4c; // constant DW_AT_vtable_elem_location = $4d; // block, reference DW_AT_lo_user = $2000; DW_AT_hi_user = $3fff; const DW_FORM_addr = $01; // address DW_FORM_block2 = $03; // block DW_FORM_block4 = $04; // block DW_FORM_data2 = $05; // constant DW_FORM_data4 = $06; // constant DW_FORM_data8 = $07; // constant DW_FORM_string = $08; // string DW_FORM_block = $09; // block DW_FORM_block1 = $0a; // block DW_FORM_data1 = $0b; // constant DW_FORM_flag = $0c; // flag DW_FORM_sdata = $0d; // constant DW_FORM_strp = $0e; // string DW_FORM_udata = $0f; // constant DW_FORM_ref_addr = $10; // reference DW_FORM_ref1 = $11; // reference DW_FORM_ref2 = $12; // reference DW_FORM_ref4 = $13; // reference DW_FORM_ref8 = $14; // reference DW_FORM_ref_udata = $15; // reference DW_FORM_indirect = $16; // (see section 7.5.3) DW_FORM_sec_offset = $17; // lineptr, loclistptr, macptr, rangelistptr DW_FORM_exprloc = $18; // exprloc DW_FORM_flag_present = $19; // flag DW_FORM_ref_sig8 = $20; // reference const DW_LANG_C89 = $0001; DW_LANG_C = $0002; DW_LANG_Ada83 = $0003; DW_LANG_C_plus_plus = $0004; DW_LANG_Cobol74 = $0005; DW_LANG_Cobol85 = $0006; DW_LANG_Fortran77 = $0007; DW_LANG_Fortran90 = $0008; DW_LANG_Pascal83 = $0009; DW_LANG_Modula2 = $000a; DW_LANG_lo_user = $8000; DW_LANG_hi_user = $ffff; type EDwarfError = class(Exception); type TDwarfCursor = record {$REGION 'Internal Declarations'} private FCur: PByte; FEnd: PByte; private class procedure ReadError; static; private {$ENDREGION 'Internal Declarations'} public class operator Implicit(const ABytes: TBytes): TDwarfCursor; static; function Eof: Boolean; inline; procedure Seek(const APtr: PByte); overload; inline; procedure Require(const ANumBytes: Integer); inline; procedure Skip(const ANumBytes: Integer); inline; procedure SkipString; function ReadUInt8: UInt8; inline; function ReadUInt16: UInt16; inline; function ReadUInt32: UInt32; inline; function ReadUInt64: UInt64; inline; function ReadULeb128: UInt64; inline; function ReadSInt8: Int8; inline; function ReadSLeb128: Int64; inline; function ReadString: String; procedure Read(var AData; const ANumBytes: Integer); inline; property Cur: PByte read FCur; end; type TDwarfAttributeDesc = record public Name: Integer; Form: Integer; public procedure SkipValue(const ACursor: TDwarfCursor); function StringValue(const ACursor: TDwarfCursor; const AStringSection: TBytes): String; function UIntValue(const ACursor: TDwarfCursor): UInt64; end; type TDwarfAbbreviation = class {$REGION 'Internal Declarations'} private FTag: Integer; FAttributes: TArray<TDwarfAttributeDesc>; FHasChildren: Boolean; protected procedure Load(const ACursor: TDwarfCursor); {$ENDREGION 'Internal Declarations'} public property Tag: Integer read FTag; property Attributes: TArray<TDwarfAttributeDesc> read FAttributes; property HasChildren: Boolean read FHasChildren; end; type TDwarfAbbreviationTable = class {$REGION 'Internal Declarations'} private FAbbreviations: TObjectDictionary<Integer, TDwarfAbbreviation>; protected procedure Load(const ACursor: TDwarfCursor; const AOffset: Integer); {$ENDREGION 'Internal Declarations'} public constructor Create; destructor Destroy; override; function Get(const AAbbrevCode: Integer): TDwarfAbbreviation; inline; end; type TDwarfSections = record public Abbrev: TBytes; Info: TBytes; Line: TBytes; Str: TBytes; end; type TDwarfFile = record public Name: String; { Index into TDwarfCompilationUnit.IncludeDirectories. 0 if in current directory. } DirectoryIndex: Integer; Time: Int64; Size: Int64; end; type TDwarfLineFlag = (IsStatement, BasicBlock, EndSequence, PrologueEnd, EpilogueBegin); TDwarfLineFlags = set of TDwarfLineFlag; type TDwarfLine = packed record Address: UInt64; FileIndex: Integer; Line: Integer; Column: Integer; Flags: TDwarfLineFlags; end; type TDwarfInfo = class; TDwarfCompilationUnit = class {$REGION 'Internal Declarations'} private FOwner: TDwarfInfo; // Reference FAbbreviations: TDwarfAbbreviationTable; // Reference FProducer: String; FName: String; FDirectory: String; FLanguage: Integer; FIncludeDirectories: TStringList; FFiles: TList<TDwarfFile>; FLines: TList<TDwarfLine>; protected procedure Load(const ACursor: TDwarfCursor); procedure LoadLineNumbers(const AOffset: Integer); {$ENDREGION 'Internal Declarations'} public constructor Create(const AOwner: TDwarfInfo; const AAbbreviations: TDwarfAbbreviationTable); destructor Destroy; override; property Producer: String read FProducer; property Name: String read FName; property Directory: String read FDirectory; { DW_LANG_* } property Language: Integer read FLanguage; property IncludeDirectories: TStringList read FIncludeDirectories; property Files: TList<TDwarfFile> read FFiles; property Lines: TList<TDwarfLine> read FLines; end; TDwarfInfo = class {$REGION 'Internal Declarations'} private FSections: TDwarfSections; FCompilationUnits: TObjectList<TDwarfCompilationUnit>; FAbbreviationTables: TObjectDictionary<Integer, TDwarfAbbreviationTable>; private procedure LoadInfo(const ACursor: TDwarfCursor); {$ENDREGION 'Internal Declarations'} public constructor Create; destructor Destroy; override; procedure Clear; procedure Load(const ASections: TDwarfSections); property CompilationUnits: TObjectList<TDwarfCompilationUnit> read FCompilationUnits; end; implementation const DW_LNS_copy = 1; DW_LNS_advance_pc = 2; DW_LNS_advance_line = 3; DW_LNS_set_file = 4; DW_LNS_set_column = 5; DW_LNS_negate_stmt = 6; DW_LNS_set_basic_block = 7; DW_LNS_const_add_pc = 8; DW_LNS_fixed_advance_pc = 9; DW_LNS_set_prologue_end = 10; DW_LNS_set_epilogue_begin = 11; DW_LNS_set_isa = 12; const DW_LNE_end_sequence = 1; DW_LNE_set_address = 2; DW_LNE_define_file = 3; { TDwarfCursor } function TDwarfCursor.Eof: Boolean; begin Result := (FCur >= FEnd); end; class operator TDwarfCursor.Implicit(const ABytes: TBytes): TDwarfCursor; begin if (ABytes = nil) then begin Result.FCur := nil; Result.FEnd := nil; end else begin Result.FCur := @ABytes[0]; Result.FEnd := @ABytes[Length(ABytes)]; end; end; procedure TDwarfCursor.Read(var AData; const ANumBytes: Integer); begin Move(FCur^, AData, ANumBytes); Inc(FCur, ANumBytes); end; class procedure TDwarfCursor.ReadError; begin raise EDwarfError.Create('Read beyond end of DWARF section'); end; function TDwarfCursor.ReadSInt8: Int8; begin Result := Int8(FCur^); Inc(FCur, SizeOf(Int8)); end; function TDwarfCursor.ReadSLeb128: Int64; var Shift: Integer; B: Byte; begin Result := 0; Shift := 0; while (True) do begin B := FCur^; Inc(FCur); Result := Result or ((B and $7F) shl Shift); Inc(Shift, 7); if ((B and $80) = 0) then Break; end; if ((B and $40) <> 0) then begin if (Shift < 63) then Result := Result or -Int64(UInt64(1) shl Shift) else Result := Result or (UInt64(1) shl Shift); end; end; function TDwarfCursor.ReadString: String; var Start: PByte; I, Len: Integer; P: PChar; begin Start := FCur; while (FCur < FEnd) and (FCur^ <> 0) do Inc(FCur); Len := FCur - Start; Inc(FCur); if (Len = 0) then Exit(''); SetLength(Result, Len); P := Pointer(Result); for I := 0 to Len - 1 do begin P^ := Char(Start^); Inc(Start); Inc(P); end; end; function TDwarfCursor.ReadUInt16: UInt16; begin Result := PWord(FCur)^; Inc(FCur, SizeOf(UInt16)); end; function TDwarfCursor.ReadUInt32: UInt32; begin Result := PUInt32(FCur)^; Inc(FCur, SizeOf(UInt32)); end; function TDwarfCursor.ReadUInt64: UInt64; begin Result := PUInt64(FCur)^; Inc(FCur, SizeOf(UInt64)); end; function TDwarfCursor.ReadUInt8: UInt8; begin Result := FCur^; Inc(FCur, SizeOf(UInt8)); end; function TDwarfCursor.ReadULeb128: UInt64; var Shift: Integer; B: Byte; begin Result := 0; Shift := 0; while (True) do begin B := FCur^; Inc(FCur); Result := Result or ((B and $7F) shl Shift); if ((B and $80) = 0) then Break; Inc(Shift, 7); end; end; procedure TDwarfCursor.Require(const ANumBytes: Integer); begin if (ANumBytes > (FEnd - FCur)) then ReadError; end; procedure TDwarfCursor.Seek(const APtr: PByte); begin FCur := APtr; end; procedure TDwarfCursor.Skip(const ANumBytes: Integer); begin Inc(FCur, ANumBytes); end; procedure TDwarfCursor.SkipString; begin while (FCur < FEnd) and (FCur^ <> 0) do Inc(FCur); Inc(FCur); end; { TDwarfAttributeDesc } procedure TDwarfAttributeDesc.SkipValue(const ACursor: TDwarfCursor); var Size: UInt32; Indirect: TDwarfAttributeDesc; begin case Form of DW_FORM_flag_present: { No data }; DW_FORM_flag, DW_FORM_data1, DW_FORM_ref1: ACursor.Skip(1); DW_FORM_data2, DW_FORM_ref2: ACursor.Skip(2); DW_FORM_data4, DW_FORM_ref4, DW_FORM_strp: ACursor.Skip(4); DW_FORM_ref_addr, DW_FORM_sec_offset: ACursor.Skip(4); // Only 32-bit DWARF sections are supported (this is checked in TDwarfInfo.LoadInfo) DW_FORM_data8, DW_FORM_ref8, DW_FORM_ref_sig8: ACursor.Skip(8); DW_FORM_addr: ACursor.Skip(8); // Only 64-bit addresses are supported (this is checked in TDwarfInfo.LoadInfo) DW_FORM_block, DW_FORM_exprloc: begin Size := ACursor.ReadULeb128; ACursor.Skip(Size); end; DW_FORM_block1: begin Size := ACursor.ReadUInt8; ACursor.Skip(Size); end; DW_FORM_block2: begin Size := ACursor.ReadUInt16; ACursor.Skip(Size); end; DW_FORM_block4: begin Size := ACursor.ReadUInt32; ACursor.Skip(Size); end; DW_FORM_udata, DW_FORM_ref_udata: ACursor.ReadULeb128; DW_FORM_sdata: ACursor.ReadSLeb128; DW_FORM_string: ACursor.SkipString; DW_FORM_indirect: begin Indirect.Name := 0; Indirect.Form := ACursor.ReadULeb128; Indirect.SkipValue(ACursor); end else raise EDwarfError.CreateFmt('Unsupported attribute form (%d)', [Form]); end; end; function TDwarfAttributeDesc.StringValue(const ACursor: TDwarfCursor; const AStringSection: TBytes): String; var Offset: Integer; StrCursor: TDwarfCursor; begin case Form of DW_FORM_string: Result := ACursor.ReadString; DW_FORM_strp: begin Offset := ACursor.ReadUInt32; StrCursor := AStringSection; StrCursor.Skip(Offset); Result := StrCursor.ReadString; end; else SkipValue(ACursor); Result := ''; end; end; function TDwarfAttributeDesc.UIntValue(const ACursor: TDwarfCursor): UInt64; begin case Form of DW_FORM_data1: Result := ACursor.ReadUInt8; DW_FORM_data2: Result := ACursor.ReadUInt16; DW_FORM_data4: Result := ACursor.ReadUInt32; DW_FORM_data8: Result := ACursor.ReadUInt64; DW_FORM_udata: Result := ACursor.ReadULeb128; DW_FORM_sdata: Result := ACursor.ReadSLeb128; else SkipValue(ACursor); Result := 0; end; end; { TDwarfAbbreviation } procedure TDwarfAbbreviation.Load(const ACursor: TDwarfCursor); var Attr: TDwarfAttributeDesc; AttrCount: Integer; begin FTag := ACursor.ReadULeb128; FHasChildren := (ACursor.ReadUInt8 = DW_CHILDREN_yes); AttrCount := 0; while (not ACursor.Eof) do begin Attr.Name := ACursor.ReadULeb128; Attr.Form := ACursor.ReadULeb128; if (Attr.Name = 0) and (Attr.Form = 0) then Break; if (AttrCount >= Length(FAttributes)) then SetLength(FAttributes, AttrCount + 8); FAttributes[AttrCount] := Attr; Inc(AttrCount); end; SetLength(FAttributes, AttrCount); end; { TDwarfAbbreviationTable } constructor TDwarfAbbreviationTable.Create; begin inherited; FAbbreviations := TObjectDictionary<Integer, TDwarfAbbreviation>.Create([doOwnsValues]); end; destructor TDwarfAbbreviationTable.Destroy; begin FAbbreviations.Free; inherited; end; function TDwarfAbbreviationTable.Get( const AAbbrevCode: Integer): TDwarfAbbreviation; begin FAbbreviations.TryGetValue(AAbbrevCode, Result); end; procedure TDwarfAbbreviationTable.Load(const ACursor: TDwarfCursor; const AOffset: Integer); var Code: Integer; Abbrev: TDwarfAbbreviation; begin ACursor.Skip(AOffset); while (not ACursor.Eof) do begin Code := ACursor.ReadULeb128; if (Code = 0) then Break; Assert(not FAbbreviations.ContainsKey(Code)); Abbrev := TDwarfAbbreviation.Create; FAbbreviations.Add(Code, Abbrev); Abbrev.Load(ACursor); end; end; { TDwarfCompilationUnit } constructor TDwarfCompilationUnit.Create(const AOwner: TDwarfInfo; const AAbbreviations: TDwarfAbbreviationTable); begin inherited Create; FOwner := AOwner; FAbbreviations := AAbbreviations; FIncludeDirectories := TStringList.Create; FFiles := TList<TDwarfFile>.Create; FLines := TList<TDwarfLine>.Create; end; destructor TDwarfCompilationUnit.Destroy; begin FLines.Free; FFiles.Free; FIncludeDirectories.Free; inherited; end; procedure TDwarfCompilationUnit.Load(const ACursor: TDwarfCursor); var AbbrevCode, StmtList: Integer; Abbrev: TDwarfAbbreviation; Attr: TDwarfAttributeDesc; begin { For now, we only load the top-level DIE for the compilation unit. We don't load any child DIE's (yet) } AbbrevCode := ACursor.ReadULeb128; Abbrev := FAbbreviations.Get(AbbrevCode); if (Abbrev = nil) then raise EDwarfError.CreateFmt('Invalid DWARF abbreviation code (%d)', [AbbrevCode]); if (Abbrev.Tag <> DW_TAG_compile_unit) then raise EDwarfError.Create('DWARF compilation unit must start with a DW_TAG_compile_unit tag'); StmtList := -1; for Attr in Abbrev.Attributes do begin case Attr.Name of DW_AT_producer: FProducer := Attr.StringValue(ACursor, FOwner.FSections.Str); DW_AT_language: FLanguage := Attr.UIntValue(ACursor); DW_AT_name: FName := Attr.StringValue(ACursor, FOwner.FSections.Str); DW_AT_comp_dir: FDirectory := Attr.StringValue(ACursor, FOwner.FSections.Str); DW_AT_stmt_list: StmtList := Attr.UIntValue(ACursor); else Attr.SkipValue(ACursor); end; end; if (StmtList >= 0) then LoadLineNumbers(StmtList); end; procedure TDwarfCompilationUnit.LoadLineNumbers(const AOffset: Integer); var Cursor: TDwarfCursor; Size: Cardinal; Version, PrologueLength, MinimumInstructionLength, OpcodeBase: Integer; LineBase, LineRange, LineAdv, AddrAdv: Integer; DefaultIsStmt: Boolean; ProgramStart, ProgramEnd, Next: PByte; Opcode: Byte; StandardOpcodeLengths: array [0..255] of Byte; Line: TDwarfLine; S: String; F: TDwarfFile; begin if (FOwner.FSections.Line = nil) then raise EDwarfError.Create('A __debug_line DWARF debug section is required'); Cursor := FOwner.FSections.Line; Cursor.Skip(AOffset); Cursor.Require(SizeOf(UInt32)); Size := Cursor.ReadUInt32; if (Size >= $FFFFFFF0) then raise EDwarfError.Create('Only 32-bit DWARF sections are supported'); Cursor.Require(Size); ProgramEnd := Cursor.Cur + Size; Version := Cursor.ReadUInt16; if (Version <> 2) then raise EDwarfError.Create('Only DWARF version 2 is supported for line numbers'); PrologueLength := Cursor.ReadUInt32; ProgramStart := Cursor.Cur + PrologueLength; MinimumInstructionLength := Cursor.ReadUInt8; DefaultIsStmt := (Cursor.ReadUInt8 <> 0); LineBase := Cursor.ReadSInt8; LineRange := Cursor.ReadUInt8; OpcodeBase := Cursor.ReadUInt8; Cursor.Read(StandardOpcodeLengths[1], OpcodeBase - 1); FIncludeDirectories.Clear; FIncludeDirectories.Add(''); // First entry is current directory while (True) do begin S := Cursor.ReadString; if (S = '') then Break; FIncludeDirectories.Add(S); end; FFiles.Clear; FillChar(F, SizeOf(F), 0); FFiles.Add(F); // Files start at index 1 while (True) do begin F.Name := Cursor.ReadString; if (F.Name = '') then Break; F.DirectoryIndex := Cursor.ReadULeb128; F.Time := Cursor.ReadULeb128; F.Size := Cursor.ReadULeb128; FFiles.Add(F); end; { Execute statement program } FLines.Clear; Cursor.Seek(ProgramStart); while (Cursor.Cur < ProgramEnd) do begin Line.Address := 0; Line.FileIndex := 1; Line.Line := 1; Line.Column := 0; if (DefaultIsStmt) then Line.Flags := [TDwarfLineFlag.IsStatement] else Line.Flags := []; while (True) do begin Opcode := Cursor.ReadUInt8; if (Opcode = 0) then begin { Extended opcode } Size := Cursor.ReadULeb128; Next := Cursor.Cur + Size; Opcode := Cursor.ReadUInt8; case Opcode of DW_LNE_end_sequence: begin Include(Line.Flags, TDwarfLineFlag.EndSequence); FLines.Add(Line); Break; end; DW_LNE_set_address: { We only support 64-bit apps } Line.Address := Cursor.ReadUInt64; DW_LNE_define_file: raise EDwarfError.Create('DW_LNE_define_file opcode not supported'); else raise EDwarfError.CreateFmt('Invalid extended opcode (%d)', [Opcode]); end; Cursor.Seek(Next); end else if (Opcode >= OpcodeBase) then begin { Special opcode } Dec(Opcode, OpcodeBase); LineAdv := LineBase + (Opcode mod LineRange); AddrAdv := (Opcode div LineRange) * MinimumInstructionLength; Inc(Line.Address, AddrAdv); Inc(Line.Line, LineAdv); FLines.Add(Line); Line.Flags := Line.Flags - [TDwarfLineFlag.BasicBlock, TDwarfLineFlag.PrologueEnd, TDwarfLineFlag.EpilogueBegin]; end else begin { Standard opcode } case Opcode of DW_LNS_copy: begin FLines.Add(Line); Line.Flags := Line.Flags - [TDwarfLineFlag.BasicBlock, TDwarfLineFlag.PrologueEnd, TDwarfLineFlag.EpilogueBegin]; end; DW_LNS_advance_pc: Inc(Line.Address, Cursor.ReadULeb128 * Cardinal(MinimumInstructionLength)); DW_LNS_advance_line: Inc(Line.Line, Cursor.ReadSLeb128); DW_LNS_set_file: Line.FileIndex := Cursor.ReadULeb128; DW_LNS_set_column: Line.Column := Cursor.ReadULeb128; DW_LNS_negate_stmt: if (TDwarfLineFlag.IsStatement in Line.Flags) then Exclude(Line.Flags, TDwarfLineFlag.IsStatement) else Include(Line.Flags, TDwarfLineFlag.IsStatement); DW_LNS_set_basic_block: Include(Line.Flags, TDwarfLineFlag.BasicBlock); DW_LNS_const_add_pc: Inc(Line.Address, MinimumInstructionLength * ((255 - OpcodeBase) div LineRange)); DW_LNS_fixed_advance_pc: Inc(Line.Address, Cursor.ReadUInt16); DW_LNS_set_prologue_end: Include(Line.Flags, TDwarfLineFlag.PrologueEnd); DW_LNS_set_epilogue_begin: Include(Line.Flags, TDwarfLineFlag.EpilogueBegin); DW_LNS_set_isa: Cursor.ReadULeb128; // Skip ISA else { Skip unknown/unsupported opcode } Cursor.Skip(StandardOpcodeLengths[Opcode]); end; end; end; end; end; { TDwarfInfo } procedure TDwarfInfo.Clear; begin FCompilationUnits.Clear; end; constructor TDwarfInfo.Create; begin inherited; FCompilationUnits := TObjectList<TDwarfCompilationUnit>.Create; FAbbreviationTables := TObjectDictionary<Integer, TDwarfAbbreviationTable>.Create([doOwnsValues]); end; destructor TDwarfInfo.Destroy; begin FAbbreviationTables.Free; FCompilationUnits.Free; inherited; end; procedure TDwarfInfo.Load(const ASections: TDwarfSections); begin Clear; FSections := ASections; // Keep data alive if (ASections.Abbrev = nil) then raise EDwarfError.Create('A __debug_abbrev DWARF debug section is required'); if (ASections.Info = nil) then raise EDwarfError.Create('A __debug_info DWARF debug section is required'); if (ASections.Line = nil) then raise EDwarfError.Create('A __debug_line DWARF debug section is required'); if (ASections.Str = nil) then raise EDwarfError.Create('A __debug_str DWARF debug section is required'); LoadInfo(ASections.Info); end; procedure TDwarfInfo.LoadInfo(const ACursor: TDwarfCursor); var Size: Cardinal; Version, AbbrevOffset: Integer; Next: PByte; CU: TDwarfCompilationUnit; Abbrevs: TDwarfAbbreviationTable; begin while (not ACursor.Eof) do begin ACursor.Require(SizeOf(UInt32)); Size := ACursor.ReadUInt32; if (Size >= $FFFFFFF0) then raise EDwarfError.Create('Only 32-bit DWARF sections are supported'); ACursor.Require(Size); Next := ACursor.Cur + Size; Version := ACursor.ReadUInt16; if (Version < 2) or (Version > 5) then raise EDwarfError.Create('Only DWARF versions 2-5 are supported'); AbbrevOffset := ACursor.ReadUInt32; if (ACursor.ReadUInt8 <> 8) then raise EDwarfError.Create('Only 64-bit apps are supported'); if (not FAbbreviationTables.TryGetValue(AbbrevOffset, Abbrevs)) then begin Abbrevs := TDwarfAbbreviationTable.Create; FAbbreviationTables.Add(AbbrevOffset, Abbrevs); Abbrevs.Load(FSections.Abbrev, AbbrevOffset); end; CU := TDwarfCompilationUnit.Create(Self, Abbrevs); FCompilationUnits.Add(CU); CU.Load(ACursor); ACursor.Seek(Next); end; end; end.
{ LzhV.Pas: Unit to view contents of .LZH files. By Steve Wierenga. Released to the Public Domain. } Unit Lzhv; (**) INTERFACE (**) Uses Dos,Crt; Type Fileheadertype = record { Lzh file header } Headsize,Headchk : byte; HeadID : packed array[1..5] of char; Packsize,Origsize,Filetime : longint; Attr : word; filename : String[12]; f32 : PathStr; dt : DateTime; end; var Fh : fileheadertype; Fha: array[1..sizeof(fileheadertype)] of byte absolute fh; crc: word; { CRC value } crcbuf : array[1..2] of byte absolute CRC; crc_table : array[0..255] of word; { Table of CRC's } infile : file; { File to be processed } registered : boolean; { Is registered? } Procedure Make_crc_table; { Create table of CRC's } Function Mksum: byte; { Get CheckSum } Procedure ViewLzh(LZHfile : string); { View the file } Function GAN(LZHfile: String): string; { Get the LZH filename } (**) IMPLEMENTATION (**) Procedure Terminate; { Exit the program } Begin Write('ARCHPEEK could not find specified file. Aborting...'); Halt; End; Procedure Make_crc_table; var i,index,ax : word; carry : boolean; begin index := 0; repeat ax := index; for i := 1 to 8 do begin carry := odd(ax); ax := ax shr 1; if carry then ax := ax xor $A001; end; crc_table[index] := ax; inc(index); until index > 255; end; { use this to calculate the CRC value of the original file } { call this function afer reading every byte from the file } Procedure calccrc(data : byte); var index : integer; begin crcbuf[1] := crcbuf[1] xor data; index := crcbuf[1]; crc := crc shr 8; crc := crc xor crc_table[index]; end; Function Mksum : byte; {calculate check sum for file header } var i : integer; b : byte; begin b := 0; for i := 3 to fh.headsize+2 do b := b+fha[i]; mksum := b; end; Procedure viewlzh(LZHfile : string); { View the LZH file } var l1,l2,oldfilepos,a,b,a1,b1,totalorig,totalpack : longint; count,z : integer; numread,i,year1,month1,day1,hour1,min1,sec1 : word; s1 : string[50]; s2 : string[20]; l : string[80]; sss : string; begin registered := false; { Unregistered } if not registered then { Registered? } begin Writeln('ArchPeek 0.01Alpha [UNREGISTERED] Copyright 1993 Steve Wierenga'); Delay(200); end; assign(infile,LZHfile); {$I-} reset(infile,1); { Open LZH file } {$I+} If IOResult <> 0 then Terminate; { Specified file exists? } sss := GAN(LZHFile); { Get filename of LZH file } Writeln( 'Lzh FileName: ',sss); WriteLn( ' Name Length Size Saved', ' Date Time '); WriteLn( ' ____________________________________________________', '______'); oldfilepos := 0; { Init variables } count := 1; z := 0; a1 := 0; repeat z := z + 1; seek(infile,oldfilepos); { Goto start of file} blockread(infile,fha,sizeof(fileheadertype),numread); { Read fileheader} oldfilepos := oldfilepos+fh.headsize+2+fh.packsize; { Where are we? } i := Mksum; { Get the checksum } if fh.headsize <> 0 then begin if i <> fh.headchk then begin Writeln('Error in file. Unable to read. Aborting...'); Close(infile); Exit; end; Case Length(Fh.FileName) Of { Straigthen out string } 1 : Fh.FileName := Fh.FileName + ' '; 2 : Fh.FileName := Fh.FileName + ' '; 3 : Fh.FileName := Fh.FileName + ' '; 4 : Fh.FileName := Fh.FileName + ' '; 5 : Fh.FileName := Fh.FileName + ' '; 6 : Fh.FileName := Fh.FileName + ' '; 7 : Fh.FileName := Fh.FileName + ' '; 8 : Fh.FileName := Fh.FileName + ' '; 9 : Fh.FileName := Fh.FileName + ' '; 10 : Fh.FileName := Fh.FileName + ' '; 11 : Fh.FileName := Fh.FileName + ' '; 12 : Fh.FileName := Fh.FileName + ''; End; UnPackTime(Fh.FileTime,Fh.DT); a1 := a1 + Fh.OrigSize; { Increase Uncompressed Size } Write( ' ',fh.filename:2,fh.origsize:9,fh.packSize:10, (100-fh.packSize/fh.origSize*100):5:0,'%'); { Display info } Case fh.dt.month of { Get date and time } 1..9 : Write( '0':4,fh.dt.month); 10..12 : Write( ' ',fh.dt.month:4); End; Write( '/'); Case fh.dt.day of 1..9 : Write( '0',fh.dt.day); 10..31 : Write( fh.dt.day); End; Write( '/'); Case fh.dt.year of 1980 : Write( '80'); 1981 : Write( '81'); 1982 : Write( '82'); 1983 : Write( '83'); 1984 : Write( '84'); 1985 : Write( '85'); 1986 : Write( '86'); 1987 : Write( '87'); 1988 : Write( '88'); 1989 : Write( '89'); 1990 : Write( '90'); 1991 : Write( '91'); 1992 : Write( '92'); 1993 : Write( '93'); 1994 : Write( '94'); 1995 : Write( '95'); 1996 : Write( '96'); End; Case fh.dt.hour of 0..9 : Write( '0':3,fh.dt.hour,':'); 10..23 : Write( ' ',fh.dt.hour:3,':'); End; Case fh.dt.min of 0..9 : Write( '0',fh.dt.min,':'); 10..59 : Write( fh.dt.min,':'); End; Case fh.dt.sec of 0..9 : Writeln( '0',fh.dt.sec); 10..59 : Writeln( fh.dt.sec); End; end; until (fh.headsize=0); Writeln( ' ======================================================', '====='); GetFTime(infile,l1); UnPackTime(l1,fh.dt); Write( ' ',z,' Files ',a1:12,FileSize(infile):10, (100-FileSize(infile)/a1*100):5:0,'%'); Case fh.dt.month of 1..9 : Write( '0':4,fh.dt.month); 10..12 : Write( ' ',fh.dt.month:4); End; Write( '/'); Case fh.dt.day of 1..9 : Write( '0',fh.dt.day); 10..31 : Write( fh.dt.day); End; Write( '/'); Case fh.dt.year of 1980 : Write( '80'); 1981 : Write( '81'); 1982 : Write( '82'); 1983 : Write( '83'); 1984 : Write( '84'); 1985 : Write( '85'); 1986 : Write( '86'); 1987 : Write( '87'); 1988 : Write( '88'); 1989 : Write( '89'); 1990 : Write( '90'); 1991 : Write( '91'); 1992 : Write( '92'); 1993 : Write( '93'); 1994 : Write( '94'); 1995 : Write( '95'); 1996 : Write( '96'); End; Case fh.dt.hour of 0..9 : Write( '0':3,fh.dt.hour,':'); 10..23 : Write( ' ',fh.dt.hour:3,':'); End; Case fh.dt.min of 0..9 : Write( '0',fh.dt.min,':'); 10..59 : Write( fh.dt.min,':'); End; Case fh.dt.sec of 0..9 : Writeln( '0',fh.dt.sec); 10..59 : Writeln( fh.dt.sec); End; End; FUNCTION GAN(LZHfile : String): string; Var Dir : DirStr; Name : NameStr; Exts : ExtStr; Begin FSplit(LZHFile,Dir,Name,Exts); GAN := Name + Exts; End; End.
//************************************************************************************************** // // Unit uMisc // unit for the VCL Styles for Notepad++ // https://github.com/RRUZ/vcl-styles-plugins // // The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); // you may not use this file except in compliance with the License. You may obtain a copy of the // License at http://www.mozilla.org/MPL/ // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either express or implied. See the License for the specific language governing rights // and limitations under the License. // // The Original Code is uMisc.pas. // // The Initial Developer of the Original Code is Rodrigo Ruz V. // // Portions created by Rodrigo Ruz V. are Copyright (C) 2014-2021 Rodrigo Ruz V. // All Rights Reserved. // //************************************************************************************************** unit uMisc; interface {.$DEFINE ENABLELOG} uses Winapi.Windows, Vcl.Graphics, System.Rtti, System.Types; type TSettings =class private FVclStyle: string; public property VclStyle: string read FVclStyle write FVclStyle; end; function GetFileVersion(const FileName: string): string; function IsAppRunning(const FileName: string): boolean; function GetLocalAppDataFolder: string; function GetTempDirectory: string; procedure MsgBox(const Msg: string); procedure CreateArrayBitmap(Width,Height:Word;Colors: Array of TColor;var bmp: TBitmap); function GetSpecialFolder(const CSIDL: integer): string; function IsUACEnabled: Boolean; procedure RunAsAdmin(const FileName, Params: string; hWnd: HWND = 0); function CurrentUserIsAdmin: Boolean; function GetModuleName: string; procedure GetAssocAppByExt(const FileName:string; var ExeName, FriendlyAppName: string); procedure ReadSettings(Settings: TSettings;const FileName: string); procedure WriteSettings(const Settings: TSettings;const FileName: string); function GetUNCNameEx(const lpLocalPath: string): string; function LocalPathToFileURL(const pszPath: string): string; function IsVistaOrLater: Boolean; implementation uses ActiveX, ShlObj, PsAPI, tlhelp32, ComObj, CommCtrl, StrUtils, ShellAPI, Classes, Dialogs, ShLwApi, System.UITypes, Registry, TypInfo, IOUtils, UxTheme, IniFiles, SysUtils; Const SECURITY_NT_AUTHORITY: TSIDIdentifierAuthority = (Value: (0, 0, 0, 0, 0, 5)); SECURITY_BUILTIN_DOMAIN_RID = $00000020; DOMAIN_ALIAS_RID_ADMINS = $00000220; DOMAIN_ALIAS_RID_USERS = $00000221; DOMAIN_ALIAS_RID_GUESTS = $00000222; DOMAIN_ALIAS_RID_POWER_USERS= $00000223; type TAssocStr = ( ASSOCSTR_COMMAND = 1, ASSOCSTR_EXECUTABLE, ASSOCSTR_FRIENDLYDOCNAME, ASSOCSTR_FRIENDLYAPPNAME, ASSOCSTR_NOOPEN, ASSOCSTR_SHELLNEWVALUE, ASSOCSTR_DDECOMMAND, ASSOCSTR_DDEIFEXEC, ASSOCSTR_DDEAPPLICATION, ASSOCSTR_DDETOPIC ); const AssocStrDisplaystrings: array [ASSOCSTR_COMMAND..ASSOCSTR_DDETOPIC] of string = ( 'ASSOCSTR_COMMAND', 'ASSOCSTR_EXECUTABLE', 'ASSOCSTR_FRIENDLYDOCNAME', 'ASSOCSTR_FRIENDLYAPPNAME', 'ASSOCSTR_NOOPEN', 'ASSOCSTR_SHELLNEWVALUE', 'ASSOCSTR_DDECOMMAND', 'ASSOCSTR_DDEIFEXEC', 'ASSOCSTR_DDEAPPLICATION', 'ASSOCSTR_DDETOPIC' ); function IsVistaOrLater: Boolean; begin Result:= (Win32MajorVersion >= 6); end; function CheckTokenMembership(TokenHandle: THandle; SidToCheck: PSID; var IsMember: BOOL): BOOL; stdcall; external advapi32; function GetComputerName: string; var nSize: Cardinal; begin nSize := MAX_COMPUTERNAME_LENGTH + 1; Result := StringOfChar(#0, nSize); Winapi.Windows.GetComputerName(PChar(Result), nSize); SetLength(Result, nSize); end; function GetUNCNameEx(const lpLocalPath: string): string; begin if GetDriveType(PChar(Copy(lpLocalPath,1,3)))=DRIVE_REMOTE then Result:=ExpandUNCFileName(lpLocalPath) else Result := '\\' + GetComputerName + '\' + StringReplace(lpLocalPath,':','$', [rfReplaceAll]); end; function LocalPathToFileURL(const pszPath: string): string; var pszUrl: string; pcchUrl: DWORD; begin Result := ''; pcchUrl := Length('file:///' + pszPath + #0); SetLength(pszUrl, pcchUrl); if UrlCreateFromPath(PChar(pszPath), PChar(pszUrl), @pcchUrl, 0) = S_OK then Result := pszUrl; end; procedure ReadSettings(Settings: TSettings;const FileName: string); var iniFile: TIniFile; LCtx: TRttiContext; LProp: TRttiProperty; BooleanValue: Boolean; StringValue: string; begin iniFile := TIniFile.Create(FileName); try LCtx:=TRttiContext.Create; try for LProp in LCtx.GetType(TypeInfo(TSettings)).GetProperties do if LProp.PropertyType.TypeKind=tkEnumeration then begin BooleanValue:= iniFile.ReadBool('Global', LProp.Name, True); LProp.SetValue(Settings, BooleanValue); end else if (LProp.PropertyType.TypeKind=tkString) or (LProp.PropertyType.TypeKind=tkUString) then begin StringValue:= iniFile.ReadString('Global', LProp.Name, ''); LProp.SetValue(Settings, StringValue); end; finally LCtx.Free; end; finally iniFile.Free; end; end; procedure WriteSettings(const Settings: TSettings;const FileName: string); var iniFile: TIniFile; LCtx: TRttiContext; LProp: TRttiProperty; BooleanValue: Boolean; StringValue: string; begin iniFile := TIniFile.Create(FileName); try LCtx:=TRttiContext.Create; try for LProp in LCtx.GetType(TypeInfo(TSettings)).GetProperties do if LProp.PropertyType.TypeKind=tkEnumeration then begin BooleanValue:= LProp.GetValue(Settings).AsBoolean; iniFile.WriteBool('Global', LProp.Name, BooleanValue); end else if (LProp.PropertyType.TypeKind=tkString) or (LProp.PropertyType.TypeKind=tkUString) then begin StringValue:= LProp.GetValue(Settings).AsString; iniFile.WriteString('Global', LProp.Name, StringValue); end; finally LCtx.Free; end; finally iniFile.Free; end; end; procedure GetAssocAppByExt(const FileName:string; var ExeName, FriendlyAppName: string); var pszOut: array [0..1024] of Char; pcchOut: DWord; begin ExeName:=''; FriendlyAppName:=''; pcchOut := Sizeof(pszOut); ZeroMemory(@pszOut, SizeOf(pszOut)); OleCheck( AssocQueryString(ASSOCF_NOTRUNCATE, ASSOCSTR(ASSOCSTR_EXECUTABLE), LPCWSTR(ExtractFileExt(FileName)), 'open', pszOut, @pcchOut)); if pcchOut>0 then SetString(ExeName, PChar(@pszOut[0]), pcchOut-1); pcchOut := Sizeof(pszOut); ZeroMemory(@pszOut, SizeOf(pszOut)); OleCheck( AssocQueryString(ASSOCF_NOTRUNCATE, ASSOCSTR(ASSOCSTR_FRIENDLYAPPNAME), LPCWSTR(ExtractFileExt(FileName)), 'open', pszOut, @pcchOut)); if pcchOut>0 then SetString(FriendlyAppName, PChar(@pszOut[0]), pcchOut-1); end; function GetModuleName: string; var lpFilename: array[0..MAX_PATH] of Char; begin ZeroMemory(@lpFilename, SizeOf(lpFilename)); GetModuleFileName(hInstance, lpFilename, MAX_PATH); Result := lpFilename; end; function IsUACEnabled: Boolean; var LRegistry: TRegistry; begin Result := False; if CheckWin32Version(6, 0) then begin LRegistry := TRegistry.Create; try LRegistry.RootKey := HKEY_LOCAL_MACHINE; if LRegistry.OpenKeyReadOnly('SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System') then Exit(LRegistry.ValueExists('EnableLUA') and LRegistry.ReadBool('EnableLUA')); finally LRegistry.Free; end; end; end; function UserInGroup(Group :DWORD): Boolean; var pIdentifierAuthority :TSIDIdentifierAuthority; pSid: Winapi.Windows.PSID; IsMember: BOOL; begin pIdentifierAuthority := SECURITY_NT_AUTHORITY; Result := AllocateAndInitializeSid(pIdentifierAuthority,2, SECURITY_BUILTIN_DOMAIN_RID, Group, 0, 0, 0, 0, 0, 0, pSid); try if Result then if not CheckTokenMembership(0, pSid, IsMember) then //passing 0 means which the function will be use the token of the calling thread. Result:= False else Result:=IsMember; finally FreeSid(pSid); end; end; function CurrentUserIsAdmin: Boolean; begin Result:=UserInGroup(DOMAIN_ALIAS_RID_ADMINS); end; procedure RunAsAdmin(const FileName, Params: string; hWnd: HWND = 0); var sei: TShellExecuteInfo; begin ZeroMemory(@sei, SizeOf(sei)); sei.cbSize := SizeOf(sei); sei.Wnd := hWnd; sei.fMask := SEE_MASK_FLAG_DDEWAIT or SEE_MASK_FLAG_NO_UI; sei.lpVerb := 'runas'; sei.lpFile := PChar(FileName); sei.lpParameters := PChar(Params); sei.nShow := SW_SHOWNORMAL; if not ShellExecuteEx(@sei) then RaiseLastOSError; end; function GetSpecialFolder(const CSIDL: integer): string; var lpszPath: PWideChar; begin lpszPath := StrAlloc(MAX_PATH); try ZeroMemory(lpszPath, MAX_PATH); if SHGetSpecialFolderPath(0, lpszPath, CSIDL, False) then Result := lpszPath else Result := ''; finally StrDispose(lpszPath); end; end; procedure MsgBox(const Msg: string); begin MessageDlg(Msg, mtInformation, [mbOK], 0); end; function GetTempDirectory: string; var lpBuffer: array[0..MAX_PATH] of Char; begin GetTempPath(MAX_PATH, @lpBuffer); Result := StrPas(lpBuffer); end; function GetLocalAppDataFolder: string; const CSIDL_LOCAL_APPDATA = $001C; var ppMalloc: IMalloc; ppidl: PItemIdList; begin ppidl := nil; try if SHGetMalloc(ppMalloc) = S_OK then begin SHGetSpecialFolderLocation(0, CSIDL_LOCAL_APPDATA, ppidl); SetLength(Result, MAX_PATH); if not SHGetPathFromIDList(ppidl, PChar(Result)) then RaiseLastOSError; SetLength(Result, lStrLen(PChar(Result))); end; finally if ppidl <> nil then ppMalloc.Free(ppidl); end; end; function ProcessFileName(dwProcessId: DWORD): string; var hModule: Cardinal; begin Result := ''; hModule := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, dwProcessId); if hModule <> 0 then try SetLength(Result, MAX_PATH); if GetModuleFileNameEx(hModule, 0, PChar(Result), MAX_PATH) > 0 then SetLength(Result, StrLen(PChar(Result))) else Result := ''; finally CloseHandle(hModule); end; end; function IsAppRunning(const FileName: string): boolean; var hSnapshot: Cardinal; EntryParentProc: TProcessEntry32; begin Result := False; hSnapshot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if hSnapshot = INVALID_HANDLE_VALUE then exit; try EntryParentProc.dwSize := SizeOf(EntryParentProc); if Process32First(hSnapshot, EntryParentProc) then repeat if CompareText(ExtractFileName(FileName), EntryParentProc.szExeFile) = 0 then if CompareText(ProcessFileName(EntryParentProc.th32ProcessID), FileName) = 0 then begin Result := True; break; end; until not Process32Next(hSnapshot, EntryParentProc); finally CloseHandle(hSnapshot); end; end; function GetFileVersion(const FileName: string): string; var FSO: OleVariant; begin FSO := CreateOleObject('Scripting.FileSystemObject'); Result := FSO.GetFileVersion(FileName); end; procedure ExtractIconFile(Icon: TIcon; const Filename: string;IconType: Cardinal); var FileInfo: TShFileInfo; begin if FileExists(Filename) then begin FillChar(FileInfo, SizeOf(FileInfo), 0); SHGetFileInfo(PChar(Filename), 0, FileInfo, SizeOf(FileInfo), SHGFI_ICON or IconType); if FileInfo.hIcon <> 0 then Icon.Handle:=FileInfo.hIcon; end; end; procedure ExtractBitmapFile(Bmp: TBitmap; const Filename: string;IconType: Cardinal); var Icon: TIcon; begin Icon:=TIcon.Create; try ExtractIconFile(Icon, Filename, SHGFI_SMALLICON); Bmp.PixelFormat:=pf24bit; Bmp.Width := Icon.Width; Bmp.Height := Icon.Height; Bmp.Canvas.Draw(0, 0, Icon); finally Icon.Free; end; end; procedure ExtractBitmapFile32(Bmp: TBitmap; const Filename: string;IconType: Cardinal); var Icon: TIcon; begin Icon:=TIcon.Create; try ExtractIconFile(Icon, Filename, SHGFI_SMALLICON); Bmp.PixelFormat:=pf32bit; { Bmp.Width := Icon.Width; Bmp.Height := Icon.Height; Bmp.Canvas.Draw(0, 0, Icon); } Bmp.Assign(Icon); finally Icon.Free; end; end; procedure CreateArrayBitmap(Width,Height:Word;Colors: Array of TColor;var bmp: TBitmap); Var i: integer; w: integer; begin bmp.PixelFormat:=pf24bit; bmp.Width:=Width; bmp.Height:=Height; bmp.Canvas.Brush.Color := clBlack; bmp.Canvas.FillRect(Rect(0,0, Width, Height)); w :=(Width-2) div (High(Colors)+1); for i:=0 to High(Colors) do begin bmp.Canvas.Brush.Color := Colors[i]; //bmp.Canvas.FillRect(Rect((w*i),0, w*(i+1), Height)); bmp.Canvas.FillRect(Rect((w*i)+1,1, w*(i+1)+1, Height-1)) end; end; procedure ShrinkImage32(const SourceBitmap, StretchedBitmap: TBitmap; Scale: Double); var ScanLines: array of PByteArray; DestLine: PByteArray; CurrentLine: PByteArray; DestX, DestY: Integer; DestA, DestR, DestB, DestG: Integer; SourceYStart, SourceXStart: Integer; SourceYEnd, SourceXEnd: Integer; AvgX, AvgY: Integer; ActualX: Integer; PixelsUsed: Integer; DestWidth, DestHeight: Integer; begin DestWidth := StretchedBitmap.Width; DestHeight := StretchedBitmap.Height; SetLength(ScanLines, SourceBitmap.Height); for DestY := 0 to DestHeight - 1 do begin SourceYStart := Round(DestY / Scale); SourceYEnd := Round((DestY + 1) / Scale) - 1; if SourceYEnd >= SourceBitmap.Height then SourceYEnd := SourceBitmap.Height - 1; { Grab the destination pixels } DestLine := StretchedBitmap.ScanLine[DestY]; for DestX := 0 to DestWidth - 1 do begin { Calculate the RGB value at this destination pixel } SourceXStart := Round(DestX / Scale); SourceXEnd := Round((DestX + 1) / Scale) - 1; DestR := 0; DestB := 0; DestG := 0; DestA := 0; PixelsUsed := 0; if SourceXEnd >= SourceBitmap.Width then SourceXEnd := SourceBitmap.Width - 1; for AvgY := SourceYStart to SourceYEnd do begin if ScanLines[AvgY] = nil then ScanLines[AvgY] := SourceBitmap.ScanLine[AvgY]; CurrentLine := ScanLines[AvgY]; for AvgX := SourceXStart to SourceXEnd do begin ActualX := AvgX*4; { 4 bytes per pixel } DestR := DestR + CurrentLine[ActualX]; DestB := DestB + CurrentLine[ActualX+1]; DestG := DestG + CurrentLine[ActualX+2]; DestA := DestA + CurrentLine[ActualX+3]; Inc(PixelsUsed); end; end; { pf32bit = 4 bytes per pixel } ActualX := DestX*4; DestLine[ActualX] := Round(DestR / PixelsUsed); DestLine[ActualX+1] := Round(DestB / PixelsUsed); DestLine[ActualX+2] := Round(DestG / PixelsUsed); DestLine[ActualX+3] := Round(DestA / PixelsUsed); end; end; end; procedure EnlargeImage32(const SourceBitmap, StretchedBitmap: TBitmap; Scale: Double); var ScanLines: array of PByteArray; DestLine: PByteArray; CurrentLine: PByteArray; DestX, DestY: Integer; DestA, DestR, DestB, DestG: Double; SourceYStart, SourceXStart: Integer; SourceYPos: Integer; AvgX, AvgY: Integer; ActualX: Integer; { Use a 4 pixels for enlarging } XWeights, YWeights: array[0..1] of Double; PixelWeight: Double; DistFromStart: Double; DestWidth, DestHeight: Integer; begin DestWidth := StretchedBitmap.Width; DestHeight := StretchedBitmap.Height; Scale := StretchedBitmap.Width / SourceBitmap.Width; SetLength(ScanLines, SourceBitmap.Height); for DestY := 0 to DestHeight - 1 do begin DistFromStart := DestY / Scale; SourceYStart := Round(DistFromSTart); YWeights[1] := DistFromStart - SourceYStart; if YWeights[1] < 0 then YWeights[1] := 0; YWeights[0] := 1 - YWeights[1]; DestLine := StretchedBitmap.ScanLine[DestY]; for DestX := 0 to DestWidth - 1 do begin { Calculate the RGB value at this destination pixel } DistFromStart := DestX / Scale; if DistFromStart > (SourceBitmap.Width - 1) then DistFromStart := SourceBitmap.Width - 1; SourceXStart := Round(DistFromStart); XWeights[1] := DistFromStart - SourceXStart; if XWeights[1] < 0 then XWeights[1] := 0; XWeights[0] := 1 - XWeights[1]; { Average the four nearest pixels from the source mapped point } DestR := 0; DestB := 0; DestG := 0; DestA := 0; for AvgY := 0 to 1 do begin SourceYPos := SourceYStart + AvgY; if SourceYPos >= SourceBitmap.Height then SourceYPos := SourceBitmap.Height - 1; if ScanLines[SourceYPos] = nil then ScanLines[SourceYPos] := SourceBitmap.ScanLine[SourceYPos]; CurrentLine := ScanLines[SourceYPos]; for AvgX := 0 to 1 do begin if SourceXStart + AvgX >= SourceBitmap.Width then SourceXStart := SourceBitmap.Width - 1; ActualX := (SourceXStart + AvgX) * 4; { 4 bytes per pixel } { Calculate how heavy this pixel is based on how far away it is from the mapped pixel } PixelWeight := XWeights[AvgX] * YWeights[AvgY]; DestR := DestR + CurrentLine[ActualX] * PixelWeight; DestB := DestB + CurrentLine[ActualX+1] * PixelWeight; DestG := DestG + CurrentLine[ActualX+2] * PixelWeight; DestA := DestA + CurrentLine[ActualX+3] * PixelWeight; end; end; ActualX := DestX * 4; { 4 bytes per pixel } DestLine[ActualX] := Round(DestR); DestLine[ActualX+1] := Round(DestB); DestLine[ActualX+2] := Round(DestG); DestLine[ActualX+3] := Round(DestA); end; end; end; procedure ScaleImage32(const SourceBitmap, ResizedBitmap: TBitmap; const ScaleAmount: Double); var DestWidth, DestHeight: Integer; begin DestWidth := Round(SourceBitmap.Width * ScaleAmount); DestHeight := Round(SourceBitmap.Height * ScaleAmount); SourceBitmap.PixelFormat := pf32bit; ResizedBitmap.Width := DestWidth; ResizedBitmap.Height := DestHeight; //ResizedBitmap.Canvas.Brush.Color := Vcl.Graphics.clNone; //ResizedBitmap.Canvas.FillRect(Rect(0, 0, DestWidth, DestHeight)); ResizedBitmap.PixelFormat := pf32bit; if ResizedBitmap.Width < SourceBitmap.Width then ShrinkImage32(SourceBitmap, ResizedBitmap, ScaleAmount) else EnlargeImage32(SourceBitmap, ResizedBitmap, ScaleAmount); end; end.
unit UFromMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, ExtCtrls, ComCtrls, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, StdCtrls, ADODB, cxLookAndFeels, ImgList; type TfDemoFormMain = class(TForm) TableView1: TcxGridDBTableView; Level1: TcxGridLevel; cxGrid1: TcxGrid; StatusBar1: TStatusBar; wPanel: TPanel; BtnConn: TButton; Edit_SQL: TLabeledEdit; BtnOK: TButton; cxLookAndFeel1: TcxLookAndFeelController; LTv1: TTreeView; Splitter1: TSplitter; ImageList1: TImageList; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure BtnConnClick(Sender: TObject); procedure LTv1DblClick(Sender: TObject); procedure BtnOKClick(Sender: TObject); procedure TableView1DblClick(Sender: TObject); private { Private declarations } procedure LockMainForm(const nLock: Boolean); procedure FormLoadConfig; procedure FormSaveConfig; function ActiveEntity(var nProg,nEntity: string): Boolean; {*活动节点*} function GetProgNode(const nProgID: string): TTreeNode; {*实体节点*} procedure BuildEntityTree; {*实体列表*} public { Public declarations } end; var fDemoFormMain: TfDemoFormMain; implementation {$R *.dfm} uses IniFiles, ULibFun, UMgrDataDict, UDataModule, UFormConn, UFormWait, USysFun, USysConst, USysDataDict; //------------------------------------------------------------------------------ procedure TfDemoFormMain.FormCreate(Sender: TObject); begin InitSystemEnvironment; InitGlobalVariant(gPath, gPath + sFormConfig, gPath + sFormConfig, gPath + sDBConfig); PopMsgOnOff(False); LoadSysParameter; FormLoadConfig; LockMainForm(True); end; procedure TfDemoFormMain.FormClose(Sender: TObject; var Action: TCloseAction); begin FormSaveConfig; end; procedure TfDemoFormMain.FormLoadConfig; var nInt: integer; nIni: TIniFile; begin nIni := TIniFile.Create(gPath + sFormConfig); try LoadFormConfig(Self); Edit_SQL.Text := nIni.ReadString(Name, 'LastSQL', ''); nInt := nIni.ReadInteger(Name, 'TreeWidth', 0); if nInt > 20 then LTv1.Width := nInt; finally nIni.Free; end; end; procedure TfDemoFormMain.FormSaveConfig; var nIni: TIniFile; begin nIni := TIniFile.Create(gPath + sFormConfig); try SaveFormConfig(Self); nIni.WriteString(Name, 'LastSQL', Edit_SQL.Text); nIni.WriteInteger(Name, 'TreeWidth', LTv1.Width); finally nIni.Free; end; end; procedure TfDemoFormMain.LockMainForm(const nLock: Boolean); begin BtnOK.Enabled := not nLock; end; //Desc: 连接测试回调 function TestConn(const nConnStr: string): Boolean; begin FDM.ADOConn.Close; FDM.ADOConn.ConnectionString := nConnStr; FDM.ADOConn.Open; Result := FDM.ADOConn.Connected; end; //------------------------------------------------------------------------------ //Desc: 搜索ProgID为nProgID的节点 function TfDemoFormMain.GetProgNode(const nProgID: string): TTreeNode; var nList: TList; nInt: integer; i,nCount: integer; begin Result := nil; nCount := LTv1.Items.Count - 1; nList := gSysEntityManager.ProgList; for i:=0 to nCount do begin nInt := LTv1.Items[i].StateIndex; with PEntityItemData(nList[nInt])^ do if CompareText(nProgID, FProgID) = 0 then begin Result := LTv1.Items[i]; Break; end; end; end; //Desc: 构建实体列表 procedure TfDemoFormMain.BuildEntityTree; var nStr: string; nList: TList; nNode: TTreeNode; i,nCount: integer; begin LTv1.Items.BeginUpdate; try LTv1.Items.Clear; if not gSysEntityManager.LoadProgList then Exit; nList := gSysEntityManager.ProgList; nCount := nList.Count - 1; for i:=0 to nCount do with PEntityItemData(nList[i])^ do begin nStr := '%s[ %s ]'; if FEntity = '' then begin nNode := nil; nStr := Format(nStr, [FTitle, FProgID]); end else begin nNode := GetProgNode(FProgID); nStr := Format(nStr, [FTitle, FEntity]); end; with LTv1.Items.AddChild(nNode, nStr) do begin StateIndex := i; if nNode = nil then ImageIndex := 7 else ImageIndex := 8; SelectedIndex := ImageIndex; end; end; finally if LTv1.Items.Count < 1 then begin LockMainForm(False); with LTv1.Items.AddChild(nil, '没有实体') do begin ImageIndex := 7; SelectedIndex := ImageIndex; end; end else begin LockMainForm(False); LTv1.FullExpand; end; LTv1.Items.EndUpdate; end; end; //------------------------------------------------------------------------------ //Desc: 连接数据库 procedure TfDemoFormMain.BtnConnClick(Sender: TObject); var nStr: string; begin if ShowConnectDBSetupForm(TestConn) then nStr := BuildConnectDBStr else Exit; ShowWaitForm(Self, '连接数据库'); try try FDM.ADOConn.Connected := False; FDM.ADOConn.ConnectionString := nStr; FDM.ADOConn.Connected := True; LockMainForm(not FDM.ADOConn.Connected); StatusBar1.SimpleText := ' ※.' + nStr; BuildEntityTree; except ShowDlg('连接数据库失败,配置错误或远程无响应', '', Handle); Exit; end; finally CloseWaitForm; end; end; //Desc: 获取活动实体标识 function TfDemoFormMain.ActiveEntity(var nProg,nEntity: string): Boolean; var nIdx: integer; begin nProg := ''; nEntity := ''; if Assigned(LTv1.Selected) then begin nIdx := LTv1.Selected.StateIndex; if (nIdx > -1) and (nIdx < gSysEntityManager.ProgList.Count) then with PEntityItemData(gSysEntityManager.ProgList[nIdx])^ do begin nProg := FProgID; nEntity := FEntity; end; end; Result := nProg <> ''; end; //Desc: 切换实体 procedure TfDemoFormMain.LTv1DblClick(Sender: TObject); var nProg,nEntity: string; begin if ActiveEntity(nProg, nEntity) and (nEntity <> '') then begin gSysParam.FProgID := nProg; gSysEntityManager.ProgID := nProg; gSysEntityManager.BuildViewColumn(TableView1, nEntity); end; end; //Desc: 载入数据 procedure TfDemoFormMain.BtnOKClick(Sender: TObject); begin FDM.SQLQuery.Close; FDM.SQLQuery.SQL.Text := Edit_SQL.Text; FDM.SQLQuery.Open; end; //Desc: 保存表头宽度和位置索引 procedure TfDemoFormMain.TableView1DblClick(Sender: TObject); var nRes: Boolean; nInt: integer; i,nCount: integer; nItem: PDictItemData; nState: TKeyboardState; begin GetKeyboardState(nState); if nState[VK_CONTROL] and 128 = 0 then Exit; nRes := False; nCount := TableView1.ColumnCount - 1; for i:=0 to nCount do begin nInt := TableView1.Columns[i].Tag; nItem := gSysEntityManager.ActiveEntity.FDictItem[nInt]; nInt := TableView1.Columns[i].Width; nRes := gSysEntityManager.UpdateActiveDictItem(nItem.FItemID, nInt, i); if not nRes then Break; end; if nRes then ShowHintMsg('表头宽度和顺序已保存', sHint, Handle); //xxxxx end; end.
unit untDBStore; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type { TDBStore } TDBStore=class type ValueType=(vtInt32, vtInt64, vtBool, vtWStr); type { ValueStore } ValueStore=class VArray:Pointer; VType:ValueType; VSize:integer; VName:string; constructor Create(ValueName:string; PValue:Pointer;ValueSize:integer; TypeOfValue:ValueType); end; private Int32Value:Int32; Int64Value:Int64; BoolValue:Boolean; StrValue:WideString; Values:array of ValueStore; public constructor Create; destructor Destroy; function AddValue(ValueName:string; PValue:Pointer;ValueSize:integer; TypeOfValue:ValueType):Boolean;overload; function AddValue(Value:ValueStore):Boolean;overload; function GetInt32(Name:String):Int32; function GetInt64(Name:String):Int64; function GetBoolean(Name:string):Boolean; function GetWideString(Name:string):WideString; end; implementation { TDBStore.ValueStore } constructor TDBStore.ValueStore.Create(ValueName: string; PValue: Pointer; ValueSize: integer; TypeOfValue: ValueType); begin VArray:=PValue; VType:=TypeOfValue; VSize:=ValueSize; VName:=ValueName; end; { TDBStore } constructor TDBStore.Create; begin SetLength(Values, 0); end; destructor TDBStore.Destroy; var i:integer; begin for i:=Low(Values) to High(Values) do begin {TODO -oBen -cC:Burasını incele değiştir} //SetLength(Values[i].VArray, 0); end; SetLength(Values, 0); end; function TDBStore.AddValue(ValueName: string; PValue: Pointer; ValueSize: integer; TypeOfValue: ValueType): Boolean; begin SetLength(Values, Length(Values)+1); Values[Length(Values)-1]:=ValueStore.Create(ValueName, PValue, ValueSize, TypeOfValue); end; function TDBStore.AddValue(Value: ValueStore): Boolean; begin SetLength(Values, Length(Values)+1); Values[Length(Values)-1]:=Value; end; function TDBStore.GetInt32(Name: String): Int32; var i:integer; begin for i:= Low(Values) to High(Values) do begin if(CompareStr(Values[i].VName, Name) = 0) then begin Result:=pInt32(Values[i].VArray)^; exit; end; end; Result:=-1; end; function TDBStore.GetInt64(Name: String): Int64; var i:integer; begin for i:= Low(Values) to High(Values) do begin if(CompareStr(Values[i].VName, Name) = 0) then begin Result:=pInt64(Values[i].VArray)^; exit; end; end; Result:=-1; end; function TDBStore.GetBoolean(Name: string): Boolean; var i:integer; begin for i:= Low(Values) to High(Values) do begin if(CompareStr(Values[i].VName, Name) = 0) then begin Result:=PBoolean(Values[i].VArray)^; exit; end; end; Result:=false; end; function TDBStore.GetWideString(Name: string): WideString; var i:integer; begin for i:= Low(Values) to High(Values) do begin if(CompareStr(Values[i].VName, Name) = 0) then begin Move(Values[i].VArray, Result, SizeOf(WideChar) * Values[i].VSize); exit; end; end; Result:=''; end; end.
unit UnitCache; interface uses Classes, Types, SysUtils, Generics.Collections, PascalUnit; type TUnitCache = class(TObjectList<TPascalUnit>) public function GetUnitByName(AName: string): TPascalUnit; function CountUnitName(AName: string): Integer; procedure ClearUnitCache(AName: string); end; implementation { TUnitCache } procedure TUnitCache.ClearUnitCache(AName: string); var LUnit: TPascalUnit; begin LUnit := GetUnitByName(AName); while Assigned(LUnit) do begin Delete(IndexOf(LUnit)); LUnit := GetUnitByName(AName); end; end; function TUnitCache.CountUnitName(AName: string): Integer; var LUnit: TPascalUnit; begin Result := 0; for LUnit in Self do begin if SameText(AName, LUnit.Name) then begin Inc(Result); end; end; end; function TUnitCache.GetUnitByName(AName: string): TPascalUnit; var LUnit: TPascalUnit; begin Result := nil; for LUnit in Self do begin if SameText(LUnit.Name, AName) then begin Result := LUnit; end; end; end; end.
(* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower LockBox * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1997-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): Roman Kassebaum * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* LBUTILS.PAS 2.08 *} {* Copyright (c) 2002 TurboPower Software Co *} {* All rights reserved. *} {*********************************************************} {$I LockBox.inc} unit LbUtils; {- odds-n-ends } interface uses System.Types, System.SysUtils; type PDWord = ^DWord; function BufferToHex(const Buf; BufSize : Cardinal) : string; function HexToBuffer(const Hex : string; var Buf; BufSize : Cardinal) : Boolean; implementation uses System.Math, System.Character; { -------------------------------------------------------------------------- } function BufferToHex(const Buf; BufSize : Cardinal) : string; var I : Integer; begin Result := ''; for I := 0 to BufSize - 1 do Result := Result + IntToHex(TByteArray(Buf)[I], 2); {!!.01} end; { -------------------------------------------------------------------------- } function HexToBuffer(const Hex : string; var Buf; BufSize : Cardinal) : Boolean; var i, C : Integer; Str : string; Count : Integer; cChar: Char; begin Result := False; Str := ''; for cChar in Hex do begin if cChar.ToUpper.IsInArray(['0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F']) then Str := Str + cChar; end; FillChar(Buf, BufSize, #0); Count := Min(Length(Hex), BufSize); for i := 0 to Count - 1 do begin Val('$' + Str.Substring(i shl 1, 2), TByteArray(Buf)[i], C); {!!.01} if C <> 0 then Exit; end; Result := True; end; end.
{ ******************************************************************************* Title: T2TiPDV Description: Pesquisa por cliente e importação para a venda. The MIT License Copyright: Copyright (C) 2014 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije @version 2.0 ******************************************************************************* } unit UImportaCliente; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, UBase, Dialogs, Grids, DBGrids, JvExDBGrids, JvDBGrid, StdCtrls, JvExStdCtrls, JvButton, JvCtrls, Buttons, JvExButtons, JvBitBtn, pngimage, ExtCtrls, Mask, JvEdit, JvValidateEdit, JvDBSearchEdit, DB, Provider, DBClient, FMTBcd, SqlExpr, JvEnterTab, JvComponentBase, Tipos, JvDBUltimGrid, Biblioteca, Controller; type TFImportaCliente = class(TFBase) Image1: TImage; Panel1: TPanel; Label1: TLabel; JvEnterAsTab1: TJvEnterAsTab; botaoConfirma: TJvBitBtn; botaoCancela: TJvImgBtn; DSCliente: TDataSource; EditLocaliza: TEdit; SpeedButton1: TSpeedButton; Label2: TLabel; CDSCliente: TClientDataSet; GridPrincipal: TJvDBUltimGrid; procedure Localiza; procedure Confirma; procedure FormActivate(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); procedure GridPrincipalKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure botaoConfirmaClick(Sender: TObject); private { Private declarations } public CpfCnpjPassou, QuemChamou: string; IdClientePassou: Integer; { Public declarations } end; var FImportaCliente: TFImportaCliente; implementation uses ClienteVO, ClienteController, UDataModule, UCaixa, UIdentificaCliente, UNotaFiscal; {$R *.dfm} {$Region 'Infra'} procedure TFImportaCliente.FormActivate(Sender: TObject); begin EditLocaliza.SetFocus; Color := StringToColor(Sessao.Configuracao.CorJanelasInternas); // Configura a Grid do Cliente ConfiguraCDSFromVO(CDSCliente, TClienteVO); ConfiguraGridFromVO(GridPrincipal, TClienteVO); end; procedure TFImportaCliente.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TFImportaCliente.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_F2 then Localiza; if Key = VK_F12 then Confirma; end; procedure TFImportaCliente.GridPrincipalKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then EditLocaliza.SetFocus; end; {$EndRegion 'Infra'} {$Region 'Pesquisa e Confirmação'} procedure TFImportaCliente.botaoConfirmaClick(Sender: TObject); begin Confirma; end; procedure TFImportaCliente.Confirma; begin if Sessao.MenuAberto = snNao then begin if CDSCliente.FieldByName('CPF_CNPJ').AsString = '' then Application.MessageBox('Cliente sem CPF ou CNPJ cadastrado.', 'Informação do Sistema', MB_OK + MB_ICONINFORMATION) else begin if QuemChamou = 'NF' then begin FNotaFiscal.editCpfCnpj.Text := CDSCliente.FieldByName('CPF_CNPJ').AsString; FNotaFiscal.EditNome.Text := CDSCliente.FieldByName('NOME').AsString; FNotaFiscal.editCodigoCliente.asinteger := CDSCliente.FieldByName('ID').asinteger; end else if QuemChamou = 'IdentificaCliente' then begin FIdentificaCliente.editCpfCnpj.Text := CDSCliente.FieldByName('CPF_CNPJ').AsString; FIdentificaCliente.EditNome.Text := CDSCliente.FieldByName('NOME').AsString; FIdentificaCliente.editIDCliente.asinteger := CDSCliente.FieldByName('ID').asinteger; end; end; end; Close; end; procedure TFImportaCliente.Localiza; var ProcurePor, Filtro: String; begin ProcurePor := '%' + EditLocaliza.Text + '%'; Filtro := 'NOME LIKE '+ QuotedStr(ProcurePor); TClienteController.SetDataSet(CDSCliente); TController.ExecutarMetodo('ClienteController.TClienteController', 'Consulta', [Filtro, '0', False], 'GET', 'Lista'); end; procedure TFImportaCliente.SpeedButton1Click(Sender: TObject); begin Localiza; end; {$EndRegion 'Pesquisa e Confirmação'} end.
unit TrivialXmlWriter; interface uses Classes, Generics.Collections; type TTrivialXmlWriter = class private FWriter: TTextWriter; FNodes: TStack<string>; FOwnsTextWriter: Boolean; public constructor Create (AWriter: TTextWriter); overload; constructor Create (AStream: TStream); overload; destructor Destroy; override; procedure WriteStartElement (const SName: string); procedure WriteEndElement (Indent: Boolean = False); procedure WriteString (const SValue: string); procedure WriteObjectPublished (AnObj: TObject); procedure WriteObjectRtti (AnObj: TObject); procedure WriteObjectAttrib (AnObj: TObject); function Indentation: string; end; XmlAttribute = class (TCustomAttribute) private FTag: string; public constructor Create (StrTag: string = ''); property TagName: string read FTag; end; implementation { TTrivialXmlWriter } uses System.TypInfo, System.SysUtils, System.RTTI; function CheckXmlAttr (AField: TRttiField; var StrTag: string): Boolean; var Attrib: TCustomAttribute; begin Result := False; for Attrib in AField.GetAttributes do if Attrib is XmlAttribute then begin StrTag := XmlAttribute(Attrib).TagName; if StrTag = '' then // default value StrTag := AField.Name; Exit (True); end; end; constructor TTrivialXmlWriter.Create(AWriter: TTextWriter); begin FWriter := AWriter; FNodes := TStack<string>.Create; end; constructor TTrivialXmlWriter.Create(AStream: TStream); begin FWriter := TStreamWriter.Create (AStream); Create (FWriter); // call first constructor FOwnsTextWriter := True; end; destructor TTrivialXmlWriter.Destroy; begin while FNodes.Count > 0 do WriteEndElement; FNodes.Free; if FOwnsTextWriter then FreeAndNil (FWriter); inherited; end; function TTrivialXmlWriter.Indentation: string; begin Result := StringOfChar (' ', FNodes.Count * 2) end; procedure TTrivialXmlWriter.WriteEndElement (Indent: Boolean); var StrNode: string; begin StrNode := FNodes.Pop; if Indent then FWriter.Write(Indentation); FWriter.Write ('</' + StrNode + '>' + sLineBreak); end; procedure TTrivialXmlWriter.WriteObjectAttrib(AnObj: TObject); var AContext: TRttiContext; AType: TRttiType; AField: TRttiField; StrTagName: string; begin WriteString (sLineBreak); // new line AType := AContext.GetType (anObj.ClassType); for AField in AType.GetFields do begin if CheckXmlAttr (AField, StrTagName) then begin if AField.FieldType.IsInstance then begin WriteStartElement (StrTagName); WriteObjectAttrib ( AField.GetValue(anObj).AsObject); WriteEndElement (True); end else begin WriteStartElement (StrTagName); WriteString ( AField.GetValue(anObj).ToString); WriteEndElement; end; end; end; end; procedure TTrivialXmlWriter.WriteObjectPublished(AnObj: TObject); var NProps, I: Integer; PropList: PPropList; InternalObject: TObject; StrPropName: string; begin WriteString (sLineBreak); // new line // get list of properties NProps := GetTypeData(AnObj.ClassInfo)^.PropCount; if NProps = 0 then Exit; GetMem(PropList, NProps * SizeOf(Pointer)); try GetPropInfos(AnObj.ClassInfo, PropList); for I := 0 to NProps - 1 do begin StrPropName := UTF8ToString (PropList[I].Name); case PropList[I].PropType^.Kind of tkUnknown, tkInteger, tkChar, tkEnumeration, tkFloat, tkString, tkUString, tkSet, tkWChar, tkLString, tkWString, tkInt64: begin WriteStartElement (StrPropName); WriteString (GetPropValue(AnObj, StrPropName)); WriteEndElement; end; tkClass: begin InternalObject := GetObjectProp(AnObj, StrPropName); if Assigned(InternalObject) and // skip if nil InternalObject.InheritsFrom(TPersistent) then begin // recurse in subclass WriteStartElement (StrPropName); WriteObjectPublished (InternalObject as TPersistent); WriteEndElement (True); end; end; // tkClass end; // case end; // for finally FreeMem(PropList); end; end; procedure TTrivialXmlWriter.WriteObjectRtti(AnObj: TObject); var AContext: TRttiContext; AType: TRttiType; AField: TRttiField; begin WriteString (sLineBreak); // new line AType := AContext.GetType (anObj.ClassType); for AField in AType.GetFields do begin if AField.FieldType.IsInstance then begin WriteStartElement (AField.Name); WriteObjectRtti ( AField.GetValue(anObj).AsObject); WriteEndElement (True); end else begin WriteStartElement (AField.Name); WriteString ( AField.GetValue(anObj).ToString); WriteEndElement; end; end; end; procedure TTrivialXmlWriter.WriteStartElement(const sName: string); begin FWriter.Write (Indentation + '<' + sName + '>'); FNodes.Push (sname); end; procedure TTrivialXmlWriter.WriteString(const sValue: string); begin FWriter.Write (sValue); end; { xmlAttribute } constructor xmlAttribute.Create(strTag: string); begin FTag := strTag; end; end.
(*******************************************************) (* *) (* Engine Paulovich DirectX *) (* Win32-DirectX API Unit *) (* *) (* Copyright (c) 2003-2004, Ivan Paulovich *) (* *) (* iskatrek@hotmail.com uin#89160524 *) (* *) (* Unit: glDialogs *) (* *) (*******************************************************) unit glDialogs; interface uses Windows, CommDlg, glConst; const {$EXTERNALSYM OPENFILENAME_SIZE_VERSION_400A} OPENFILENAME_SIZE_VERSION_400A = SizeOf(TOpenFileNameA) - SizeOf(Pointer) - (2 * SizeOf(DWord)); {$EXTERNALSYM OPENFILENAME_SIZE_VERSION_400W} OPENFILENAME_SIZE_VERSION_400W = SizeOf(TOpenFileNameW) - Sizeof(Pointer) - (2 * SizeOf(DWord)); {$EXTERNALSYM OPENFILENAME_SIZE_VERSION_400} OPENFILENAME_SIZE_VERSION_400 = OPENFILENAME_SIZE_VERSION_400A; function IsNT5OrHigher: Boolean; function OpenFile(Handle: HWnd): string; function SaveFile(Handle: HWnd): string; implementation function IsNT5OrHigher: Boolean; var Ovi: TOSVERSIONINFO; begin ZeroMemory(@Ovi, SizeOf(TOSVERSIONINFO)); Ovi.dwOSVersionInfoSize := SizeOf(TOSVERSIONINFO); GetVersionEx(Ovi); if (Ovi.dwPlatformId = VER_PLATFORM_WIN32_NT) and (ovi.dwMajorVersion >= 5) then Result := True else Result := False; end; function OpenFile(Handle: HWnd): string; var Ofn: TOpenFilename; Buffer: array[0..MAX_PATH - 1] of Char; begin Result := ''; ZeroMemory(@Buffer[0], SizeOf(Buffer)); ZeroMemory(@Ofn, SizeOf(TOpenFilename)); if IsNt5OrHigher then Ofn.lStructSize := SizeOf(TOpenFilename) else Ofn.lStructSize := OPENFILENAME_SIZE_VERSION_400; Ofn.hWndOwner := Handle; Ofn.hInstance := hInstance; Ofn.lpstrFile := @Buffer[0]; Ofn.lpstrFilter := FILE_FILTER; Ofn.nMaxFile := SizeOf(Buffer); Ofn.Flags := OFN_FILEMUSTEXIST or OFN_PATHMUSTEXIST or OFN_LONGNAMES or OFN_EXPLORER or OFN_HIDEREADONLY; Ofn.lpstrTitle := MSG_OPEN; if GetOpenFileName(Ofn) then Result := Ofn.lpstrFile; end; function SaveFile(Handle: HWnd): string; var Ofn: TOpenFilename; Buffer: array[0..MAX_PATH - 1] of Char; begin Result := ''; ZeroMemory(@Buffer[0], SizeOf(Buffer)); ZeroMemory(@Ofn, SizeOf(TOpenFilename)); if IsNt5OrHigher then Ofn.lStructSize := SizeOf(TOpenFilename) else Ofn.lStructSize := OPENFILENAME_SIZE_VERSION_400; Ofn.hWndOwner := Handle; Ofn.hInstance := hInstance; Ofn.lpstrFile := @Buffer[0]; Ofn.lpstrFilter := FILE_FILTER; Ofn.nMaxFile := SizeOf(Buffer); Ofn.Flags := OFN_FILEMUSTEXIST or OFN_PATHMUSTEXIST or OFN_LONGNAMES or OFN_EXPLORER or OFN_HIDEREADONLY; Ofn.lpstrTitle := MSG_SAVE; if GetSaveFileName(Ofn) then Result := Ofn.lpstrFile; end; end.
{*******************************************************} { } { Utility definitions for VirtualTree implementation } { The rTreeData data type is also defined here } { } {*******************************************************} unit VSTUtils; {$IFDEF FPC} {$MODE DELPHI} {$ENDIF} interface uses VirtualTrees, SysUtils; type rFileTreeData = record Name : String; Size : Int64; Attr : Integer; ExcludeAttr : Integer; Time : Integer; OpenIndex : Integer; ClosedIndex : Integer; end; PFileTreeData = ^rFileTreeData; { Returns whether an item (node) in the tree is a file } function IsFile(Sender : TBaseVirtualTree; Node : PVirtualNode) : Boolean; { Adds an item (file or folder) to the tree by filename (or rather path) Sender is the tree to add the item to Parent is the parent node (nil for root) Recursive will add folders recursively (else just the top level will get added Checks for non-existance first and does not add if check fails } function AddItem(Sender : TBaseVirtualTree; Parent : PVirtualNode; const Filename : String; const Recursive : Boolean = true) : PVirtualNode; overload; { Adds an item (file or folder) to the tree by SearchRec (see above) } function AddItem(Sender : TBaseVirtualTree; Parent : PVirtualNode; const SR : TSearchRec; Directory : String; const Recursive : Boolean = true) : PVirtualNode; overload; { Adds the contents of a folder to the tree Node should be the node of the folder in the tree Directory is the dir to scan Recursive will recursively add other found folders to the list by calling AddItem All files will get added, also hidden ones } procedure AddFolder(Sender : TBaseVirtualTree; Node : PVirtualNode; Directory : String; const Recursive : Boolean = true); { Adds the file-data (in the associated PFileTreeData) of the passed node to two passed strings, which can be passed to CopyFileEx Checks whether Source and Target are identical to prevent errors TargetDir is the new path the file should be copied to } procedure CopyTreeData(Tree : TBaseVirtualTree; Node : PVirtualNode; TargetDir : String; var Source : String; var Target : String); { Checks whether a file (represented by the passed Value) is already present in the tree-level represented by Node (and siblings) Only pass filenames (without path) for Value Returns a Node if one with the same filename is found, nil otherwise Case-sensitive check on Linux, in-sensitive on Windows Use to make sure no file-conflics will be produced when actually copying files } function CheckForExistance(Tree : TBaseVirtualTree; Node : PVirtualNode; const Value : String) : PVirtualNode; overload; function CheckForExistance(Tree : TBaseVirtualTree; const Value : String) : PVirtualNode; overload; { Summs all file-data (stored in PFileTreeData) of the tree and returns it } function CalculateTotalSize(Tree : TBaseVirtualTree) : Int64; { Returns the filepath of the passed node relative from the root of the PND The path will be Linux formatted (forward slashes) } function GetFilepathInPND(Tree : TBaseVirtualTree; Node : PVirtualNode) : String; implementation uses Dialogs, Controls, MainForm, StrUtils; const LINUX_PATH_DELIMITER : String = '/'; function IsFile(Sender : TBaseVirtualTree; Node: PVirtualNode) : Boolean; var PData : PFileTreeData; begin if Node = nil then begin Result := false; Exit; end; PData := Sender.GetNodeData(Node); Result := (PData.Attr and faDirectory = 0); end; function AddItem(Sender : TBaseVirtualTree; Parent : PVirtualNode; const Filename : String; const Recursive : Boolean = true) : PVirtualNode; var SR : TSearchRec; begin FindFirst(Filename,$3F,SR); try Result := AddItem(Sender,Parent,SR,ExtractFilePath(Filename),Recursive); finally FindClose(SR); end; end; function AddItem(Sender : TBaseVirtualTree; Parent : PVirtualNode; const SR : TSearchRec; Directory : String; const Recursive : Boolean = true) : PVirtualNode; var PData : PFileTreeData; Node : PVirtualNode; begin Result := nil; Directory := IncludeTrailingPathDelimiter(Directory); // Check for "special" files if frmMain.Settings.SmartAdd then begin if SameText(ExtractFileExt(SR.Name),frmMain.PND_EXT) then begin if MessageDlg('You are trying to add a PND file to a PND.' + #13#10 + 'Do you want to open and browse its contents instead?'+ #13#10#13#10 + 'The file in question is: ' + Directory + SR.Name, mtConfirmation,[mbYes,mbNo],0) = mrYes then begin frmMain.OpenPND(Directory + SR.Name); Exit; end; end else if SameText(SR.Name,frmMain.PXML_PATH) then begin if MessageDlg('To add PXML metadata to a PND it has to be appended, ' + 'not simply added to the PND''s contents.' + #13#10 + 'Therefore it needs to be specified separately.' + #13#10 + 'Do you want to do that?'+ #13#10#13#10 + 'The file in question is: ' + Directory + SR.Name, mtConfirmation,[mbYes,mbNo],0) = mrYes then begin frmMain.edtPXML.Text := Directory + SR.Name; Exit; end; end else if SameText(SR.Name,frmMain.ICON_PATH) then begin if MessageDlg('It seems like you are trying to add an icon to the PND.' + #13#10 + 'Do you want it to show up as the PND''s icon on the desktop ' + 'or the menu?' + #13#10#13#10 + 'The file in question is: ' + Directory + SR.Name, mtConfirmation,[mbYes,mbNo],0) = mrYes then begin frmMain.edtIcon.Text := Directory + SR.Name; end; end; end; // Check for existance Result := CheckForExistance(Sender,Sender.GetFirstChild(Parent),SR.Name); if Result <> nil then Exit; if IsFile(Sender,Parent) then Parent := nil; Node := Sender.AddChild(Parent); PData := Sender.GetNodeData(Node); PData.Name := Directory + SR.Name; PData.Attr := SR.Attr; PData.ExcludeAttr := SR.ExcludeAttr; PData.Time := SR.Time; // Icons are set in InitNode event of the virtual tree if (SR.Attr and faDirectory > 0) then begin PData.Size := 0; AddFolder(Sender,Node,PData.Name,Recursive); end else begin PData.Size := SR.Size; end; Result := Node; end; procedure AddFolder(Sender : TBaseVirtualTree; Node : PVirtualNode; Directory : String; const Recursive : Boolean = true); var SR : TSearchRec; begin try Directory := IncludeTrailingPathDelimiter(Directory); if FindFirst(Directory + '*', faAnyFile, SR) = 0 then begin repeat if (SR.Name = '.') OR (SR.Name = '..') then Continue; if Recursive OR ((SR.Attr AND faDirectory) = 0) then AddItem(Sender,Node,SR,Directory,Recursive); until (FindNext(SR) <> 0); end; finally FindClose(SR); end; end; procedure CopyTreeData(Tree : TBaseVirtualTree; Node : PVirtualNode; TargetDir : String; var Source : String; var Target : String); var PData : PFileTreeData; begin while Node <> nil do begin PData := Tree.GetNodeData(Node); TargetDir := IncludeTrailingPathDelimiter(TargetDir); if (PData.Attr and faDirectory > 0) then begin CopyTreeData(Tree,Tree.GetFirstChild(Node), TargetDir + ExtractFileName(PData.Name),Source,Target); end else begin {$Ifdef Win32} if NOT AnsiSameText(PData.Name,TargetDir + ExtractFileName(PData.Name)) then {$Else} if NOT AnsiSameStr(PData.Name,TargetDir + ExtractFileName(PData.Name)) then {$EndIf} begin Source := Source + PData.Name + #0; Target := Target + TargetDir + ExtractFileName(PData.Name) + #0; end; end; Node := Tree.GetNextSibling(Node); end; end; function CheckForExistance(Tree : TBaseVirtualTree; Node : PVirtualNode; const Value : String) : PVirtualNode; var PData : PFileTreeData; begin Result := nil; while (Node <> nil) do begin PData := Tree.GetNodeData(Node); {$Ifdef Win32} if AnsiSameText(ExtractFileName(PData.Name),Value) then {$Else} if AnsiSameStr(ExtractFileName(PData.Name),Value) then {$EndIf} begin Result := Node; Exit; end; Node := Tree.GetNextSibling(Node); end; end; function CheckForExistance(Tree : TBaseVirtualTree; const Value : String) : PVirtualNode; var temp : String; begin Result := nil; if Length(Value) = 0 then Exit; temp := Trim(Value); Result := Tree.RootNode; if RightStr(temp,1) <> LINUX_PATH_DELIMITER then temp := temp + LINUX_PATH_DELIMITER; if LeftStr(temp,2) = './' then temp := RightStr(temp,Length(temp)-2); while (Pos(LINUX_PATH_DELIMITER,temp) <> 0) AND (Result <> nil) do begin Result := Tree.GetFirstChild(Result); Result := CheckForExistance(Tree,Result,LeftStr(temp,Pos(LINUX_PATH_DELIMITER,temp)-1)); temp := RightStr(temp,Length(temp)-Pos(LINUX_PATH_DELIMITER,temp)); end; end; function CalculateTotalSize(Tree : TBaseVirtualTree) : Int64; var Node : PVirtualNode; PData : PFileTreeData; begin Result := 0; Node := Tree.GetFirst(); while Node <> nil do begin PData := Tree.GetNodeData(Node); Result := Result + PData.Size; Node := Tree.GetNext(Node); end; end; function GetFilepathInPND(Tree : TBaseVirtualTree; Node : PVirtualNode) : String; var PData : PFileTreeData; begin Result := ''; while (Node <> nil) AND (Node <> Tree.RootNode) do begin PData := Tree.GetNodeData(Node); Result := LINUX_PATH_DELIMITER + ExtractFileName(PData.Name) + Result; Node := Node.Parent; end; Result := '.' + Result; end; end.
unit Func; interface uses DDDK; function FuncIsGoodReadPtr(ABuf:Pointer;ASize:Cardinal):Boolean; implementation // // this function checks user buffer for read access // returns true if the buffer is ok // function FuncIsGoodReadPtr(ABuf:Pointer;ASize:Cardinal):Boolean; var LSum:Cardinal; LPC:PCardinal; LPB:PByte; LI:Integer; begin DbgMsg('func.pas: FuncIsGoodReadPtr(ABuf:0x%.8X;ASize:0x%.8X)',[ABuf,ASize]); Result:=True; try ProbeForRead(ABuf,ASize,SizeOf(Byte)); LSum:=0; LPC:=ABuf; for LI:=1 to ASize div SizeOf(Cardinal) do begin Inc(LSum,LPC^); Inc(LPC); end; LPB:=Pointer(LPC); for LI:=1 to ASize mod SizeOf(Cardinal) do begin Inc(LSum,LPB^); Inc(LPB); end; if LSum=0 then ; except DbgPrint('func.pas: FuncIsGoodReadPtr error: exception occurred',[]); Result:=False; end; DbgMsg('func.pas: FuncIsGoodReadPtr(-):%d',[Result]); end; end.
unit Promise.Proto; interface uses System.SysUtils, System.Classes, System.Generics.Collections, System.SyncObjs ; {$REGION 'Interfaces'} type TState = (Pending, Resolved, Rejected, Finished); EPromiseException = class(Exception); EInvalidPromiseStateException = class(EPromiseException); IFailureReason<TFailure:Exception> = interface ['{A7C29DBC-D00B-4B5D-ABD6-3280F9F49971}'] function GetReason: TFailure; property Reason: TFailure read GetReason; end; IPromise<TSuccess; TFailure:Exception> = interface; IPromiseAccess<TSuccess; TFailure:Exception> = interface; TFailureProc<TFailure:Exception> = reference to procedure (failure: IFailureReason<TFailure>); TPromiseInitProc<TResult; TFailure:Exception> = reference to procedure (const resolver: TProc<TResult>; const rejector: TFailureProc<TFailure>); TPipelineFunc<TSource, TSuccess; TFailure:Exception> = reference to function (value: TSource): IPromise<TSuccess, TFailure>; IFuture<TResult> = interface; TPromiseOp<TSuccess; TFailure:Exception> = record private FPromise: IpromiseAccess<TSuccess, TFailure>; private class function Create(const promise: IpromiseAccess<TSuccess, TFailure>): TPromiseOp<TSuccess, TFailure>; static; function ThenByInternal<TNextSuccess; TNextFailure:Exception>( const whenSuccess: TPipelineFunc<TSuccess, TNextSuccess, TNextFailure>; const whenfailure: TPipelineFunc<IFailureReason<TFailure>, TNextSuccess, TNextFailure>): IPromise<TNextSuccess, TNextFailure>; public function ThenBy<TNextSuccess>(const whenSuccess: TPipelineFunc<TSuccess, TNextSuccess, TFailure>): IPromise<TNextSuccess, TFailure>; overload; function ThenBy<TNextSuccess; TNextFailure:Exception>( const whenSuccess: TPipelineFunc<TSuccess, TNextSuccess, TNextFailure>; const whenfailure: TPipelineFunc<IFailureReason<TFailure>, TNextSuccess, TNextFailure>): IPromise<TNextSuccess, TNextFailure>; overload; function Catch<TNextFailure:Exception>(const whenfailure: TPipelineFunc<IFailureReason<TFailure>, TSuccess, TNextFailure>): IPromise<TSuccess, TNextFailure>; end; IPromise<TSuccess; TFailure:Exception> = interface ['{19311A2D-7DDD-41CA-AD42-29FCC27179C5}'] function GetFuture: IFuture<TSuccess>; function Done(const proc: TProc<TSuccess>): IPromise<TSuccess, TFailure>; function Fail(const proc: TFailureProc<TFailure>): IPromise<TSuccess, TFailure>; function ThenBy(const fn: TPipelineFunc<TSuccess, TSuccess, TFailure>): IPromise<TSuccess, TFailure>; overload; function ThenBy( const whenSuccess: TPipelineFunc<TSuccess, TSuccess, TFailure>; const whenfailure: TPipelineFunc<IFailureReason<TFailure>, TSuccess, TFailure>): IPromise<TSuccess, TFailure>; overload; function Catch(const whenfailure: TPipelineFunc<IFailureReason<TFailure>, TSuccess, TFailure>): IPromise<TSuccess, TFailure>; function Op: TPromiseOp<TSuccess, TFailure>; property Future: IFuture<TSuccess> read GetFuture; end; IPromiseAccess<TSuccess; TFailure:Exception> = interface ['{D6A8317E-CF96-41A5-80EE-5FFB2D1D7676}'] function GetValue: TSuccess; function GetFailure: IFailureReason<TFailure>; function GetState: TState; function GetSelf: IPromise<TSuccess, TFailure>; property State: TState read GetState; property Self: IPromise<TSuccess, TFailure> read GetSelf; end; IPromiseResolvable<TSuccess; TFailure:Exception> = interface function Resolve(value: TSuccess): IPromise<TSuccess, TFailure>; function Reject(value: IFailureReason<TFailure>): IPromise<TSuccess, TFailure>; end; IFuture<TResult> = interface ['{844488AD-0136-41F8-94B1-B7BA2EB0C019}'] function GetValue: TResult; procedure Cancell; function WaitFor: boolean; property Value: TResult read GetValue; end; {$ENDREGION} {$REGION 'Entry Point'} TPromise = record public class function When<TSuccess>(const fn: TFunc<TSuccess>): IPromise<TSuccess, Exception>; overload; static; class function When<TSuccess>(const initializer: TPromiseInitProc<TSuccess, Exception>): IPromise<TSuccess, Exception>; overload; static; class function When<TSuccess; TFailure:Exception>(const initializer: TPromiseInitProc<TSuccess, TFailure>): IPromise<TSuccess, TFailure>; overload; static; class function Resolve<TSuccess>(value: TSuccess): IPromise<TSuccess, Exception>; static; class function Reject<TSuccess; TFailure:Exception>(value: TFailure): IPromise<TSuccess, TFailure>; overload; static; class function Reject<TFailure:Exception>(value: TFailure): IPromise<TObject, TFailure>; overload; static; end; {$ENDREGION} {$REGION 'Implementaion types'} TDeferredTask<TResult; TFailure:Exception> = class (TInterfacedObject, IFuture<TResult>) strict private var FThread: TThread; FSignal: TEvent; FResult: TResult; private var FPromise: IPromiseResolvable<TResult,TFailure>; private function GetValue: TResult; procedure NotifyThreadTerminated(Sender: TObject); protected { IDeferredTask<TResult> } procedure Cancell; function WaitFor: boolean; protected procedure DoExecute(const initializer: TPromiseInitProc<TResult, TFailure>); public constructor Create(const promise: IPromiseResolvable<TResult,TFailure>; const initializer: TPromiseInitProc<TResult,TFailure>); overload; destructor Destroy; override; end; TFailureReason<TFailure:Exception> = class(TInterfacedObject, IFailureReason<TFailure>) private FReason: TFailure; protected function GetReason: TFailure; public constructor Create(const reason: TFailure); destructor Destroy; override; end; TAbstractPromise<TSuccess; TFailure:Exception> = class abstract (TInterfacedObject, IPromiseAccess<TSuccess, TFailure>) private function GetState: TState; function GetSelf: IPromise<TSuccess, TFailure>; function GetValue: TSuccess; function GetFailure: IFailureReason<TFailure>; protected function GetSelfInternal: IPromise<TSuccess, TFailure>; virtual; abstract; function GetStateInternal: TState; virtual; abstract; function GetValueInternal: TSuccess; virtual; abstract; function GetFailureInternal: IFailureReason<TFailure>; virtual; abstract; protected function ThenByInternal( const whenSuccess: TPipelineFunc<TSuccess, TSuccess, TFailure>; const whenfailure: TPipelineFunc<IFailureReason<TFailure>, TSuccess, TFailure>): IPromise<TSuccess, TFailure>; end; TDeferredObject<TSuccess; TFailure:Exception> = class (TAbstractPromise<TSuccess, TFailure>, IPromise<TSuccess, TFailure>, IPromiseResolvable<TSuccess,TFailure>) private FState: TState; FSuccess: TSuccess; FFailure: IFailureReason<TFailure>; FFuture: IFuture<TSuccess>; private function GetFuture: IFuture<TSuccess>; procedure AssertState(const acceptable: boolean; const msg: string); protected function GetSelfInternal: IPromise<TSuccess, TFailure>; override; function GetStateInternal: TState; override; function GetValueInternal: TSuccess; override; function GetFailureInternal: IFailureReason<TFailure>; override; protected { IPromise<TSuccess, TFailure> } function Done(const proc: TProc<TSuccess>): IPromise<TSuccess, TFailure>; function Fail(const proc: TFailureProc<TFailure>): IPromise<TSuccess, TFailure>; function ThenBy(const whenSuccess: TPipelineFunc<TSuccess, TSuccess, TFailure>): IPromise<TSuccess, TFailure>; overload; function ThenBy( const whenSuccess: TPipelineFunc<TSuccess, TSuccess, TFailure>; const whenfailure: TPipelineFunc<IFailureReason<TFailure>, TSuccess, TFailure>): IPromise<TSuccess, TFailure>; overload; function Catch(const whenfailure: TPipelineFunc<IFailureReason<TFailure>, TSuccess, TFailure>): IPromise<TSuccess, TFailure>; function Op: TPromiseOp<TSuccess, TFailure>; protected { IPromiseResolvable<TSuccess,TFailure> } function Resolve(value: TSuccess): IPromise<TSuccess, TFailure>; function Reject(value: IFailureReason<TFailure>): IPromise<TSuccess, TFailure>; public constructor Create(const initializer: TPromiseInitProc<TSuccess,TFailure>); destructor Destroy; override; end; TPipedPromise<TSuccessSource, TSuccess; TFailureSource, TFailure:Exception> = class (TAbstractPromise<TSuccess, TFailure>, IPromise<TSuccess, TFailure>, IPromiseResolvable<TSuccess, TFailure>) private FFuture: IFuture<TSuccess>; FPrevPromise: IPromiseAccess<TSuccessSource, TFailureSource>; FState: TState; FFailure: IFailureReason< TFailure>; private function GetFuture: IFuture<TSuccess>; protected function GetSelfInternal: IPromise<TSuccess, TFailure>; override; function GetStateInternal: TState; override; function GetValueInternal: TSuccess; override; function GetFailureInternal: IFailureReason<TFailure>; override; protected { IPromise<TSuccess, TFailure> } function Done(const proc: TProc<TSuccess>): IPromise<TSuccess, TFailure>; function Fail(const proc: TFailureProc<TFailure>): IPromise<TSuccess, TFailure>; function ThenBy(const whenSuccess: TPipelineFunc<TSuccess, TSuccess, TFailure>): IPromise<TSuccess, TFailure>; overload; function ThenBy( const whenSuccess: TPipelineFunc<TSuccess, TSuccess, TFailure>; const whenfailure: TPipelineFunc<IFailureReason<TFailure>, TSuccess, TFailure>): IPromise<TSuccess, TFailure>; overload; function Catch(const whenfailure: TPipelineFunc<IFailureReason<TFailure>, TSuccess, TFailure>): IPromise<TSuccess, TFailure>; function Op: TPromiseOp<TSuccess, TFailure>; protected { IPromiseResolvable<TSuccess, TFailure> } function Resolve(value: TSuccess): IPromise<TSuccess, TFailure>; function Reject(value: IFailureReason<TFailure>): IPromise<TSuccess, TFailure>; public constructor Create( const prev: IPromiseAccess<TSuccessSource, TFailureSource>; const whenSucces: TPipelineFunc<TSuccessSource,TSuccess,TFailure>; const whenFailure: TPipelineFunc<IFailureReason<TFailureSource>,TSuccess,TFailure>); overload; destructor Destroy; override; end; TTerminatedPromise<TResult; TFailure:Exception> = class(TInterfacedObject, IPromise<TResult, TFailure>, IPromiseResolvable<TResult,TFailure>) private FPrevPromise: IPromiseAccess<TResult, TFailure>; FState: TState; FFuture: IFuture<TResult>; FDoneActions: TList<TProc<TResult> >; FFailActions: TList<TFailureProc<TFailure>>; private function GetFuture: IFuture<TResult>; function GetState: TState; protected { IPromise<TSuccess, TFailure> } function Done(const proc: TProc<TResult>): IPromise<TResult, TFailure>; function Fail(const proc: TFailureProc<TFailure>): IPromise<TResult, TFailure>; function ThenBy(const fn: TPipelineFunc<TResult, TResult, TFailure>): IPromise<TResult, TFailure>; overload; function ThenBy( const whenSuccess: TPipelineFunc<TResult, TResult, TFailure>; const whenfailure: TPipelineFunc<IFailureReason<TFailure>, TResult, TFailure>): IPromise<TResult, TFailure>; overload; function Catch(const whenfailure: TPipelineFunc<IFailureReason<TFailure>, TResult, TFailure>): IPromise<TResult, TFailure>; function Op: TPromiseOp<TResult, TFailure>; protected { IPromiseResolvable<TResult,TFailure> } function Resolve(value: TResult): IPromise<TResult, TFailure>; function Reject(value: IFailureReason<TFailure>): IPromise<TResult, TFailure>; public constructor Create(const prev: IPromiseAccess<TResult, TFailure>); destructor Destroy; override; end; TPromiseValue<TResult; TFailure:Exception> = class(TAbstractPromise<TResult, TFailure>, IPromise<TResult, TFailure>) private type TFuture = class(TInterfacedObject, IFuture<TResult>) private FValue: TResult; protected { IFuture<TResult> } function GetValue: TResult; procedure Cancell; function WaitFor: boolean; public constructor Create(value: TResult); end; private FSuccess: TResult; FFailure: IFailureReason< TFailure>; FState: TState; private function GetFuture: IFuture<TResult>; protected function GetSelfInternal: IPromise<TResult, TFailure>; override; function GetStateInternal: TState; override; function GetValueInternal: TResult; override; function GetFailureInternal: IFailureReason<TFailure>; override; protected { IPromise<TResult, TFailure> } function Done(const proc: TProc<TResult>): IPromise<TResult, TFailure>; function Fail(const proc: TFailureProc<TFailure>): IPromise<TResult, TFailure>; function ThenBy(const fn: TPipelineFunc<TResult, TResult, TFailure>): IPromise<TResult, TFailure>; overload; function ThenBy( const whenSuccess: TPipelineFunc<TResult, TResult, TFailure>; const whenfailure: TPipelineFunc<IFailureReason<TFailure>, TResult, TFailure>): IPromise<TResult, TFailure>; overload; function Catch(const whenfailure: TPipelineFunc<IFailureReason<TFailure>, TResult, TFailure>): IPromise<TResult, TFailure>; function Op: TPromiseOp<TResult, TFailure>; public class function Resolve(success: TResult): TPromiseValue<TResult,TFailure>; static; class function Reject(failure: IFailureReason<TFailure>): TPromiseValue<TResult,TFailure>; static; end; {$ENDREGION} implementation { TPromiseOp<TSuccess, TFailure> } class function TPromiseOp<TSuccess, TFailure>.Create( const promise: IpromiseAccess<TSuccess, TFailure>): TPromiseOp<TSuccess, TFailure>; begin Assert(Assigned(promise)); Result.FPromise := promise; end; function TPromiseOp<TSuccess, TFailure>.ThenBy<TNextSuccess>( const whenSuccess: TPipelineFunc<TSuccess, TNextSuccess, TFailure>): IPromise<TNextSuccess, TFailure>; var p: IPromiseAccess<TSuccess, TFailure>; begin p := FPromise; Result := ThenByInternal<TNextSuccess, TFailure>( whenSuccess, function (value: IFailureReason<TFailure>): IPromise<TNextSuccess,TFailure> begin Result := TPromiseValue<TNextSuccess,TFailure>.Reject(p.GetFailure); end ); end; function TPromiseOp<TSuccess, TFailure>.Catch<TNextFailure>( const whenfailure: TPipelineFunc<IFailureReason<TFailure>, TSuccess, TNextFailure>): IPromise<TSuccess, TNextFailure>; var p: IPromiseAccess<TSuccess, TFailure>; begin p := FPromise; Result := ThenByInternal<TSuccess, TNextFailure>( function (value: TSuccess): IPromise<TSuccess,TNextFailure> begin Result := TPromiseValue<TSuccess, TNextFailure>.Resolve(p.GetValue); end, whenfailure ); end; function TPromiseOp<TSuccess, TFailure>.ThenBy<TNextSuccess, TNextFailure>( const whenSuccess: TPipelineFunc<TSuccess, TNextSuccess, TNextFailure>; const whenfailure: TPipelineFunc<IFailureReason<TFailure>, TNextSuccess, TNextFailure>): IPromise<TNextSuccess, TNextFailure>; begin Result := ThenByInternal<TNextSuccess, TNextFailure>(whenSuccess, whenfailure); end; function TPromiseOp<TSuccess, TFailure>.ThenByInternal<TNextSuccess, TNextFailure>( const whenSuccess: TPipelineFunc<TSuccess, TNextSuccess, TNextFailure>; const whenfailure: TPipelineFunc<IFailureReason<TFailure>, TNextSuccess, TNextFailure>): IPromise<TNextSuccess, TNextFailure>; var locker: TObject; begin locker := TObject(FPromise); TMonitor.Enter(locker); try Result := TPipedPromise<TSuccess,TNextSuccess,TFailure,TNextFailure>.Create(FPromise, whenSuccess, whenfailure); finally TMonitor.Exit(locker); end; end; { TDefferredManager } class function TPromise.When<TSuccess>( const fn: TFunc<TSuccess>): IPromise<TSuccess, Exception>; begin Result := TDeferredObject<TSuccess,Exception> .Create( procedure (const resolver: TProc<TSuccess>; const rejector: TFailureProc<Exception>) var r: TSuccess; begin if Assigned(fn) then begin r := fn; end else begin r := System.Default(TSuccess); end; resolver(r); end ); end; class function TPromise.Reject<TFailure>( value: TFailure): IPromise<TObject, TFailure>; begin Result := Reject<TObject,TFailure>(value); end; class function TPromise.Reject<TSuccess,TFailure>( value: TFailure): IPromise<TSuccess, TFailure>; begin Result := TDeferredObject<TSuccess,TFailure> .Create( procedure (const resolver: TProc<TSuccess>; const rejector: TFailureProc<TFailure>) begin rejector(TFailureReason<TFailure>.Create(value)); end ); end; class function TPromise.Resolve<TSuccess>( value: TSuccess): IPromise<TSuccess, Exception>; begin Result := TDeferredObject<TSuccess,Exception> .Create( procedure (const resolver: TProc<TSuccess>; const rejector: TFailureProc<Exception>) begin resolver(value); end ); end; class function TPromise.When<TSuccess, TFailure>( const initializer: TPromiseInitProc<TSuccess, TFailure>): IPromise<TSuccess, TFailure>; begin Result := TDeferredObject<TSuccess,TFailure> .Create(initializer) end; class function TPromise.When<TSuccess>( const initializer: TPromiseInitProc<TSuccess, Exception>): IPromise<TSuccess, Exception>; begin Result := When<TSuccess,Exception>(initializer); end; { TDefferredTask<TResult> } procedure TDeferredTask<TResult,TFailure>.Cancell; begin end; constructor TDeferredTask<TResult, TFailure>.Create( const promise: IPromiseResolvable<TResult,TFailure>; const initializer: TPromiseInitProc<TResult, TFailure>); begin FPromise := promise; FSignal := TEvent.Create; FThread := TThread.CreateAnonymousThread( procedure begin Self.DoExecute(initializer); end ); FThread.OnTerminate := Self.NotifyThreadTerminated; FThread.Start; end; destructor TDeferredTask<TResult,TFailure>.Destroy; begin FreeAndNil(FSignal); inherited; end; procedure TDeferredTask<TResult,TFailure>.DoExecute(const initializer: TPromiseInitProc<TResult, TFailure>); var obj: TObject; begin try initializer( procedure (value: TResult) begin FResult := value; FPromise.Resolve(value); end, procedure (value: IFailureReason<TFailure>) begin FPromise.Reject(value); end ); except obj := AcquireExceptionObject; FPromise.Reject(TFailureReason<TFailure>.Create(obj as TFailure)); end; FSignal.SetEvent; end; function TDeferredTask<TResult,TFailure>.GetValue: TResult; begin Self.WaitFor; Result := FResult; end; procedure TDeferredTask<TResult, TFailure>.NotifyThreadTerminated( Sender: TObject); begin FPromise := nil; end; function TDeferredTask<TResult, TFailure>.WaitFor: boolean; begin Result := false; if Assigned(FThread) then begin if not FThread.Finished then begin Result := FSignal.WaitFor = wrSignaled; end; FPromise := nil; end; if TThread.CurrentThread.ThreadID = MainThreadID then begin while not CheckSynchronize do TThread.Sleep(100); end; end; { TFailureReason<TFailure> } constructor TFailureReason<TFailure>.Create(const reason: TFailure); begin FReason := reason; end; destructor TFailureReason<TFailure>.Destroy; begin FReason.Free; inherited; end; function TFailureReason<TFailure>.GetReason: TFailure; begin Result := FReason; end; { TAbstractPromise<TSuccess, TFailure> } function TAbstractPromise<TSuccess, TFailure>.GetFailure: IFailureReason<TFailure>; begin Result := Self.GetFailureInternal; end; function TAbstractPromise<TSuccess, TFailure>.GetState: TState; begin Result := Self.GetStateInternal; end; function TAbstractPromise<TSuccess, TFailure>.GetValue: TSuccess; begin Result := Self.GetValueInternal; end; function TAbstractPromise<TSuccess, TFailure>.GetSelf: IPromise<TSuccess, TFailure>; begin Result := Self.GetSelfInternal; end; function TAbstractPromise<TSuccess, TFailure>.ThenByInternal( const whenSuccess: TPipelineFunc<TSuccess, TSuccess, TFailure>; const whenfailure: TPipelineFunc<IFailureReason<TFailure>, TSuccess, TFailure>): IPromise<TSuccess, TFailure>; begin TMonitor.Enter(Self); try Result := TPipedPromise<TSuccess, TSuccess, TFailure, TFailure>.Create( Self, function (value: TSuccess): IPromise<TSuccess, TFailure> begin if Assigned(whenSuccess) then begin Result := whenSuccess(value); end else begin Result := TPromiseValue<TSuccess, TFailure>.Resolve(value); end; end, function (value: IFailureReason<TFailure>): IPromise<TSuccess, TFailure> begin if Assigned(whenfailure) then begin Result := whenfailure(value); end else begin Result := TPromiseValue<TSuccess, TFailure>.Reject(value); end; end ); finally TMonitor.Exit(Self); end; end; { TDeferredObject<TSuccess, TFailure> } destructor TDeferredObject<TSuccess, TFailure>.Destroy; begin inherited; end; procedure TDeferredObject<TSuccess, TFailure>.AssertState( const acceptable: boolean; const msg: string); begin if not acceptable then begin FState := TState.Pending; raise EInvalidPromiseStateException.Create(msg); end; end; function TDeferredObject<TSuccess, TFailure>.Catch( const whenfailure: TPipelineFunc<IFailureReason<TFailure>, TSuccess, TFailure>): IPromise<TSuccess, TFailure>; begin Result := Self.ThenByInternal(nil, whenfailure); end; constructor TDeferredObject<TSuccess, TFailure>.Create(const initializer: TPromiseInitProc<TSuccess,TFailure>); begin FFuture := TDeferredTask<TSuccess,TFailure>.Create(Self, initializer); end; function TDeferredObject<TSuccess, TFailure>.Done( const proc: TProc<TSuccess>): IPromise<TSuccess, TFailure>; begin TMonitor.Enter(Self); try Result := TTerminatedPromise<TSuccess, TFailure>.Create(Self).Done(proc); finally TMonitor.Exit(Self); end; end; function TDeferredObject<TSuccess, TFailure>.Fail( const proc: TFailureProc<TFailure>): IPromise<TSuccess, TFailure>; begin TMonitor.Enter(Self); try Result := TTerminatedPromise<TSuccess, TFailure>.Create(Self).Fail(proc); finally TMonitor.Exit(Self); end; end; function TDeferredObject<TSuccess, TFailure>.ThenBy( const whenSuccess: TPipelineFunc<TSuccess, TSuccess, TFailure>; const whenfailure: TPipelineFunc<IFailureReason<TFailure>, TSuccess, TFailure>): IPromise<TSuccess, TFailure>; begin Assert(Assigned(whenSuccess)); Assert(Assigned(whenfailure)); Result := Self.ThenByInternal(whenSuccess, whenfailure); end; function TDeferredObject<TSuccess, TFailure>.ThenBy( const whenSuccess: TPipelineFunc<TSuccess, TSuccess, TFailure>): IPromise<TSuccess, TFailure>; begin Assert(Assigned(whenSuccess)); Result := Self.ThenByInternal(whenSuccess, nil); end; function TDeferredObject<TSuccess, TFailure>.GetFailureInternal: IFailureReason<TFailure>; begin Result := FFailure; end; function TDeferredObject<TSuccess, TFailure>.GetSelfInternal: IPromise<TSuccess, TFailure>; begin Result := Self; end; function TDeferredObject<TSuccess, TFailure>.GetStateInternal: TState; begin Result := FState; end; function TDeferredObject<TSuccess, TFailure>.GetFuture: IFuture<TSuccess>; begin Result := FFuture; end; function TDeferredObject<TSuccess, TFailure>.GetValueInternal: TSuccess; begin Result := FFuture.Value; end; function TDeferredObject<TSuccess, TFailure>.Op: TPromiseOp<TSuccess, TFailure>; begin Result := TPromiseOp<TSuccess, TFailure>.Create(Self); end; function TDeferredObject<TSuccess, TFailure>.Resolve( value: TSuccess): IPromise<TSuccess, TFailure>; begin TMonitor.Enter(Self); try AssertState(Self.GetState = TState.Pending, 'Deferred object already finished.'); FSuccess := value; FState := TState.Resolved; finally TMonitor.Exit(Self); end; end; function TDeferredObject<TSuccess, TFailure>.Reject( value: IFailureReason<TFailure>): IPromise<TSuccess, TFailure>; begin TMonitor.Enter(Self); try AssertState(Self.GetState = TState.Pending, 'Deferred object already finished.'); FFailure := value; FState := TState.Rejected; finally TMonitor.Exit(Self); end; end; { TPipedPromise<TSuccessSource, TSuccess, TFailureSource, TFailure> } function TPipedPromise<TSuccessSource, TSuccess, TFailureSource, TFailure>.Catch( const whenfailure: TPipelineFunc<IFailureReason<TFailure>, TSuccess, TFailure>): IPromise<TSuccess, TFailure>; begin Result := Self.ThenByInternal(nil, whenfailure); end; constructor TPipedPromise<TSuccessSource, TSuccess, TFailureSource, TFailure>.Create( const prev: IPromiseAccess<TSuccessSource, TFailureSource>; const whenSucces: TPipelineFunc<TSuccessSource, TSuccess, TFailure>; const whenFailure: TPipelineFunc<IFailureReason<TFailureSource>, TSuccess, TFailure>); begin Assert(Assigned(prev)); FPrevPromise := prev; FFuture := TDeferredTask<TSuccess, TFailure>.Create(Self, procedure (const resolver: TProc<TSuccess>; const rejector: TFailureProc<TFailure>) var nextPromise: IPromiseAccess<TSuccess, TFailure>; begin FPrevPromise.Self.Future.WaitFor; nextPromise := nil; case FPrevpromise.State of TState.Resolved: begin Assert(Supports(whenSucces(FPrevPromise.GetValue), IPromiseAccess<TSuccess,TFailure>,nextPromise)); end; TState.Rejected: begin Assert(Supports(whenFailure(FPrevPromise.GetFailure), IPromiseAccess<TSuccess,TFailure>,nextPromise)); end; end; nextPromise.Self.Future.WaitFor; case nextPromise.State of TState.Resolved: begin resolver(nextPromise.GetValue) end; TState.Rejected: begin rejector(nextPromise.GetFailure); end; end; end ) end; function TPipedPromise<TSuccessSource, TSuccess, TFailureSource, TFailure>.Reject( value: IFailureReason<TFailure>): IPromise<TSuccess, TFailure>; begin TMonitor.Enter(Self); try FFailure := value; FState := TState.Rejected; finally TMonitor.Exit(Self); end; end; function TPipedPromise<TSuccessSource, TSuccess, TFailureSource, TFailure>.Resolve( value: TSuccess): IPromise<TSuccess, TFailure>; begin TMonitor.Enter(Self); try FState := TState.Resolved; finally TMonitor.Exit(Self); end; end; destructor TPipedPromise<TSuccessSource, TSuccess, TFailureSource, TFailure>.Destroy; begin inherited; end; function TPipedPromise<TSuccessSource, TSuccess, TFailureSource, TFailure>.Done( const proc: TProc<TSuccess>): IPromise<TSuccess, TFailure>; begin TMonitor.Enter(Self); try Result := TTerminatedPromise<TSuccess, TFailure>.Create(Self).Done(proc); finally TMonitor.Exit(Self); end; end; function TPipedPromise<TSuccessSource, TSuccess, TFailureSource, TFailure>.Fail( const proc: TFailureProc<TFailure>): IPromise<TSuccess, TFailure>; begin TMonitor.Enter(Self); try Result := TTerminatedPromise<TSuccess, TFailure>.Create(Self).Fail(proc); finally TMonitor.Exit(Self); end; end; function TPipedPromise<TSuccessSource, TSuccess, TFailureSource, TFailure>.ThenBy( const whenSuccess: TPipelineFunc<TSuccess, TSuccess, TFailure>; const whenfailure: TPipelineFunc<IFailureReason<TFailure>, TSuccess, TFailure>): IPromise<TSuccess, TFailure>; begin Assert(Assigned(whenSuccess)); Assert(Assigned(whenFailure)); Result := Self.ThenByInternal(whenSuccess, whenfailure); end; function TPipedPromise<TSuccessSource, TSuccess, TFailureSource, TFailure>.ThenBy( const whenSuccess: TPipelineFunc<TSuccess, TSuccess, TFailure>): IPromise<TSuccess, TFailure>; begin Assert(Assigned(whenSuccess)); Result := Self.ThenByInternal(whenSuccess, nil); end; function TPipedPromise<TSuccessSource, TSuccess, TFailureSource, TFailure>.GetFuture: IFuture<TSuccess>; begin Result := FFuture; end; function TPipedPromise<TSuccessSource, TSuccess, TFailureSource, TFailure>.GetSelfInternal: IPromise<TSuccess, TFailure>; begin Result := Self; end; function TPipedPromise<TSuccessSource, TSuccess, TFailureSource, TFailure>.GetStateInternal: TState; begin Result := FState; end; function TPipedPromise<TSuccessSource, TSuccess, TFailureSource, TFailure>.GetValueInternal: TSuccess; begin Result := FFuture.Value; end; function TPipedPromise<TSuccessSource, TSuccess, TFailureSource, TFailure>.Op: TPromiseOp<TSuccess, TFailure>; begin Result := TPromiseOp<TSuccess, TFailure>.Create(Self); end; function TPipedPromise<TSuccessSource, TSuccess, TFailureSource, TFailure>.GetFailureInternal: IFailureReason<TFailure>; begin Result := FFailure; end; { TTerminatedPromise<TResult, TFailure> } constructor TTerminatedPromise<TResult, TFailure>.Create( const prev: IPromiseAccess<TResult, TFailure>); begin Assert(Assigned(prev)); FPrevPromise := prev; FDoneActions := TList<TProc<TResult>>.Create; FFailActions := TList<TFailureProc<TFailure>>.Create; FFuture := TDeferredTask<TResult,TFailure>.Create(Self, procedure (const resolver: TProc<TResult>; const rejector: TFailureProc<TFailure>) begin FPrevPromise.Self.Future.WaitFor; case FPrevPromise.State of TSTate.Resolved: begin resolver(FPrevPromise.GetValue); end; TSTate.Rejected: begin rejector(FPrevPromise.GetFailure); end; end; end ); end; destructor TTerminatedPromise<TResult, TFailure>.Destroy; begin FDoneActions.Free; FFailActions.Free; inherited; end; function TTerminatedPromise<TResult, TFailure>.Resolve( value: TResult): IPromise<TResult, TFailure>; var proc: TProc<TResult>; begin TMonitor.Enter(Self); try for proc in FDoneActions do begin proc(value); end; FState := TState.Resolved; finally TMonitor.Exit(Self); end; end; function TTerminatedPromise<TResult, TFailure>.Reject( value: IFailureReason<TFailure>): IPromise<TResult, TFailure>; var proc: TFailureProc<TFailure>; begin TMonitor.Enter(Self); try for proc in FFailActions do begin proc(value); end; FState := TState.Rejected; finally TMonitor.Exit(Self); end; end; function TTerminatedPromise<TResult, TFailure>.Done( const proc: TProc<TResult>): IPromise<TResult, TFailure>; begin TMonitor.Enter(Self); try case Self.GetState of TState.Pending: begin FDoneActions.Add(proc); end; TState.Resolved: begin proc(FPrevPromise.GetValue); end; end; Result := Self; finally TMonitor.Exit(Self); end; end; function TTerminatedPromise<TResult, TFailure>.Fail( const proc: TFailureProc<TFailure>): IPromise<TResult, TFailure>; begin TMonitor.Enter(Self); try case Self.GetState of TState.Pending: begin FFailActions.Add(proc); end; TState.Rejected: begin proc(FPrevPromise.GetFailure); end; end; Result := Self; finally TMonitor.Exit(Self); end; end; function TTerminatedPromise<TResult, TFailure>.GetFuture: IFuture<TResult>; begin Result := FFuture; end; function TTerminatedPromise<TResult, TFailure>.GetState: TState; begin Result := FState; end; function TTerminatedPromise<TResult, TFailure>.Op: TPromiseOp<TResult, TFailure>; begin Assert(false, 'Promise pipe is not supported'); end; function TTerminatedPromise<TResult, TFailure>.ThenBy( const whenSuccess: TPipelineFunc<TResult, TResult, TFailure>; const whenfailure: TPipelineFunc<IFailureReason<TFailure>, TResult, TFailure>): IPromise<TResult, TFailure>; begin Assert(false, 'Promise pipe is not supported'); end; function TTerminatedPromise<TResult, TFailure>.ThenBy( const fn: TPipelineFunc<TResult, TResult, TFailure>): IPromise<TResult, TFailure>; begin Assert(false, 'Promise pipe is not supported'); end; function TTerminatedPromise<TResult, TFailure>.Catch( const whenfailure: TPipelineFunc<IFailureReason<TFailure>, TResult, TFailure>): IPromise<TResult, TFailure>; begin Assert(false, 'Promise pipe is not supported'); end; { TPromiseValue<TResult, TFailure> } class function TPromiseValue<TResult, TFailure>.Resolve( success: TResult): TPromiseValue<TResult, TFailure>; begin Result := TPromiseValue<TResult, TFailure>.Create; Result.FSuccess := success; Result.FState := TSTate.Resolved; end; class function TPromiseValue<TResult, TFailure>.Reject( failure: IFailureReason<TFailure>): TPromiseValue<TResult, TFailure>; begin Result := TPromiseValue<TResult, TFailure>.Create; Result.FFailure := failure; Result.FState := TSTate.Rejected; end; function TPromiseValue<TResult, TFailure>.GetFuture: IFuture<TResult>; begin Result := TFuture.Create(FSuccess); end; function TPromiseValue<TResult, TFailure>.GetSelfInternal: IPromise<TResult, TFailure>; begin Result := Self; end; function TPromiseValue<TResult, TFailure>.GetFailureInternal: IFailureReason<TFailure>; begin Result := FFailure; end; function TPromiseValue<TResult, TFailure>.GetStateInternal: TState; begin Result := FState; end; function TPromiseValue<TResult, TFailure>.GetValueInternal: TResult; begin Result := FSuccess; end; function TPromiseValue<TResult, TFailure>.Op: TPromiseOp<TResult, TFailure>; begin Result := TPromiseOp<TResult, TFailure>.Create(Self); end; function TPromiseValue<TResult, TFailure>.Catch( const whenfailure: TPipelineFunc<IFailureReason<TFailure>, TResult, TFailure>): IPromise<TResult, TFailure>; begin Assert(false, 'Promise pipe is not supported'); end; function TPromiseValue<TResult, TFailure>.Done( const proc: TProc<TResult>): IPromise<TResult, TFailure>; begin Assert(false, 'Promise pipe is not supported'); end; function TPromiseValue<TResult, TFailure>.Fail( const proc: TFailureProc<TFailure>): IPromise<TResult, TFailure>; begin Assert(false, 'Promise pipe is not supported'); end; function TPromiseValue<TResult, TFailure>.ThenBy( const whenSuccess: TPipelineFunc<TResult, TResult, TFailure>; const whenfailure: TPipelineFunc<IFailureReason<TFailure>, TResult, TFailure>): IPromise<TResult, TFailure>; begin Assert(false, 'Promise pipe is not supported'); end; function TPromiseValue<TResult, TFailure>.ThenBy( const fn: TPipelineFunc<TResult, TResult, TFailure>): IPromise<TResult, TFailure>; begin Assert(false, 'Promise pipe is not supported'); end; { TPromiseValue<TResult, TFailure>.TFuture<TResult> } constructor TPromiseValue<TResult, TFailure>.TFuture.Create(value: TResult); begin FValue := value; end; procedure TPromiseValue<TResult, TFailure>.TFuture.Cancell; begin end; function TPromiseValue<TResult, TFailure>.TFuture.GetValue: TResult; begin Result := FValue; end; function TPromiseValue<TResult, TFailure>.TFuture.WaitFor: boolean; begin Result := true; end; end.
unit DataProxy.Products; interface uses Data.DB, Data.DataProxy, // FireDAC - TFDQuery ------------------------------ FireDAC.Comp.Client, FireDAC.DApt, FireDAC.Stan.Param, FireDAC.Stan.Async; type TProductsProxy = class(TDatasetProxy) protected procedure ConnectFields; override; public ProductID: TIntegerField; ProductName: TWideStringField; SupplierID: TIntegerField; CategoryID: TIntegerField; QuantityPerUnit: TWideStringField; UnitPrice: TBCDField; UnitsInStock: TSmallintField; UnitsOnOrder: TSmallintField; ReoderLevel: TSmallintField; Discontinued: TSmallintField; procedure Open(OrderID: integer); procedure Close; // property DataSet: TDataSet read FDataSet; end; implementation uses System.SysUtils, Database.Connector; const SQL_SELECT = 'SELECT PRODUCTID, PRODUCTNAME, SUPPLIERID, CATEGORYID, ' + ' QUANTITYPERUNIT, UNITPRICE, UNITSINSTOCK, UNITSONORDER, REORDERLEVEL, ' + ' DISCONTINUED FROM {id Products} '; procedure TProductsProxy.Close; begin end; procedure TProductsProxy.ConnectFields; begin ProductID := FDataSet.FieldByName('PRODUCTID') as TIntegerField; ProductName := FDataSet.FieldByName('PRODUCTNAME') as TWideStringField; SupplierID := FDataSet.FieldByName('SUPPLIERID') as TIntegerField; CategoryID := FDataSet.FieldByName('CATEGORYID') as TIntegerField; QuantityPerUnit := FDataSet.FieldByName('QUANTITYPERUNIT') as TWideStringField; UnitPrice := FDataSet.FieldByName('UNITPRICE') as TBCDField; UnitsInStock := FDataSet.FieldByName('UNITSINSTOCK') as TSmallintField; UnitsOnOrder := FDataSet.FieldByName('UNITSONORDER') as TSmallintField; ReoderLevel := FDataSet.FieldByName('REORDERLEVEL') as TSmallintField; Discontinued := FDataSet.FieldByName('DISCONTINUED') as TSmallintField; end; procedure TProductsProxy.Open(OrderID: integer); var fdq: TFDQuery; begin if not Assigned(FDataSet) then raise Exception.Create('The DataSet is required'); fdq := TFDQuery.Create(nil); fdq.SQL.Text := SQL_SELECT; fdq.Connection := GlobalConnector.GetMainConnection; FDataSet := fdq; FDataSet.Open; ConnectFields; end; end.
{$INCLUDE switches} unit Draft; interface uses Protocol,ClientTools,Term,ScreenTools,PVSB,BaseWin, Windows,Messages,SysUtils,Classes,Graphics,Controls,Forms,ExtCtrls,ButtonA, ButtonB, ButtonBase, Area; type TDraftDlg = class(TBufferedDrawDlg) OKBtn: TButtonA; CloseBtn: TButtonB; GroundArea: TArea; SeaArea: TArea; AirArea: TArea; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure CloseBtnClick(Sender: TObject); procedure PaintBox1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; x, y: integer); procedure OKBtnClick(Sender: TObject); procedure PaintBox1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; x, y: integer); procedure FormDestroy(Sender: TObject); public procedure ShowNewContent(NewMode: integer); protected procedure OffscreenPaint; override; private Domain,MaxLines,Lines,Cut,yDomain,yFeature,yWeight,yTotal,yView,IncCap, DecCap: integer; code: array[0..nFeature-1] of integer; Template,Back: TBitmap; function IsFeatureInList(d,i: integer): boolean; procedure SetDomain(d: integer); end; var DraftDlg: TDraftDlg; implementation uses Help,Tribes,Directories; {$R *.DFM} const MaxLines0=11; LinePitch=20; xDomain=30; yDomain0=464; DomainPitch=40; xFeature=38; yFeature0=42; xWeight=100; yWeight0=271; xTotal=20; xTotal2=34; yTotal0=354; xView=17; yView0=283; procedure TDraftDlg.FormCreate(Sender: TObject); begin inherited; InitButtons(); HelpContext:='CLASSES'; Caption:=Phrases.Lookup('TITLE_DRAFT'); OKBtn.Caption:=Phrases.Lookup('BTN_OK'); if not Phrases2FallenBackToEnglish then begin GroundArea.Hint:=Phrases2.Lookup('DRAFTDOMAIN',0); SeaArea.Hint:=Phrases2.Lookup('DRAFTDOMAIN',1); AirArea.Hint:=Phrases2.Lookup('DRAFTDOMAIN',2); end else begin GroundArea.Hint:=Phrases.Lookup('DOMAIN',0); SeaArea.Hint:=Phrases.Lookup('DOMAIN',1); AirArea.Hint:=Phrases.Lookup('DOMAIN',2); end; Back:=TBitmap.Create; Back.PixelFormat:=pf24bit; Back.Width:=ClientWidth; Back.Height:=ClientHeight; Template:=TBitmap.Create; LoadGraphicFile(Template, HomeDir+'Graphics\MiliRes', gfNoGamma); Template.PixelFormat:=pf8bit; end; procedure TDraftDlg.FormDestroy(Sender: TObject); begin Back.Free; Template.Free; end; procedure TDraftDlg.CloseBtnClick(Sender: TObject); begin ModalResult:=mrCancel; end; procedure TDraftDlg.OffscreenPaint; function DomainAvailable(d: integer): boolean; begin result:=(upgrade[d,0].Preq=preNone) or (MyRO.Tech[upgrade[d,0].Preq]>=tsApplicable); end; procedure PaintTotalBars; var i,y,dx,num,w: integer; s: string; begin with offscreen.Canvas do begin // strength bar y:=yTotal; DarkGradient(Offscreen.Canvas,xTotal-6,y+1,184,2); DarkGradient(Offscreen.Canvas,xTotal2+172,y+1,95,2); RisedTextOut(Offscreen.Canvas,xTotal-2,y,Phrases.Lookup('UNITSTRENGTH')); RisedTextOut(Offscreen.Canvas,xTotal+112+30,y,'x'+IntToStr(MyRO.DevModel.MStrength)); RisedTextOut(Offscreen.Canvas,xTotal2+148+30,y,'='); s:=IntToStr(MyRO.DevModel.Attack)+'/'+IntToStr(MyRO.DevModel.Defense); RisedTextOut(Offscreen.Canvas,xTotal2+170+64+30-BiColorTextWidth(Offscreen.Canvas,s),y,s); // transport bar if MyRO.DevModel.MTrans>0 then begin y:=yTotal+19; DarkGradient(Offscreen.Canvas,xTotal-6,y+1,184,1); DarkGradient(Offscreen.Canvas,xTotal2+172,y+1,95,1); RisedTextOut(Offscreen.Canvas,xTotal-2,y,Phrases.Lookup('UNITTRANSPORT')); RisedTextOut(Offscreen.Canvas,xTotal+112+30,y,'x'+IntToStr(MyRO.DevModel.MTrans)); RisedTextOut(Offscreen.Canvas,xTotal2+148+30,y,'='); Font.Color:=$000000; dx:=-237-30; for i:=mcFirstNonCap-1 downto 3 do if i in [mcSeaTrans,mcCarrier,mcAirTrans] then begin num:=MyRO.DevModel.Cap[i]*MyRO.DevModel.MTrans; if num>0 then begin inc(dx,15); Brush.Color:=$C0C0C0; FrameRect(Rect(xTotal2-3-dx,y+2,xTotal2+11-dx,y+16)); Brush.Style:=bsClear; Sprite(Offscreen,HGrSystem,xTotal2-1-dx,y+4,10,10,66+i mod 11 *11,137+i div 11 *11); if num>1 then begin s:=IntToStr(num); w:=TextWidth(s); inc(dx,w+1); Brush.Color:=$FFFFFF; FillRect(Rect(xTotal2-3-dx,y+2,xTotal2+w-1-dx,y+16)); Brush.Style:=bsClear; Textout(xTotal2-3-dx+1,y,s); end; end; end end; // speed bar y:=yTotal+38; LoweredTextOut(offscreen.Canvas,-1,MainTexture,xTotal-2,y,Phrases.Lookup('UNITSPEED')); DLine(offscreen.Canvas,xTotal-2,xTotal+174,y+16,MainTexture.clBevelShade, MainTexture.clBevelLight); DLine(offscreen.Canvas,xTotal2+176,xTotal2+263,y+16,MainTexture.clBevelShade, MainTexture.clBevelLight); s:=MovementToString(MyRO.DevModel.Speed); RisedTextOut(offscreen.Canvas,xTotal2+170+64+30-TextWidth(s),y,s); // cost bar y:=yTotal+57; LoweredTextOut(offscreen.Canvas,-1,MainTexture,xTotal-2,y,Phrases.Lookup('UNITCOST')); LoweredTextOut(Offscreen.Canvas,-1,MainTexture,xTotal+112+30,y,'x'+IntToStr(MyRO.DevModel.MCost)); LoweredTextOut(Offscreen.Canvas,-1,MainTexture,xTotal2+148+30,y,'='); DLine(offscreen.Canvas,xTotal-2,xTotal+174,y+16,MainTexture.clBevelShade, MainTexture.clBevelLight); DLine(offscreen.Canvas,xTotal2+176,xTotal2+263,y+16,MainTexture.clBevelShade, MainTexture.clBevelLight); s:=IntToStr(MyRO.DevModel.Cost); RisedTextOut(offscreen.Canvas,xTotal2+170+64+30-12-TextWidth(s),y,s); Sprite(offscreen,HGrSystem,xTotal2+170+54+30,y+4,10,10,88,115); if G.Difficulty[me]<>2 then begin // corrected cost bar y:=yTotal+76; LoweredTextOut(offscreen.Canvas,-1,MainTexture,xTotal-2,y, Phrases.Lookup('COSTDIFF'+char(48+G.Difficulty[me]))); LoweredTextOut(Offscreen.Canvas,-1,MainTexture,xTotal2+148+30,y,'='); DLine(offscreen.Canvas,xTotal-2,xTotal+174,y+16,MainTexture.clBevelShade, MainTexture.clBevelLight); DLine(offscreen.Canvas,xTotal2+176,xTotal2+263,y+16,MainTexture.clBevelShade, MainTexture.clBevelLight); s:=IntToStr(MyRO.DevModel.Cost*BuildCostMod[G.Difficulty[me]] div 12); RisedTextOut(offscreen.Canvas,xTotal2+170+64+30-12-TextWidth(s),y,s); Sprite(offscreen,HGrSystem,xTotal2+170+54+30,y+4,10,10,88,115); end; end; end; var i,j,x,d,n,TextColor,CapWeight,DomainCount: integer; begin inherited; ClientHeight:=Template.Height-Cut; if ClientHeight>hMainTexture then // assemble background from 2 texture tiles begin bitblt(Back.Canvas.Handle,0,0,ClientWidth,64,MainTexture.Image.Canvas.Handle, (wMainTexture-ClientWidth) div 2,hMainTexture-64,SRCCOPY); bitblt(Back.Canvas.Handle,0,64,ClientWidth,ClientHeight-64, MainTexture.Image.Canvas.Handle,(wMainTexture-ClientWidth) div 2,0,SRCCOPY); end else bitblt(Back.Canvas.Handle,0,0,ClientWidth,ClientHeight,MainTexture.Image.Canvas.Handle, (wMainTexture-ClientWidth) div 2,(hMainTexture-ClientHeight) div 2,SRCCOPY); ImageOp_B(Back,Template,0,0,0,0,Template.Width,64); ImageOp_B(Back,Template,0,64,0,64+Cut,Template.Width,Template.Height-64-Cut); bitblt(offscreen.canvas.handle,0,0,ClientWidth,ClientHeight,Back.Canvas.handle,0,0,SRCCOPY); offscreen.Canvas.Font.Assign(UniFont[ftCaption]); RisedTextout(offscreen.Canvas,10,7,Caption); offscreen.Canvas.Font.Assign(UniFont[ftSmall]); with MyRO.DevModel do begin DomainCount:=0; for d:=0 to nDomains-1 do if DomainAvailable(d) then inc(DomainCount); if DomainCount>1 then begin for d:=0 to nDomains-1 do if DomainAvailable(d) then begin x:=xDomain+d*DomainPitch; if d=Domain then ImageOp_BCC(Offscreen,Templates,x,yDomain,142,246+37*d,36,36,0,$00C0FF) else ImageOp_BCC(Offscreen,Templates,x,yDomain,142,246+37*d,36,36,0,$606060); end; Frame(Offscreen.Canvas,xDomain-11,yDomain-3,xDomain+2*DomainPitch+46, yDomain+38,$B0B0B0,$FFFFFF); RFrame(Offscreen.Canvas,xDomain-12,yDomain-4,xDomain+2*DomainPitch+47, yDomain+39,$FFFFFF,$B0B0B0); end; GroundArea.Top:=yDomain; GroundArea.Visible:=DomainAvailable(dGround); SeaArea.Top:=yDomain; SeaArea.Visible:=DomainAvailable(dSea); AirArea.Top:=yDomain; AirArea.Visible:=DomainAvailable(dAir); PaintTotalBars; // display weight with offscreen.Canvas do begin for i:=0 to MaxWeight-1 do if i<Weight then ImageOp_BCC(Offscreen,Templates,xWeight+20*i, yWeight,123,400,18,20,0,$949494) else ImageOp_BCC(Offscreen,Templates,xWeight+20*i, yWeight,105,400,18,20,0,$949494); end; with offscreen.Canvas do for i:=0 to Lines-1 do begin if not (code[i] in AutoFeature) then begin // paint +/- butttons if code[i]<mcFirstNonCap then begin Dump(offscreen,HGrSystem,xFeature-21,yFeature+2+LinePitch*i, 12,12,169,172); Dump(offscreen,HGrSystem,xFeature-9,yFeature+2+LinePitch*i, 12,12,169,159); RFrame(offscreen.Canvas,xFeature-(21+1),yFeature+2+LinePitch*i-1, xFeature-(21-24),yFeature+2+LinePitch*i+12, MainTexture.clBevelShade,MainTexture.clBevelLight); end else begin Dump(offscreen,HGrSystem,xFeature-9,yFeature+2+LinePitch*i, 12,12,169,185+13*MyRO.DevModel.Cap[code[i]]); RFrame(offscreen.Canvas,xFeature-(9+1),yFeature+2+LinePitch*i-1, xFeature-(21-24),yFeature+2+LinePitch*i+12, MainTexture.clBevelShade,MainTexture.clBevelLight); end; // paint cost LightGradient(offscreen.Canvas,xFeature+34,yFeature+LinePitch*i,50, GrExt[HGrSystem].Data.Canvas.Pixels[187,137]); if (Domain=dGround) and (code[i]=mcDefense) then CapWeight:=2 else CapWeight:=Feature[code[i]].Weight; n:=CapWeight+Feature[code[i]].Cost; d:=6; while (n-1)*d*2>48-10 do dec(d); for j:=0 to n-1 do if j<CapWeight then Sprite(offscreen,HGrSystem,xFeature+54+(j*2+1-n)*d, yFeature+2+LinePitch*i+1,10,10,88,126) else Sprite(offscreen,HGrSystem,xFeature+54+(j*2+1-n)*d, yFeature+2+LinePitch*i+1,10,10,88,115); end; // if not (code[i] in AutoFeature) DarkGradient(offscreen.Canvas,xFeature+17,yFeature+LinePitch*i,16,1); Frame(offscreen.canvas,xFeature+18,yFeature+1+LinePitch*i, xFeature+20-2+13,yFeature+2+1-2+13+LinePitch*i,$C0C0C0,$C0C0C0); Sprite(offscreen,HGrSystem,xFeature+20,yFeature+2+1+LinePitch*i, 10,10,66+code[i] mod 11 *11,137+code[i] div 11 *11); if MyRO.DevModel.Cap[code[i]]>0 then TextColor:=MainTexture.clLitText else TextColor:=-1; if code[i]<mcFirstNonCap then LoweredTextOut(offscreen.Canvas,TextColor,MainTexture,xFeature+7, yFeature+LinePitch*i-1,IntToStr(MyRO.DevModel.Cap[code[i]])); LoweredTextOut(offscreen.Canvas,TextColor,MainTexture,xFeature+88, yFeature+LinePitch*i-1,Phrases.Lookup('FEATURES',code[i])); end; end; // free features j:=0; for i:=0 to nFeature-1 do if (i in AutoFeature) and (1 shl Domain and Feature[i].Domains<>0) and (Feature[i].Preq<>preNA) and ((Feature[i].Preq=preSun) and (MyRO.Wonder[woSun].EffectiveOwner=me) or (Feature[i].Preq>=0) and (MyRO.Tech[Feature[i].Preq]>=tsApplicable)) and not ((Feature[i].Preq=adSteamEngine) and (MyRO.Tech[adNuclearPower]>=tsApplicable)) then begin DarkGradient(offscreen.Canvas,xWeight+4,yWeight+32+LinePitch*j,16,1); Frame(offscreen.canvas,xWeight+5,yWeight+33+LinePitch*j, xWeight+18,yWeight+47+LinePitch*j,$C0C0C0,$C0C0C0); Sprite(offscreen,HGrSystem,xWeight+7,yWeight+36+LinePitch*j, 10,10,66+i mod 11 *11,137+i div 11 *11); LoweredTextOut(offscreen.Canvas,-1,MainTexture,xWeight+26, yWeight+31+LinePitch*j,Phrases.Lookup('FEATURES',i)); inc(j); end; with Tribe[me].ModelPicture[MyRO.nModel] do begin FrameImage(offscreen.canvas,BigImp,xView+4,yView+4,xSizeBig,ySizeBig,0,0); Sprite(offscreen,HGr,xView,yView,64,44,pix mod 10 *65+1,pix div 10*49+1); end; MarkUsedOffscreen(ClientWidth,ClientHeight); end;{MainPaint} procedure TDraftDlg.SetDomain(d: integer); function Prio(fix: integer): integer; var FeaturePreq: integer; begin FeaturePreq:=Feature[fix].Preq; assert(FeaturePreq<>preNA); if fix<mcFirstNonCap then result:=10000+fix else if FeaturePreq=preNone then result:=20000 else if FeaturePreq<0 then result:=40000 else result:=30000+AdvValue[FeaturePreq]; if not (fix in AutoFeature) then inc(result,90000); end; var i,j,x: integer; begin Domain:=d; Lines:=0; for i:=0 to nFeature-1 do if IsFeatureInList(Domain,i) then begin code[Lines]:=i; inc(Lines) end; yFeature:=yFeature0+(MaxLines-Lines)*LinePitch div 2; // sort features for i:=0 to Lines-2 do for j:=i+1 to Lines-1 do if Prio(code[i])>Prio(code[j]) then begin // exchange x:=code[i]; code[i]:=code[j]; code[j]:=x end; end; function TDraftDlg.IsFeatureInList(d,i: integer): boolean; begin result:= not (i in AutoFeature) and (1 shl d and Feature[i].Domains<>0) and (Feature[i].Preq<>preNA) and ((Feature[i].Preq=preNone) or (Feature[i].Preq=preSun) and (MyRO.Wonder[woSun].EffectiveOwner=me) or (Feature[i].Preq>=0) and (MyRO.Tech[Feature[i].Preq]>=tsApplicable)); end; procedure TDraftDlg.FormShow(Sender: TObject); var count,d,i: integer; begin Domain:=dGround; while (Domain<dAir) and (upgrade[Domain,0].Preq<>preNone) and (MyRO.Tech[upgrade[Domain,0].Preq]<tsApplicable) do inc(Domain); // count max number of features in any domain MaxLines:=0; for d:=0 to nDomains-1 do if (upgrade[d,0].Preq=preNone) or (MyRO.Tech[upgrade[d,0].Preq]>=tsApplicable) then begin count:=0; for i:=0 to nFeature-1 do if IsFeatureInList(d,i) then inc(count); if count>MaxLines then MaxLines:=count; end; Cut:=(MaxLines0-MaxLines)*LinePitch; OKBtn.Top:=477-Cut; yDomain:=yDomain0-Cut; yWeight:=yWeight0-Cut; yTotal:=yTotal0-Cut; yView:=yView0-Cut; if WindowMode=wmModal then begin {center on screen} Left:=(Screen.Width-Template.Width) div 2; Top:=(Screen.Height-(Template.Height-Cut)) div 2; end; SetDomain(Domain); Server(sCreateDevModel,me,Domain,nil^); MyModel[MyRO.nModel]:=MyRO.DevModel; InitMyModel(MyRO.nModel,false); OffscreenPaint; IncCap:=-1; DecCap:=-1; end; procedure TDraftDlg.ShowNewContent(NewMode: integer); begin inherited ShowNewContent(NewMode); end; procedure TDraftDlg.PaintBox1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; x, y: integer); var i,d: integer; begin if Button=mbLeft then begin for d:=0 to nDomains-1 do if (d<>Domain) and ((upgrade[d,0].Preq=preNone) or (MyRO.Tech[upgrade[d,0].Preq]>=tsApplicable)) and (x>=xDomain+d*DomainPitch) and (x<xDomain+d*DomainPitch+36) and (y>=yDomain) and (y<yDomain+36) then begin SetDomain(d); Server(sCreateDevModel,me,Domain,nil^); MyModel[MyRO.nModel]:=MyRO.DevModel; InitMyModel(MyRO.nModel,false); SmartUpdateContent; end; if (y>=yFeature) and (y<yFeature+LinePitch*Lines) then begin i:=(y-yFeature) div LinePitch; if (x>=xFeature-21) and (x<ClientWidth) and (ssShift in Shift) then HelpDlg.ShowNewContent(FWindowMode or wmPersistent, hkFeature, code[i]) else if not (code[i] in AutoFeature) then begin if (code[i]<mcFirstNonCap) and (x>=xFeature-21) and (x<xFeature-21+12) then begin IncCap:=code[i]; Dump(offscreen,HGrSystem,xFeature-21,yFeature+2+LinePitch*i,12,12,182,172); SmartInvalidate; end else if (x>=xFeature-9) and (x<xFeature-9+12) then begin DecCap:=code[i]; if code[i]<mcFirstNonCap then Dump(offscreen,HGrSystem,xFeature-9,yFeature+2+LinePitch*i,12,12,182,159) else Dump(offscreen,HGrSystem,xFeature-9,yFeature+2+LinePitch*i, 12,12,182,185+13*MyRO.DevModel.Cap[code[i]]); SmartInvalidate; end; end end end end; procedure TDraftDlg.PaintBox1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; x, y: integer); var NewValue: integer; begin if IncCap>=0 then begin NewValue:=MyRO.DevModel.Cap[IncCap]+1; Server(sSetDevModelCap+NewValue shl 4,me,IncCap,nil^); MyModel[MyRO.nModel]:=MyRO.DevModel; InitMyModel(MyRO.nModel,false); SmartUpdateContent; IncCap:=-1; end else if DecCap>=0 then begin if (DecCap>=mcFirstNonCap) or (MyRO.DevModel.Cap[DecCap]>0) then begin NewValue:=MyRO.DevModel.Cap[DecCap]-1; if DecCap>=mcFirstNonCap then NewValue:=-NewValue; Server(sSetDevModelCap+NewValue shl 4,me,DecCap,nil^); MyModel[MyRO.nModel]:=MyRO.DevModel; InitMyModel(MyRO.nModel,false); end; SmartUpdateContent; DecCap:=-1; end; end; procedure TDraftDlg.OKBtnClick(Sender: TObject); begin ModalResult:=mrOK; end; end.
{ Subroutine STRING_CMLINE_TOKEN (TOKEN, STAT) * * Fetch the next token from the command line. STRING_CMLINE_INIT must have been * called once before this routine. If STRING_CMLINE_REUSE was called since the * last call to this routine, then the last token will be returned again. * * This version is for any operating system where we are given the entire * command line as one string, then parse it ourselves. } module string_cmline_token; define string_cmline_token; %include 'string2.ins.pas'; %include 'string_sys.ins.pas'; procedure string_cmline_token ( {get next token from command line} in out token: univ string_var_arg_t; {returned token} out stat: sys_err_t); {completion status, used to signal end} begin if cmline_reuse then begin {return the same token as last time} cmline_reuse := false; {reset to read fresh token next time} if cmline_last_eos then begin {EOS was returned for the last token ?} sys_stat_set (string_subsys_k, string_stat_eos_k, stat); return; {return with end of string status} end; sys_error_none (stat); {init to no error} end else begin {return the next token from the command line} if cmline_next_n = 1 then begin {getting first token on command line ?} vcmline_parse := vcmline_parse_start; {reset to get first argument next} end; string_token ( {extract next token from command line string} vcmline, {input string} vcmline_parse, {VCMLINE parse index} cmline_token_last, {returned token string} stat); cmline_last_eos := {remember if hit end of string} stat.err and (stat.subsys = string_subsys_k) and (stat.code = string_stat_eos_k); cmline_next_n := cmline_next_n + 1; {update number of next command line token} end ; string_copy (cmline_token_last, token); {return token to caller} end;
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, DSE_theater, Vcl.ExtCtrls, Vcl.StdCtrls, Generics.Collections ,Generics.Defaults, DSE_Bitmap; type TForm1 = class(TForm) SE_Theater1: SE_Theater; SE_Background: SE_Engine; SE_Characters: SE_Engine; Panel1: TPanel; Label1: TLabel; CheckBox1: TCheckBox; CheckBox2: TCheckBox; Edit1: TEdit; Panel2: TPanel; Label2: TLabel; CheckBox3: TCheckBox; CheckBox4: TCheckBox; Edit2: TEdit; SE_Arrows: SE_Engine; procedure FormCreate(Sender: TObject); procedure CheckBox1Click(Sender: TObject); procedure CheckBox2Click(Sender: TObject); procedure CheckBox3Click(Sender: TObject); procedure CheckBox4Click(Sender: TObject); procedure Edit2Change(Sender: TObject); procedure Edit1Change(Sender: TObject); procedure SE_Theater1SpriteMouseDown(Sender: TObject; lstSprite: TObjectList<DSE_theater.SE_Sprite>; Button: TMouseButton; Shift: TShiftState); private { Private declarations } procedure ScaleArrows; procedure PreLoadMemoryBitmaps; public { Public declarations } end; var Form1: TForm1; gabriel,shahira: SE_BITMAP; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); var Background: SE_Sprite; begin SE_Theater1.VirtualWidth := 1920; SE_Theater1.VirtualHeight := 1200; SE_Theater1.Width := 1024; SE_Theater1.Height := 600; SE_Background.Priority := 0; SE_Characters.Priority := 1; Background:= SE_Background.CreateSprite('..\!media\back1.bmp','background',{framesX}1,{framesY}1,{Delay}0,{X}0,{Y}0,{transparent}false); Background.Position := Point( Background.FrameWidth div 2 , Background.FrameHeight div 2 ); SE_Theater1.Active := True; SE_Arrows.CreateSprite('..\!media\arrow1.bmp','arrow1',{framesX}1,{framesY}1,{Delay}0,{X}100,{Y}560,{transparent}false); SE_Arrows.CreateSprite('..\!media\arrow2.bmp','arrow2',{framesX}1,{framesY}1,{Delay}0,{X}134,{Y}560,{transparent}false); SE_Arrows.CreateSprite('..\!media\arrow3.bmp','arrow3',{framesX}1,{framesY}1,{Delay}0,{X}134,{Y}524,{transparent}false); SE_Arrows.CreateSprite('..\!media\arrow4.bmp','arrow4',{framesX}1,{framesY}1,{Delay}0,{X}100,{Y}524,{transparent}false); SE_Arrows.CreateSprite('..\!media\arrow5.bmp','arrow5',{framesX}1,{framesY}1,{Delay}0,{X}66,{Y}524,{transparent}false); SE_Arrows.CreateSprite('..\!media\arrow6.bmp','arrow6',{framesX}1,{framesY}1,{Delay}0,{X}66,{Y}560,{transparent}false); ScaleArrows; PreLoadMemoryBitmaps; SE_Characters.CreateSprite(gabriel.Bitmap ,'gabriel',{framesX}15,{framesY}6,{Delay}5,{X}100,{Y}100,{transparent}true); SE_Characters.CreateSprite(shahira.Bitmap,'shahira',{framesX}15,{framesY}6,{Delay}5,{X}200,{Y}100,{transparent}true); gabriel.Free; shahira.Free; end; procedure TForm1.PreLoadMemoryBitmaps; var i: Integer; tmp: SE_BITMAP; begin gabriel := SE_BITMAP.Create ( 1920 , 128 * 6); tmp:= SE_Bitmap.Create ( '..\!media\gabriel_IDLE.1.bmp'); tmp.CopyRectTo(gabriel,0,0,0,0,1920,128, false ,0 ) ; tmp.Free; tmp:= SE_Bitmap.Create ( '..\!media\gabriel_IDLE.2.bmp'); tmp.CopyRectTo(gabriel,0,0,0,128,1920,128, false ,0 ) ; tmp.Free; tmp:= SE_Bitmap.Create ( '..\!media\gabriel_IDLE.3.bmp'); tmp.CopyRectTo(gabriel,0,0,0,256,1920,128, false ,0 ) ; tmp.Free; tmp:= SE_Bitmap.Create ( '..\!media\gabriel_IDLE.4.bmp'); tmp.CopyRectTo(gabriel,0,0,0,384,1920,128, false ,0 ) ; tmp.Free; tmp:= SE_Bitmap.Create ( '..\!media\gabriel_IDLE.5.bmp'); tmp.CopyRectTo(gabriel,0,0,0,512,1920,128, false ,0 ) ; tmp.Free; tmp:= SE_Bitmap.Create ( '..\!media\gabriel_IDLE.6.bmp'); tmp.CopyRectTo(gabriel,0,0,0,640,1920,128, false ,0 ) ; tmp.Free; shahira := SE_BITMAP.Create ( 1920 , 128 * 6); tmp:= SE_Bitmap.Create ( '..\!media\shahira_IDLE.1.bmp'); tmp.CopyRectTo(shahira,0,0,0,0,1920,128, false ,0 ) ; tmp.Free; tmp:= SE_Bitmap.Create ( '..\!media\shahira_IDLE.2.bmp'); tmp.CopyRectTo(shahira,0,0,0,128,1920,128, false ,0 ) ; tmp.Free; tmp:= SE_Bitmap.Create ( '..\!media\shahira_IDLE.3.bmp'); tmp.CopyRectTo(shahira,0,0,0,256,1920,128, false ,0 ) ; tmp.Free; tmp:= SE_Bitmap.Create ( '..\!media\shahira_IDLE.4.bmp'); tmp.CopyRectTo(shahira,0,0,0,384,1920,128, false ,0 ) ; tmp.Free; tmp:= SE_Bitmap.Create ( '..\!media\shahira_IDLE.5.bmp'); tmp.CopyRectTo(shahira,0,0,0,512,1920,128, false ,0 ) ; tmp.Free; tmp:= SE_Bitmap.Create ( '..\!media\shahira_IDLE.6.bmp'); tmp.CopyRectTo(shahira,0,0,0,640,1920,128, false ,0 ) ; tmp.Free; end; procedure TForm1.ScaleArrows; var i: Integer; begin for I := 0 to SE_Arrows.SpriteCount -1 do begin SE_Arrows.Sprites [i].Scale := 50; end; end; procedure TForm1.SE_Theater1SpriteMouseDown(Sender: TObject; lstSprite: TObjectList<DSE_theater.SE_Sprite>; Button: TMouseButton; Shift: TShiftState); var SpriteGabriel, SpriteShahira: SE_Sprite; begin SpriteGabriel:= SE_Characters.FindSprite('gabriel'); SpriteShahira:= SE_Characters.FindSprite('shahira'); // uses Generics.Collections ,Generics.Defaults if lstSprite[0].Engine = SE_Arrows then begin if lstSprite[0].Guid = 'arrow1' then begin SpriteGabriel.FrameY := 1; SpriteShahira.FrameY := 1; end else if lstSprite[0].Guid = 'arrow2' then begin SpriteGabriel.FrameY := 2; SpriteShahira.FrameY := 2; end else if lstSprite[0].Guid = 'arrow3' then begin SpriteGabriel.FrameY := 3; SpriteShahira.FrameY := 3; end else if lstSprite[0].Guid = 'arrow4' then begin SpriteGabriel.FrameY := 4; SpriteShahira.FrameY := 4; end else if lstSprite[0].Guid = 'arrow5' then begin SpriteGabriel.FrameY := 5; SpriteShahira.FrameY := 5; end else if lstSprite[0].Guid = 'arrow6' then begin SpriteGabriel.FrameY := 6; SpriteShahira.FrameY := 6; end end; end; procedure TForm1.CheckBox1Click(Sender: TObject); begin SE_Theater1.MousePan := checkBox1.Checked ; end; procedure TForm1.CheckBox2Click(Sender: TObject); begin SE_Theater1.MouseScroll := checkBox2.Checked ; end; procedure TForm1.CheckBox3Click(Sender: TObject); begin SE_Theater1.MouseWheelZoom := checkBox3.Checked ; end; procedure TForm1.CheckBox4Click(Sender: TObject); begin SE_Theater1.MouseWheelInvert := checkBox4.Checked ; end; procedure TForm1.Edit1Change(Sender: TObject); begin SE_Theater1.MouseScrollRate := StrToFloatDef ( edit1.Text ,0 ); end; procedure TForm1.Edit2Change(Sender: TObject); begin SE_Theater1.MouseWheelValue := StrToIntDef ( edit2.Text ,0 ); end; end.