text
stringlengths
14
6.51M
Unit GraphWindowUnit; interface uses GraphWPF, StateMachineUnit; procedure CreateWindow; const n = 20; var celltype: integer; machine: StateMachine; canEdit: boolean; implementation procedure ColorCell(x, y: real; mb: integer); begin if (mb = 1)and(canEdit = true) then begin machine.ClearAlgorithmLayout(); machine.SetCellType(celltype, trunc(x), trunc(y)); end; end; procedure DrawGrid; begin SetMathematicCoords(0, n, 0, true); for var x:=0 to n-1 do for var y:=0 to n-1 do begin case machine.GridData[x,y] of 0: Brush.Color := Colors.White; // пустая 1: Brush.Color := Colors.Black; // преграда 2: Brush.Color := Colors.Gray; // помеченная 3: Brush.Color := Colors.SkyBlue; // в очереди 4: Brush.Color := Colors.Yellow; // путь 5: Brush.Color := Colors.Green; // начало 6: Brush.Color := Colors.Red; // конец end; Rectangle(x + 0.04, y + 0.04, 0.92, 0.92); (* рисуем клетку *) end; end; procedure CreateWindow; begin Window.SetSize(700, 700); Window.CenterOnScreen; Window.IsFixedSize := true; Window.Caption := 'Визуализация алгоритмов поиска кратчайшего пути'; SetMathematicCoords(0, 20, 0, true); DrawGrid; end; procedure Animation; begin BeginFrameBasedAnimation(DrawGrid, 30); end; begin canEdit := true; machine := new StateMachine(20); machine.OnGridChange := Animation; Pen.Color := Colors.White; CreateWindow; OnMouseDown := ColorCell; OnMouseMove := ColorCell; end.
unit D_IssueProps; { $Id: D_IssueProps.pas,v 1.16 2016/06/16 05:38:44 lukyanets Exp $ } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, Mask, l3Date, daTypes, dt_Types, DT_Const, DT_Dict, BottomBtnDlg, ToolEdit, vtCombo, vtDateEdit, ActnList, tb97GraphicControl, TB97Ctls, vtSpeedButton, dt_DictTypes; type TGetIssuePropsDlg = class(TBottomBtnDlg) edtDate1: TvtDateEdit; edtDate2: TvtDateEdit; edtNumber: TEdit; Label3: TLabel; Label4: TLabel; Label5: TLabel; Bevel1: TBevel; Bevel2: TBevel; Label2: TLabel; lblPubSource: TLabel; Label6: TLabel; Bevel3: TBevel; Label7: TLabel; Bevel4: TBevel; ActionList1: TActionList; acAddIssueImage: TAction; vtSpeedButton1: TvtSpeedButton; Bevel5: TBevel; Label1: TLabel; edtComment: TEdit; procedure edtDate2Enter(Sender: TObject); procedure acAddIssueImageExecute(Sender: TObject); private { Private declarations } fDocFam : TdaFamilyID; fSourID : TDictID; fOrigIssueRec : PPublishedDictRec; fNonPeriodic : Boolean; procedure CheckImageIcon(aEnabled : boolean); public function Execute(aDocFamily: TdaFamilyID; const aPubSource : AnsiString; aSourceNonPeriodic : boolean; aIssueRec : PPublishedDictRec; aWasEmpty: Boolean): Boolean; end; function RunGetIssuePropsDlg(aOwner: TComponent; aDocFamily : TdaFamilyID; const aPubSource : AnsiString; aSourceNonPeriodic : boolean; aIssueRec : PPublishedDictRec; aWasEmpty : Boolean): Boolean; implementation {$R *.DFM} uses l3String, l3Tree, l3Nodes, l3TreeInterfaces, l3Tree_TLB, l3IniFile, l3FileUtils, vtDialogs, DT_DocImages, IniShop, StrShop, ResShop, DictMetaForm, TreeDWin; (* PPublishedDictRec = ^TPublishedDictRec; TPublishedDictRec = Record ID : Longint; Sour : TDictID; SDate : TStDate; EDate : TStDate; Num : Word; Coment : Array[1..70] of Char; end; *) procedure TGetIssuePropsDlg.CheckImageIcon(aEnabled : boolean); begin with fOrigIssueRec^ do if aEnabled and DocImageServer.IsImageExists(Sour, SDate, EDate, l3ArrayToString(Num, SizeOf(Num)), fNonPeriodic) then acAddIssueImage.ImageIndex := picSrcCheck else acAddIssueImage.ImageIndex := picPublishSrc; end; function TGetIssuePropsDlg.Execute(aDocFamily: TdaFamilyID; const aPubSource : AnsiString; aSourceNonPeriodic : boolean; aIssueRec : PPublishedDictRec; aWasEmpty: Boolean): Boolean; var lSDate : TstDate; lEDate : TstDate; begin fOrigIssueRec := aIssueRec; fNonPeriodic := aSourceNonPeriodic; fDocFam := aDocFamily; lblPubSource.Caption := aPubSource; with aIssueRec^ do if not aWasEmpty then begin edtDate1.StDate := SDate; edtDate2.StDate := EDate; edtNumber.Text := l3ArrayToString(Num, SizeOf(Num)); edtComment.Text := l3ArrayToString(Comment, SizeOf(Comment)); end else l3StringToArray(Comment, SizeOf(Comment), ''); ActionList1.Images := ArchiResources.CommonImageList; acAddIssueImage.Enabled := not fNonPeriodic; CheckImageIcon(not (aWasEmpty or fNonPeriodic)); Result := ShowModal = mrOk; if Result then with aIssueRec^ do begin Result := False; lSDate := StDateToDemon(edtDate1.StDate); lEDate := StDateToDemon(edtDate2.StDate); If lEDate = BlankDate then lEDate := lSDate else If lSDate = BlankDate then lSDate := lEDate; if SDate <> lSDate then begin SDate := lSDate; Result := True; end; if EDate <> lEDate then begin EDate := lEDate; Result := True; end; if l3ArrayToString(Num, SizeOf(Num)) <> edtNumber.Text then begin l3StringToArray(Num, SizeOf(Num), edtNumber.Text); Result := True; end; if l3ArrayToString(Comment, SizeOf(Comment)) <> edtComment.Text then begin l3StringToArray(Comment, SizeOf(Comment), edtComment.Text); Result := True; end; end; end; procedure TGetIssuePropsDlg.edtDate2Enter(Sender: TObject); begin if (edtDate2.Date = NullDate) and (edtDate1.Date <> NullDate) then edtDate2.Date := edtDate1.Date; end; procedure TGetIssuePropsDlg.acAddIssueImageExecute(Sender: TObject); var lFileName: AnsiString; begin UserConfig.Section := PrefSectName; lFileName := UserConfig.ReadParamStrDef('ImageOpenInitialDir',''); if vtExecuteOpenDialog(lFileName, sidDocImageDlgFilter) then begin try with fOrigIssueRec^ do DocImageServer.AddImageFile(lFileName, Sour, SDate, EDate, l3ArrayToString(Num, SizeOf(Num)), fNonPeriodic); except On E : Exception do begin Application.ShowException(E); Exit; end; end; UserConfig.WriteParamStr('ImageOpenInitialDir',ExtractDirName(lFileName)+'\'); end; CheckImageIcon(not fNonPeriodic); end; function RunGetIssuePropsDlg(aOwner: TComponent; aDocFamily : TdaFamilyID; const aPubSource : AnsiString; aSourceNonPeriodic : boolean; aIssueRec : PPublishedDictRec; aWasEmpty : Boolean): Boolean; begin with TGetIssuePropsDlg.Create(aOwner) do try Result := Execute(aDocFamily, aPubSource, aSourceNonPeriodic, aIssueRec, aWasEmpty); finally Free; end; end; end.
unit WallpaperSetter; {$mode objfpc}{$H+} interface uses Classes, SysUtils, WpcCommonTypes, WpcWallpaperStyles, WpcExceptions; type // TODO add all types, like WINDOWS_7, XFCE, ... TWpcWallpaperSetterType = ( WPST_AUTODETECT, WPST_DEBUG, WPST_CUSTOM, WPST_ ); { IWallpaperSetter } IWallpaperSetter = class(TObject) procedure SetDesktopWallpaper(Path : String; Style : TWallpaperStyle); virtual; abstract; end; { TWpcDebugWallpaperSetter } TWpcDebugWallpaperSetter = class(IWallpaperSetter) private FLogFile : TextFile; public constructor Create(LogFile : String); destructor Destroy; override; procedure SetDesktopWallpaper(Path : String; Style : TWallpaperStyle); override; end; implementation { TWpcDebugWallpaperSetter } constructor TWpcDebugWallpaperSetter.Create(LogFile: String); begin if (LogFile = '') then raise TWpcIllegalArgumentException.Create('Log file should be specified.'); AssignFile(FLogFile, LogFile); Rewrite(FLogFile); end; destructor TWpcDebugWallpaperSetter.Destroy(); begin CloseFile(FLogFile); inherited Destroy(); end; procedure TWpcDebugWallpaperSetter.SetDesktopWallpaper(Path: String; Style: TWallpaperStyle); begin Writeln(FLogFile, Path, ' : ', Style, ' at ', DateTimeToStr(Now())); end; end.
unit ListViewers; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TSizeOptions = (soClientHeight, soSystemLarge, soSystemSmall, soImageListSize); type TPaintMode = (pmNormal, pmSelected); EIconListViewerError = class (Exception); { TIconListViewer => Shows icons from ImageList object. function IconAt(x, y : integer) : integer; > Returns the index, in the ImageList object, of the icon at the position "x", "y" in the control's area; procedure PaintIcon(const Index : integer; const Mode : TPaintMode); > Paints the icon specified by index(if it is Visible). "Mode" describes how to paint the icon : selected or not (pmSelected, pmNormal) procedure DrawIcons; > Paints all visibles icons function ItemVisible(const Item : integer) : boolean; > Returns true if the Item is completely visible function VisiblesIcons : integer; > Returns the number of icons that can be painted in the control procedure UpdateRect(Rect : TRect); > Paints all icons that are, partially o completely, contained in "Rect" property ColorSelected : TColor; > Color used for the background of the selected icon property FirstVisibleIcon : integer; > The first icon property ImageList : TImageList; > ImageList contains the images of the icons property ItemIndex : integer; > The index of the selected Item property HorzIconSeparation : integer default 8; > The horizontal separation between icons property VertIconSeparation : integer default 4; > The vertical separation between icons and the control's ClientRect property IconSize : TPoint; > The size used to paint the icons property SizeOption : TSizeOptions; > soClientHeight = IconSize := Point(ClientRect.Height, ClientRect.Height) > soSystemLarge = IconSize := Point(GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON)) > soSystemSmall = IconSize := Point(GetSystemMetrics(SM_CXSICON), GetSystemMetrics(SM_CYSICON)) > soImageListSize = IconSize := Point(fImageList.Width, fImageList.Height) property OnSelection : TNotifyEvent; > Occurs when an item is selected property OnIconSizing : TNotifyEvent; > Occurs when IconSize value changes } TIconListViewer = class (TCustomControl) private LButtonDown : boolean; procedure WMGetDlgCode(var Msg: TWMGetDlgCode); message WM_GetDlgCode; procedure WMHSCROLL(var Message : TWMScroll); message WM_HSCROLL; procedure WMSIZE(var Message); message WM_SIZE; protected procedure CreateParams(var Params: TCreateParams); override; procedure CreateWnd; override; protected procedure UpdateHeight; virtual; procedure UpdateScrollBar; virtual; procedure SetScrollBarPos(Position : integer); function GetScrollBarPos : integer; function ScrollBarHeight : integer; protected procedure Paint; override; procedure Loaded; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; public constructor Create(aOwner : TComponent); override; destructor Destroy; override; property Align default alClient; private fColorSel : TColor; fImageList : TImageList; fIconSize : TPoint; fXIconSeparation : integer; fYIconSeparation : integer; fItemIndex : integer; f1stVisIcon : integer; fSizeOption : TSizeOptions; fOnIconSizing : TNotifyEvent; fOnSelection : TNotifyEvent; procedure Set1stVisIcon(value : integer); procedure SetColorSel(value : TColor); procedure SetImageList(value : TImageList); procedure SetItemIndex(value : integer); procedure SetIconSeparation(index : integer; value : integer); procedure SetIconSize(value : TPoint); procedure SetSizeOption(value : TSizeOptions); protected function IconAt(x, y : integer) : integer; procedure PaintIcon(const Index : integer; const Mode : TPaintMode); procedure DrawIcons; property FirstVisibleIcon : integer read f1stVisIcon write Set1stVisIcon; property IconSize : TPoint read fIconSize write SetIconSize; public function ItemPartialVisible(const Item : integer) : boolean; function ItemCompleteVisible(const Item : integer) : boolean; function VisiblesIcons : integer; procedure UpdateRect(Rect : TRect); public property ItemIndex : integer read fItemIndex write SetItemIndex; published property ColorSelected : TColor read fColorSel write SetColorSel default clActiveCaption; property ImageList : TImageList read fImageList write SetImageList; property HorzIconSeparation : integer index 0 read fXIconSeparation write SetIconSeparation default 8; //Must be Even property VertIconSeparation : integer index 1 read fYIconSeparation write SetIconSeparation default 4; //Must be Even property SizeOption : TSizeOptions read fSizeOption write SetSizeOption default soSystemLarge; property OnSelection : TNotifyEvent read fOnSelection write fOnSelection; property OnIconSizing : TNotifyEvent read fOnIconSizing write fOnIconSizing; published property DragCursor; property DragMode; property Enabled; property Color default clWindow; property Ctl3D; property Font; property ParentColor default false; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; procedure Register; implementation {$BOOLEVAL OFF} uses CommCtrl; const SInvalidIconSize = 'Invalid icon sizew :(%d, %d)'; { TIconListViewer } constructor TIconListViewer.Create(aOwner : TComponent); begin inherited; ControlStyle := ControlStyle - [csAcceptsControls] + [csCaptureMouse, csClickEvents]; Color := clWindow; ParentColor := false; fImageList := nil; fColorSel := clActiveCaption; fItemIndex := -1; fSizeOption := soSystemLarge; fIconSize.X := GetSystemMetrics(SM_CXICON); fIconSize.Y := GetSystemMetrics(SM_CYICON); fXIconSeparation := 8; fYIconSeparation := 4; Width := fIconSize.X * 6; end; destructor TIconListViewer.Destroy; begin inherited; end; procedure TIconListViewer.Loaded; begin UpdateHeight; end; procedure TIconListViewer.CreateParams(var Params: TCreateParams); begin inherited; with Params do begin Style := Style or WS_HSCROLL; if NewStyleControls and Ctl3D then ExStyle := ExStyle or WS_EX_CLIENTEDGE ; end; end; procedure TIconListViewer.CreateWnd; begin inherited; UpdateScrollBar; end; procedure TIconListViewer.UpdateScrollBar; var ScrollInfo : TScrollInfo; begin with ScrollInfo do begin cbSize := SizeOf(ScrollInfo); fMask := SIF_ALL or SIF_DISABLENOSCROLL; nMin := 0; if fImageList <> nil then begin nMax := fImageList.Count - VisiblesIcons; nPage := 1; end else begin nMax := 0; nPage := 0; end; nPos := f1stVisIcon; nTrackPos := f1stVisIcon; end; Windows.SetScrollInfo(Handle, SB_HORZ, ScrollInfo, True); end; procedure TIconListViewer.UpdateHeight; begin if (not(csReading in ComponentState)) then begin if(fSizeOption <> soClientHeight) then begin if (ClientHeight <> (fIconSize.Y + VertIconSeparation)) then ClientHeight := fIconSize.Y + VertIconSeparation end else if (fIconSize.X <> (ClientHeight - VertIconSeparation)) or (fIconSize.Y <> (ClientHeight - VertIconSeparation)) then begin fIconSize := Point(ClientHeight - VertIconSeparation, ClientHeight - VertIconSeparation); DrawIcons; end; end; end; procedure TIconListViewer.WMSIZE(var Message); begin inherited; if (not(csReading in ComponentState)) then begin UpdateHeight; UpdateScrollBar; end; end; procedure TIconListViewer.SetScrollBarPos(Position : integer); begin Windows.SetScrollPos(Handle, SB_HORZ, Position, True); end; function TIconListViewer.GetScrollBarPos : integer; begin result := Windows.GetScrollPos(Handle, SB_HORZ); end; function TIconListViewer.ScrollBarHeight : integer; begin result := Windows.GetSystemMetrics(SM_CYHSCROLL); end; procedure TIconListViewer.WMHSCROLL(var Message : TWMScroll); begin Message.Result := 1; with Message do case TScrollCode(ScrollCode) of scLineUp: FirstVisibleIcon := f1stVisIcon - 1; scLineDown: FirstVisibleIcon := f1stVisIcon + 1; scPageUp: FirstVisibleIcon := f1stVisIcon - VisiblesIcons; scPageDown: FirstVisibleIcon := f1stVisIcon + VisiblesIcons; scPosition, scTrack: FirstVisibleIcon := Pos; scTop: FirstVisibleIcon := 0; scBottom: if fImageList <> nil then FirstVisibleIcon := GetScrollBarPos; else Result := 0; end; end; function TIconListViewer.IconAt(x, y : integer) : integer; begin result := x div (fIconSize.X+fXIconSeparation) + f1stVisIcon; end; procedure TIconListViewer.WMGetDlgCode(var Msg: TWMGetDlgCode); begin Msg.Result := DLGC_WANTARROWS; end; procedure TIconListViewer.KeyDown(var Key: Word; Shift: TShiftState); var LastItem : integer; begin case Key of VK_PRIOR : begin LastItem := ItemIndex; ItemIndex := -1; FirstVisibleIcon := FirstVisibleIcon + VisiblesIcons; ItemIndex := LastItem + VisiblesIcons; end; VK_NEXT : if (ItemIndex - VisiblesIcons) >= 0 then begin LastItem := ItemIndex; ItemIndex := -1; FirstVisibleIcon := FirstVisibleIcon - VisiblesIcons; ItemIndex := LastItem - VisiblesIcons end else ItemIndex := 0; VK_HOME : ItemIndex := 0; VK_END : if fImageList <> nil then begin ItemIndex := -1; FirstVisibleIcon := pred(fImageList.Count); ItemIndex := pred(fImageList.Count); end; VK_LEFT : if ItemIndex > 0 then ItemIndex := pred(ItemIndex); VK_RIGHT : begin if not ItemCompleteVisible(succ(ItemIndex)) then FirstVisibleIcon := succ(FirstVisibleIcon); ItemIndex := succ(ItemIndex); end; else inherited; end; end; procedure TIconListViewer.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; if Button = mbLeft then begin ItemIndex := IconAt(X, Y); LButtonDown := true; SetFocus; end; end; procedure TIconListViewer.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; if LButtonDown then begin LButtonDown := false; if Assigned(fOnSelection) then fOnSelection(Self); end; end; procedure TIconListViewer.MouseMove(Shift: TShiftState; X, Y: Integer); var Item : integer; begin inherited; if LButtonDown then begin Item := IconAt(X, Y); if Item < 0 then Item := 0; if X > Width then FirstVisibleIcon := FirstVisibleIcon + 1 else if (X < 0) then FirstVisibleIcon := FirstVisibleIcon - 1; ItemIndex := Item; end end; function TIconListViewer.ItemPartialVisible(const Item : integer) : boolean; begin result := ((Item - f1stVisIcon) >=0) and ((Item - f1stVisIcon) <= VisiblesIcons) end; function TIconListViewer.ItemCompleteVisible(const Item : integer) : boolean; begin result := ((Item - f1stVisIcon) >=0) and ((Item - f1stVisIcon) < VisiblesIcons) end; function TIconListViewer.VisiblesIcons : integer; begin with ClientRect do result := (Right - Left) div (fIconSize.X + fXIconSeparation); end; procedure TIconListViewer.PaintIcon(const Index: integer; const Mode : TPaintMode); function IconPosition(const Index : integer) : integer; begin result := Index - f1stVisIcon; end; function IconRect(const Position : integer) : TRect; begin result := ClientRect; with result do begin Inc(Left, (Position*fIconSize.X) + (Position*fXIconSeparation)); Right := Left + fIconSize.X + fXIconSeparation; end; end; var Icon : HICON; R : TRect; begin if fImageList <> nil then begin if ItemPartialVisible(index) then with fIconSize do begin Icon := ImageList_GetIcon(fImageList.Handle, Index, ILD_TRANSPARENT); R := IconRect(IconPosition(Index)); if Mode = pmSelected then Canvas.Brush.Color := ColorSelected else Canvas.Brush.Color := Color; Canvas.FillRect(R); with R do begin Inc(Left, fXIconSeparation div 2); Inc(Top, fYIconSeparation div 2); Dec(Right, fXIconSeparation div 2); Dec(Bottom, fYIconSeparation div 2); DrawIconEx(Canvas.Handle, Left, Top, Icon, X, Y, 0, 0, DI_NORMAL); end; DestroyIcon(Icon); end; end; end; procedure TIconListViewer.DrawIcons; var IconIndex : integer; IconPos : integer; begin Canvas.Brush.Color := Color; Canvas.FillRect(ClientRect); if (fImageList <> nil) and (fImageList.Count <> 0) then begin IconIndex := FirstVisibleIcon; IconPos := 0; while (IconPos <= VisiblesIcons) and (IconIndex < fImageList.Count) do begin if ItemIndex = IconIndex then PaintIcon(IconIndex, pmSelected) else PaintIcon(IconIndex, pmNormal); Inc(IconPos); Inc(IconIndex); end; end; end; procedure TIconListViewer.Paint; begin DrawIcons; end; procedure TIconListViewer.SetColorSel(value : TColor); begin fColorSel := value; PaintIcon(fItemIndex, pmSelected); end; procedure TIconListViewer.SetItemIndex(value : integer); begin if (fImageList <> nil) and (fImageList.Count > 0) then begin if value >= fImageList.Count then value := pred(fImageList.Count) else if value < 0 then value := -1; if (value <> fItemIndex) and (fImagelist <> nil) then begin PaintIcon(fItemIndex, pmNormal); fItemIndex := value; if fItemIndex <> -1 then if ItemPartialVisible(fItemIndex) then PaintIcon(fItemIndex, pmSelected) else FirstVisibleIcon := ItemIndex; if Assigned(fOnSelection) then fOnSelection(Self); end; end; end; procedure TIconListViewer.SetImageList(value : TImageList); begin f1stVisIcon := 0; fItemIndex := -1; fImageList := value; if (fSizeOption = soImageListSize) and (fImageList <> nil) then IconSize := Point(fImageList.Width, fImageList.Height) else begin UpdateHeight; UpdateScrollBar; Invalidate; end; end; procedure TIconListViewer.SetIconSeparation(index : integer; value : integer); begin if value < 0 then value := 0; if (value mod 2) <> 0 then inc(value); case index of 0 : fXIconSeparation := value; 1 : begin fYIconSeparation := value; UpdateHeight; if assigned(OnIconSizing) then OnIconSizing(Self); end; end; UpdateScrollBar; Invalidate; end; procedure TIconListViewer.UpdateRect(Rect : TRect); function IconRect(const Position : integer) : TRect; begin result := ClientRect; with result do begin Inc(Left, (Position*fIconSize.X) + (Position*fXIconSeparation)); Right := Left + fIconSize.X + fXIconSeparation; end; end; var R : TRect; i : integer; begin for i := 0 to VisiblesIcons do if IntersectRect(R, Rect, IconRect(i)) then if fItemIndex = (i + f1stVisIcon) then PaintIcon(i + f1stVisIcon, pmSelected) else PaintIcon(i + f1stVisIcon, pmNormal); end; procedure TIconListViewer.Set1stVisIcon(value : integer); procedure ScrollX(dx : integer); var RS, RD, RU : TRect; begin RS := ClientRect; RD := ClientRect; RU := ClientRect; if abs(dx) < (ClientRect.Right - ClientRect.Left) then begin if dx > 0 then begin dec(RS.Right, dx); inc(RD.Left, dx); RU.Right := RU.Left + dx; end else begin dec(RS.Left, dx); inc(RD.Right, dx); RU.Left := RU.Right + dx; end; Canvas.CopyRect(RD, Canvas, RS); UpdateRect(RU); end else DrawIcons; end; var dIcons : integer; begin if fImageList <> nil then begin if value > fImageList.Count - VisiblesIcons then value := fImageList.Count - VisiblesIcons; if value < 0 then value := 0; dIcons := f1stVisIcon - value; if dIcons <> 0 then begin f1stVisIcon := value; SetScrollBarPos(value); ScrollX(dIcons*(fIconSize.X + fXIconSeparation)); end; end else f1stVisIcon := 0; end; procedure TIconListViewer.SetIconSize(value : TPoint); begin if (value.X < 1) or (value.Y < 1) then if csDesigning in ComponentState then begin ShowMessage(Format(SInvalidIconSize, [value.X, value.Y])); end else EIconListViewerError.CreateFmt(SInvalidIconSize, [value.X, value.Y]) else begin fIconSize := value; if assigned(OnIconSizing) then OnIconSizing(Self); UpdateHeight; UpdateScrollBar; Invalidate; end; end; procedure TIconListViewer.SetSizeOption(value : TSizeOptions); begin if fSizeOption <> value then begin fSizeOption := value; case fSizeOption of soClientHeight : IconSize := Point(ClientHeight - VertIconSeparation, ClientHeight - VertIconSeparation); soSystemLarge : IconSize := Point(GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON)); soSystemSmall : IconSize := Point(GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON)); soImageListSize : if fImageList <> nil then IconSize := Point(fImageList.Width, fImageList.Height); end; end; end; procedure Register; begin RegisterComponents('WISE', [TIconListViewer]); end; end.
unit crazyclimber_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,main_engine,controls_engine,ay_8910,gfx_engine,rom_engine, pal_engine,sound_engine,crazyclimber_hw_dac; function iniciar_cclimber:boolean; implementation const cclimber_rom:array[0..4] of tipo_roms=( (n:'cc11';l:$1000;p:0;crc:$217ec4ff),(n:'cc10';l:$1000;p:$1000;crc:$b3c26cef), (n:'cc09';l:$1000;p:$2000;crc:$6db0879c),(n:'cc08';l:$1000;p:$3000;crc:$f48c5fe3), (n:'cc07';l:$1000;p:$4000;crc:$3e873baf)); cclimber_pal:array[0..2] of tipo_roms=( (n:'cclimber.pr1';l:$20;p:0;crc:$751c3325),(n:'cclimber.pr2';l:$20;p:$20;crc:$ab1940fa), (n:'cclimber.pr3';l:$20;p:$40;crc:$71317756)); cclimber_char:array[0..3] of tipo_roms=( (n:'cc06';l:$800;p:0;crc:$481b64cc),(n:'cc05';l:$800;p:$1000;crc:$2c33b760), (n:'cc04';l:$800;p:$2000;crc:$332347cb),(n:'cc03';l:$800;p:$3000;crc:$4e4b3658)); cclimber_bigsprites:array[0..1] of tipo_roms=( (n:'cc02';l:$800;p:$0;crc:$14f3ecc9),(n:'cc01';l:$800;p:$800;crc:$21c0f9fb)); cclimber_samples:array[0..1] of tipo_roms=( (n:'cc13';l:$1000;p:$0;crc:$e0042f75),(n:'cc12';l:$1000;p:$1000;crc:$5da13aaa)); //DIP cclimber_dip_a:array [0..3] of def_dip=( (mask:$3;name:'Lives';number:4;dip:((dip_val:$0;dip_name:'3'),(dip_val:$1;dip_name:'4'),(dip_val:$2;dip_name:'5'),(dip_val:$3;dip_name:'6'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Coin A';number:4;dip:((dip_val:$30;dip_name:'4C 1C'),(dip_val:$20;dip_name:'3C 1C'),(dip_val:$10;dip_name:'2C 1C'),(dip_val:$0;dip_name:'1C 1C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c0;name:'Coin B';number:4;dip:((dip_val:$0;dip_name:'1C 1C'),(dip_val:$40;dip_name:'1C 2C'),(dip_val:$80;dip_name:'1C 3C'),(dip_val:$c0;dip_name:'Free Play'),(),(),(),(),(),(),(),(),(),(),(),())),()); cclimber_dip_b:array [0..1] of def_dip=( (mask:$10;name:'Cabinet';number:2;dip:((dip_val:$10;dip_name:'Upright'),(dip_val:$0;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); var nmi_mask:boolean; mem_decode:array[0..$5fff] of byte; scroll_y:array[0..$1f] of word; procedure update_video_cclimber; procedure draw_sprites; var f,x,y,nchar,attr,attr2,color:byte; flipx,flipy:boolean; begin for f:=$7 downto 0 do begin x:=memoria[$9883+(f*4)]+1; y:=240-memoria[$9882+(f*4)]; attr:=memoria[(f*4)+$9881]; attr2:=memoria[(f*4)+$9880]; nchar:=((attr and $10) shl 3) or ((attr and $20) shl 1) or (attr2 and $3f); color:=(attr and $0f) shl 2; flipx:=(attr2 and $40)<>0; flipy:=(attr2 and $80)<>0; put_gfx_sprite_mask(nchar,color,flipx,flipy,1,0,3); actualiza_gfx_sprite(x,y,3,1); end; end; var f,tile_index,nchar:word; color,attr,x,y:byte; flipx,flipy,bs_changed:boolean; begin bs_changed:=false; for f:=0 to $3ff do begin //Fondo attr:=memoria[f+$9c00]; flipy:=(attr and $20)<>0; tile_index:=f; if flipy then tile_index:=tile_index xor $20; if gfx[0].buffer[tile_index] then begin flipx:=(attr and $40)<>0; attr:=memoria[tile_index+$9c00]; x:=f mod 32; y:=f div 32; color:=(attr and $f) shl 2; nchar:=((attr and $10) shl 5) or ((attr and $20) shl 3) or memoria[$9000+tile_index]; put_gfx_flip(x*8,y*8,nchar,color,1,0,flipx,flipy); gfx[0].buffer[tile_index]:=false; end; //Sprites grandes tile_index:=((f and $1e0) shr 1) or (f and $f); if gfx[2].buffer[tile_index] then begin x:=f mod 32; y:=f div 32; if (f and $210)=$210 then begin attr:=memoria[$98dd]; color:=(attr and $7) shl 2; nchar:=((attr and $08) shl 5) or memoria[$8800+tile_index]; put_gfx_mask(x*8,y*8,nchar,color+64,2,2,0,$3); gfx[2].buffer[tile_index]:=false; bs_changed:=true; end else put_gfx_block_trans(x*8,y*8,2,8,8); end; end; //La pantalla de los sprites grandes, puede invertir el eje x y/o el y flipx:=(memoria[$98dd] and $10)<>0; flipy:=(memoria[$98dd] and $20)<>0; if bs_changed then flip_surface(2,flipx,flipy); x:=memoria[$98df]-$8-(byte(flipx)*$80)-(byte(main_screen.flip_main_screen)*$27); y:=memoria[$98de]-(byte(flipy)*$80); //Poner todo en su sitio scroll__y_part2(1,3,8,@scroll_y); //for f:=0 to 31 do scroll__y_part(1,3,memoria[$9800+f],0,f*8,8); if (memoria[$98dc] and 1)<>0 then begin scroll_x_y(2,3,x,y); draw_sprites; end else begin draw_sprites; scroll_x_y(2,3,x,y); end; actualiza_trozo_final(0,16,256,224,3); end; procedure eventos_cclimber; begin if event.arcade then begin //P1 if arcade_input.up[0] then marcade.in0:=(marcade.in0 or $1) else marcade.in0:=(marcade.in0 and $fe); if arcade_input.down[0] then marcade.in0:=(marcade.in0 or $2) else marcade.in0:=(marcade.in0 and $fd); if arcade_input.left[0] then marcade.in0:=(marcade.in0 or $4) else marcade.in0:=(marcade.in0 and $fb); if arcade_input.right[0] then marcade.in0:=(marcade.in0 or $8) else marcade.in0:=(marcade.in0 and $f7); if arcade_input.up[1] then marcade.in0:=(marcade.in0 or $10) else marcade.in0:=(marcade.in0 and $ef); if arcade_input.down[1] then marcade.in0:=(marcade.in0 or $20) else marcade.in0:=(marcade.in0 and $df); if arcade_input.left[1] then marcade.in0:=(marcade.in0 or $40) else marcade.in0:=(marcade.in0 and $bf); if arcade_input.right[1] then marcade.in0:=(marcade.in0 or $80) else marcade.in0:=(marcade.in0 and $7f); //P2 if arcade_input.up[1] then marcade.in1:=(marcade.in1 or $1) else marcade.in1:=(marcade.in1 and $fe); if arcade_input.down[1] then marcade.in1:=(marcade.in1 or $2) else marcade.in1:=(marcade.in1 and $fd); if arcade_input.left[1] then marcade.in1:=(marcade.in1 or $4) else marcade.in1:=(marcade.in1 and $fb); if arcade_input.right[1] then marcade.in1:=(marcade.in1 or $8) else marcade.in1:=(marcade.in1 and $f7); if arcade_input.up[0] then marcade.in1:=(marcade.in1 or $10) else marcade.in1:=(marcade.in1 and $ef); if arcade_input.down[0] then marcade.in1:=(marcade.in1 or $20) else marcade.in1:=(marcade.in1 and $df); if arcade_input.left[0] then marcade.in1:=(marcade.in1 or $40) else marcade.in1:=(marcade.in1 and $bf); if arcade_input.right[0] then marcade.in1:=(marcade.in1 or $80) else marcade.in1:=(marcade.in1 and $7f); //SYSTEM if arcade_input.coin[0] then marcade.in2:=(marcade.in2 or $1) else marcade.in2:=(marcade.in2 and $fe); if arcade_input.coin[1] then marcade.in2:=(marcade.in2 or $2) else marcade.in2:=(marcade.in2 and $fd); if arcade_input.start[0] then marcade.in2:=(marcade.in2 or $4) else marcade.in2:=(marcade.in2 and $fb); if arcade_input.start[1] then marcade.in2:=(marcade.in2 or $8) else marcade.in2:=(marcade.in2 and $f7); end; end; procedure cclimber_principal; var f:byte; frame:single; begin init_controls(false,false,false,true); frame:=z80_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin //main z80_0.run(frame); frame:=frame+z80_0.tframes-z80_0.contador; if f=239 then begin if nmi_mask then z80_0.change_nmi(PULSE_LINE); update_video_cclimber; end; end; eventos_cclimber; video_sync; end; end; function cclimber_getbyte(direccion:word):byte; begin case direccion of $0..$5fff:if z80_0.opcode then cclimber_getbyte:=mem_decode[direccion] else cclimber_getbyte:=memoria[direccion]; $6000..$6bff,$8000..$83ff,$8800..$8bff,$9820..$9fff:cclimber_getbyte:=memoria[direccion]; $9000..$97ff:cclimber_getbyte:=memoria[$9000+(direccion and $3ff)]; $9800..$981f:cclimber_getbyte:=scroll_y[direccion and $1f]; $a000:cclimber_getbyte:=marcade.in0; $a800:cclimber_getbyte:=marcade.in1; $b000:cclimber_getbyte:=marcade.dswa; $b800:cclimber_getbyte:=marcade.dswb or marcade.in2; end; end; procedure cclimber_putbyte(direccion:word;valor:byte); begin case direccion of 0..$5fff:; //ROM $6000..$6bff,$8000..$83ff,$8900..$8bff,$9820..$98dc,$98de..$9bff:memoria[direccion]:=valor; $8800..$88ff:if memoria[direccion]<>valor then begin memoria[direccion]:=valor; gfx[2].buffer[direccion and $ff]:=true; end; $9000..$97ff:if memoria[$9000+(direccion and $3ff)]<>valor then begin memoria[$9000+(direccion and $3ff)]:=valor; gfx[0].buffer[direccion and $3ff]:=true; end; $9800..$981f:scroll_y[direccion and $1f]:=valor; $98dd:if memoria[$98dd]<>valor then begin fillchar(gfx[2].buffer,$400,1); memoria[$98dd]:=valor; end; $9c00..$9fff:begin memoria[$9c00+((direccion and $3ff) and not($20))]:=valor; gfx[0].buffer[(direccion and $3ff) and not($20)]:=true; memoria[$9c00+((direccion and $3ff) or $20)]:=valor; gfx[0].buffer[(direccion and $3ff) or $20]:=true; end; $a000,$a003:nmi_mask:=(valor and $1)<>0; $a001..$a002:main_screen.flip_main_screen:=(valor and 1)<>0; $a004:if valor<>0 then cclimber_audio.trigger_w; $a800:cclimber_audio.change_freq(valor); $b000:cclimber_audio.change_volume(valor); end; end; function cclimber_inbyte(port:word):byte; begin if (port and $ff)=$c then cclimber_inbyte:=ay8910_0.Read; end; procedure cclimber_outbyte(port:word;valor:byte); begin case (port and $ff) of $8:ay8910_0.control(valor); $9:ay8910_0.write(valor); end; end; procedure cclimber_porta_write(valor:byte); begin cclimber_audio.change_sample(valor); end; procedure cclimber_sound_update; begin ay8910_0.update; cclimber_audio.update; end; //Main procedure reset_cclimber; begin z80_0.reset; ay8910_0.reset; cclimber_audio.reset; reset_audio; marcade.in0:=0; marcade.in1:=0; marcade.in2:=0; nmi_mask:=false; end; procedure cclimber_decode; var f:word; i,j,src:byte; const convtable:array[0..7,0..15] of byte=( // 0xff marks spots which are unused and therefore unknown */ ( $44,$14,$54,$10,$11,$41,$05,$50,$51,$00,$40,$55,$45,$04,$01,$15 ), ( $44,$10,$15,$55,$00,$41,$40,$51,$14,$45,$11,$50,$01,$54,$04,$05 ), ( $45,$10,$11,$44,$05,$50,$51,$04,$41,$14,$15,$40,$01,$54,$55,$00 ), ( $04,$51,$45,$00,$44,$10,$ff,$55,$11,$54,$50,$40,$05,$ff,$14,$01 ), ( $54,$51,$15,$45,$44,$01,$11,$41,$04,$55,$50,$ff,$00,$10,$40,$ff ), ( $ff,$54,$14,$50,$51,$01,$ff,$40,$41,$10,$00,$55,$05,$44,$11,$45 ), ( $51,$04,$10,$ff,$50,$40,$00,$ff,$41,$01,$05,$15,$11,$14,$44,$54 ), ( $ff,$ff,$54,$01,$15,$40,$45,$41,$51,$04,$50,$05,$11,$44,$10,$14 )); begin for f:=0 to $5fff do begin src:=memoria[f]; // pick the translation table from bit 0 of the address */ // and from bits 1 7 of the source data */ i:=(f and 1) or (src and $2) or ((src and $80) shr 5); // pick the offset in the table from bits 0 2 4 6 of the source data */ j:=(src and $01) or ((src and $04) shr 1) or ((src and $10) shr 2) or ((src and $40) shr 3); // decode the opcodes */ mem_decode[f]:=(src and $aa) or convtable[i,j]; end; end; function iniciar_cclimber:boolean; var colores:tpaleta; f:word; memoria_temp:array[0..$3fff] of byte; bit0,bit1,bit2:byte; rg_weights:array[0..2] of single; b_weights:array[0..1] of single; const ps_x:array[0..15] of dword=(0, 1, 2, 3, 4, 5, 6, 7, 8*8+0, 8*8+1, 8*8+2, 8*8+3, 8*8+4, 8*8+5, 8*8+6, 8*8+7); ps_y:array[0..15] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 16*8, 17*8, 18*8, 19*8, 20*8, 21*8, 22*8, 23*8); resistances_rg:array[0..2] of integer=(1000,470,220); resistances_b:array[0..1] of integer=(470,220); begin llamadas_maquina.bucle_general:=cclimber_principal; llamadas_maquina.reset:=reset_cclimber; iniciar_cclimber:=false; iniciar_audio(false); screen_init(1,256,256); screen_mod_scroll(1,256,256,255,256,256,255); screen_init(2,256,256,true); screen_mod_scroll(2,256,256,255,256,256,255); screen_init(3,256,256,false,true); iniciar_video(256,224); //Main CPU z80_0:=cpu_z80.create(18432000 div 3 div 2,256); z80_0.change_ram_calls(cclimber_getbyte,cclimber_putbyte); z80_0.change_io_calls(cclimber_inbyte,cclimber_outbyte); z80_0.init_sound(cclimber_sound_update); //Sound Chips ay8910_0:=ay8910_chip.create(3072000 div 2,AY8910,1); ay8910_0.change_io_calls(nil,nil,cclimber_porta_write,nil); cclimber_audio:=tcclimber_audio.create; //cargar y desencriptar las ROMS if not(roms_load(@memoria,cclimber_rom)) then exit; cclimber_decode; //samples if not(roms_load(cclimber_audio.get_rom_addr,cclimber_samples)) then exit; //convertir chars if not(roms_load(@memoria_temp,cclimber_char)) then exit; init_gfx(0,8,8,$400); gfx_set_desc_data(2,0,8*8,0,$400*8*8); convert_gfx(0,0,@memoria_temp,@ps_x,@ps_y,false,false); //convertir sprites init_gfx(1,16,16,$100); gfx_set_desc_data(2,0,32*8,0,$100*8*32); convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,false,false); //big sprites if not(roms_load(@memoria_temp,cclimber_bigsprites)) then exit; init_gfx(2,8,8,$100); gfx_set_desc_data(2,0,8*8,0,$100*8*8); convert_gfx(2,0,@memoria_temp,@ps_x,@ps_y,false,false); //poner la paleta if not(roms_load(@memoria_temp,cclimber_pal)) then exit; compute_resistor_weights(0, 255, -1.0, 3,@resistances_rg,@rg_weights,0,0, 3,@resistances_b,@b_weights,0,0, 0,nil,nil,0,0); for f:=0 to $5f do begin // red component */ bit0:=(memoria_temp[f] shr 0) and $01; bit1:=(memoria_temp[f] shr 1) and $01; bit2:=(memoria_temp[f] shr 2) and $01; colores[f].r:=combine_3_weights(@rg_weights, bit0, bit1, bit2); // green component */ bit0:=(memoria_temp[f] shr 3) and $01; bit1:=(memoria_temp[f] shr 4) and $01; bit2:=(memoria_temp[f] shr 5) and $01; colores[f].g:=combine_3_weights(@rg_weights, bit0, bit1, bit2); // blue component */ bit0:=(memoria_temp[f] shr 6) and $01; bit1:=(memoria_temp[f] shr 7) and $01; colores[f].b:=combine_2_weights(@b_weights, bit0, bit1); end; set_pal(colores,$60); //DIP marcade.dswa:=0; marcade.dswb:=$10; marcade.dswa_val:=@cclimber_dip_a; marcade.dswb_val:=@cclimber_dip_b; //final reset_cclimber; iniciar_cclimber:=true; end; end.
unit UnitDemo1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm1 = class(TForm) btnWrite: TButton; btnRead: TButton; btnRecord: TButton; btnReadRecord: TButton; mmoDispalyRecord: TMemo; procedure btnWriteClick(Sender: TObject); procedure btnReadClick(Sender: TObject); procedure btnRecordClick(Sender: TObject); procedure btnReadRecordClick(Sender: TObject); private { Private declarations } public { Public declarations } end; TPerson = record name:string[20]; {必须是一个指定长度的字符串,没有指定不知道多长,无法构造} age:Integer; end; var Form1: TForm1; const SOURCE_FILE ='D:\test\Demo1.txt'; implementation {$R *.dfm} procedure TForm1.btnReadClick(Sender: TObject); var dataSourceFile:TextFile; // 读取文本文档的类型 content:string; begin try // 将磁盘上的文件跟我们的变量关联绑定 AssignFile(dataSourceFile,SOURCE_FILE); // 打开文件 reset方式打开,只读 Reset(dataSourceFile); // 读取文本数据 Readln(dataSourceFile,content); ShowMessage(content); finally // 关闭文件 1、把内存中的数据写入到磁盘 2、释放资源 CloseFile(dataSourceFile); end; end; procedure TForm1.btnReadRecordClick(Sender: TObject); var Person:TPerson; PersonFile:File of TPerson; begin // 关联文件和变量 AssignFile(PersonFile,SOURCE_FILE); // 以写方式打开文件 Reset(PersonFile); // 改变文件指针位置,文件指针的索引是从0开始的 Seek(PersonFile,1); // 将结构体的数据写入文件 Read(PersonFile,Person); mmoDispalyRecord.Clear; mmoDispalyRecord.Lines.Add(Person.name); mmoDispalyRecord.Lines.Add(Person.age.ToString); // 关闭文件 1、把内存中的数据写入到磁盘 2、释放资源 CloseFile(PersonFile); end; procedure TForm1.btnRecordClick(Sender: TObject); var Person:TPerson; PersonFile:File of TPerson; begin try // 关联文件和变量 AssignFile(PersonFile,SOURCE_FILE); // 以写方式打开文件 Rewrite(PersonFile); // 构造结构体的数据 Person.name:='陈怡彬'; Person.age:=29; // 将结构体的数据写入文件 Write(PersonFile,Person); ShowMessage('记录数'+IntToStr(FileSize(PersonFile))+',当前文件指针'+IntToStr(FilePos(PersonFile))); // 构造结构体的数据 Person.name:='杨紫薇'; Person.age:=25; // 将结构体的数据写入文件 Write(PersonFile,Person); ShowMessage('记录数'+IntToStr(FileSize(PersonFile))+',当前文件指针'+IntToStr(FilePos(PersonFile))); finally // 关闭文件 1、把内存中的数据写入到磁盘 2、释放资源 CloseFile(PersonFile); end; end; procedure TForm1.btnWriteClick(Sender: TObject); var dataSourceFile:TextFile; // 读取文本文档的类型 begin try // 将磁盘上的文件跟我们的变量关联绑定 AssignFile(dataSourceFile,SOURCE_FILE); // 打开文件 rewirte方式打开,如果该文件已存在,将被覆盖 Rewrite(dataSourceFile); // 向文档写入数据 Writeln(dataSourceFile,'Hello,World.I am cybinlyc.'); finally // 关闭文件 1、把内存中的数据写入到磁盘 2、释放资源 CloseFile(dataSourceFile); end; end; end.
unit EaseFltDemo; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Samples.Spin, Vcl.ComCtrls, Vcl.CheckLst, System.SyncObjs, FilterAPI, GlobalConfig; type TDisplayThread = class(TThread) private UseForm: TObject; procedure SendToDisplay(UseFormIn: TObject); protected procedure Execute; override; public fCompletedEvent: THandle; //used to signal completion PendingDisplayItems: TStringList; constructor Create(UseFormIn: TObject); destructor Destroy; override; procedure AddDisplayInfo(DisplayStr: String); //; UseFormIn: TObject); procedure ClearLists; procedure SendToDisplaySync; end; type TForm1 = class(TForm) PageControl1: TPageControl; TabSheet2: TTabSheet; Label1: TLabel; Edit_IncludeFileFilterMask: TEdit; TabSheet1: TTabSheet; Label2: TLabel; CheckListBox_FileEvents: TCheckListBox; Memo1: TMemo; Button_Start: TButton; Button_Stop: TButton; Button_SaveSettings: TButton; Label3: TLabel; Edit_ExcludeFileFilterMask: TEdit; Label4: TLabel; CheckListBox_AccessFlags: TCheckListBox; Label5: TLabel; CheckListBox_MonitorIO: TCheckListBox; Label6: TLabel; CheckListBox_ControlIO: TCheckListBox; Label7: TLabel; Edit_PasswordPhrase: TEdit; procedure FormCreate(Sender: TObject); procedure Button_SaveSettingsClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); function AddMessage(MsgStrIn: String): Boolean; procedure Button_StartClick(Sender: TObject); procedure Button_StopClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; GlobalConfig: TGlobalConfig; INIFileName: String; LDisplayThread: TDisplayThread; Lock_DisplayListing: TCriticalSection; CloseAppInProgress: BOOL; implementation uses GeneralFunctions; {$R *.dfm} procedure TForm1.Button_StartClick(Sender: TObject); begin AddMessage(StartFilterService(AddMessage,GlobalConfig)); end; procedure TForm1.Button_StopClick(Sender: TObject); begin CloseAppInProgress := True; StopService(); end; function TForm1.AddMessage(MsgStrIn: String): Boolean; begin LDisplayThread.AddDisplayInfo(MsgStrIn); end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin CloseAppInProgress := True; end; procedure TForm1.FormCreate(Sender: TObject); begin LDisplayThread := TDisplayThread.Create(Self); INIFileName := ChangeFileExt(Application.ExeName, '.ini'); Lock_DisplayListing := TCriticalSection.Create; Memo1.Clear; GlobalConfig := TGlobalConfig.Create(INIFileName); GlobalConfig.LoadINI; Edit_IncludeFileFilterMask.Text := GlobalConfig.IncludeFileFilterMask; Edit_ExcludeFileFilterMask.Text := GlobalConfig.ExcludeFileFilterMask; Edit_PasswordPhrase.Text := GlobalConfig.EncryptionPasswordPhrase; if(GlobalConfig.AccessFlags And LongWord(FILE_ENCRYPTION_RULE) > 0) then CheckListBox_AccessFlags.Checked[0] := True; if(GlobalConfig.AccessFlags And LongWord(ALLOW_READ_ACCESS) > 0) then CheckListBox_AccessFlags.Checked[1] := True; if (GlobalConfig.AccessFlags And LongWord(ALLOW_WRITE_ACCESS) > 0) then CheckListBox_AccessFlags.Checked[2] := True; if(GlobalConfig.AccessFlags And LongWord(ALLOW_FILE_DELETE) > 0) then CheckListBox_AccessFlags.Checked[3] := True; if( GlobalConfig.AccessFlags And LongWord(ALLOW_FILE_RENAME) > 0) then CheckListBox_AccessFlags.Checked[4] := True; if(GlobalConfig.AccessFlags And LongWord(ALLOW_OPEN_WITH_CREATE_OR_OVERWRITE_ACCESS) >0) then CheckListBox_AccessFlags.Checked[5] := True; if(GlobalConfig.AccessFlags And LongWord(ALLOW_FILE_MEMORY_MAPPED) >0) then CheckListBox_AccessFlags.Checked[6] := True; if(GlobalConfig.AccessFlags And LongWord(ALLOW_SET_SECURITY_ACCESS) >0) then CheckListBox_AccessFlags.Checked[7] := True; if(GlobalConfig.AccessFlags And LongWord(ALLOW_FILE_ACCESS_FROM_NETWORK) >0) then CheckListBox_AccessFlags.Checked[8] := True; if( GlobalConfig.MonitorFileEvents and LongWord(FILE_CREATEED) > 0) then CheckListBox_FileEvents.Checked[0] := True; if( GlobalConfig.MonitorFileEvents and LongWord(FILE_WRITTEN) > 0) then CheckListBox_FileEvents.Checked[1] := True; if( GlobalConfig.MonitorFileEvents and LongWord(FILE_RENAMED) > 0) then CheckListBox_FileEvents.Checked[2] := True; if( GlobalConfig.MonitorFileEvents and LongWord(FILE_DELETED) > 0) then CheckListBox_FileEvents.Checked[3] := True; if( GlobalConfig.MonitorFileEvents and LongWord(FILE_SECURITY_CHANGED) > 0) then CheckListBox_FileEvents.Checked[4] := True; if( GlobalConfig.MonitorFileEvents and LongWord(FILE_INFO_CHANGED) > 0) then CheckListBox_FileEvents.Checked[5] := True; if( GlobalConfig.MonitorFileEvents and LongWord(FILE_READ) > 0) then CheckListBox_FileEvents.Checked[6] := True; if( GlobalConfig.MonitorIOs and LongWord(POST_CREATE) > 0) then CheckListBox_MonitorIO.Checked[0] := True; if( GlobalConfig.MonitorIOs and LongWord(POST_FASTIO_READ) > 0) then CheckListBox_MonitorIO.Checked[1] := True; if( GlobalConfig.MonitorIOs and LongWord(POST_CACHE_READ) > 0) then CheckListBox_MonitorIO.Checked[2] := True; if( GlobalConfig.MonitorIOs and LongWord(POST_NOCACHE_READ) > 0) then CheckListBox_MonitorIO.Checked[3] := True; if( GlobalConfig.MonitorIOs and LongWord(POST_PAGING_IO_READ) > 0) then CheckListBox_MonitorIO.Checked[4] := True; if( GlobalConfig.MonitorIOs and LongWord(POST_FASTIO_WRITE) > 0) then CheckListBox_MonitorIO.Checked[5] := True; if( GlobalConfig.MonitorIOs and LongWord(POST_CACHE_WRITE) > 0) then CheckListBox_MonitorIO.Checked[6] := True; if( GlobalConfig.MonitorIOs and LongWord(POST_NOCACHE_WRITE) > 0) then CheckListBox_MonitorIO.Checked[7] := True; if( GlobalConfig.MonitorIOs and LongWord(POST_PAGING_IO_WRITE) > 0) then CheckListBox_MonitorIO.Checked[8] := True; if( GlobalConfig.MonitorIOs and LongWord(POST_QUERY_INFORMATION) > 0) then CheckListBox_MonitorIO.Checked[9] := True; if( GlobalConfig.MonitorIOs and LongWord(POST_SET_INFORMATION) > 0) then CheckListBox_MonitorIO.Checked[10] := True; if( GlobalConfig.MonitorIOs and LongWord(POST_DIRECTORY) > 0) then CheckListBox_MonitorIO.Checked[11] := True; if( GlobalConfig.MonitorIOs and LongWord(POST_QUERY_SECURITY) > 0) then CheckListBox_MonitorIO.Checked[12] := True; if( GlobalConfig.MonitorIOs and LongWord(POST_SET_SECURITY) > 0) then CheckListBox_MonitorIO.Checked[13] := True; if( GlobalConfig.MonitorIOs and LongWord(POST_CLEANUP) > 0) then CheckListBox_MonitorIO.Checked[14] := True; if( GlobalConfig.MonitorIOs and LongWord(POST_CLOSE) > 0) then CheckListBox_MonitorIO.Checked[15] := True; if( GlobalConfig.ControlIOs and LongWord(PRE_CREATE) > 0) then CheckListBox_ControlIO.Checked[0] := True; if( GlobalConfig.ControlIOs and LongWord(POST_CREATE) > 0) then CheckListBox_ControlIO.Checked[1] := True; if( GlobalConfig.ControlIOs and LongWord(PRE_FASTIO_READ) > 0) then CheckListBox_ControlIO.Checked[2] := True; if( GlobalConfig.ControlIOs and LongWord(POST_FASTIO_READ) > 0) then CheckListBox_ControlIO.Checked[3] := True; if( GlobalConfig.ControlIOs and LongWord(PRE_CACHE_READ) > 0) then CheckListBox_ControlIO.Checked[4] := True; if( GlobalConfig.ControlIOs and LongWord(POST_CACHE_READ) > 0) then CheckListBox_ControlIO.Checked[5] := True; if( GlobalConfig.ControlIOs and LongWord(PRE_NOCACHE_READ) > 0) then CheckListBox_ControlIO.Checked[6] := True; if( GlobalConfig.ControlIOs and LongWord(POST_NOCACHE_READ) > 0) then CheckListBox_ControlIO.Checked[7] := True; if( GlobalConfig.ControlIOs and LongWord(PRE_PAGING_IO_READ) > 0) then CheckListBox_ControlIO.Checked[8] := True; if( GlobalConfig.ControlIOs and LongWord(POST_PAGING_IO_READ) > 0) then CheckListBox_ControlIO.Checked[9] := True; if( GlobalConfig.ControlIOs and LongWord(PRE_FASTIO_WRITE) > 0) then CheckListBox_ControlIO.Checked[10] := True; if( GlobalConfig.ControlIOs and LongWord(POST_FASTIO_WRITE) > 0) then CheckListBox_ControlIO.Checked[11] := True; if( GlobalConfig.ControlIOs and LongWord(PRE_CACHE_WRITE) > 0) then CheckListBox_ControlIO.Checked[12] := True; if( GlobalConfig.ControlIOs and LongWord(POST_CACHE_WRITE) > 0) then CheckListBox_ControlIO.Checked[13] := True; if( GlobalConfig.ControlIOs and LongWord(PRE_NOCACHE_WRITE) > 0) then CheckListBox_ControlIO.Checked[14] := True; if( GlobalConfig.ControlIOs and LongWord(POST_NOCACHE_WRITE) > 0) then CheckListBox_ControlIO.Checked[15] := True; if( GlobalConfig.ControlIOs and LongWord(PRE_PAGING_IO_WRITE) > 0) then CheckListBox_ControlIO.Checked[16] := True; if( GlobalConfig.ControlIOs and LongWord(POST_PAGING_IO_WRITE) > 0) then CheckListBox_ControlIO.Checked[17] := True; if( GlobalConfig.ControlIOs and LongWord(PRE_QUERY_INFORMATION) > 0) then CheckListBox_ControlIO.Checked[18] := True; if( GlobalConfig.ControlIOs and LongWord(POST_QUERY_INFORMATION) > 0) then CheckListBox_ControlIO.Checked[19] := True; if( GlobalConfig.ControlIOs and LongWord(PRE_SET_INFORMATION) > 0) then CheckListBox_ControlIO.Checked[20] := True; if( GlobalConfig.ControlIOs and LongWord(POST_SET_INFORMATION) > 0) then CheckListBox_ControlIO.Checked[21] := True; if( GlobalConfig.ControlIOs and LongWord(PRE_DIRECTORY) > 0) then CheckListBox_ControlIO.Checked[22] := True; if( GlobalConfig.ControlIOs and LongWord(POST_DIRECTORY) > 0) then CheckListBox_ControlIO.Checked[23] := True; if( GlobalConfig.ControlIOs and LongWord(PRE_QUERY_SECURITY) > 0) then CheckListBox_ControlIO.Checked[24] := True; if( GlobalConfig.ControlIOs and LongWord(POST_QUERY_SECURITY) > 0) then CheckListBox_ControlIO.Checked[25] := True; if( GlobalConfig.ControlIOs and LongWord(PRE_SET_SECURITY) > 0) then CheckListBox_ControlIO.Checked[26] := True; if( GlobalConfig.ControlIOs and LongWord(POST_SET_SECURITY) > 0) then CheckListBox_ControlIO.Checked[27] := True; if( GlobalConfig.ControlIOs and LongWord(PRE_CLEANUP) > 0) then CheckListBox_ControlIO.Checked[28] := True; if( GlobalConfig.ControlIOs and LongWord(POST_CLEANUP) > 0) then CheckListBox_ControlIO.Checked[29] := True; if( GlobalConfig.ControlIOs and LongWord(PRE_CLOSE) > 0) then CheckListBox_ControlIO.Checked[30] := True; if( GlobalConfig.ControlIOs and LongWord(POST_CLOSE) > 0) then CheckListBox_ControlIO.Checked[31] := True; end; procedure TForm1.Button_SaveSettingsClick(Sender: TObject); begin GlobalConfig.IncludeFileFilterMask := Edit_IncludeFileFilterMask.Text; GlobalConfig.ExcludeFileFilterMask := Edit_ExcludeFileFilterMask.Text; GlobalConfig.EncryptionPasswordPhrase := Edit_PasswordPhrase.Text; GlobalConfig.AccessFlags := LongWord(ALLOW_MAX_RIGHT_ACCESS); if( not CheckListBox_AccessFlags.Checked[0]) then GlobalConfig.AccessFlags := GlobalConfig.AccessFlags And (not LongWord(FILE_ENCRYPTION_RULE)); if( not CheckListBox_AccessFlags.Checked[1]) then GlobalConfig.AccessFlags := GlobalConfig.AccessFlags And (not LongWord(ALLOW_READ_ACCESS)); if( not CheckListBox_AccessFlags.Checked[2]) then GlobalConfig.AccessFlags := GlobalConfig.AccessFlags And (not LongWord(ALLOW_WRITE_ACCESS)); if( not CheckListBox_AccessFlags.Checked[3]) then GlobalConfig.AccessFlags := GlobalConfig.AccessFlags And (not LongWord(ALLOW_FILE_DELETE)); if( not CheckListBox_AccessFlags.Checked[4]) then GlobalConfig.AccessFlags := GlobalConfig.AccessFlags And (not LongWord(ALLOW_FILE_RENAME)); if( not CheckListBox_AccessFlags.Checked[5]) then GlobalConfig.AccessFlags := GlobalConfig.AccessFlags And (not LongWord(ALLOW_OPEN_WITH_CREATE_OR_OVERWRITE_ACCESS)); if( not CheckListBox_AccessFlags.Checked[6]) then GlobalConfig.AccessFlags := GlobalConfig.AccessFlags And (not LongWord(ALLOW_FILE_MEMORY_MAPPED)); if( not CheckListBox_AccessFlags.Checked[7]) then GlobalConfig.AccessFlags := GlobalConfig.AccessFlags And (not LongWord(ALLOW_SET_SECURITY_ACCESS)); if( not CheckListBox_AccessFlags.Checked[8]) then GlobalConfig.AccessFlags := GlobalConfig.AccessFlags And (not LongWord(ALLOW_FILE_ACCESS_FROM_NETWORK)); GlobalConfig.MonitorFileEvents := 0; if( CheckListBox_FileEvents.Checked[0]) then GlobalConfig.MonitorFileEvents := GlobalConfig.MonitorFileEvents or LongWord(FILE_CREATEED); if( CheckListBox_FileEvents.Checked[1]) then GlobalConfig.MonitorFileEvents := GlobalConfig.MonitorFileEvents or LongWord(FILE_WRITTEN); if( CheckListBox_FileEvents.Checked[2]) then GlobalConfig.MonitorFileEvents := GlobalConfig.MonitorFileEvents or LongWord(FILE_RENAMED); if( CheckListBox_FileEvents.Checked[3]) then GlobalConfig.MonitorFileEvents := GlobalConfig.MonitorFileEvents or LongWord(FILE_DELETED); if( CheckListBox_FileEvents.Checked[4]) then GlobalConfig.MonitorFileEvents := GlobalConfig.MonitorFileEvents or LongWord(FILE_SECURITY_CHANGED); if( CheckListBox_FileEvents.Checked[5]) then GlobalConfig.MonitorFileEvents := GlobalConfig.MonitorFileEvents or LongWord(FILE_INFO_CHANGED); if( CheckListBox_FileEvents.Checked[6]) then GlobalConfig.MonitorFileEvents := GlobalConfig.MonitorFileEvents or LongWord(FILE_READ); GlobalConfig.MonitorIOs := 0; if( CheckListBox_MonitorIO.Checked[0]) then GlobalConfig.MonitorIOs := GlobalConfig.MonitorIOs or LongWord(POST_CREATE); if( CheckListBox_MonitorIO.Checked[1]) then GlobalConfig.MonitorIOs := GlobalConfig.MonitorIOs or LongWord(POST_FASTIO_READ); if( CheckListBox_MonitorIO.Checked[2]) then GlobalConfig.MonitorIOs := GlobalConfig.MonitorIOs or LongWord(POST_CACHE_READ); if( CheckListBox_MonitorIO.Checked[3]) then GlobalConfig.MonitorIOs := GlobalConfig.MonitorIOs or LongWord(POST_NOCACHE_READ); if( CheckListBox_MonitorIO.Checked[4]) then GlobalConfig.MonitorIOs := GlobalConfig.MonitorIOs or LongWord(POST_PAGING_IO_READ); if( CheckListBox_MonitorIO.Checked[5]) then GlobalConfig.MonitorIOs := GlobalConfig.MonitorIOs or LongWord(POST_FASTIO_WRITE); if( CheckListBox_MonitorIO.Checked[6]) then GlobalConfig.MonitorIOs := GlobalConfig.MonitorIOs or LongWord(POST_CACHE_WRITE); if( CheckListBox_MonitorIO.Checked[7]) then GlobalConfig.MonitorIOs := GlobalConfig.MonitorIOs or LongWord(POST_NOCACHE_WRITE); if( CheckListBox_MonitorIO.Checked[8]) then GlobalConfig.MonitorIOs := GlobalConfig.MonitorIOs or LongWord(POST_PAGING_IO_WRITE); if( CheckListBox_MonitorIO.Checked[9]) then GlobalConfig.MonitorIOs := GlobalConfig.MonitorIOs or LongWord(POST_QUERY_INFORMATION); if( CheckListBox_MonitorIO.Checked[10]) then GlobalConfig.MonitorIOs := GlobalConfig.MonitorIOs or LongWord(POST_SET_INFORMATION); if( CheckListBox_MonitorIO.Checked[11]) then GlobalConfig.MonitorIOs := GlobalConfig.MonitorIOs or LongWord(POST_DIRECTORY); if( CheckListBox_MonitorIO.Checked[12]) then GlobalConfig.MonitorIOs := GlobalConfig.MonitorIOs or LongWord(POST_QUERY_SECURITY); if( CheckListBox_MonitorIO.Checked[13]) then GlobalConfig.MonitorIOs := GlobalConfig.MonitorIOs or LongWord(POST_SET_SECURITY); if( CheckListBox_MonitorIO.Checked[14]) then GlobalConfig.MonitorIOs := GlobalConfig.MonitorIOs or LongWord(POST_CLEANUP); if( CheckListBox_MonitorIO.Checked[15]) then GlobalConfig.MonitorIOs := GlobalConfig.MonitorIOs or LongWord(POST_CLOSE); GlobalConfig.ControlIOs := 0; if( CheckListBox_ControlIO.Checked[0]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(PRE_CREATE); if( CheckListBox_ControlIO.Checked[1]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(POST_CREATE); if( CheckListBox_ControlIO.Checked[2]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(PRE_FASTIO_READ); if( CheckListBox_ControlIO.Checked[3]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(POST_FASTIO_READ); if( CheckListBox_ControlIO.Checked[4]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(PRE_CACHE_READ); if( CheckListBox_ControlIO.Checked[5]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(POST_CACHE_READ); if( CheckListBox_ControlIO.Checked[6]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(PRE_NOCACHE_READ); if( CheckListBox_ControlIO.Checked[7]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(POST_NOCACHE_READ); if( CheckListBox_ControlIO.Checked[8]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(PRE_PAGING_IO_READ); if( CheckListBox_ControlIO.Checked[9]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(POST_PAGING_IO_READ); if( CheckListBox_ControlIO.Checked[10]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(PRE_FASTIO_WRITE); if( CheckListBox_ControlIO.Checked[11]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(POST_FASTIO_WRITE); if( CheckListBox_ControlIO.Checked[12]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(PRE_CACHE_WRITE); if( CheckListBox_ControlIO.Checked[13]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(POST_CACHE_WRITE); if( CheckListBox_ControlIO.Checked[14]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(PRE_NOCACHE_WRITE); if( CheckListBox_ControlIO.Checked[15]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(POST_NOCACHE_WRITE); if( CheckListBox_ControlIO.Checked[16]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(PRE_PAGING_IO_WRITE); if( CheckListBox_ControlIO.Checked[17]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(POST_PAGING_IO_WRITE); if( CheckListBox_ControlIO.Checked[18]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(PRE_QUERY_INFORMATION); if( CheckListBox_ControlIO.Checked[19]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(POST_QUERY_INFORMATION); if( CheckListBox_ControlIO.Checked[20]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(PRE_SET_INFORMATION); if( CheckListBox_ControlIO.Checked[21]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(POST_SET_INFORMATION); if( CheckListBox_ControlIO.Checked[22]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(PRE_DIRECTORY); if( CheckListBox_ControlIO.Checked[23]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(POST_DIRECTORY); if( CheckListBox_ControlIO.Checked[24]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(PRE_QUERY_SECURITY); if( CheckListBox_ControlIO.Checked[25]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(POST_QUERY_SECURITY); if( CheckListBox_ControlIO.Checked[26]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(PRE_SET_SECURITY); if( CheckListBox_ControlIO.Checked[27]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(POST_SET_SECURITY); if( CheckListBox_ControlIO.Checked[28]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(PRE_CLEANUP); if( CheckListBox_ControlIO.Checked[29]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(POST_CLEANUP); if( CheckListBox_ControlIO.Checked[30]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(PRE_CLOSE); if( CheckListBox_ControlIO.Checked[31]) then GlobalConfig.ControlIOs := GlobalConfig.ControlIOs or LongWord(POST_CLOSE); GlobalConfig.SaveINI; end; ///////////////////////////////////////////////////////////////////////////// constructor TDisplayThread.Create(UseFormIn: TObject); begin inherited Create(True); PendingDisplayItems := TStringList.Create; UseForm := TForm1(UseFormIn); FreeOnTerminate := True; fCompletedEvent := CreateEvent(nil, False, False, nil); Resume; end; procedure TDisplayThread.ClearLists; begin if PendingDisplayItems = nil then exit; try if (Assigned(UseForm)) and (Assigned(PendingDisplayItems)) then begin PendingDisplayItems.Clear; end; except end; end; destructor TDisplayThread.Destroy; begin try UseForm := nil; PendingDisplayItems.Free; PendingDisplayItems := nil; except end; inherited Destroy; end; procedure TDisplayThread.Execute; const SendMax = 1; begin // {$IFNDEF WIN64} NameThreadForDebugging('DisplayThread'); // {$ENDIF} while (UseForm <> nil) and (Not Terminated) do try if CloseAppInProgress then break; SendToDisplay(Form1); except end; //send one more time to flush last Vars... //SendToDisplay(UseForm); end; procedure TDisplayThread.SendToDisplay(UseFormIn: TObject); begin if CloseAppInProgress then begin UseForm := UseFormIn; exit; end; try UseForm := UseFormIn; Synchronize(SendToDisplaySync); except end; end; procedure TDisplayThread.SendToDisplaySync; var I, N: integer; StrOut: String; tStr: String; tCount: Cardinal; UseMethod: Integer; begin UseMethod := 0; try tStr := ''; with TForm1(UseForm) do begin try if PendingDisplayItems.Count > 0 then begin I := 0; try Lock_DisplayListing.Acquire; tCount := GetTickCount; while PendingDisplayItems.Count > 0 do begin //if CanceledByUser then break; Memo1.Lines.Add(PendingDisplayItems[0]); PendingDisplayItems.Delete(0); Inc(I); if (I > 1000) or ((GetTickCount - tCount) > 500) then break; //limit display time..... end; except end; Lock_DisplayListing.Release; end else Sleep(1); except end; end; //end with finally end; end; procedure TDisplayThread.AddDisplayInfo(DisplayStr: String); begin try PendingDisplayItems.Add(DisplayStr); finally end; end; end.
unit uFeriadoController; interface uses System.SysUtils, uDMFeriado, uRegras, uEnumerador, uDM, Data.DB, Vcl.Forms, uFuncoesSIDomper, Data.DBXJSON, Data.DBXJSONReflect, uConverter, uGenericProperty; type TFeriadoController = class private FModel: TDMFeriado; FOperacao: TOperacao; procedure Post; public procedure Filtrar(ACampo, ATexto, AAtivo: string; AContem: Boolean = False); procedure FiltrarCodigo(ACodigo: Integer); procedure FiltrarPrograma(AObservacaoPrograma: TEnumPrograma; ACampo, ATexto, AAtivo: string; AContem: Boolean = False); procedure LocalizarPadrao(APrograma: TEnumPrograma); procedure LocalizarId(AId: Integer); procedure LocalizarCodigo(ACodigo: integer); procedure Novo(AIdUsuario: Integer); procedure Editar(AId: Integer; AFormulario: TForm); function Salvar(AIdUsuario: Integer): Integer; procedure Excluir(AIdUsuario, AId: Integer); procedure Cancelar(); procedure Imprimir(AIdUsuario: Integer); function ProximoId(): Integer; function ProximoCodigo(): Integer; procedure Pesquisar(AId, Codigo: Integer); function CodigoAtual: Integer; property Model: TDMFeriado read FModel write FModel; constructor Create(); destructor Destroy; override; end; implementation { TObservacaoController } uses uObservacaoVO; procedure TFeriadoController.Cancelar; begin if FModel.CDSCadastro.State in [dsEdit, dsInsert] then FModel.CDSCadastro.Cancel; end; function TFeriadoController.CodigoAtual: Integer; begin Result := 0; end; constructor TFeriadoController.Create; begin inherited Create; FModel := TDMFeriado.Create(nil); end; destructor TFeriadoController.Destroy; begin FreeAndNil(FModel); inherited; end; procedure TFeriadoController.Editar(AId: Integer; AFormulario: TForm); var Negocio: TServerModule2Client; Resultado: Boolean; begin if AId = 0 then raise Exception.Create('Não há Registro para Editar!'); DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Resultado := Negocio.Editar(CFeriado, dm.IdUsuario, AId); FModel.CDSCadastro.Open; TFuncoes.HabilitarCampo(AFormulario, Resultado); FOperacao := opEditar; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TFeriadoController.Excluir(AIdUsuario, AId: Integer); var Negocio: TServerModule2Client; begin if AId = 0 then raise Exception.Create('Não há Registro para Excluir!'); DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try Negocio.Excluir(CFeriado, AIdUsuario, AId); FModel.CDSConsulta.Delete; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TFeriadoController.Filtrar(ACampo, ATexto, AAtivo: string; AContem: Boolean); var Negocio: TServerModule2Client; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSConsulta.Close; Negocio.Filtrar(CFeriado, ACampo, ATexto, AAtivo, AContem); FModel.CDSConsulta.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TFeriadoController.FiltrarCodigo(ACodigo: Integer); var Negocio: TServerModule2Client; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSConsulta.Close; Negocio.FiltrarCodigo(CFeriado, ACodigo); FModel.CDSConsulta.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TFeriadoController.FiltrarPrograma(AObservacaoPrograma: TEnumPrograma; ACampo, ATexto, AAtivo: string; AContem: Boolean); //var // Negocio: TServerModule2Client; // iEnum: Integer; begin // Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); // try // iEnum := Integer(AObservacaoPrograma); // // FModel.CDSConsulta.Close; // Negocio.FiltrarObservacaoPrograma(ACampo, ATexto, AAtivo, iEnum, AContem); // FModel.CDSConsulta.Open; // finally // FreeAndNil(Negocio); // end; end; procedure TFeriadoController.Imprimir(AIdUsuario: Integer); var Negocio: TServerModule2Client; begin DM.Conectar; Negocio := TServerModule2Client.Create(dm.Conexao.DBXConnection); try Negocio.Relatorio(CFeriado, AIdUsuario); dm.Desconectar; // FModel.Rel.Print; finally FreeAndNil(Negocio); end; end; procedure TFeriadoController.LocalizarCodigo(ACodigo: integer); var Negocio: TServerModule2Client; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Negocio.LocalizarCodigo(CFeriado, ACodigo); FModel.CDSCadastro.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TFeriadoController.LocalizarId(AId: Integer); var Negocio: TServerModule2Client; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Negocio.LocalizarId(CFeriado, AId); FModel.CDSCadastro.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TFeriadoController.LocalizarPadrao(APrograma: TEnumPrograma); var Negocio: TServerModule2Client; iEnum: Integer; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try iEnum := Integer(APrograma); FModel.CDSCadastro.Close; Negocio.ObservacaoPadrao(iEnum); FModel.CDSCadastro.Open; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TFeriadoController.Novo(AIdUsuario: Integer); var Negocio: TServerModule2Client; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try FModel.CDSCadastro.Close; Negocio.Novo(CFeriado, AIdUsuario); FModel.CDSCadastro.Open; FModel.CDSCadastro.Append; //FModel.CDSCadastroCid_Codigo.AsInteger := ProximoCodigo(); FOperacao := opIncluir; dm.Desconectar; finally FreeAndNil(Negocio); end; end; procedure TFeriadoController.Pesquisar(AId, Codigo: Integer); begin if AId > 0 then LocalizarId(AId) else LocalizarCodigo(Codigo); end; procedure TFeriadoController.Post; begin if FModel.CDSConsulta.State in [dsEdit, dsInsert] then FModel.CDSConsulta.Post; end; function TFeriadoController.ProximoCodigo: Integer; var Negocio: TServerModule2Client; iCodigo: Integer; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try iCodigo := StrToInt(Negocio.ProximoCodigo(CFeriado).ToString); Result := iCodigo; dm.Desconectar; finally FreeAndNil(Negocio); end; end; function TFeriadoController.ProximoId: Integer; var Negocio: TServerModule2Client; iCodigo: Integer; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try iCodigo := StrToInt(Negocio.ProximoId(CFeriado).ToString); Result := iCodigo; dm.Desconectar; finally FreeAndNil(Negocio); end; end; function TFeriadoController.Salvar(AIdUsuario: Integer): Integer; var Negocio: TServerModule2Client; begin DM.Conectar; Negocio := TServerModule2Client.Create(DM.Conexao.DBXConnection); try try if (FModel.CDSCadastroFer_Data.AsFloat = 0) or (FModel.CDSCadastroFer_Data.AsString = '') then raise Exception.Create('Informe a Data!'); if Trim(FModel.CDSCadastroFer_Descricao.AsString) = '' then raise Exception.Create('Informe a Descrição!'); Post; FModel.CDSCadastro.ApplyUpdates(0); Negocio.Salvar(CFeriado, AIdUsuario); FOperacao := opNavegar; dm.Desconectar; except on E: Exception do begin dm.ErroConexao(E.Message); end; end; finally FreeAndNil(Negocio); end; end; end.
{*******************************************************} { Проект: Repository } { Модуль: uServices.pas } { Описание: Службы приложения } { Copyright (C) 2015 Боборыкин В.В. (bpost@yandex.ru) } { } { Распространяется по лицензии GPLv3 } {*******************************************************} unit uServices; interface uses Classes, Db, uMultiCastEvent; type // интерфейс для службы приложения IService = interface(IInterface) ['{7369FBA5-8ABA-4395-AB5F-3EE58ACD5772}'] end; // сервис-локатор TServices = class(TObject) private FGuildList: TStringList; FRegistry: IInterfaceList; public constructor Create; destructor Destroy; override; function Exists(IID: TGUID; AName: String = ''): Boolean; procedure RegisterService(IID: TGUID; AService: IInterface; AName: String = ''); function TryGetService(IID: TGUID; out AService; AName: String = ''): Boolean; procedure UnregisterService(IID: TGUID; AName: String = ''); end; {************************** SqlService *************************************} TDataSetRecordAction = procedure (DataSet: TDataSet; AContext: IInterface); ISqlService = interface(IService) ['{90F2982E-7413-4BC1-AA17-EE61C03DD8BB}'] function ColumnExists(ATableName, AColumnName: string): Boolean; stdcall; function DatabaseToString: string; stdcall; function DataModule: TDataModule; stdcall; function GetCurrentDbVersion: Integer; stdcall; procedure RefreshDataSet(ADataSet: TDataSet); stdcall; procedure ScanDataSet(ADataSet: TDataSet; RecordAction: TDataSetRecordAction; AContext: IInterface); stdcall; procedure SetCurrentDbVersion(AVersion: Integer); stdcall; function SqlCalc(ASqlText: String; AParams: array of Variant): Variant; stdcall; function SqlCalcIntf(ASqlText: String; AParams: array of IInterface): Variant; stdcall; function SqlExec(ASqlText: String; AParams: array of Variant): Variant; stdcall; function SqlExecIntf(ASqlText: String; AParams: array of IInterface): Variant; stdcall; function SqlExecScript(ASqlText: String): Boolean; stdcall; function SqlExecSp(AStoredProcedureName: String; AParams: array of Variant): Variant; stdcall; function SqlExecSpIntf(AStoredProcedureName: String; AParams: array of IInterface): Variant; stdcall; function SqlSelect(ASqlText: String; AParams: array of Variant): TDataSet; stdcall; function SqlSelectIntf(ASqlText: String; AParams: array of IInterface): TDataSet; stdcall; function StoredProcedureExists(AStoredProcedureName: String): Boolean; stdcall; function TableExists(ATableName: string): Boolean; stdcall; function UpdateDatabase(RequiredDbVersion: Integer): Boolean; stdcall; end; {************************** LogService *************************************} TEventKind = (lekDebug, lekInfo, lekWarning, lekError); ILogEvent = interface(IInterface) ['{52540088-7F12-4771-BA76-4D342AE28294}'] function GetApplicationName: string; stdcall; function GetApplicationUserName: string; stdcall; function GetComputerName: string; stdcall; function GetComputerUserName: string; stdcall; function GetEventDateTime: TDateTime; stdcall; function GetEventKind: TEventKind; stdcall; function GetEventText: string; stdcall; procedure SetApplicationName(const Value: string); stdcall; procedure SetApplicationUserName(const Value: string); stdcall; procedure SetComputerName(const Value: string); stdcall; procedure SetComputerUserName(const Value: string); stdcall; procedure SetEventDateTime(Value: TDateTime); stdcall; procedure SetEventKind(Value: TEventKind); stdcall; procedure SetEventText(const Value: string); stdcall; property ApplicationName: string read GetApplicationName write SetApplicationName; property ApplicationUserName: string read GetApplicationUserName write SetApplicationUserName; property ComputerName: string read GetComputerName write SetComputerName; property ComputerUserName: string read GetComputerUserName write SetComputerUserName; property EventDateTime: TDateTime read GetEventDateTime write SetEventDateTime; property EventKind: TEventKind read GetEventKind write SetEventKind; property EventText: string read GetEventText write SetEventText; end; ILogService = interface(IService) ['{C392F78E-F492-4BD7-80C9-7F0B6B43D657}'] procedure Add(AEventText: string; AEventKind: TEventKind = lekDebug); overload; stdcall; procedure Add(AEvent: ILogEvent); overload; stdcall; end; {************************** TimeService *************************************} ITimeService = interface(IService) ['{91B4C0F1-1753-4F0F-8F4D-4C8F58CD5273}'] function CurrentDateTime: TDateTime; stdcall; end; {************************** SecurityService *********************************} IAppUser = interface(IInterface) ['{53B69E7D-1965-49E6-A96B-68F241E2FC38}'] function ChangePassword(AOldPassword, ANewPassword: String): Boolean; stdcall; function GetFio: string; stdcall; function GetId: Variant; stdcall; function GetLoginName: string; stdcall; function InRole(ARoleName: string): Boolean; stdcall; procedure SetFio(const Value: string); stdcall; procedure SetId(Value: Variant); stdcall; procedure SetLoginName(const Value: string); stdcall; property Fio: string read GetFio write SetFio; property Id: Variant read GetId write SetId; property LoginName: string read GetLoginName write SetLoginName; end; TAccessType = (atyExecute, atyRead, atyWrite, atyCreate, atyDelete, atyFull); IPermission = interface(IInterface) ['{61278D65-B3C8-4F72-98A0-AB969422A3A3}'] function GetAccessType: TAccessType; stdcall; function GetGranted: Boolean; stdcall; function GetRoles: TStringList; stdcall; function GetTokenName: string; stdcall; procedure SetAccessType(Value: TAccessType); stdcall; procedure SetGranted(Value: Boolean); stdcall; procedure SetTokenName(const Value: string); stdcall; property AccessType: TAccessType read GetAccessType write SetAccessType; property Granted: Boolean read GetGranted write SetGranted; property Roles: TStringList read GetRoles; property TokenName: string read GetTokenName write SetTokenName; end; ISecurityService = interface(IService) ['{FA3E6CBC-69D2-4E78-A7A6-F752E2FBF154}'] function AccessGranted(ATokenName: String; AAccessType: TAccessType; AContext: IInterface = nil; AAppUser: IAppUser = nil): Boolean; overload; stdcall; function AccessGranted(AComponent: TComponent; AAccessType: TAccessType; AContext: IInterface = nil; AAppUser: IAppUser = nil): Boolean; overload; stdcall; function AfterLogin: IMultiCastEvent; stdcall; function AfterLogout: IMultiCastEvent; stdcall; function BeforeLogin: IMultiCastEvent; stdcall; function BeforeLogout: IMultiCastEvent; stdcall; procedure ClearPermissions; stdcall; function CurrentAppUser: IAppUser; stdcall; function CurrentUserFio: string; stdcall; function CurrentUserId: Variant; stdcall; function GetAccessGrantedByDefault: Boolean; stdcall; function GetComponentToken(AComponent: TComponent): string; stdcall; function IsLoggedIn: Boolean; stdcall; function Login(ALoginName, APassword: string): Boolean; stdcall; procedure Logout; stdcall; function OnCheckAccess: IMultiCastEvent; stdcall; procedure RegisterPermission(APermission: IPermission); stdcall; procedure SetAccessGrantedByDefault(Value: Boolean); stdcall; property AccessGrantedByDefault: Boolean read GetAccessGrantedByDefault write SetAccessGrantedByDefault; end; {************************** ReportService **********************************} TPaperOrientation = (poDefault, poPortrait, poLandscape); TDuplex = (dupDefault, dupVertical, dupHorizontal); IPrintReportParameters = interface(IInterface) ['{BE97B0D6-FBD3-4922-9BC6-582BC725B46F}'] function GetDuplex: TDuplex; stdcall; function GetNumCopy: Integer; stdcall; function GetPaperOrientation: TPaperOrientation; stdcall; function GetPrinterName: string; stdcall; function GetShowPrintDialog: Boolean; stdcall; procedure SetDuplex(Value: TDuplex); stdcall; procedure SetNumCopy(Value: Integer); stdcall; procedure SetPaperOrientation(Value: TPaperOrientation); stdcall; procedure SetPrinterName(const Value: string); stdcall; procedure SetShowPrintDialog(Value: Boolean); stdcall; property Duplex: TDuplex read GetDuplex write SetDuplex; property NumCopy: Integer read GetNumCopy write SetNumCopy; property PaperOrientation: TPaperOrientation read GetPaperOrientation write SetPaperOrientation; property PrinterName: string read GetPrinterName write SetPrinterName; property ShowPrintDialog: Boolean read GetShowPrintDialog write SetShowPrintDialog; end; IReportListItem = interface(IInterface) ['{41C008EB-DA0E-4DA2-AF5D-A0C5BFAF991B}'] function GetName: string; stdcall; procedure SetName(const Value: string); stdcall; property Name: string read GetName write SetName; end; IReportTemplate = interface(IReportListItem) ['{8F91CC03-8453-4DF5-8A4E-F11B7D4CE2C9}'] function GetTemplateFileName: string; stdcall; procedure SetTemplateFileName(const Value: string); stdcall; property TemplateFileName: string read GetTemplateFileName write SetTemplateFileName; end; IReportList = interface(IReportListItem) ['{ABDA68DE-88B7-453F-AAFC-F9D75D0EE8B2}'] function Add(AItem: IReportListItem): Integer; stdcall; procedure Delete(Index: Integer); stdcall; function GetCount: Integer; stdcall; function GetItems(Index: Integer): IReportListItem; stdcall; procedure SetItems(Index: Integer; Value: IReportListItem); stdcall; property Count: Integer read GetCount; property Items[Index: Integer]: IReportListItem read GetItems write SetItems; end; IReportService = interface(IService) ['{E8FE1675-128A-4E86-92F4-351E59043E12}'] function GetReportNames(AReportList: IReportList; AContext: IInterface = nil): Boolean; stdcall; function GetTemplatesDir: string; stdcall; function PrintReport(AReportName, ATemplateFileName: String; AContext: IInterface = nil; APrintParameters: IPrintReportParameters = nil): Boolean; stdcall; procedure SetTemplatesDir(const Value: string); stdcall; function ShowReport(AReportName, ATemplateFileName: String; AContext: IInterface = nil): Boolean; stdcall; property TemplatesDir: string read GetTemplatesDir write SetTemplatesDir; end; {************************** OptionsService **********************************} TOptionScope = (opsDomainUser, opsComputer, opsAppUser, opsApplication, opsGlobal); IOptionsService = interface(IService) ['{39471039-6274-4E1A-92D8-621982E5E818}'] function ReadOption(AOptionName: String; ADefaultValue: Variant; AScope: TOptionScope = opsDomainUser): Variant; stdcall; procedure WriteOption(AOptionName: String; AValue: Variant; AScope: TOptionScope = opsDomainUser); stdcall; end; {************************** NotificationService **************************} ISubscription = interface(IInterface) ['{0E2CBD70-71D0-4AD7-B85E-50B89033C18B}'] procedure DoEvent(Sender: TObject; AEventData: IInterface); stdcall; function EventIsMatches(Sender: TObject; AEventData: IInterface): Boolean; stdcall; end; INotificationService = interface(IService) ['{E92194F4-9BB7-42DF-8768-3192D434C5F0}'] procedure Notify(Sender: TObject; AEventData: IInterface); stdcall; procedure NotifyAsync(Sender: TObject; AEventData: IInterface); stdcall; procedure Subscribe(Subscriber: TObject; Subscription: ISubscription); stdcall; procedure Unsubscribe(Subscriber: TObject; Subscription: ISubscription); stdcall; procedure UnsubscribeAll(Subscriber: TObject); stdcall; end; {************************** DatabaseWatchService **************************} ITableWatchParameters = interface(IInterface) ['{B850F38A-E858-4420-B391-4E51400FCD1E}'] function IdFieldName: string; stdcall; function TableName: string; stdcall; function TimeStampFieldName: string; stdcall; end; IRecordWatchParameters = interface(ITableWatchParameters) ['{1D95A4DF-3BC9-48A3-AB4E-69BE9956F29A}'] function RecordId: Variant; stdcall; end; IDatabaseWatchService = interface(IService) ['{4BD6AD88-2EAD-4CA2-8BAB-D8218339C7EE}'] procedure AddRecordWatch(AWatchParams: IRecordWatchParameters); stdcall; procedure AddTableWatch(AWatchParams: ITableWatchParameters); stdcall; end; ITableChangedEvent = interface(IInterface) ['{72995C25-360A-470B-A762-642E569647B4}'] function TableName: string; stdcall; end; // синглетон сервис - локатора function Services: TServices; // быстрый доступ к службам function SqlService: ISqlService; function TimeService: ITimeService; function LogService: ILogService; function SecurityService: ISecurityService; implementation uses sysutils; var FServices: TServices; function Services: TServices; begin Result := FServices; end; function SqlService: ISqlService; begin Services.TryGetService(ISqlService, Result); end; function TimeService: ITimeService; begin Services.TryGetService(ITimeService, Result); end; function LogService: ILogService; begin Services.TryGetService(ILogService, Result); end; function SecurityService: ISecurityService; begin Services.TryGetService(ISecurityService, Result); end; { ********************************** TServices *********************************** } constructor TServices.Create; begin inherited Create; FGuildList := TStringList.Create(); FRegistry := TInterfaceList.Create(); end; destructor TServices.Destroy; begin FreeAndNil(FGuildList); inherited Destroy; end; function TServices.Exists(IID: TGUID; AName: String = ''): Boolean; begin Result := FGuildList.IndexOf(GUIDToString(IID) + AName) > -1; end; procedure TServices.RegisterService(IID: TGUID; AService: IInterface; AName: String = ''); begin if Exists(IID, AName) then UnregisterService(IID, AName); FGuildList.Add(GUIDToString(IID) + AName); FRegistry.Add(AService); end; function TServices.TryGetService(IID: TGUID; out AService; AName: String = ''): Boolean; var GuidIndex: Integer; begin GuidIndex := FGuildList.IndexOf(GUIDToString(IID) + AName); Result := GuidIndex > -1; if Result then Supports(FRegistry.Items[GuidIndex], IID, AService); end; procedure TServices.UnregisterService(IID: TGUID; AName: String = ''); var GuidIndex: Integer; begin GuidIndex := FGuildList.IndexOf(GUIDToString(IID) + AName); if GuidIndex > -1 then begin FGuildList.Delete(GuidIndex); FRegistry.Delete(GuidIndex); end; end; initialization FServices := TServices.Create; finalization FServices.Free; end.
unit uFrmCadastro; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.Buttons, Vcl.StdCtrls, Vcl.ExtCtrls, uLembreteDAO, System.Generics.Collections, uLembrete; type TForm1 = class(TForm) Panel1: TPanel; Panel2: TPanel; Label1: TLabel; EdtBuscaTitulo: TEdit; BtnBuscar: TSpeedButton; ListView1: TListView; Panel3: TPanel; BtnNovo: TSpeedButton; BtnEditar: TSpeedButton; BtnExcluir: TSpeedButton; private { Private declarations } LembreteDAO: TLembreteDAO; procedure CarregarColecao; procedure PreencherListView(pListaLembrete: TList<TLembrete>); public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} { TForm1 } procedure TForm1.CarregarColecao; begin end; procedure TForm1.PreencherListView(pListaLembrete: TList<TLembrete>); var I: integer; tempItem: TListItem; begin if Assigned(pListaLembrete) then begin ListView1.Clear; for I := 0 to pListaLembrete.Count - 1 do begin tempItem := ListView1.Items.Add; tempItem.Caption := IntToStr(TLembrete(pListaLembrete[I].IDLembrete)); tempItem.SubItems.Add(TLembrete(pListaLembrete[I].titulo)); tempItem.SubItems.Add(FormatDateTime('dd/mm/yyyy hh:mm', TLembrete(pListaLembrete[I].dataHora))); end; end else ShowMessage('Nada Encontrado'); end; end.
program fptutorial14; { rpg game to show off record use } {$mode objfpc}{$H+} uses crt, sysutils, {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes { you can add units after this }; type creature = record name: string; armor, health, magic, power: integer; end; var hero, jellball, smallspider, largespider, opponent: creature; enemNum: integer; { used to select the opponent monster } selection: string; { used for user input } score: integer; { keeps score } procedure LoadSettings; begin score := 0; with hero do begin name := 'Sir Bill'; armor := 0; health := 10; magic := 2; power := 5; end; with jellball do begin name := 'JellBall'; armor := 0; health := 1; magic := 0; power := 1; end; with smallspider do begin name := 'Small Spider'; armor := 0; health := 1; magic := 0; power := 2; end; with largespider do begin name := 'Large Spider'; armor := 0; health := 2; magic := 0; power := 2; end; end; procedure GetEnemy; begin randomize; enemNum := random(3) + 1; if enemNum = 1 then opponent := jellball else if enemNum = 2 then opponent := smallspider else opponent := largespider; end; procedure WriteStats; begin with hero do begin writeln(name, ' Score = ', score); writeln('Health: ', health); writeln('Armor: ', armor); writeln('Magic: ', magic); writeln('Power: ', power); end; writeln; writeln; with opponent do begin writeln('Opponent: ', name); writeln('Health: ', health); writeln('Armor: ', armor); writeln('Magic: ', magic); writeln('Power: ', power); end; end; procedure Menu; begin repeat writeln; writeln('(F)ight'); writeln('(M)agic'); write('Selection: '); readln(selection); selection := UpperCase(selection); randomize; if selection = 'F' then begin hero.health := hero.health - random(opponent.power + 1); opponent.health := opponent.health - random(hero.power + 1); end else if (selection = 'M') and (hero.magic > 0) then begin opponent.health := opponent.health - 10; hero.magic := hero.magic - 1; if opponent.health > 0 then hero.health := hero.health - random(opponent.power + 1); end; until (selection = 'F') or (selection = 'M'); end; procedure Battle; begin GetEnemy; repeat clrscr(); WriteStats; Menu; until (hero.health <= 0) or (opponent.health <= 0); if opponent.health <= 0 then begin writeln(opponent.name, ' was killed!'); score := score + opponent.power; sleep(1000); end; end; begin { main statement } repeat LoadSettings; repeat Battle; until hero.health <= 0; clrscr(); writeln(Hero.name, ' was killed'); writeln('Final Score: ', score); repeat write('Play Again Y/N: '); readln(selection); selection := UpperCase(selection); until (selection = 'Y') or (selection = 'N'); until selection = 'N'; end.
{!DOCTOPIC}{ Type » T2DPointArray } {!DOCREF} { @method: function T2DPointArray.Len(): Int32; @desc: Returns the length of the ATPA. Same as c'Length(ATPA)' } function T2DPointArray.Len(): Int32; begin Result := Length(Self); end; {!DOCREF} { @method: function T2DPointArray.IsEmpty(): Boolean; @desc: Returns True if the ATPA is empty. Same as c'Length(ATPA) = 0' } function T2DPointArray.IsEmpty(): Boolean; begin Result := Length(Self) = 0; end; {!DOCREF} { @method: procedure T2DPointArray.Append(const TPA:TPointArray); @desc: Add another TPA to the ATPA } procedure T2DPointArray.Append(const TPA:TPointArray); var l:Int32; begin l := Length(Self); SetLength(Self, l+1); Self[l] := TPA; end; {!DOCREF} { @method: procedure T2DPointArray.Insert(idx:Int32; Value:TPointArray); @desc: Inserts a new item `value` in the array at the given position. If position `idx` is greater then the length, it will append the item `value` to the end. If it's less then 0 it will substract the index from the length of the array.[br] `Arr.Insert(0, x)` inserts at the front of the list, and `Arr.Insert(length(a), x)` is equivalent to `Arr.Append(x)`. } procedure T2DPointArray.Insert(idx:Int32; Value:TPointArray); var i,l:Int32; begin l := Length(Self); if (idx < 0) then idx := math.modulo(idx,l); if (l <= idx) then begin self.append(value); Exit(); end; SetLength(Self, l+1); for i:=l downto idx+1 do Self[i] := Self[i-1]; Self[i] := Value; end; {!DOCREF} { @method: function T2DPointArray.Pop(): TPointArray; @desc: Removes and returns the last item in the array } function T2DPointArray.Pop(): TPointArray; var H:Int32; begin H := high(Self); Result := Self[H]; SetLength(Self, H); end; {!DOCREF} { @method: function T2DPointArray.PopLeft(): TPointArray; @desc: Removes and returns the first item in the array } function T2DPointArray.PopLeft(): TPointArray; begin Result := Self[0]; Self := Self.Slice(1,-1); end; {!DOCREF} { @method: function T2DPointArray.Slice(Start,Stop: Int32; Step:Int32=1): T2DPointArray; @desc: Slicing similar to slice in Python, tho goes from 'start to and including stop' Can be used to eg reverse an array, and at the same time allows you to c'step' past items. You can give it negative start, and stop, then it will wrap around based on length(..) If c'Start >= Stop', and c'Step <= -1' it will result in reversed output. [note]Don't pass positive c'Step', combined with c'Start > Stop', that is undefined[/note] } function T2DPointArray.Slice(Start:Int64=DefVar64; Stop: Int64=DefVar64; Step:Int64=1): T2DPointArray; begin if (Start = DefVar64) then if Step < 0 then Start := -1 else Start := 0; if (Stop = DefVar64) then if Step > 0 then Stop := -1 else Stop := 0; if Step = 0 then Exit; try Result := exp_slice(Self, Start,Stop,Step); except SetLength(Result,0) end; end; {!DOCREF} { @method: procedure T2DPointArray.Extend(Arr:T2DPointArray); @desc: Extends the 2d-array with a 2d-array } procedure T2DPointArray.Extend(Arr:T2DPointArray); var L,i:Int32; begin L := Length(Self); SetLength(Self, Length(Arr) + L); for i:=L to High(Self) do begin SetLength(Self[i],Length(Arr[i-L])); MemMove(Arr[i-L][0], Self[i][0], Length(Arr[i-L])*SizeOf(TPoint)); end; end; {!DOCREF} { @method: function T2DPointArray.Merge(): TPointArray; @desc: Merges all the groups in the ATPA, and return the TPA } function T2DPointArray.Merge(): TPointArray; {$IFDEF SRL6}override;{$ENDIF} begin Result := MergeATPA(Self); end; {!DOCREF} { @method: function T2DPointArray.Sorted(Key:TSortKey=sort_Default): T2DPointArray; @desc: Sorts a copy of the ATPA with the given key, returns a copy Supported keys: c'sort_Default, sort_Length, sort_Mean, sort_First' } function T2DPointArray.Sorted(Key:TSortKey=sort_Default): T2DPointArray; begin Result := Self.Slice(); case Key of sort_Default, sort_Length: se.SortATPAByLength(Result); sort_Mean: se.SortATPAByMean(Result); sort_First: se.SortATPAByFirst(Result); else WriteLn('TSortKey not supported'); end; end; {!DOCREF} { @method: function T2DPointArray.Sorted(Index:Integer): T2DPointArray; overload; @desc: Sorts a copy of the ATPA by the given index in each group } function T2DPointArray.Sorted(Index:Integer): T2DPointArray; overload; begin Result := Self.Slice(); se.SortATPAByIndex(Result, Index); end; {!DOCREF} { @method: procedure T2DPointArray.Sort(Key:TSortKey=sort_Default); @desc: Sorts the ATPA with the given key, returns a copy Supported keys: c'sort_Default, sort_Length, sort_Mean, sort_First' } procedure T2DPointArray.Sort(Key:TSortKey=sort_Default); begin case Key of sort_Default, sort_Length: se.SortATPAByLength(Self); sort_Mean: se.SortATPAByMean(Self); sort_First: se.SortATPAByFirst(Self); else WriteLn('TSortKey not supported'); end; end; {!DOCREF} { @method: procedure T2DPointArray.Sort(Index:Integer); overload; @desc: Sorts the ATPA by the given index in each group. If the group is not that large it will be set to the last item in that group. Negative 'index' will result in counting from right to left: High(Arr[i]) - index } procedure T2DPointArray.Sort(Index:Integer); overload; begin se.SortATPAByIndex(Self, Index); end; {!DOCREF} { @method: function T2DPointArray.Reversed(): T2DPointArray; @desc: Creates a reversed copy of the array } function T2DPointArray.Reversed(): T2DPointArray; begin Result := Self.Slice(,,-1); end; {!DOCREF} { @method: procedure T2DPointArray.Reverse(); @desc: Reverses the array } procedure T2DPointArray.Reverse(); begin Self := Self.Slice(,,-1); end; {=============================================================================} // The functions below this line is not in the standard array functionality // // By "standard array functionality" I mean, functions that all standard // array types should have. {=============================================================================}
unit Ammunition; interface uses // Delphi units Classes, // Own units UItems, UCommon; const NoPrefix = 0; NoSuffix = 0; FullTough = -1; FullCount = -1; MinCostMod = 0.1; type NItemCap = (icNo, icLevel, icStrength, icAgility, icStamina, icIntellect, icSpirit); TPrefix = Integer; TSuffix = Integer; TItemProp = record Crash, Slash, Pierce, Ice, Lightning, Fire, Poison, Acid: Integer; end; TOldInvItem = record Name, Description, Hint, Script: string; ID, ImageIndex, ItemType, Sound, AdvType, Strength, Dexterity, Stamina, Magic, Spirit, NeedLevel, NeedStrength, NeedDexterity, NeedStamina, NeedMagic, NeedSpirit, Cost, Tough, DollID: Integer; Damage, Protect: TItemProp; Gender: Byte; end; /// <summary> /// The Item with all its properties - all descending from BaseItem and also modifiable /// </summary> /// <remarks> /// unavailable standard Create constructor /// </remarks> TInvItem = class(THiddenCreateObject) private FModifiableProps: array[ModifiableItemParamsStart..ModifiableItemParamsEnd] of Integer; FBaseItemId: Integer; FPref: TPrefix; FSuff: TSuffix; function GetTextProp(ItemParam: NItemParam): string; function GetIntProp(ItemParam: NItemParam): Integer; procedure SetPref(const Value: TPrefix); procedure SetSuff(const Value: TSuffix); function GetPref: TPrefix; function GetSuff: TSuffix; function GetAsString: string; function GetDamage: TItemProp; function GetProtect: TItemProp; function GetBaseItem: TBaseItem; protected function GetCost: Integer; property BaseItem: TBaseItem read GetBaseItem; public constructor Create(ABaseItemID: Integer; APref: TPrefix = NoPrefix; ASuff: TSuffix = NoSuffix); overload; /// <param name="IsFull"> /// means item created with full Tough and Count /// </param> constructor Create(Item: string; IsFull: Boolean = False); overload; property AsString: string read GetAsString; property Cost: Integer read GetCost; property Suff: TSuffix read GetSuff write SetSuff; property Pref: TPrefix read GetPref write SetPref; function IsSimpleItem: Boolean; class function CanStringBeItem(S: string): Boolean; class function GenItem(ItemID, ItemLevel: Integer): string; // modifiable properties private function GetModifiableProp(ItemParam: NItemParam): Integer; procedure SetModifiableProp(ItemParam: NItemParam; const Value: Integer); protected property ModifiableProps[ItemParam: NItemParam]: Integer read GetModifiableProp write SetModifiableProp; public property Tough: Integer index ipTough read GetModifiableProp write SetModifiableProp; property Count: Integer index ipCount read GetModifiableProp write SetModifiableProp; // baseitem properties accessors protected property IntProps[ItemParam: NItemParam]: Integer read GetIntProp; property TextProps[ItemParam: NItemParam]: string read GetTextProp; public property Name: string Index ipName read GetTextProp; property Description: string Index ipDescription read GetTextProp; property Hint: string Index ipHint read GetTextProp; property Script: string Index ipScript read GetTextProp; property MaxTough: Integer Index ipTough read GetIntProp; property ImageIndex: Integer Index ipImageIndex read GetIntProp; property ItemType: Integer Index ipType read GetIntProp; property Sound: Integer Index ipSound read GetIntProp; property BaseCost: Integer Index ipCost read GetIntProp; property BaseItemID: Integer Index ipID read GetIntProp; property BaseCount: Integer Index ipCount read GetIntProp; property NeedLevel: Integer Index ipNeedLevel read GetIntProp; property NeedStrength: Integer Index ipNeedStrength read GetIntProp; property NeedDexterity: Integer Index ipNeedDexterity read GetIntProp; property NeedStamina: Integer Index ipNeedStamina read GetIntProp; property NeedMagic: Integer Index ipNeedMagic read GetIntProp; property NeedSpirit: Integer Index ipNeedSpirit read GetIntProp; property Strength: Integer Index ipStrength read GetIntProp; property Dexterity: Integer Index ipDexterity read GetIntProp; property Stamina: Integer Index ipStamina read GetIntProp; property Magic: Integer Index ipMagic read GetIntProp; property Spirit: Integer Index ipSpirit read GetIntProp; property Damage: TItemProp read GetDamage; property Protect: TItemProp read GetProtect; end; TMapItem = class(THODObject) private FX: Integer; FY: Integer; FIdx: Integer; FItem: TInvItem; procedure SetX(const Value: Integer); procedure SetY(const Value: Integer); procedure SetIdx(const Value: Integer); procedure SetItem(const Value: TInvItem); public property X: Integer read FX write SetX; property Y: Integer read FY write SetY; property Idx: Integer read FIdx write SetIdx; property Item: TInvItem read FItem write SetItem; constructor Create (AX, AY, AIdx: Integer; AItem: TInvItem); destructor Destroy; override; end; TMapItemList = class(TObjList) private function GetItem(Index: Integer): TMapItem; procedure SetItem(Index: Integer; const Value: TMapItem); public property Items[Index: Integer]: TMapItem read GetItem write SetItem; function Add(Item: TMapItem): Integer; end; TItemStringList = class(TStringList) private TempAdding: TInvItem; FSlotCount: Integer; protected function GetInvItems(Index: Integer): TInvItem; procedure SetInvItems(Index: Integer; const Value: TInvItem); procedure SetSlotCount(const Value: Integer); function Get(Index: Integer): string; procedure Put(Index: Integer; const Value: string); public constructor Create; destructor Destroy; override; function Add(S: string): Integer; reintroduce; overload; function Add(Item: TInvItem): Integer; reintroduce; overload; procedure Append(S: string); reintroduce; overload; procedure Append(Item: TInvItem); reintroduce; overload; procedure Clear; reintroduce; procedure Delete(Index: Integer); reintroduce; property SlotCount: Integer read FSlotCount write SetSlotCount; property InvItems[Index: Integer]: TInvItem read GetInvItems write SetInvItems; property Strings[Index: Integer]: string read Get write Put; default; function FindItem(BaseId: Integer; SearchFrom: Integer = 0): Integer; function IsEmptyItem(Index: Integer): Boolean; function ClearItem(Index: Integer): Boolean; end; /// <summary> /// Makes a string of deserialized item, default -1 makes item of full toughness and count /// </summary> function BuildItem(ID: Integer; Pref: TPrefix = NoPrefix; Suff: TSuffix = NoSuffix; Tough: Integer = FullTough; Count: Integer = FullCount): string; function IsEmptyItem(Item: string): Boolean; implementation uses // Delphi units SysUtils, Math, // own units UConfig, Affixes, uStrUtils; type TItemList = class(TObjList) private function GetItem(Index: Integer): TInvItem; procedure SetItem(Index: Integer; const Value: TInvItem); public property Items[Index: Integer]: TInvItem read GetItem write SetItem; default; function Add(Item: TInvItem): Integer; end; var TheItemList: TItemList; function ItemList: TItemList; begin if not Assigned(TheItemList) then TheItemList := TItemList.Create; Result := TheItemList; end; function BuildItem(ID: Integer; Pref: TPrefix = NoPrefix; Suff: TSuffix = NoSuffix; Tough: Integer = FullTough; Count: Integer = FullCount): string; begin if Tough = FullTough then Tough := BaseItems(ID).IntProps[ipTough]; if Count = FullCount then Count := BaseItems(ID).IntProps[ipCount]; Result := Format('%d|%d|%d|%d|%d', [ID, Pref, Suff, Tough, Count]); end; function IsEmptyItem(Item: string): Boolean; begin Result := (Item = '') or (Item[1] = '0'); end; { TInvItem } constructor TInvItem.Create(ABaseItemID: Integer; APref: TPrefix = NoPrefix; ASuff: TSuffix = NoSuffix); var ItemParam: NItemParam; begin inherited Create; FBaseItemID := ABaseItemID; FSuff := ASuff; FPref := APref; for ItemParam := Low(NItemParam) to High(NItemParam) do if ItemParam in ModifiableItemParams then ModifiableProps[ItemParam] := BaseItem.IntProps[ItemParam]; ItemList.Add(Self); end; constructor TInvItem.Create(Item: string; IsFull: Boolean = False); var ItemID, PrefID, SuffID, CurTough, CurCount: Integer; ItemParts: TSplitResult; function ItemPartValue(Idx: Integer): Integer; begin Result := 0; if (Idx <= High(ItemParts)) and TryStrToInt(ItemParts[Idx], Result) then ; end; begin Assert(CanStringBeItem(Item), 'Passed string is not serialized item'); ItemParts := Explode('|', Item); ItemID := ItemPartValue(0); PrefID := ItemPartValue(1); SuffID := ItemPartValue(2); CurTough := ItemPartValue(3); CurCount := ItemPartValue(4); Create(ItemID, PrefID, SuffID); if IsFull then begin Tough := MaxTough; Count := BaseCount; end else begin Tough := CurTough; Count := CurCount; end; end; function TInvItem.GetAsString: string; begin Result := Format('%d|%d|%d|%d|%d', [BaseItemID, Pref, Suff, Tough, Count]); end; function TInvItem.GetBaseItem: TBaseItem; begin Result := BaseItems(FBaseItemID); end; function TInvItem.GetCost: Integer; var CountMod, ToughMod: Single; begin // Result := BaseCost; if BaseCount = 0 then CountMod := 1 else CountMod := Count / BaseCount; if MaxTough = 0 then ToughMod := 1 else ToughMod := Tough / MaxTough; Result := Round(Max(CountMod * ToughMod, MinCostMod) * (BaseCost + AffixConfig.IntValues[Pref, apPrice] + AffixConfig.IntValues[Suff, apPrice])); end; function TInvItem.GetDamage: TItemProp; begin with Result do begin Crash := IntProps[ipDamageCrash]; Slash := IntProps[ipDamageSlash]; Pierce := IntProps[ipDamagePierce]; Ice := IntProps[ipDamageIce]; Lightning := IntProps[ipDamageLightning]; Fire := IntProps[ipDamageFire]; Poison := IntProps[ipDamagePoison]; Acid := IntProps[ipDamageAcid]; end; end; function TInvItem.GetIntProp(ItemParam: NItemParam): Integer; begin Assert(ItemParamType[ItemParam] in IntParamTypes); Result := BaseItem.IntProps[ItemParam]; end; function TInvItem.GetModifiableProp(ItemParam: NItemParam): Integer; begin Assert(ItemParam in ModifiableItemParams, 'ItemProp error'); Result := FModifiableProps[ItemParam]; end; function TInvItem.GetPref: Integer; begin Result := FPref; end; function TInvItem.GetProtect: TItemProp; begin with Result do begin Crash := IntProps[ipProtectCrash]; Slash := IntProps[ipProtectSlash]; Pierce := IntProps[ipProtectPierce]; Ice := IntProps[ipProtectIce]; Lightning := IntProps[ipProtectLightning]; Fire := IntProps[ipProtectFire]; Poison := IntProps[ipProtectPoison]; Acid := IntProps[ipProtectAcid]; end; end; function TInvItem.GetSuff: Integer; begin Result := FSuff; end; function TInvItem.GetTextProp(ItemParam: NItemParam): string; begin Assert(ItemParamType[ItemParam] in TextParamTypes); Result := BaseItem.TextProps[ItemParam]; end; function TInvItem.IsSimpleItem: Boolean; begin Result := (Pref = NoPrefix) and (Suff = NoSuffix); end; procedure TInvItem.SetModifiableProp(ItemParam: NItemParam; const Value: Integer); begin Assert(ItemParam in ModifiableItemParams, 'ItemProp error'); FModifiableProps[ItemParam] := Value; end; procedure TInvItem.SetPref(const Value: TPrefix); begin FPref := Value; end; procedure TInvItem.SetSuff(const Value: TSuffix); begin FSuff := Value; end; class function TInvItem.CanStringBeItem(S: string): Boolean; begin Result := (Pos('|', S) > 0) or InRange(StrToIntDef(S, -1), 0, ItemMax); end; class function TInvItem.GenItem(ItemID, ItemLevel: Integer): string; function ItemGroup: Integer; begin Result := 0; case StrToInt(ItemConfig.Items[ItemID, ipType]) of // Шлемы, плащи, туники, пояса - группа аффиксов бронь (2) 1, 3, 4, 5: Result := 2; // Оружие - группа аффиксов оружие (1) 9: Result := 1; end; end; function GenAffix(Chance: Byte; AffixType: NAffixType): Integer; begin Result := 0; if (Random(101) <= Chance) then Result := Random(AffixConfig.AffixCountByType(AffixType)) + 1; if (Result > 0) then Result := AffixConfig.GenAffix(AffixType, ItemLevel, ItemGroup); end; begin Result := BuildItem(ItemID, GenAffix(11, atPrefix), GenAffix(22, atSuffix)); end; { TItemList } function TItemList.Add(Item: TInvItem): Integer; begin Result := inherited Add(Item); end; function TItemList.GetItem(Index: Integer): TInvItem; begin Result := inherited GetItem(Index) as TInvItem; end; procedure TItemList.SetItem(Index: Integer; const Value: TInvItem); begin inherited SetItem(Index, Value); end; { TMapItem } constructor TMapItem.Create(AX, AY, AIdx: Integer; AItem: TInvItem); begin x := AX; Y := AY; Idx := AIdx; Item := AItem; end; destructor TMapItem.Destroy; begin // FreeAndNil(FItem); inherited; end; procedure TMapItem.SetIdx(const Value: Integer); begin FIdx := Value; end; procedure TMapItem.SetItem(const Value: TInvItem); begin FItem := Value; end; procedure TMapItem.SetX(const Value: Integer); begin FX := Value; end; procedure TMapItem.SetY(const Value: Integer); begin FY := Value; end; { TMapItemList } function TMapItemList.Add(Item: TMapItem): Integer; begin Result := inherited Add(Item); end; function TMapItemList.GetItem(Index: Integer): TMapItem; begin Result := inherited GetItem(Index) as TMapItem; end; procedure TMapItemList.SetItem(Index: Integer; const Value: TMapItem); begin inherited SetItem(Index, Value); end; { TItemStringList } function TItemStringList.Add(S: string): Integer; var Item: TInvItem; begin if Assigned(TempAdding) then Item := TempAdding else if TInvItem.CanStringBeItem(S) then Item := TInvItem.Create(S) else begin Item := nil; S := ''; end; // store item with a string, allows bind sorted strings with items Result := inherited AddObject(S, Item); end; function TItemStringList.Add(Item: TInvItem): Integer; begin if Assigned(Item) then TempAdding := Item; Result := Add(''); TempAdding := nil; end; procedure TItemStringList.Append(Item: TInvItem); begin Add(Item); end; procedure TItemStringList.Append(S: string); begin Add(S); end; procedure TItemStringList.Clear; begin inherited Clear; SlotCount := SlotCount; // clears and refills list if needed end; function TItemStringList.ClearItem(Index: Integer): Boolean; begin // if no item to be cleared - false Result := not IsEmptyItem(Index); if not Result then Exit; InvItems[Index] := nil; Strings[Index] := ''; end; constructor TItemStringList.Create; begin inherited Create; end; procedure TItemStringList.Delete(Index: Integer); begin inherited Delete(Index); end; destructor TItemStringList.Destroy; begin inherited; end; function TItemStringList.FindItem(BaseId: Integer; SearchFrom: Integer = 0): Integer; var I: Integer; S: string; begin Result := -1; if (BaseId <= 0) or (BaseId > ItemConfig.Wrapper.MaxID) then Exit; for I := SearchFrom to Count - 1 do if not IsEmptyItem(I) and (InvItems[I].BaseItemID = BaseId) then begin Result := I; Break; end; end; function TItemStringList.Get(Index: Integer): string; begin Result := inherited Get(Index); end; function TItemStringList.GetInvItems(Index: Integer): TInvItem; begin Result := Objects[Index] as TInvItem; end; function TItemStringList.IsEmptyItem(Index: Integer): Boolean; begin Result := Ammunition.IsEmptyItem(Strings[Index]); end; procedure TItemStringList.Put(Index: Integer; const Value: string); begin if TInvItem.CanStringBeItem(Value) then begin InvItems[Index] := TInvItem.Create(Value); inherited Put(Index, Value); end else begin InvItems[Index] := nil; inherited Put(Index, ''); end; end; procedure TItemStringList.SetInvItems(Index: Integer; const Value: TInvItem); begin Objects[Index] := Value; end; procedure TItemStringList.SetSlotCount(const Value: Integer); var I: Integer; begin FSlotCount := Value; if Count <> 0 then Clear; for I := 0 to SlotCount - 1 do Add(''); end; initialization finalization if Assigned(TheItemList) then TheItemList.FreeClear; FreeAndNil(TheItemList); end.
unit ntvSplitters; {** * This file is part of the "Mini Library" * * @url http://www.sourceforge.net/projects/minilib * @license modifiedLGPL (modified of http://www.gnu.org/licenses/lgpl.html) * See the file COPYING.MLGPL, included in this distribution, * @author Zaher Dirkey * @ported ported from Lazarus component TSplitter in ExtCtrls *} {$mode objfpc}{$H+} {$define USE_NTV_THEME} interface uses SysUtils, Classes, Graphics, Controls, Variants, LCLIntf, LCLType, IntfGraphics, FPimage, GraphType, {$ifdef USE_NTV_THEME} ntvThemes, {$endif USE_NTV_THEME} Types; type { TntvCustomSplitter } TntvResizeStyle = ( nrsLine, // draw a line, don't update splitter position during moving nrsUpdate, // draw nothing, update splitter position during moving nrsNone // draw nothing and don't update splitter position during moving ); TCanOffsetEvent = procedure(Sender: TObject; var NewOffset: Integer; var Accept: Boolean) of object; TCanResizeEvent = procedure(Sender: TObject; var NewSize: Integer; var Accept: Boolean) of object; TntvSplitterStyle = (spsSpace, spsLoweredLine, spsRaisedLine); TntvCustomSplitter = class(TGraphicControl) private FAutoSnap: Boolean; FMouseInControl: Boolean; FOnCanOffset: TCanOffsetEvent; FOnCanResize: TCanResizeEvent; FOnMoved: TNotifyEvent; FResizeAnchor: TAnchorKind; FResizeStyle: TntvResizeStyle; FSplitDragging: Boolean; FSplitterPoint: TPoint; // in screen coordinates FSplitterStartPoint: TPoint; // in screen coordinates FResizeControl: TControl; FSplitterWindow: HWND; FStyle: TntvSplitterStyle; procedure SetResizeControl(AValue: TControl); procedure SetStyle(AValue: TntvSplitterStyle); protected procedure OnControlChanged(Sender: TObject); procedure AnchorSideChanged(TheAnchorSide: TAnchorSide); override; procedure AlignTo(AControl: TControl); procedure BoundsChanged; override; function AdaptAnchors(const aAnchors: TAnchors): TAnchors; function CheckNewSize(var NewSize: Integer): Boolean; virtual; function CheckOffset(var NewOffset: Integer): Boolean; virtual; procedure MouseEnter; override; procedure MouseLeave; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure Paint; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure SetAlign(Value: TAlign); override; procedure SetAnchors(const AValue: TAnchors); override; procedure SetResizeAnchor(const AValue: TAnchorKind); virtual; procedure StartSplitterMove(const MousePos: TPoint); procedure StopSplitterMove(const MousePos: TPoint); procedure UpdateCursor; public constructor Create(TheOwner: TComponent); override; procedure Loaded; override; procedure MoveSplitter(Offset: Integer); public property AutoSnap: Boolean read FAutoSnap write FAutoSnap default False; property Style: TntvSplitterStyle read FStyle write SetStyle default spsLoweredLine; property ResizeAnchor: TAnchorKind read FResizeAnchor write SetResizeAnchor default akLeft; property ResizeStyle: TntvResizeStyle read FResizeStyle write FResizeStyle default nrsUpdate; property ResizeControl: TControl read FResizeControl write SetResizeControl; property OnCanOffset: TCanOffsetEvent read FOnCanOffset write FOnCanOffset; property OnCanResize: TCanResizeEvent read FOnCanResize write FOnCanResize; property OnMoved: TNotifyEvent read FOnMoved write FOnMoved; end; TntvSplitter = class(TntvCustomSplitter) published property Anchors; property AutoSnap; property Color; property Constraints; property Height; property OnCanOffset; property OnCanResize; property OnChangeBounds; property OnMoved; property ParentColor; property ParentShowHint; property PopupMenu; property ResizeStyle; property ResizeControl; property ShowHint; property Visible; property Width; end; implementation uses Math; { TntvCustomSplitter } procedure TntvCustomSplitter.MoveSplitter(Offset: Integer); var aMinSize: Integer; aMaxSize: Integer; function GetParentClientSize: Integer; begin case ResizeAnchor of akLeft, akRight: Result := Parent.ClientWidth; akTop, akBottom: Result := Parent.ClientHeight; end; end; function GetControlMinPos(Control: TControl): Integer; begin case ResizeAnchor of akLeft, akRight: Result := Control.Left; akTop, akBottom: Result := Control.Top; end; end; function GetControlSize(Control: TControl): Integer; begin Result := 0; if Assigned(Control) then case ResizeAnchor of akLeft, akRight: Result := Control.Width; akTop, akBottom: Result := Control.Height; end; end; function GetControlConstraintsMinSize(Control: TControl): Integer; begin case ResizeAnchor of akLeft, akRight: Result := Control.Constraints.EffectiveMinWidth; akTop, akBottom: Result := Control.Constraints.EffectiveMinHeight; end; end; function GetControlConstraintsMaxSize(Control: TControl): Integer; begin case ResizeAnchor of akLeft, akRight: Result := Control.Constraints.EffectiveMaxWidth; akTop, akBottom: Result := Control.Constraints.EffectiveMaxHeight; end; end; procedure SetAlignControlSize(NewSize: Integer); var NewBounds: TRect; begin NewBounds := ResizeControl.BoundsRect; case ResizeAnchor of akLeft: NewBounds.Right := NewBounds.Left + NewSize; akRight: NewBounds.Left := NewBounds.Right - NewSize; akTop: NewBounds.Bottom := NewBounds.Top + NewSize; akBottom: NewBounds.Top := NewBounds.Bottom - NewSize; end; ResizeControl.BoundsRect := NewBounds; end; procedure DrawAlignControlSize(NewSize: Integer); var NewRect: TRect; OldSize: Integer; begin // get the splitter position NewRect := BoundsRect; NewRect.TopLeft := Parent.ClientToScreen(NewRect.TopLeft); NewRect.BottomRight := Parent.ClientToScreen(NewRect.BottomRight); // offset it accordinly OldSize := GetControlSize(ResizeControl); case ResizeAnchor of akLeft: OffsetRect(NewRect, NewSize - OldSize, 0); akRight: OffsetRect(NewRect, OldSize - NewSize, 0); akTop: OffsetRect(NewRect, 0, NewSize - OldSize); akBottom: OffsetRect(NewRect, 0, OldSize - NewSize); end; SetRubberBandRect(FSplitterWindow, NewRect); end; function CalcNewSize(MinSize, EndSize, Offset: Integer): Integer; var NewSize: Integer; begin NewSize := GetControlSize(ResizeControl); case ResizeAnchor of akLeft, akTop: Inc(NewSize, Offset); akRight, akBottom: Dec(NewSize, Offset); end; if NewSize > EndSize then NewSize := EndSize; if NewSize < MinSize then NewSize := MinSize; if AutoSnap and (NewSize < MinSize) then NewSize := MinSize; Result := NewSize; end; var NewSize: Integer; begin if Offset = 0 then Exit; if not Assigned(ResizeControl) then Exit; // calculate minimum size if not AutoSnap then aMinSize := GetControlConstraintsMinSize(ResizeControl) else aMinSize := 1; if aMinSize > 1 then Dec(aMinSize); // calculate maximum size case ResizeAnchor of akLeft, akTop: begin aMaxSize := GetControlSize(ResizeControl) - GetControlMinPos(ResizeControl) + GetParentClientSize - GetControlSize(ResizeControl); end; akRight, akBottom: begin aMaxSize := GetControlSize(ResizeControl) + GetControlMinPos(ResizeControl); end; end; aMaxSize := Max(GetControlConstraintsMaxSize(ResizeControl), aMaxSize); NewSize := CalcNewSize(aMinSize, aMaxSize, Offset); // OnCanResize event if CheckOffset(Offset) and CheckNewSize(NewSize) then if not FSplitDragging or (ResizeStyle = nrsUpdate) then SetAlignControlSize(NewSize) else DrawAlignControlSize(NewSize); end; procedure TntvCustomSplitter.SetResizeControl(AValue: TControl); begin if FResizeControl = AValue then Exit; if FResizeControl <> nil then FResizeControl.RemoveFreeNotification(Self); FResizeControl := AValue; if FResizeControl <> nil then FResizeControl.FreeNotification(Self); AlignTo(FResizeControl); end; procedure TntvCustomSplitter.SetStyle(AValue: TntvSplitterStyle); begin if FStyle = AValue then Exit; FStyle := AValue; end; procedure TntvCustomSplitter.OnControlChanged(Sender: TObject); begin if Visible and (FResizeControl <> nil) then begin case FResizeControl.Align of alLeft: Left := FResizeControl.Left + FResizeControl.Width + 1; alRight: Left := FResizeControl.Left - Width - 1; alTop: Top := FResizeControl.Top + FResizeControl.Height + 1; alBottom: Top := FResizeControl.Top - Height - 1; end; end; end; procedure TntvCustomSplitter.AnchorSideChanged(TheAnchorSide: TAnchorSide); begin inherited; end; procedure TntvCustomSplitter.AlignTo(AControl: TControl); begin if AControl <> nil then begin Align := AControl.Align; // FResizeControl.AddHandlerOnChangeBounds(@OnControlChanged); // FResizeControl.AddHandlerOnVisibleChanged(@OnControlChanged); end; end; procedure TntvCustomSplitter.BoundsChanged; begin inherited BoundsChanged; end; procedure TntvCustomSplitter.SetResizeAnchor(const AValue: TAnchorKind); begin if FResizeAnchor = AValue then Exit; FResizeAnchor := AValue; if not (csLoading in ComponentState) then begin UpdateCursor; Invalidate; end; end; procedure TntvCustomSplitter.StartSplitterMove(const MousePos: TPoint); var NewRect: TRect; Pattern: HBrush; begin if FSplitDragging then Exit; FSplitDragging := True; FSplitterPoint := MousePos; FSplitterStartPoint := Point(Left, Top); if ResizeStyle in [nrsLine] then begin NewRect := BoundsRect; NewRect.TopLeft := Parent.ClientToScreen(NewRect.TopLeft); NewRect.BottomRight := Parent.ClientToScreen(NewRect.BottomRight); Pattern := GetStockObject(BLACK_BRUSH); FSplitterWindow := CreateRubberband(NewRect, Pattern); end; end; procedure TntvCustomSplitter.StopSplitterMove(const MousePos: TPoint); var Offset: Integer; begin if FSplitDragging then begin case ResizeAnchor of akLeft, akRight: Offset := (MousePos.X - FSplitterPoint.X) - (Self.Left - FSplitterStartPoint.X); akTop, akBottom: Offset := (MousePos.Y - FSplitterPoint.Y) - (Self.Top - FSplitterStartPoint.Y); end; FSplitDragging := False; if Offset <> 0 then MoveSplitter(Offset); if Assigned(OnMoved) then OnMoved(Self); if ResizeStyle in [nrsLine] then DestroyRubberBand(FSplitterWindow); end; end; procedure TntvCustomSplitter.UpdateCursor; begin if ResizeAnchor in [akLeft, akRight] then Cursor := crHSplit else Cursor := crVSplit; end; procedure TntvCustomSplitter.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var MousePos: TPoint; begin inherited; // While resizing X, Y are not valid. Use absolute mouse position. if Button = mbLeft then begin MousePos := Point(X, Y); GetCursorPos(MousePos); StartSplitterMove(MousePos); end; end; procedure TntvCustomSplitter.MouseMove(Shift: TShiftState; X, Y: Integer); var Offset: Integer; MousePos: TPoint; begin inherited; if (ssLeft in Shift) and (Parent <> nil) and (FSplitDragging) then begin MousePos := Point(X, Y); // While resizing X, Y are not valid. Use the absolute mouse position. GetCursorPos(MousePos); case ResizeAnchor of akLeft, akRight: Offset := (MousePos.X - FSplitterPoint.X) - (Self.Left - FSplitterStartPoint.X); akTop, akBottom: Offset := (MousePos.Y - FSplitterPoint.Y) - (Self.Top - FSplitterStartPoint.Y); end; if Offset <> 0 then MoveSplitter(Offset); end; end; procedure TntvCustomSplitter.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var MousePos: TPoint; begin inherited; MousePos := Point(X, Y); GetCursorPos(MousePos); StopSplitterMove(MousePos); end; procedure TntvCustomSplitter.SetAlign(Value: TAlign); begin inherited; case Value of alLeft: ResizeAnchor := akLeft; alTop: ResizeAnchor := akTop; alRight: ResizeAnchor := akRight; alBottom: ResizeAnchor := akBottom; end; end; procedure TntvCustomSplitter.SetAnchors(const AValue: TAnchors); var NewValue: TAnchors; begin NewValue := AdaptAnchors(AValue); if NewValue = Anchors then exit; inherited SetAnchors(NewValue); end; function TntvCustomSplitter.AdaptAnchors(const aAnchors: TAnchors): TAnchors; begin Result := aAnchors; case Align of alLeft: Result := Result - [akRight] + [akLeft]; alTop: Result := Result - [akBottom] + [akTop]; alRight: Result := Result + [akRight] - [akLeft]; alBottom: Result := Result + [akBottom] - [akTop]; end; end; function TntvCustomSplitter.CheckNewSize(var NewSize: Integer): Boolean; begin Result := True; if Assigned(OnCanResize) then OnCanResize(Self, NewSize, Result); end; function TntvCustomSplitter.CheckOffset(var NewOffset: Integer): Boolean; begin Result := True; if Assigned(OnCanOffset) then OnCanOffset(Self, NewOffset, Result); end; procedure TntvCustomSplitter.Paint; var C1, C2: TColor; x, y: Integer; begin inherited; Canvas.Brush.Color := Color; Canvas.FillRect(ClientRect); case Style of spsRaisedLine: begin {$ifdef USE_NTV_THEME} C1 := Theme.Separator.Foreground; C2 := Theme.Separator.Background; {$else} C1 := clBtnHiLight; C2 := clBtnShadow; {$endif} end; spsLoweredLine: begin {$ifdef USE_NTV_THEME} C1 := Theme.Separator.Foreground; C2 := Theme.Separator.Background; {$else} C1 := clBtnShadow; C2 := clBtnHiLight; {$endif} end; else begin inherited; exit; end; end; Canvas.Pen.Width := 1; with Canvas, ClientRect do case ResizeAnchor of akTop, akBottom: begin y := (Bottom - Top) div 2; Pen.Color := C1; MoveTo(Left, y); LineTo(Right - 1, y); Pen.Color := C2; MoveTo(Left, y + 1); LineTo(Right - 1, y + 1); end; akLeft, akRight: begin x := (Right - Left) div 2; Pen.Color := C1; MoveTo(x, Top); LineTo(x, Bottom - 1); Pen.Color := C2; MoveTo(x + 1, Top); LineTo(x + 1, Bottom - 1); end; end; end; procedure TntvCustomSplitter.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if Operation = opRemove then begin if AComponent = ResizeControl then ResizeControl := nil; end; end; procedure TntvCustomSplitter.MouseEnter; begin inherited; if csDesigning in ComponentState then exit; if not FMouseInControl and Enabled and (GetCapture = 0) then begin FMouseInControl := True; invalidate; end; end; procedure TntvCustomSplitter.MouseLeave; begin inherited; if csDesigning in ComponentState then exit; if FMouseInControl then begin FMouseInControl := False; invalidate; end; end; constructor TntvCustomSplitter.Create(TheOwner: TComponent); begin inherited Create(TheOwner); FResizeStyle := nrsUpdate; FAutoSnap := False; FMouseInControl := False; FResizeAnchor := akLeft; FStyle := spsLoweredLine; Width := 5; end; procedure TntvCustomSplitter.Loaded; begin inherited Loaded; UpdateCursor; end; end.
unit uPrincipal; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, uAutomato, uConstantes; type { TfrmPrincipal } TfrmPrincipal = class(TForm) btnIniciar: TButton; btnSelecionaArquivo: TButton; edtCaminhoArquivo: TEdit; Label1: TLabel; memoArquivo: TMemo; memoLog: TMemo; openDlg: TOpenDialog; pnlFundo: TPanel; procedure btnIniciarClick(Sender: TObject); procedure btnSelecionaArquivoClick(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormCreate(Sender: TObject); private const DESC_EDT_ARQ = 'Selecione o arquivo com as cadeias a serem testadas'; var FArquivo: TStringList; procedure ValidaArquivo; procedure Iniciar; public end; var frmPrincipal: TfrmPrincipal; implementation {$R *.lfm} { TfrmPrincipal } procedure TfrmPrincipal.FormCreate(Sender: TObject); begin end; procedure TfrmPrincipal.ValidaArquivo; begin if not FileExists(edtCaminhoArquivo.Text) then begin ShowMessage('Arquivo inexistente!'); Abort; end else if ExtractFileExt(edtCaminhoArquivo.Text) <> '.txt' then begin ShowMessage('O arquivo deve ter a extensão txt!'); edtCaminhoArquivo.Text := DESC_EDT_ARQ; Abort; end; end; procedure TfrmPrincipal.Iniciar; var lAutomato: TAutomato; lLinha: String; begin memoLog.Clear; lAutomato := TAutomato.Create; try if Assigned(FArquivo) then begin FArquivo.Clear; end else begin FArquivo := TStringList.Create; end; FArquivo.LoadFromFile(edtCaminhoArquivo.Text); for lLinha in FArquivo do begin memoLog.Lines.Add(lAutomato.Execute(lLinha)); end; finally lAutomato.Free;; end; end; procedure TfrmPrincipal.btnSelecionaArquivoClick(Sender: TObject); begin if openDlg.Execute then begin edtCaminhoArquivo.Text := openDlg.FileName; ValidaArquivo; memoArquivo.Lines.LoadFromFile(edtCaminhoArquivo.Text); end else begin if edtCaminhoArquivo.Text = '' then begin edtCaminhoArquivo.Text := DESC_EDT_ARQ; end; end; end; procedure TfrmPrincipal.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin if Assigned(FArquivo) then begin FArquivo.Destroy; end; CloseAction := caFree; end; procedure TfrmPrincipal.btnIniciarClick(Sender: TObject); begin if FileExists(edtCaminhoArquivo.Text) then begin Iniciar; end else begin ShowMessage('Selecione um arquivo valido!'); Exit; end; end; end.
unit FileManager; interface type TFile = class(TObject) private class var FCurrentDir: String; public function CreateTextFile(filePath: string): Boolean; procedure TextFileAppend(filePath, msg: String); function CreateAllDir(directory: String): Boolean; function GetParentDir(const Directory: String): String; function CopyFile(srcFile, desFile: String): Boolean; class property CurrentDir: String read FCurrentDir write FCurrentDir; end; implementation uses SysUtils, Windows; //-----------------------------------------------------------------+ // 텍스트 파일의 기존 내용에 새로이 추가 해 준다. // 만약 지정한 경로에 파일이 없을 경우 새로 생성 한다. // filePath: 내용을 추가 할 텍스트 파일의 경로. // msg: 추가할 내용. //-----------------------------------------------------------------+ procedure TFile.TextFileAppend(filePath, msg: String); var targetFile: TextFile; begin CreateTextFile(filePath); AssignFile(targetFile, filePath); Append(targetFile); Writeln(targetFile, msg); CloseFile(targetFile); end; //-----------------------------------------------------------------+ // 지정한 경로에 텍스트 파일을 만든다. // 만약 그 경로에 해당되는 부모 폴더가 없다면 스스로 만든다. // filePath: 텍스트 파일을 만들 경로. //-----------------------------------------------------------------+ function TFile.CreateTextFile(filePath: string): Boolean; var iFileHandlerId: Integer; begin try CreateAllDir(GetParentDir(filePath)); if FileExists(filePath) = false then begin iFileHandlerId := FileCreate(filePath); SysUtils.FileClose(iFileHandlerId); end; result := true; except result := false; end; end; //-----------------------------------------------------------------+ // 설정한 경로의 폴더를 만든다. // 만약 상위 폴더가 없다면 그것도 함께 만든다. (재귀 호출 사용) // directory: 폴더를 만들 경로./ //-----------------------------------------------------------------+ function TFile.CreateAllDir(directory: String): Boolean; var targetFile: TextFile; parentPath: String; iFileHandlerId: Integer; begin parentPath := GetParentDir(directory); try if DirectoryExists(parentPath) = false then begin CreateAllDir(parentPath); end; CreateDir(directory); result := true; except result := false; end; end; //-----------------------------------------------------------------+ // 지정한 경로를 통해 부모 폴더의 경로를 얻는다. // Directory: 부모 폴더의 경로를 얻고 싶은 전체 경로. //-----------------------------------------------------------------+ function TFile.GetParentDir(const Directory: String): String; var TempStr: String; begin TempStr := Directory; if (TempStr[Length(Result)] = '\') then begin Delete(TempStr, Length(TempStr), 1); end; Result := Copy(TempStr, 1, LastDelimiter('\', TempStr) - 1); end; function TFile.CopyFile(srcFile, desFile: String): Boolean; begin try CreateAllDir( ExtractFilePath( desFile ) ); Windows.CopyFile( PWideChar( srcFile ), PWideChar( desFile ), false); result := true; exit; except // on e: Exception // do WriteErrorMessage( e.Message ); end; result := false; end; end.
unit GetSingleGeocodingAddressUnit; interface uses SysUtils, BaseExampleUnit, DirectionPathPointUnit; type TGetSingleGeocodingAddress = class(TBaseExample) public procedure Execute(Pk: integer); end; implementation uses GeocodingAddressUnit; procedure TGetSingleGeocodingAddress.Execute(Pk: integer); var ErrorString: String; Address: TGeocodingAddress; begin Address := Route4MeManager.Geocoding.GetSingleAddress(Pk, ErrorString); try WriteLn(''); if (Address <> nil) then begin WriteLn('GetSingleGeocodingAddress executed successfully'); WriteLn(Format('StreeName: %s, Zip: %s', [Address.StreetName.Value, Address.ZipCode.Value])); end else WriteLn(Format('GetSingleGeocodingAddress error: "%s"', [ErrorString])); finally FreeAndNil(Address); end; end; end.
unit DW.SystemHelper; {*******************************************************} { } { Kastri Free } { } { DelphiWorlds Cross-Platform Library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface type TPermissionResult = record Permission: string; Granted: Boolean end; TPermissionResults = TArray<TPermissionResult>; TPermissionResultsHelper = record helper for TPermissionResults public function Add(const AValue: TPermissionResult): Integer; function AreAllGranted: Boolean; procedure Clear; function Count: Integer; function DeniedResults: TPermissionResults; end; TPermissionsResultEvent = procedure(Sender: TObject; const RequestCode: Integer; const Results: TPermissionResults) of object; TSystemHelper = class; TCustomPlatformSystemHelper = class(TObject) private FSystemHelper: TSystemHelper; protected procedure RequestPermissions(const APermissions: array of string; const ARequestCode: Integer); virtual; abstract; public constructor Create(const ASystemHelper: TSystemHelper); virtual; property SystemHelper: TSystemHelper read FSystemHelper; end; TSystemHelper = class(TObject) private FPlatformSystemHelper: TCustomPlatformSystemHelper; FOnPermissionsResult: TPermissionsResultEvent; protected procedure DoPermissionsResult(const RequestCode: Integer; const Results: TPermissionResults); public constructor Create; destructor Destroy; override; class function CheckPermissions(const APermissions: array of string): Boolean; overload; class function CheckPermissions(const APermissions: array of string; var AResults: TPermissionResults): Boolean; overload; procedure RequestPermissions(const APermissions: array of string; const ARequestCode: Integer); property OnPermissionsResult: TPermissionsResultEvent read FOnPermissionsResult write FOnPermissionsResult; end; implementation uses DW.OSLog, {$IF Defined(ANDROID)} DW.SystemHelper.Android; {$ELSE} DW.SystemHelper.Default; {$ENDIF} { TPermissionResultsHelper } function TPermissionResultsHelper.Add(const AValue: TPermissionResult): Integer; begin SetLength(Self, Count + 1); Self[Count - 1] := AValue; Result := Count - 1; end; function TPermissionResultsHelper.AreAllGranted: Boolean; var I: Integer; begin Result := True; for I := 0 to Count - 1 do begin if not Self[I].Granted then begin Result := False; Break; end; end; end; procedure TPermissionResultsHelper.Clear; begin SetLength(Self, 0); end; function TPermissionResultsHelper.Count: Integer; begin Result := Length(Self); end; function TPermissionResultsHelper.DeniedResults: TPermissionResults; var I: Integer; begin for I := 0 to Count - 1 do begin if not Self[I].Granted then Result.Add(Self[I]); end; end; { TCustomPlatformSystemHelper } constructor TCustomPlatformSystemHelper.Create(const ASystemHelper: TSystemHelper); begin inherited Create; FSystemHelper := ASystemHelper; end; { TSystemHelper } constructor TSystemHelper.Create; begin inherited; FPlatformSystemHelper := TPlatformSystemHelper.Create(Self); end; destructor TSystemHelper.Destroy; begin FPlatformSystemHelper.Free; inherited; end; class function TSystemHelper.CheckPermissions(const APermissions: array of string; var AResults: TPermissionResults): Boolean; var I: Integer; begin SetLength(AResults, Length(APermissions)); for I := 0 to AResults.Count - 1 do begin AResults[I].Permission := APermissions[I]; AResults[I].Granted := TPlatformSystemHelper.CheckPermission(AResults[I].Permission); if AResults[I].Granted then TOSLog.d('%s granted', [AResults[I].Permission]) else TOSLog.d('%s denied', [AResults[I].Permission]); end; Result := AResults.AreAllGranted; end; class function TSystemHelper.CheckPermissions(const APermissions: array of string): Boolean; var LResults: TPermissionResults; begin Result := TSystemHelper.CheckPermissions(APermissions, LResults); end; procedure TSystemHelper.DoPermissionsResult(const RequestCode: Integer; const Results: TPermissionResults); begin if Assigned(FOnPermissionsResult) then FOnPermissionsResult(Self, RequestCode, Results); end; procedure TSystemHelper.RequestPermissions(const APermissions: array of string; const ARequestCode: Integer); begin FPlatformSystemHelper.RequestPermissions(APermissions, ARequestCode); end; end.
unit MyDialogs; interface uses System.SysUtils, System.Classes, System.Types, Vcl.Dialogs; type TDialogs = class public class function YesNo(Msg: string; BtnDefault: TMsgDlgBtn = mbNo): integer; class function YesNoCancel(Msg: string; BtnDefault: TMsgDlgBtn = mbCancel): integer; end; implementation { TMyDialogs } class function TDialogs.YesNo(Msg: string; BtnDefault: TMsgDlgBtn): integer; begin Result := MessageDlg(Msg, mtWarning, mbYesNo, 0, BtnDefault); end; class function TDialogs.YesNoCancel(Msg: string; BtnDefault: TMsgDlgBtn): integer; begin Result := MessageDlg(Msg, mtConfirmation, mbYesNoCancel, 0, BtnDefault); end; end.
unit Conciliar; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, JvFormPlacement, JvAppStorage, JvAppIniStorage, DB, JvDBUltimGrid, Grids, DBGrids, JvExDBGrids, JvDBGrid, StdCtrls, ActnList, ImgList, JvNavigationPane, ComCtrls, JvComponentBase, JvDBGridExport, JvExControls, JvOutlookBar, JvExComCtrls, JvComCtrls, Provider, DBClient, DBCtrls, JvDBCheckBox, JvDBGridFooter, JvDBLookup, JvExStdCtrls, JvEdit, JvValidateEdit, Mask, JvExMask, JvToolEdit, JvBaseEdits, JvDBControls, Buttons, JvExButtons, JvBitBtn, System.Actions, Utiles, vcl.wwspeedbutton, vcl.wwdbnavigator, vcl.wwclearpanel, vcl.wwdbigrd, vcl.wwdbgrid, vcl.wwdblook, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridLevel, cxClasses, cxGridCustomView, cxGrid, cxCheckBox, cxDBLookupComboBox, cxCalc, ToolPanels; resourcestring CTEASTO = 'ASTO'; type TFConciliar = class(TForm) jvControl: TJvOutlookBar; exportar: TJvDBGridExcelExport; img: TImageList; ActionList1: TActionList; acSelBanco: TAction; acConciliar: TAction; acModificar: TAction; acResumen: TAction; acInforme: TAction; acSalir: TAction; acGrabar: TAction; ds: TDataSource; acAnular: TAction; dsConcilia: TDataSource; cdsConcilia: TClientDataSet; dsp: TDataSetProvider; cdsResumen: TClientDataSet; dsResumen: TDataSource; cdsResumenCODIGO: TStringField; cdsResumenCREDITO: TCurrencyField; cdsResumenDEBITO: TCurrencyField; cdsResumenTOTCRED: TAggregateField; cdsResumenTOTDEB: TAggregateField; cdsResumenCONCEPTO: TStringField; cdsResumenGRABA: TBooleanField; DCodigos: TDataSource; DConcilia: TDataSource; pagina: TPageControl; tbInicio: TTabSheet; Label1: TLabel; Memo1: TMemo; tbSelBanco: TTabSheet; Label2: TLabel; tbConcilia: TTabSheet; Label3: TLabel; jvConcilia: TJvDBCheckBox; tbResumen: TTabSheet; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; Label10: TLabel; Label11: TLabel; Bevel1: TBevel; Label12: TLabel; Label13: TLabel; edSalBco: TJvValidateEdit; edMarcadas: TJvValidateEdit; edSaldoAnt: TJvValidateEdit; edSaldoPosterior: TJvValidateEdit; edDiferencia: TJvValidateEdit; FecConcilia: TJvDateEdit; mObserva: TMemo; tbInformes: TTabSheet; Label4: TLabel; Label14: TLabel; griInfo: TJvDBGrid; btnInforme: TJvBitBtn; ImageList1: TImageList; tbModif: TTabSheet; JvDBGrid1: TJvDBGrid; Label15: TLabel; Label16: TLabel; bbSeleccionar: TJvBitBtn; bbEliminar: TBitBtn; JvFormStorage1: TJvFormStorage; JvAppIniFileStorage1: TJvAppIniFileStorage; lookcod: TwwDBLookupCombo; vista: TcxGridDBTableView; nivel: TcxGridLevel; GriConcilia: TcxGrid; vistaNUMERO: TcxGridDBColumn; vistaCONFIRMADO: TcxGridDBColumn; vistaCONCILIADO: TcxGridDBColumn; vistaCODBANCO: TcxGridDBColumn; vistaFECHAOPER: TcxGridDBColumn; vistaFECHACONF: TcxGridDBColumn; vistaIMPORTE: TcxGridDBColumn; vistaCODOPER: TcxGridDBColumn; vistaDETALLE: TcxGridDBColumn; vistaCHEQUE: TcxGridDBColumn; repositorio: TcxStyleRepository; fila: TcxStyle; selec: TcxStyle; vistabanco: TcxGridDBTableView; nivelbco: TcxGridLevel; griBancos: TcxGrid; vistabancoCODBAN: TcxGridDBColumn; vistabancoDENOMINA: TcxGridDBColumn; vistabancoSALDOACT: TcxGridDBColumn; vistabancoSALDOTOT: TcxGridDBColumn; vistabancoTIPOCTA: TcxGridDBColumn; vistabancoNUMCTA: TcxGridDBColumn; vistabancoSALDOCON: TcxGridDBColumn; griResumen: TcxGrid; vistaResumen: TcxGridDBTableView; lvlResumen: TcxGridLevel; vistaResumenCODIGO: TcxGridDBColumn; vistaResumenCONCEPTO: TcxGridDBColumn; vistaResumenCREDITO: TcxGridDBColumn; vistaResumenDEBITO: TcxGridDBColumn; vistaResumenGRABA: TcxGridDBColumn; cdsConciliaNUMERO: TAutoIncField; cdsConciliaCONFIRMADO: TWideStringField; cdsConciliaCONCILIADO: TWideStringField; cdsConciliaCODBANCO: TWideStringField; cdsConciliaFECHAOPER: TDateTimeField; cdsConciliaFECHACONF: TDateTimeField; cdsConciliaIMPORTE: TFloatField; cdsConciliaCODOPER: TWideStringField; cdsConciliaDETALLE: TWideStringField; cdsConciliaCODCONTA: TWideStringField; cdsConciliaOPAGO: TSmallintField; cdsConciliaASIENTO: TIntegerField; cdsConciliaNUMCTE: TWideStringField; cdsConciliaNUMCHE: TWideStringField; cdsConciliaPROVE: TWideStringField; vistaNUMCHE: TcxGridDBColumn; vistaCODCONTA: TcxGridDBColumn; vistaOPAGO: TcxGridDBColumn; vistaASIENTO: TcxGridDBColumn; vistaNUMCTE: TcxGridDBColumn; vistaPROVE: TcxGridDBColumn; cdsResumenCUENTA: TStringField; vistaResumenCUENTA: TcxGridDBColumn; dCuentas: TDataSource; procedure acSalirExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure acSelBancoExecute(Sender: TObject); procedure acModificarExecute(Sender: TObject); procedure acResumenExecute(Sender: TObject); procedure acInformeExecute(Sender: TObject); procedure acGrabarExecute(Sender: TObject); procedure acAnularExecute(Sender: TObject); procedure acConciliarExecute(Sender: TObject); procedure tbResumenEnter(Sender: TObject); procedure jvSaldoKeyPress(Sender: TObject; var Key: Char); procedure edSalBcoChange(Sender: TObject); procedure cdsResumenNewRecord(DataSet: TDataSet); procedure cdsResumenBeforePost(DataSet: TDataSet); function griResumenCheckIfBooleanField(Grid: TJvDBGrid; Field: TField; var StringForTrue, StringForFalse: string): Boolean; procedure jvLookCodExit(Sender: TObject); procedure cdsResumenAfterPost(DataSet: TDataSet); procedure edDiferenciaValueChanged(Sender: TObject); procedure cdsResumenAfterDelete(DataSet: TDataSet); procedure btnInformeClick(Sender: TObject); procedure tbInformesExit(Sender: TObject); procedure tbSelBancoHide(Sender: TObject); procedure dspBeforeUpdateRecord(Sender: TObject; SourceDS: TDataSet; DeltaDS: TCustomClientDataSet; UpdateKind: TUpdateKind; var Applied: Boolean); procedure bbSeleccionarClick(Sender: TObject); procedure bbEliminarClick(Sender: TObject); procedure dspGetTableName(Sender: TObject; DataSet: TDataSet; var TableName: WideString); procedure dspUpdateError(Sender: TObject; DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind; var Response: TResolverResponse); procedure calcredExit(Sender: TObject); procedure tbSelBancoShow(Sender: TObject); procedure cdsConciliaCONCILIADOChange(Sender: TField); procedure vistaStylesGetContentStyle(Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord; AItem: TcxCustomGridTableItem; var AStyle: TcxStyle); procedure vistabancoDblClick(Sender: TObject); procedure vistaResumenKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure vistaResumenEditKeyDown(Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem; AEdit: TcxCustomEdit; var Key: Word; Shift: TShiftState); private { Private declarations } FBanco, FCuenta: string; fConc: Boolean; FModificacion: Boolean; FNumeroConcilia: Integer; last_code,last_desc,last_cta: string; procedure activarAcciones( sino: Boolean = True ); procedure anularProceso; procedure abrirDetalle( const banco: string ); function sumarMarcadas: double; procedure calcularSaldo; function getTotal( Campo: TAggregateField ):Double; procedure insertarDetalle( operacion, numero: Integer; ajuste: boolean ); function insertarMovimBanco( cds: TClientDataset; const Banco: string; fecha: TDateTime ): integer; function insertarPendiente( cds: TClientDataset; concilia: Integer; const Banco: string; fecha: TDateTime ): integer; procedure EliminarConciliados( numero: integer; const banco: string ); procedure doElimConcilia( numero: integer ); procedure desconcilia( operacion: integer; const banco: string; importe: double ); procedure eliminarPendientes( numero: integer ); procedure eliminarConciliacion( numero: integer ); procedure cargarResumen( numero: integer ); function getNumeroAnt( const bancos: string): Integer; procedure grabar_asiento( cds: TClientDataset; Concilia: integer ); public { Public declarations } end; var FConciliar: TFConciliar; implementation uses DataMod, VerDep, Informes, selfecasto, Concilia; {$R *.dfm} procedure TFConciliar.abrirDetalle(const banco: string); begin try cdsConcilia.Active := False; cdsConcilia.Params.ParamByName('CODBAN').value := banco; cdsConcilia.Params.ParamByName('CONC').value := '1'; // diferente de... cdsConcilia.Params.ParamByName('CONCILIA').value := FNumeroConcilia; // para modificaciones finally cdsConcilia.Open; end; end; procedure TFConciliar.acAnularExecute(Sender: TObject); begin if (Messagedlg( 'Anula los datos de conciliacion actuales?', mtConfirmation, mbYesNo, 0 )=mrYes ) then anularProceso; end; procedure TFConciliar.acConciliarExecute(Sender: TObject); begin pagina.ActivePage := tbConcilia; if Not(FConc) then begin abrirDetalle( FBanco ); FConc := true; end; end; procedure TFConciliar.acGrabarExecute(Sender: TObject); var FOperacion, FConcilia: Integer; FCuenta, mensaje: string; begin if cdsResumen.State in [dsEdit,dsInsert] then raise Exception.Create( 'Por favor, primero grabe o anule los cambios en la hoja resumen' ); if ( edDiferencia.value <> 0 ) then mensaje := 'Atencion!! Confirma conciliacion de datos ' + #13 + ' Saldos no coinciden, Diferencia: ' + format('%12.2f', [edDiferencia.asfloat ]) else mensaje := 'Confirma conciliacion de datos?'; if ( messagedlg( mensaje, mtConfirmation, mbYesNo, 0 ) = mrYes ) then with dm do try selfecastoDlg := TSelFecAstoDlg.create( self ); selfecastoDlg.fecha.date := date; if not ADO.InTransaction then ADO.BeginTrans; { if FModificacion then begin doElimConcilia( Dm.selConciliaNUMERO.value ); eliminarPendientes( Dm.selConciliaNUMERO.value ); eliminarConciliacion( Dm.selConciliaNUMERO.value ); end; } insConcilia.Parameters.ParamByName( 'banco' ).value := FBanco; insConcilia.Parameters.ParamByName( 'fecha' ).value := FecConcilia.Date; insConcilia.Parameters.ParamByName( 'saldoant' ).value := edSaldoAnt.Value; insConcilia.Parameters.ParamByName( 'saldoact' ).value := edSaldoPosterior.Value; // no documente y no recuerdo para que la diferencia entre saldoact y saldofin insConcilia.Parameters.ParamByName( 'saldofin' ).value := edSaldoPosterior.Value; insConcilia.Parameters.ParamByName( 'saldobanco' ).value := edSalBco.Value; insConcilia.Parameters.ParamByName( 'observa' ).value := mObserva.text; InsConcilia.Execute; FConcilia := getid('CONCILIA'); cdsConcilia.First; while Not cdsConcilia.eof do begin if cdsConciliaCONCILIADO.value = '1' then begin if cdsConciliaCONFIRMADO.Value <> '1' then begin cdsConcilia.Edit; cdsConciliaCONFIRMADO.value := '1'; if ( cdsConciliaCODOPER.value = 'CHE') then begin FCuenta := getcuentaBanco(cdsConciliaCODBANCO.value); if (FCuenta <> cdsConciliaCODBANCO.Value ) then begin selFecAstoDlg.mdatos.lines.clear; selFecAstoDlg.mdatos.lines.add( 'Cheque confirmado: ' + cdsConciliaCODBANCO.value + ' Cheque N.' + cdsConciliaNUMCHE.value + ' = ' + format( '%12.2f', [cdsConciliaIMPORTE.value] ) + ' - ' + cdsConciliaDETALLE.value ); selFecAstoDlg.showmodal; if (selFecAstoDlg.modalresult = mrOK) then begin dm.grabarAsientoConfirma( selfecastodlg.fecha.date, Abs(cdsConciliaIMPORTE.value), cdsConciliaCODBANCO.value, FCuenta, copy( 'Concilia:' + IntToStr(FConcilia) + ' Ch.' + cdsConciliaNUMCHE.value + '-Bco.' + cdsConciliaCODBANCO.value + '- ' + cdsConciliaDETALLE.value,1,50)); end else Showmessage('No se pudo debitar cheque. Por favor, hagalo manualmente: ' + #13 + cdsConciliaCODBANCO.value + ' ' + cdsConciliaNUMCHE.value + ' de ' + cdsConciliaCODBANCO.value + ' ' + format( '%12.2f', [cdsConciliaIMPORTE.value])); end; end; cdsConcilia.Post; end; insertarDetalle( FConcilia, cdsConciliaNUMERO.value, false ); end; cdsConcilia.Next; end; cdsConcilia.ApplyUpdates(-1); cdsResumen.First; while not cdsResumen.eof do begin if cdsResumenGRABA.value then begin FOperacion := insertarMovimBanco(cdsResumen, FBanco, FecConcilia.date ); insertarDetalle( FConcilia, FOperacion, true ); // si graba entonces hacer un asiento contable... end else insertarPendiente(cdsResumen, FConcilia, FBanco, FecConcilia.date ); cdsResumen.Next; end; grabar_asiento( cdsResumen, FConcilia ); ADO.CommitTrans; ShowMessage('Se han grabado los cambios' ); selfecastoDlg.free; anularProceso; acInformeExecute(self); except on e:exception do begin ShowMessage('Error al grabar operacion: ' + #13 + e.Message ); ADO.RollbackTrans; end; end; end; procedure TFConciliar.acInformeExecute(Sender: TObject); begin dm.selConcilia.Close; pagina.ActivePage := tbInformes; dm.selConcilia.Open; end; procedure TFConciliar.acModificarExecute(Sender: TObject); begin pagina.ActivePage := tbModif; dm.selConcilia.Open; end; procedure TFConciliar.acResumenExecute(Sender: TObject); begin pagina.ActivePage := tbResumen; if Not(FConc) then begin abrirDetalle( FBanco ); FConc := true; end; end; procedure TFConciliar.acSalirExecute(Sender: TObject); begin Close; end; procedure TFConciliar.acSelBancoExecute(Sender: TObject); begin pagina.ActivePage := tbSelBanco; activarAcciones; end; procedure TFConciliar.activarAcciones( sino: boolean = true ); begin acConciliar.Enabled := sino; acResumen.Enabled := sino; acGrabar.Enabled := (Pagina.activePage = tbResumen); acAnular.Enabled := sino; acSelBanco.enabled := not sino; end; procedure TFConciliar.anularProceso; begin edSalBco.Value := 0; FModificacion := False; FNumeroConcilia := -1; activarAcciones( false ); FecConcilia.Date := Now; cdsResumen.EmptyDataSet; cdsConcilia.Close; FBanco := ''; FCuenta := ''; Pagina.ActivePage := tbInicio; FConc := False; end; procedure TFConciliar.bbEliminarClick(Sender: TObject); begin if (MessageDlg( 'Elimina conciliacion seleccionada', mtWarning, mbYesNo, 0 )= mrYes) then begin Dm.Ado.BeginTrans; try EliminarConciliados( Dm.selConciliaNUMERO.value, Dm.selConciliaBANCO.value ); // elimina conciliados y corrige saldo eliminarPendientes( Dm.selConciliaNUMERO.value ); eliminarConciliacion( Dm.selConciliaNUMERO.value ); Dm.ADO.CommitTrans; Dm.selConcilia.Close; Dm.selConcilia.open; ShowMessage('Conciliacion ha sido eliminada' ); except on e:Exception do begin Dm.ADO.RollbackTrans; ShowMessage( 'Error al eliminar conciliacion' + #13 + e.Message ); end; end; end; end; procedure TFConciliar.bbSeleccionarClick(Sender: TObject); begin raise exception.Create('Modificacion no es posible. Elimine y genere nueva conciliacion'); FModificacion := True; FNumeroConcilia := Dm.selConciliaNUMERO.Value; FBanco := Dm.selConciliaBANCO.Value; FCuenta := Dm.selconciliaCUENTA_CONTABLE.value; dm.Bancos.Locate( 'CODBAN', FBanco, [loCaseInsensitive]); cargarResumen( FNumeroConcilia ); activarAcciones( true ); acSelBanco.enabled := false; // no permitir seleccionar nuevo banco en modificacion fConc := False; // para forzar relectura de archivo acConciliarExecute(Sender); // comenzar nueva conciliacion end; procedure TFConciliar.btnInformeClick(Sender: TObject); var fecha: TDateTime; begin try Dm.DetConcilia.Close; Dm.selPendiente.Close; dm.selMovimPen.Close; Dm.DetConcilia.Parameters.ParamByName('CONCILIA').value := Dm.selConciliaNUMERO.Value; Dm.selPendiente.Parameters.ParamByName('CONCILIA').value := Dm.selConciliaNUMERO.Value; Dm.selMovimPen.Parameters.ParamByName('COD').value := Dm.selConciliaBANCO.Value; fecha := Dm.selConciliaFECHA.Value; Dm.selMovimPen.Parameters.ParamByName('FEC').value := fecha; dm.selMovimPen.Open; //ShowMessage(IntToStr(dm.selMovimPen.RecordCount)); Dm.selMovimPen.Parameters.ParamByName('COD').value := Dm.selConciliaNUMERO.Value; VerInformeUno( 'conciliacion.rtm', Dm.selConcilia, Dm.DetConcilia, Dm.selPendiente, Dm.selMovimPen ); finally Dm.DetConcilia.Active := False; Dm.selPendiente.Active := False; Dm.selMovimPen.Active := False; end; end; procedure TFConciliar.calcredExit(Sender: TObject); begin ActiveControl := griResumen; // griResumen.SelectedIndex := 1; end; procedure TFConciliar.calcularSaldo; var totdebe, tothaber: double; begin try totdebe := getTotal( cdsResumenTOTDEB ); tothaber := getTotal( cdsResumenTOTCRED ); edSaldoPosterior.value := edMarcadas.Value + edSaldoAnt.Value + tothaber - totdebe; edDiferencia.value := edSalBco.Value - edSaldoPosterior.value; except ShowMessage('Error al recalcular saldos' ); end; end; procedure TFConciliar.cargarResumen(numero: integer); begin Dm.selPendiente.Parameters.ParamByName('CONCILIA').value := numero; Dm.selPendiente.open; while not Dm.selPendiente.eof do begin cdsResumen.Append; cdsResumenCODIGO.value := dm.selPendienteCODIGO.Value; if dm.selPendienteIMPORTE.Value>0 then cdsResumenCREDITO.value := dm.selPendienteIMPORTE.Value else cdsResumenDEBITO.value := dm.selPendienteIMPORTE.Value; cdsResumenCONCEPTO.value := dm.selPendienteDETALLE.Value; cdsResumenGRABA.Value := False; Dm.selPendiente.Next; end; Dm.selPendiente.Close; end; procedure TFConciliar.cdsConciliaCONCILIADOChange(Sender: TField); begin vista.Controller.FocusedRecord.Invalidate(); end; procedure TFConciliar.cdsResumenAfterDelete(DataSet: TDataSet); begin calcularSaldo; end; procedure TFConciliar.cdsResumenAfterPost(DataSet: TDataSet); begin calcularSaldo; last_code := cdsResumenCODIGO.Value; last_desc := cdsResumenCONCEPTO.Value; last_cta := cdsResumenCUENTA.Value; end; procedure TFConciliar.cdsResumenBeforePost(DataSet: TDataSet); begin if ( cdsResumenCREDITO.value = 0 ) and ( cdsResumenDEBITO.Value = 0 ) or ( cdsResumenCODIGO.value = '' ) or ( cdsResumenCONCEPTO.value = '' ) or ( cdsResumenCUENTA.value = '' ) then raise exception.Create( 'Por favor, complete codigo, concepto, importe debito o credito y cuenta' ); if ( cdsResumenCREDITO.value = null ) then cdsResumenCREDITO.value := 0; if ( cdsResumenDEBITO.value = null ) then cdsResumenDEBITO.value := 0; end; procedure TFConciliar.cdsResumenNewRecord(DataSet: TDataSet); begin cdsResumenCREDITO.value := 0; cdsResumenDEBITO.value := 0; cdsResumenGRABA.value := True; cdsResumenCODIGO.Value := last_code; cdsResumenCONCEPTO.Value := last_desc; cdsResumenCUENTA.Value := last_cta; end; procedure TFConciliar.desconcilia(operacion: integer; const banco: string; importe: double ); begin Dm.anulaConcilia.parameters.paramByName( 'NUMERO' ).value := operacion; Dm.anulaConcilia.Execute; Dm.ActSdoCon.Parameters.ParamByName('CODBAN').value := banco; Dm.ActSdoCon.Parameters.ParamByName('IMPORTE').value := importe; Dm.ActSdoCon.Execute; end; procedure TFConciliar.doElimConcilia(numero: integer); begin dm.elimDetConcilia.Parameters.ParamByName('NUMERO').value := numero; dm.elimDetConcilia.Execute; end; procedure TFConciliar.dspBeforeUpdateRecord(Sender: TObject; SourceDS: TDataSet; DeltaDS: TCustomClientDataSet; UpdateKind: TUpdateKind; var Applied: Boolean); begin if (DeltaDs.FieldByName( 'CONFIRMADO').OldValue <> DeltaDs.FieldByName( 'CONFIRMADO').Value) and (DeltaDs.FieldByName( 'CONFIRMADO').value = '1' ) then begin Dm.ActSdoBan.Parameters.ParamByName( 'BANCO' ).value := DeltaDs.FieldByName( 'CODBANCO').OldValue; Dm.ActSdoBan.Parameters.ParamByName( 'IMPORTE' ).value := DeltaDs.FieldByName( 'IMPORTE').OldValue; Dm.ActSdoBan.Execute; end; if (DeltaDs.FieldByName( 'CONCILIADO').OldValue <> DeltaDs.FieldByName( 'CONCILIADO').Value) and (DeltaDs.FieldByName( 'CONCILIADO').value = '1' ) then begin Dm.ActSdoCon.Parameters.ParamByName( 'CODBAN' ).value := DeltaDs.FieldByName( 'CODBANCO').OldValue; Dm.ActSdoCon.Parameters.ParamByName( 'IMPORTE' ).value := DeltaDs.FieldByName( 'IMPORTE').OldValue; Dm.ActSdoCon.Execute; end; end; procedure TFConciliar.dspGetTableName(Sender: TObject; DataSet: TDataSet; var TableName: WideString); begin TableName := 'MovBanco'; end; procedure TFConciliar.dspUpdateError(Sender: TObject; DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind; var Response: TResolverResponse); begin ShowMessage( E.Message ); end; procedure TFConciliar.edDiferenciaValueChanged(Sender: TObject); begin if edDiferencia.value >= 0 then edDiferencia.font.Color := clBlack else edDiferencia.font.Color := clRed; end; procedure TFConciliar.edSalBcoChange(Sender: TObject); begin calcularSaldo; end; procedure TFConciliar.eliminarConciliacion(numero: integer); begin dm.elimConcilia.Parameters.ParamByName('NUMERO').value := numero; dm.elimConcilia.Execute; end; procedure TFConciliar.EliminarConciliados(numero: integer; const banco: string ); begin dm.DetConcilia.Close; dm.DetConcilia.Parameters.ParamByName('CONCILIA').value := numero; dm.DetConcilia.Open; while not dm.DetConcilia.eof do begin desconcilia( dm.DetConciliaOPERACION.value, banco, dm.DetConciliaIMPORTE.value*-1 ); dm.DetConcilia.next; end; doElimConcilia( numero ); dm.DetConcilia.close; end; procedure TFConciliar.eliminarPendientes(numero: integer); begin dm.elimPendiente.Parameters.ParamByName('NUMERO').value := numero; dm.elimPendiente.Execute; end; procedure TFConciliar.FormClose(Sender: TObject; var Action: TCloseAction); begin Dm.Bancos.close; Dm.Codigos.close; dm.selConcilia.Close; dm.getCuentas.close; end; procedure TFConciliar.FormCreate(Sender: TObject); begin Dm.Bancos.filtered := true; Dm.Bancos.Open; Dm.Codigos.Open; dm.getCuentas.open; cdsResumen.CreateDataSet; FecConcilia.Date := Now; FNumeroConcilia := -1; pagina.ActivePage := tbInicio; end; function TFConciliar.getNumeroAnt(const bancos: string): Integer; begin try Dm.getNumpendiente.parameters.parambyName('BANCO').value := bancos; Dm.getNumpendiente.Open; if not (Dm.getNumpendiente.IsEmpty) then result := Dm.getNumpendienteNUMERO.value else result := -1; finally Dm.getNumpendiente.close; end; end; function TFConciliar.getTotal(Campo: TAggregateField): Double; begin if ( Campo.value = null ) then result := 0 else result := campo.value; end; procedure TFConciliar.grabar_asiento(cds: TClientDataset; Concilia: integer); var FTotal, valor: double; FAsiento, FNumero, x: integer; begin with Dm do try TDatos.Open; ActCod.Parameters.ParamByName( 'CODIGO' ).value := CTEASTO; ActCod.Execute; // leo ultimo numero actualizado SelCod.Parameters.ParamByName( 'CODIGO' ).value := CTEASTO; SelCod.Open; FNumero := SelCodULTINUM.value; SelCod.Close; // Tomo siguiente numero de asiento QUltinum.open; if not ( QUltinum.Locate( 'CODIGO', 'MAESBAS', [ ] )) then raise exception.create( 'Codigo maestro no encontrado' ); QUltinum.edit; QUltinumNUMERO.value := QUltinumNUMERO.value + 1; QUltinum.post; FAsiento := QUltinumNUMERO.value; QUltiNum.close; SpMaesbas.Parameters.ParamByName( 'CODIGO' ).value := 'ASTO'; SpMaesbas.Parameters.ParamByName( 'FECHA' ).value := FecConcilia.Date; SpMaesbas.Parameters.ParamByName( 'DETALLE' ).value := 'Conciliacion bancaria Nš ' + inttostr(concilia); SpMaesbas.Parameters.ParamByName( 'OPERADOR' ).value := 'BCO'; SpMaesbas.Parameters.ParamByName( 'FECHAOP' ).value := date; SpMaesbas.Parameters.ParamByName( 'COEFICIENTE' ).value := 1; SpMaesbas.Parameters.ParamByName( 'NUMERO' ).value := FNumero; SpMaesbas.Parameters.ParamByName( 'ASIENTO' ).value := FAsiento; SpMaesbas.Execute; FTotal := 0; cds.First; while not cds.eof do begin SpMaestro.Parameters.ParamByName( 'ASIENTO' ).value := FAsiento; SpMaestro.Parameters.ParamByName( 'FECHA' ).value := FecConcilia.Date;; SpMaestro.Parameters.ParamByName( 'LEYENDA' ).value := cds.fieldbyName( 'CONCEPTO').Value; SpMaestro.Parameters.ParamByName( 'SUBCOD' ).value := ' '; SpMaestro.Parameters.ParamByName( 'CUENTA' ).value := cds.FieldByName('CUENTA').Value; valor := cds.FieldByName('DEBITO').Value - cds.FieldByName('CREDITO').Value; FTotal := FTotal + valor; SpMaestro.Parameters.ParamByName( 'IMPORTE' ).value := valor; SpMaestro.Parameters.ParamByName( 'SALDO' ).value := valor; SpMaestro.Execute; spupdSdoCta.Parameters.ParamByName( 'IMPORTE' ).value := valor; spupdSdoCta.Parameters.ParamByName( 'CUENTA' ).value := cds.FieldByName('CUENTA').Value; spupdSdoCta.Execute; SpMaestro.Parameters.ParamByName( 'CUENTA' ).value := FBanco; SpMaestro.Parameters.ParamByName( 'IMPORTE' ).value := round( valor*-1*100) / 100; SpMaestro.Parameters.ParamByName( 'SALDO' ).value := round( valor*-1*100) / 100; SpMaestro.Execute; spupdSdoCta.Parameters.ParamByName( 'IMPORTE' ).value := round( valor*-1*100) / 100; spupdSdoCta.Parameters.ParamByName( 'CUENTA' ).value := FBanco; spupdSdoCta.Execute; cds.Next; end; finally TDatos.Close; end; end; function TFConciliar.griResumenCheckIfBooleanField(Grid: TJvDBGrid; Field: TField; var StringForTrue, StringForFalse: string): Boolean; begin if Field.FieldName = 'GRABA' then result := True else result := False; end; procedure TFConciliar.insertarDetalle(operacion, numero: Integer; ajuste: boolean); begin with dm do begin InsdetConcilia.parameters.paramByName( 'NUMERO' ).value := Operacion; InsdetConcilia.parameters.paramByName( 'OPERACION' ).value := numero; InsdetConcilia.parameters.paramByName( 'ESAJUSTE' ).value := ajuste; insdetConcilia.execute; end; end; procedure TFConciliar.jvLookCodExit(Sender: TObject); begin ActiveControl := griResumen; // griResumen.SelectedIndex := 1; end; procedure TFConciliar.jvSaldoKeyPress(Sender: TObject; var Key: Char); begin if ( key in [',', '.'] ) then key := DecimalSeparator; end; function TFConciliar.sumarMarcadas: double; begin try if not cdsConcilia.active then exit; cdsConcilia.DisableControls; result := 0; cdsConcilia.First; while not cdsConcilia.Eof do begin if cdsConciliaCONCILIADO.Value = '1' then result := result + cdsConciliaIMPORTE.Value; cdsConcilia.Next; end; finally cdsConcilia.EnableControls; end; end; procedure TFConciliar.tbInformesExit(Sender: TObject); begin dm.selConcilia.close; end; procedure TFConciliar.tbResumenEnter(Sender: TObject); begin edMarcadas.value := sumarMarcadas; edSaldoAnt.Value := Dm.BancosSALDOCON.Value; calcularSaldo; acGrabar.Enabled := True; // if vistaResumen.DataController.RecordCount = 0 then // VistaResumen.DataController.AppendRecord; end; procedure TFConciliar.tbSelBancoHide(Sender: TObject); begin FBanco := Dm.BancosCODBAN.Value; cargarResumen( getNumeroAnt( FBanco )); end; procedure TFConciliar.tbSelBancoShow(Sender: TObject); begin if Dm.Bancos.active then Dm.Bancos.Close; Dm.Bancos.Open; end; procedure TFConciliar.vistabancoDblClick(Sender: TObject); begin // FBanco := Dm.BancosCODBAN.Value; pagina.ActivePage := tbConcilia; acConciliarExecute(Sender); end; procedure TFConciliar.vistaResumenEditKeyDown(Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem; AEdit: TcxCustomEdit; var Key: Word; Shift: TShiftState); begin if (Key = VK_TAB ) and ( Shift = [ssCtrl ]) then PostMessage( Handle, WM_NEXTDLGCTL, 0, 0 ); end; procedure TFConciliar.vistaResumenKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = VK_TAB ) and ( Shift = [ssCtrl ]) then PostMessage( Handle, WM_NEXTDLGCTL, 0, 0 ); end; procedure TFConciliar.vistaStylesGetContentStyle(Sender: TcxCustomGridTableView; ARecord: TcxCustomGridRecord; AItem: TcxCustomGridTableItem; var AStyle: TcxStyle); begin if ARecord.Values[0] = '1' then AStyle := selec else AStyle := fila; end; function TFConciliar.insertarMovimBanco( cds: TClientDataset; const Banco: string; fecha: TDateTime ): integer; begin with Dm, spMovBan do try Parameters.ParamByName( 'CONFIRMADO' ).value := '1'; Parameters.ParamByName( 'CONCILIADO' ).value := '1'; Parameters.ParamByName( 'CODBANCO' ).value := Banco; Parameters.ParamByName( 'FECHAOPER' ).value := fecha; Parameters.ParamByName( 'FECHACONF' ).value := fecha; Parameters.ParamByName( 'IMPORTE' ).value := cds.FieldByName('CREDITO').value - cds.FieldByName('DEBITO').value; Parameters.ParamByName( 'CODOPER' ).value := cds.FieldByName('CODIGO').value; Parameters.ParamByName( 'DETALLE' ).value := cds.FieldByName('CONCEPTO').value; Parameters.ParamByName( 'ASIENTO' ).value := 0; execute; Result := getId('MOVBANCO'); ActSdoBan.Parameters.ParamByName( 'BANCO' ).value := Banco; ActSdoBan.Parameters.ParamByName( 'IMPORTE' ).value := cds.FieldByName('CREDITO').value - cds.FieldByName('DEBITO').value; ActSdoBan.Execute; ActSdoCon.Parameters.ParamByName( 'CODBAN' ).value := Banco; ActSdoCon.Parameters.ParamByName( 'IMPORTE' ).value := cds.FieldByName('CREDITO').value - cds.FieldByName('DEBITO').value; ActSdoCon.Execute; spSdoBanco.Parameters.ParamByName( 'BANCO' ).value := Banco; spSdoBanco.Parameters.ParamByName( 'IMPORTE' ).value := cds.FieldByName('CREDITO').value - cds.FieldByName('DEBITO').value; spSdoBanco.Execute; finally end; end; function TFConciliar.insertarPendiente(cds: TClientDataset; concilia: integer; const Banco: string; fecha: TDateTime): integer; begin with Dm do begin spInsPendiente.Parameters.ParamByName('OPERACION').value := concilia; spInsPendiente.Parameters.ParamByName('CODBANCO').value := Banco; spInsPendiente.Parameters.ParamByName('FECHA').value := fecha; spInsPendiente.Parameters.ParamByName('IMPORTE').value := cds.FieldByName('CREDITO').value- cds.FieldByName('DEBITO').value; spInsPendiente.Parameters.ParamByName('DETALLE').value := cds.FieldByName('CONCEPTO').value; spInsPendiente.Parameters.ParamByName('CODIGO').value := cds.FieldByName('CODIGO').value; spInsPendiente.Execute; end; end; end.
unit GetTerritoriesResponseUnit; interface uses REST.Json.Types, JSONNullableAttributeUnit, GenericParametersUnit, TerritoryUnit; type TGetTerritoriesResponse = class(TGenericParameters) private // Array of objects must named "FItems" for correct unmarshaling. FItems: TArray<TTerritory>; public constructor Create; override; destructor Destroy; override; property Territories: TArray<TTerritory> read FItems; end; implementation constructor TGetTerritoriesResponse.Create; begin inherited; SetLength(FItems, 0); end; destructor TGetTerritoriesResponse.Destroy; begin Finalize(FItems); inherited; end; end.
unit ValidationRules.TMaxLengthValidationRule; interface uses System.SysUtils, System.Variants, Framework.Interfaces; type TMaxLengthValidationRule = class(TInterfacedObject, IValidationRule) const INVALID_LENGTH_MESSAGE = 'Invalid length'; strict private FMaxLength: Integer; procedure SetMaxLength(const AValue: Integer); public constructor Create(const AMaxLength: Integer); destructor Destroy; override; function Parse(const AValue: Variant; var AReasonForRejection: String): Boolean; end; implementation { TMaxLengthValidationRule } constructor TMaxLengthValidationRule.Create(const AMaxLength: Integer); begin inherited Create; SetMaxLength(AMaxLength); end; destructor TMaxLengthValidationRule.Destroy; begin inherited; end; function TMaxLengthValidationRule.Parse(const AValue: Variant; var AReasonForRejection: String): Boolean; begin Result := Length(Trim(AValue)) <= FMaxLength; if not Result then AReasonForRejection := Self.INVALID_LENGTH_MESSAGE; end; procedure TMaxLengthValidationRule.SetMaxLength(const AValue: Integer); begin FMaxLength := AValue; end; end.
unit uChamadoEmail; interface uses uDM, System.SysUtils, Data.DB, FireDAC.Comp.Client, uContaEmail, System.Generics.Collections; type TChamadoEmail = class private FLista: TList<string>; FListaCliente: TList<string>; function RetornarEmailConta_Email(IdUsuario: integer): string; procedure RetornarEmailClientes(IdChamado, IdUsuario: Integer); procedure RetornarEmailSupervisor(IdUsuario, IdStatus: Integer); procedure RetornarEmailConsultor(IdChamado, IdUsuario, IdStatus: Integer); procedure RetornarEmailRevenda(IdChamado, IdUsuario, IdStatus: Integer); procedure Adicionar(email: string); procedure AdicionarCliente(email: string); public function RetornaEmails(IdChamado, IdUsuario, IdStatus: integer): string; function RetornaEmailCliente(IdChamado, IdUsuario: integer): string; constructor create; destructor destroy; override; end; implementation { TChamadoEmail } uses uStatus, uDepartamento, uFuncoesServidor; procedure TChamadoEmail.Adicionar(email: string); begin if not TFuncoes.EmailExisteNaLista(email, FLista) then FLista.Add(email); end; procedure TChamadoEmail.AdicionarCliente(email: string); begin if not TFuncoes.EmailExisteNaLista(email, FListaCliente) then FListaCliente.Add(email); end; constructor TChamadoEmail.create; begin inherited create; FListaCliente := TList<string>.Create; FLista := TList<string>.Create; end; destructor TChamadoEmail.destroy; begin FreeAndNil(FLista); FreeAndNil(FListaCliente); inherited; end; function TChamadoEmail.RetornaEmailCliente(IdChamado, IdUsuario: integer): string; begin RetornarEmailClientes(IdChamado, IdUsuario); Result := TFuncoes.RetornaListaEmail(FListaCliente); end; function TChamadoEmail.RetornaEmails(IdChamado, IdUsuario, IdStatus: integer): string; begin RetornarEmailSupervisor(IdUsuario, IdStatus); RetornarEmailConsultor(IdChamado, IdUsuario, IdStatus); RetornarEmailRevenda(IdChamado, IdUsuario, IdStatus); Result := TFuncoes.RetornaListaEmail(FLista); end; procedure TChamadoEmail.RetornarEmailClientes(IdChamado, IdUsuario: Integer); var Qry: TFDQuery; sEmail: string; iContador: Integer; Status: TStatus; bNotificar: Boolean; idStatus: Integer; begin sEmail := RetornarEmailConta_Email(IdUsuario); if Trim(sEmail) = '' then // se não tem conta email, exit Exit; Qry := TFDQuery.Create(nil); try Qry.Connection := dm.Conexao; Qry.SQL.Add(' SELECT'); Qry.SQL.Add(' Sta_Id'); Qry.SQL.Add(' FROM Chamado'); Qry.SQL.Add(' INNER JOIN Cliente_Email ON Cha_Cliente = CliEm_Cliente'); Qry.SQL.Add(' INNER JOIN Status ON Cha_Status = Sta_Id'); Qry.SQL.Add(' WHERE Sta_NotificarCliente = 1'); Qry.SQL.Add(' AND Cha_Id = ' + IntToStr(IdChamado)); Qry.Open(); if qry.FieldByName('Sta_Id').AsInteger = 0 then Exit; Qry.Close; Qry.SQL.Clear; Qry.SQL.Add(' SELECT'); Qry.SQL.Add(' CliEm_Email'); Qry.SQL.Add(' FROM Chamado'); Qry.SQL.Add(' INNER JOIN Cliente_Email ON Cha_Cliente = CliEm_Cliente'); Qry.SQL.Add(' INNER JOIN Status ON Cha_Status = Sta_Id'); Qry.SQL.Add(' WHERE Sta_NotificarCliente = 1'); Qry.SQL.Add(' AND CliEm_Notificar = 1'); Qry.SQL.Add(' AND Cha_Id = ' + IntToStr(IdChamado)); Qry.Open(); iContador := 0; if not Qry.IsEmpty then begin while not Qry.Eof do begin AdicionarCliente(Qry.FieldByName('CliEm_Email').AsString); Inc(iContador); Qry.Next; end; end; // se não tem no cliente, buscar no usuário logado if iContador = 0 then AdicionarCliente(sEmail); finally FreeAndNil(Qry); end; end; procedure TChamadoEmail.RetornarEmailConsultor(IdChamado, IdUsuario, IdStatus: Integer); var Qry: TFDQuery; sEmail: string; objStatus: TStatus; TemRegistro: Boolean; begin sEmail := RetornarEmailConta_Email(IdUsuario); if Trim(sEmail) = '' then Exit; objStatus := TStatus.Create; try TemRegistro := objStatus.NotificarConsultor(IdStatus); finally FreeAndNil(objStatus); end; Qry := TFDQuery.Create(nil); try if TemRegistro then begin Qry.Connection := DM.Conexao; Qry.Close; Qry.SQL.Clear; Qry.SQL.Add(' SELECT'); Qry.SQL.Add(' Usu_Email'); Qry.SQL.Add(' FROM Chamado'); Qry.SQL.Add(' INNER JOIN Cliente ON Cha_Cliente = Cli_Id'); Qry.SQL.Add(' INNER JOIN Usuario ON Cli_Usuario = Usu_Id'); Qry.SQL.Add(' WHERE Cha_Id = ' + IntToStr(IdChamado)); Qry.Open(); if not Qry.IsEmpty then Adicionar(Qry.FieldByName('usu_Email').AsString); end; finally FreeAndNil(Qry); end; end; function TChamadoEmail.RetornarEmailConta_Email(IdUsuario: integer): string; var ContaEmail: TContaEmail; begin ContaEmail := TContaEmail.Create; try Result := ContaEmail.RetornarEmail(IdUsuario); finally FreeAndNil(ContaEmail); end; end; procedure TChamadoEmail.RetornarEmailRevenda(IdChamado, IdUsuario, IdStatus: Integer); var Qry: TFDQuery; sEmail: string; objStatus: TStatus; TemRegistro: Boolean; begin sEmail := RetornarEmailConta_Email(IdUsuario); if Trim(sEmail) = '' then Exit; objStatus := TStatus.Create; try TemRegistro := objStatus.NotificarRevenda(IdStatus); finally FreeAndNil(objStatus); end; Qry := TFDQuery.Create(nil); try if TemRegistro then begin Qry.Connection := dm.Conexao; Qry.Close; Qry.SQL.Clear; Qry.SQL.Add(' SELECT'); Qry.SQL.Add(' RevEm_Email'); Qry.SQL.Add(' FROM Chamado'); Qry.SQL.Add(' INNER JOIN Cliente On Cha_Cliente = Cli_Id'); Qry.SQL.Add(' INNER JOIN Revenda ON Cli_Revenda = Rev_Id'); Qry.SQL.Add(' INNER JOIN Revenda_Email ON Rev_id = RevEm_Revenda'); Qry.SQL.Add(' WHERE Cha_Id = ' + IntToStr(IdChamado)); Qry.Open(); while not Qry.Eof do begin Adicionar(Qry.Fields[0].AsString); Qry.Next; end; end; finally FreeAndNil(Qry); end; end; procedure TChamadoEmail.RetornarEmailSupervisor(IdUsuario, IdStatus: Integer); var sEmail: string; objStatus: TStatus; TemRegistro: Boolean; objDepartamento: TDepartamento; ListaEmail: TList<string>; begin sEmail := RetornarEmailConta_Email(IdUsuario); if Trim(sEmail) = '' then // se não tem conta email, nao faz nada Exit; objStatus := TStatus.Create; try TemRegistro := objStatus.NotificarSupervisor(IdStatus); finally FreeAndNil(objStatus); end; if TemRegistro then begin objDepartamento := TDepartamento.Create; try ListaEmail := objDepartamento.RetornarEmail(IdUsuario); for sEmail in ListaEmail do Adicionar(sEmail); finally FreeAndNil(objDepartamento); FreeAndNil(ListaEmail); end; end; end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.Grids, Vcl.DBGrids, Data.Win.ADODB, Vcl.ExtCtrls, Vcl.DBCtrls, VclTee.TeeGDIPlus, VclTee.TeEngine, VclTee.DBChart, VclTee.TeeDBCrossTab, VclTee.Series, VclTee.TeeProcs, VclTee.Chart, Vcl.StdCtrls, Vcl.ExtDlgs, RzPanel, RzDlgBtn; type TFormMain = class(TForm) DataSource1: TDataSource; ADOQuery1: TADOQuery; DBGrid1: TDBGrid; DBNavigator1: TDBNavigator; btnSave: TButton; PanelTop: TPanel; SavePictureDialog1: TSavePictureDialog; Button1: TButton; Chart1: TChart; Series1: TBarSeries; DBCrossTabSource1: TDBCrossTabSource; RzDialogButtons1: TRzDialogButtons; ADOConnection1: TADOConnection; procedure btnSaveClick(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var FormMain: TFormMain; implementation {$R *.dfm} uses System.IOUtils; procedure TFormMain.btnSaveClick(Sender: TObject); begin if SavePictureDialog1.Execute then Chart1.SaveToBitmapFile(SavePictureDialog1.FileName + '.bmp'); end; procedure TFormMain.Button1Click(Sender: TObject); begin Chart1.Print; end; end.
{ Exercicio 80: Uma empresa possui 5 vendedores que ganham por comissão sobre a quantidade de produtos vendidos. Cada vendedor em um determinado mês vendeu X produtos do mesmo tipo. A empresa deseja obter um relatório com o Nome, o total de vendas e o valor a ser pago a cada vendedor. A comissão paga pela empresa é de 30% sobre o valor de cada produto vendido. } { Solução em Portugol Algoritmo Exercicio 80; Var nome_vendedor: vetor[1..5] de caracter; vendas_vendedor: vetor[1..5] de inteiro; comissao_vendedor: vetor[1..5] de real; preco <- real; i: inteiro; Inicio exiba("Programa que exibe um relatório de vendas e a comissão a ser paga aos 5 vendedores."); exiba("Digite o preço do produto:"); leia(preco); enquanto(preco <= 0)faça exiba("Digite um preco válido: "); leia(preco); fimenquanto; para i <- 1 até 5 faça exiba("Digite o nome do ",i,"º vendedor:"); leia(nome_vendedor[i]); exiba("Digite a quantidade de produtos que ",nome_vendedor[i]," vendeu:"); leia(vendas_vendedor[i]); comissao_vendedor[i] <- vendas_vendedor[i] * preco * 0,3; fimpara; exiba("Nome do vendedor Produtos Vendidos Comissao a Receber"); para i <- 1 até 5 faça exiba(" ",nome_vendedor[i]," ",vendas_vendedor[i]," ",comissao_vendedor[i]); fimpara; Fim. } // Solução em Pascal Program Exercicio80; uses crt; var nome_vendedor: array[1..5] of string; vendas_vendedor: array[1..5] of integer; comissao_vendedor: array[1..5] of real; preco : real; i: integer; begin clrscr; writeln('Programa que exibe um relatório de vendas e a comissão a ser paga aos 5 vendedores.'); writeln('Digite o preço do produto:'); readln(preco); while(preco <= 0)do Begin writeln('Digite um preco válido: '); readln(preco); End; for i := 1 to 5 do Begin writeln('Digite o nome do ',i,'º vendedor:'); readln(nome_vendedor[i]); writeln('Digite a quantidade de produtos que ',nome_vendedor[i],' vendeu:'); readln(vendas_vendedor[i]); comissao_vendedor[i] := vendas_vendedor[i] * preco * 0.3; End; WriteLn('Nome do vendedor Produtos Vendidos Comissao a Receber'); // Ainda não sei alinhar. For i := 1 to 5 do writeln(' ',nome_vendedor[i],' ',vendas_vendedor[i],' ',comissao_vendedor[i]:0:2); repeat until keypressed; end.
PROGRAM SortMonth(INPUT, OUTPUT); USES DateIO; VAR Mo1, Mo2: Month; BEGIN ReadMonth(INPUT, Mo1); ReadMonth(INPUT, Mo2); IF (Mo1 = NoMonth) OR (Mo2 = NoMonth) THEN WRITELN('Входные данные записаны неверно') ELSE BEGIN IF Mo1 < Mo2 THEN BEGIN WriteMonth(OUTPUT, Mo1); WRITE(OUTPUT, ' предшествует ') END ELSE BEGIN IF Mo1 > Mo2 THEN BEGIN WriteMonth(OUTPUT, Mo1); WRITE(OUTPUT, ' следует за ') END ELSE WRITE(OUTPUT, 'Оба месяца ') END; WriteMonth(OUTPUT, Mo2); WRITELN(OUTPUT) END END.
//Exercicio 51: Escreva um algoritmo que receba um número inteiro e informe se esse número é ou não primo. { Solução em Portugol //OBS: Um número N é primo se só é divisível por +-1 e +-N. Algoritmo Exercicio 51; // No caso, podemos avaliar apenas a parte positiva e então N só pode ter 2 divisores. Var numero,contador,primo: inteiro; Inicio exiba("Programa que diz se um número é primo."); exiba("Digite um número: "); leia(numero); primo <- 0; para contador <- 1 até numero faça se(resto(numero,contador) = 0) então primo <- primo + 1; fimse; fimpara; se(primo = 2) então exiba("O número ",numero," é primo.") senão exiba("O número ",numero," não é primo.); fimse; Fim. } // Solução em Pascal Program Exercicio51; uses crt; var numero,contador,primo: integer; begin clrscr; writeln('Programa que diz se um número é primo.'); writeln('Digite um número: '); readln(numero); primo := 0; for contador := 1 to numero do Begin if((numero mod contador) = 0) then primo := primo + 1; End; if(primo = 2) then writeln('O número ',numero,' é primo.') else writeln('O número ',numero,' não é primo.'); repeat until keypressed; end.
unit uGeraSQL; interface uses windows, System.Classes; type TGeradorSQL = class private FColunas: TStringList; FTabelas: TStringList; FCondicoes: TStringList; function PegarColunas: string; function PegarTabelas: string; function PegaCondicoes: string; public constructor Create(); destructor Destroy; procedure AdicionarColuna(const sColuna: string); procedure AdicionarTabela(const sTabela: string); procedure AdicionarCondicao(const sCondicao: string); function GerarSQL: string; end; implementation uses System.SysUtils; { TGeradorSQL } procedure TGeradorSQL.AdicionarColuna(const sColuna: string); begin FColunas.Add(sColuna); end; procedure TGeradorSQL.AdicionarCondicao(const sCondicao: string); begin FCondicoes.Add(sCondicao); end; procedure TGeradorSQL.AdicionarTabela(const sTabela: string); begin FTabelas.Add(sTabela); end; constructor TGeradorSQL.Create; begin FColunas := TStringList.Create; FTabelas := TStringList.Create; FCondicoes := TStringList.Create; end; destructor TGeradorSQL.destroy; begin FreeAndNil(FColunas); FreeAndNil(FTabelas); FreeAndNil(FCondicoes); end; function TGeradorSQL.GerarSQL: string; begin Result := PegarColunas+ PegarTabelas+ PegaCondicoes; end; function TGeradorSQL.PegaCondicoes: string; var I: Integer; begin for I := 0 to FCondicoes.Count -1 do begin if I = FColunas.Count -1 then Result := Result +#13#10+ FCondicoes[I] else Result := Result + FCondicoes[I]+ ' and '; end; end; function TGeradorSQL.PegarColunas: string; var I: Integer; begin Result := 'Select '+ #13#10; for I := 0 to FColunas.Count -1 do begin if I = FColunas.Count -1 then Result := Result + FColunas[I] else Result := Result +' '+ FColunas[I] + ' , '; end; Result := Result + #13#10+' From ' ; end; function TGeradorSQL.PegarTabelas: string; var I: Integer; begin for I := 0 to FTabelas.Count -1 do begin if I = 0 then Result := Result + FTabelas[I] else Result := Result +' '+ FTabelas[I] + ' , '; end; Result := Result + #13#10 +' Where ' ; end; end.
unit n2a03; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} cpu_misc,sound_engine,timer_engine,main_engine,m6502,misc_functions; const // GLOBAL CONSTANTS SYNCS_MAX1=$20; SYNCS_MAX2=$80; TOTAL_BUFFER_SIZE=150; // CHANNEL TYPE DEFINITIONS type tcall_frame_irq=procedure (status:byte); tadditional_sound=procedure; square_t=packed record // Square Wave regs:array[0..3] of byte; vbl_length:integer; freq:integer; phaseacc:single; env_phase:single; sweep_phase:single; adder:byte; env_vol:byte; enabled:boolean; end; psquare_t=^square_t; triangle_t=packed record // Triangle Wave regs:array[0..3] of byte; // regs[1] unused linear_length:integer; vbl_length:integer; write_latency:integer; phaseacc:single; output_vol:shortint; adder:byte; counter_started:boolean; enabled:boolean; end; ptriangle_t=^triangle_t; noise_t=packed record // Noise Wave regs:array[0..3] of byte; // regs[1] unused seed:dword; vbl_length:integer; phaseacc:single; env_phase:single; env_vol:byte; enabled:boolean; end; pnoise_t=^noise_t; dpcm_t=packed record // DPCM Wave regs:array[0..3] of byte; address:word; length:dword; bits_left:integer; phaseacc:single; cur_byte:byte; enabled:boolean; irq:boolean; output:smallint; getbyte:tgetbyte; end; pdpcm_t=^dpcm_t; apu_t=packed record // APU type // Sound channels squ:array[0..1] of psquare_t; tri:ptriangle_t; noi:pnoise_t; dpcm:pdpcm_t; // APU registers regs:array[0..$17] of byte; step_mode:integer; end; papu_t=^apu_t; cpu_n2a03=class constructor Create(clock:dword;frames:word); destructor free; public m6502:cpu_m6502; additional_sound:tadditional_sound; procedure reset; function read(direccion:word):byte; procedure write(posicion:word;value:byte); procedure change_internals(read_byte_dpcm:tgetbyte); procedure add_more_sound(additional_sound:tadditional_sound); function save_snapshot(data:pbyte):word; procedure load_snapshot(data:pbyte); private apu:papu_t; // Actual APUs samps_per_sync:dword; // Number of samples per vsync vbl_times:array[0..$1f] of dword; // VBL durations in samples sync_times1:array[0..(SYNCS_MAX1-1)] of dword; // Samples per sync table sync_times2:array[0..(SYNCS_MAX2-1)] of dword; // Samples per sync table buffer:array[1..TOTAL_BUFFER_SIZE] of integer; buffer_pos:byte; num_sample:byte; frame_irq_timer:byte; old_res:integer; frame_irq:boolean; frame_call_irq:tcall_frame_irq; procedure apu_regwrite(address,value:byte); procedure create_vbltimes(rate:dword); procedure create_syncs(sps:dword); function apu_square(chan:byte):integer; function apu_triangle:integer; function apu_noise:integer; function apu_dpcm:integer; procedure sound_advance; procedure sound_update; end; var n2a03_0,n2a03_1:cpu_n2a03; procedure n2a03_sound_advance(index:byte); procedure n2a03_update_sound_0; procedure n2a03_update_sound(index:byte); procedure n2a03_irq_call(index:byte); implementation var chips_total:integer=-1; const APU_WRA0=$00; APU_WRA1=$01; APU_WRA2=$02; APU_WRA3=$03; APU_WRB0=$04; APU_WRB1=$05; APU_WRB2=$06; APU_WRB3=$07; APU_WRC0=$08; APU_WRC2=$0A; APU_WRC3=$0B; APU_WRD0=$0C; APU_WRD2=$0E; APU_WRD3=$0F; APU_WRE0=$10; APU_WRE1=$11; APU_WRE2=$12; APU_WRE3=$13; APU_SMASK=$15; APU_IRQCTRL=$17; // CONSTANTS // vblank length table used for squares, triangle, noise vbl_length:array[0..31] of byte=( 5, 127, 10, 1, 19, 2, 40, 3, 80, 4, 30, 5, 7, 6, 13, 7, 6, 8, 12, 9, 24, 10, 48, 11, 96, 12, 36, 13, 8, 14, 16, 15); // frequency limit of square channels freq_limit:array[0..7] of word=($3FF,$555,$666,$71C,$787,$7C1,$7E0,$7F0); // table of noise frequencies noise_freq:array[0..15] of word=( 4, 8, 16, 32, 64, 96, 128, 160, 202, 254, 380, 508, 762, 1016, 2034, 2046); // dpcm transfer freqs dpcm_clocks:array[0..15] of word=( 428, 380, 340, 320, 286, 254, 226, 214, 190, 160, 142, 128, 106, 85, 72, 54); // ratios of pos/neg pulse for square waves // 2/16 = 12.5%, 4/16 = 25%, 8/16 = 50%, 12/16 = 75% duty_lut:array[0..3] of byte=(2,4,8,12); function sshr(num:integer;fac:byte):integer; begin if num<0 then sshr:=-(abs(num) shr fac) else sshr:=num shr fac; end; function cpu_n2a03.save_snapshot(data:pbyte):word; begin end; procedure cpu_n2a03.load_snapshot(data:pbyte); begin end; // INITIALIZE WAVE TIMES RELATIVE TO SAMPLE RATE procedure cpu_n2a03.create_vbltimes(rate:dword); var i:integer; begin for i:=0 to $1f do self.vbl_times[i]:=vbl_length[i]*rate; end; // INITIALIZE SAMPLE TIMES IN TERMS OF VSYNCS procedure cpu_n2a03.create_syncs(sps:dword); var i:integer; val:dword; begin val:=sps; for i:=0 to (SYNCS_MAX1-1) do begin self.sync_times1[i]:=val; val:=val+sps; end; val:=0; for i:=0 to (SYNCS_MAX2-1) do begin self.sync_times2[i]:=val; self.sync_times2[i]:=sshr(self.sync_times2[i],2); val:=val+sps; end; end; constructor cpu_n2a03.create(clock:dword;frames:word); var rate:integer; begin self.m6502:=cpu_m6502.Create(clock,frames,TCPU_NES); getmem(self.apu,sizeof(apu_t)); getmem(self.apu.squ[0],sizeof(square_t)); getmem(self.apu.squ[1],sizeof(square_t)); getmem(self.apu.tri,sizeof(triangle_t)); getmem(self.apu.noi,sizeof(noise_t)); getmem(self.apu.dpcm,sizeof(dpcm_t)); // Initialize global variables rate:=clock div 4; self.samps_per_sync:=round(rate/llamadas_maquina.fps_max); // Use initializer calls self.create_vbltimes(self.samps_per_sync); self.create_syncs(self.samps_per_sync); chips_total:=chips_total+1; self.frame_irq_timer:=timers.init(self.m6502.numero_cpu,29830,nil,n2a03_irq_call,false,chips_total); if chips_total=0 then self.m6502.init_sound(n2a03_update_sound_0) else timers.init(self.m6502.numero_cpu,clock/FREQ_BASE_AUDIO,nil,n2a03_update_sound,true,chips_total); //Crear aqui este timer es muy IMPORTANTE, por el orden despues timers.init(self.m6502.numero_cpu,4,nil,n2a03_sound_advance,true,chips_total); self.num_sample:=init_channel; self.apu.dpcm.getbyte:=nil; self.frame_call_irq:=nil; self.additional_sound:=nil; end; procedure cpu_n2a03.change_internals(read_byte_dpcm:tgetbyte); begin self.apu.dpcm.getbyte:=read_byte_dpcm; end; procedure cpu_n2a03.add_more_sound(additional_sound:tadditional_sound); begin self.additional_sound:=additional_sound; end; destructor cpu_n2a03.free; begin freemem(self.apu.squ[0]); self.apu.squ[0]:=nil; freemem(self.apu.squ[1]); self.apu.squ[1]:=nil; freemem(self.apu.tri); self.apu.tri:=nil; freemem(self.apu.noi); self.apu.noi:=nil; freemem(self.apu.dpcm); self.apu.dpcm:=nil; freemem(self.apu); self.apu:=nil; self.m6502.Free; chips_total:=chips_total-1; end; procedure cpu_n2a03.reset; var f:byte; begin fillchar(self.apu.squ[0]^,sizeof(square_t),0); fillchar(self.apu.squ[1]^,sizeof(square_t),0); fillchar(self.apu.tri^,sizeof(triangle_t),0); fillchar(self.apu.noi^,sizeof(noise_t),0); self.apu.noi.seed:=1; for f:=0 to 3 do self.apu.dpcm.regs[f]:=0; self.apu.dpcm.address:=$c000; self.apu.dpcm.length:=1; self.apu.dpcm.bits_left:=8; self.apu.dpcm.phaseacc:=dpcm_clocks[0]; self.apu.dpcm.cur_byte:=0; self.apu.dpcm.enabled:=false; self.apu.dpcm.irq:=false; self.apu.dpcm.output:=0; fillchar(self.apu.regs[0],$17,0); fillchar(self.buffer[1],TOTAL_BUFFER_SIZE*sizeof(integer),0); self.apu.step_mode:=0; self.buffer_pos:=1; self.frame_irq:=false; timers.enabled(self.frame_irq_timer,false); self.m6502.reset; end; procedure apu_dpcmreset(dpcm:pdpcm_t); begin dpcm.address:=$c000+(dpcm.regs[2] shl 6); dpcm.length:=(dpcm.regs[3] shl 4)+1; dpcm.bits_left:=8; dpcm.irq:=(dpcm.regs[0] and $80)<>0; dpcm.enabled:=true; //dpcm.output:=0; end; // WRITE REGISTER VALUE procedure cpu_n2a03.apu_regwrite(address,value:byte); var chan:byte; begin if (address and 4)<>0 then chan:=1 else chan:=0; case address of // squares APU_WRA0,APU_WRB0:self.apu.squ[chan].regs[0]:=value; APU_WRA1,APU_WRB1:self.apu.squ[chan].regs[1]:=value; APU_WRA2,APU_WRB2:begin self.apu.squ[chan].regs[2]:=value; if (self.apu.squ[chan].enabled) then self.apu.squ[chan].freq:=((((self.apu.squ[chan].regs[3] and 7) shl 8)+value)+1) shl 16; end; APU_WRA3,APU_WRB3:begin self.apu.squ[chan].regs[3]:=value; if self.apu.squ[chan].enabled then begin self.apu.squ[chan].vbl_length:=self.vbl_times[value shr 3]; self.apu.squ[chan].env_vol:=0; self.apu.squ[chan].freq:=((((value and 7) shl 8)+self.apu.squ[chan].regs[2])+1) shl 16; end; end; // triangle APU_WRC0:begin self.apu.tri.regs[0]:=value; if self.apu.tri.enabled then begin if not(self.apu.tri.counter_started) then self.apu.tri.linear_length:=self.sync_times2[value and $7F]; end; end; $09:self.apu.tri.regs[1]:=value; // unused APU_WRC2:self.apu.tri.regs[2]:=value; APU_WRC3:begin self.apu.tri.regs[3]:=value; {this is somewhat of a hack. there is some latency on the Real ** Thing between when trireg0 is written to and when the linear ** length counter actually begins its countdown. we want to prevent ** the case where the program writes to the freq regs first, then ** to reg 0, and the counter accidentally starts running because of ** the sound queue's timestamp processing. ** ** set to a few NES sample -- should be sufficient ** ** 3 * (1789772.727 / 44100) = ~122 cycles, just around one scanline ** ** should be plenty of time for the 6502 code to do a couple of table ** dereferences and load up the other triregs} // used to be 3, but now we run the clock faster, so base it on samples/sync */ self.apu.tri.write_latency:=trunc((self.samps_per_sync+239)/240); if self.apu.tri.enabled then begin self.apu.tri.counter_started:=false; self.apu.tri.vbl_length:=self.vbl_times[value shr 3]; self.apu.tri.linear_length:=self.sync_times2[apu.tri.regs[0] and $7f]; end; end; // noise APU_WRD0:self.apu.noi.regs[0]:=value; $0D:self.apu.noi.regs[1]:=value; // unused APU_WRD2:self.apu.noi.regs[2]:=value; APU_WRD3:begin self.apu.noi.regs[3]:=value; if self.apu.noi.enabled then begin self.apu.noi.vbl_length:=self.vbl_times[value shr 3]; self.apu.noi.env_vol:=0; // reset envelope end; end; // DMC APU_WRE0:begin self.apu.dpcm.regs[0]:=value; self.apu.dpcm.irq:=(value and $80)<>0; end; APU_WRE1:begin // 7-bit DAC self.apu.dpcm.output:=(value and $7f)-64; end; APU_WRE2:begin self.apu.dpcm.regs[2]:=value; self.apu.dpcm.address:=$c000+(value shl 6); end; APU_WRE3:begin self.apu.dpcm.regs[3]:=value; self.apu.dpcm.length:=(value shl 4)+1; end; APU_IRQCTRL:if (value and $80)<>0 then begin self.apu.step_mode:=5; timers.enabled(self.frame_irq_timer,false); end else begin self.apu.step_mode:=4; timers.enabled(self.frame_irq_timer,true); n2a03_0.frame_irq:=(value and $40)=0; end; APU_SMASK:begin //Necesario para TimeLord!!!! self.apu.dpcm.irq:=false; if (value and $01)<>0 then self.apu.squ[0].enabled:=true else begin self.apu.squ[0].enabled:=false; self.apu.squ[0].vbl_length:=0; end; if (value and $02)<>0 then self.apu.squ[1].enabled:=true else begin self.apu.squ[1].enabled:=false; self.apu.squ[1].vbl_length:=0; end; if (value and $04)<>0 then self.apu.tri.enabled:=true else begin self.apu.tri.enabled:=false; self.apu.tri.vbl_length:=0; self.apu.tri.linear_length:=0; self.apu.tri.counter_started:=false; self.apu.tri.write_latency:=0; end; if (value and $08)<>0 then self.apu.noi.enabled:=true else begin self.apu.noi.enabled:=false; self.apu.noi.vbl_length:=0; end; if (value and $10)<>0 then begin // only reset dpcm values if DMA is finished if not(self.apu.dpcm.enabled) then begin self.apu.dpcm.enabled:=true; apu_dpcmreset(self.apu.dpcm); end; end else self.apu.dpcm.enabled:=false; end; end; end; // READ VALUES FROM REGISTERS function cpu_n2a03.read(direccion:word):byte; var address,readval:byte; begin address:=direccion and $ff; if (address=$15) then begin readval:=0; if self.apu.squ[0].vbl_length<>0 then readval:=readval or 1; if self.apu.squ[1].vbl_length<>0 then readval:=readval or 2; if self.apu.tri.vbl_length<>0 then readval:=readval or 4; if self.apu.noi.vbl_length<>0 then readval:=readval or 8; if self.apu.dpcm.length<>0 then readval:=readval or $10; if self.frame_irq then readval:=readval or $40; if self.apu.dpcm.irq then readval:=readval or $80; self.frame_irq:=false; end else readval:=self.apu.regs[address]; read:=readval; end; // WRITE VALUE TO TEMP REGISTRY AND QUEUE EVENT procedure cpu_n2a03.write(posicion:word;value:byte); var address:byte; begin address:=posicion and $ff; self.apu.regs[address]:=value; self.apu_regwrite(address,value); end; // OUTPUT SQUARE WAVE SAMPLE (VALUES FROM -16 to +15) function cpu_n2a03.apu_square(chan:byte):integer; var env_delay,sweep_delay:integer; output_:shortint; begin { reg0: 0-3=volume, 4=envelope, 5=hold, 6-7=duty cycle ** reg1: 0-2=sweep shifts, 3=sweep inc/dec, 4-6=sweep length, 7=sweep on ** reg2: 8 bits of freq ** reg3: 0-2=high freq, 7-4=vbl length counter} if not(self.apu.squ[chan].enabled) then begin apu_square:=0; exit; end; // enveloping env_delay:=self.sync_times1[self.apu.squ[chan].regs[0] and $f]; // decay is at a rate of (env_regs + 1) / 240 secs self.apu.squ[chan].env_phase:=self.apu.squ[chan].env_phase-4; while (self.apu.squ[chan].env_phase<0) do begin self.apu.squ[chan].env_phase:=self.apu.squ[chan].env_phase+env_delay; if (self.apu.squ[chan].regs[0] and $20)<>0 then self.apu.squ[chan].env_vol:=(self.apu.squ[chan].env_vol+1) and 15 else if (self.apu.squ[chan].env_vol<15) then self.apu.squ[chan].env_vol:=self.apu.squ[chan].env_vol+1; end; // vbl length counter if ((self.apu.squ[chan].vbl_length>0) and ((self.apu.squ[chan].regs[0] and $20)=0)) then self.apu.squ[chan].vbl_length:=self.apu.squ[chan].vbl_length-1; if (self.apu.squ[chan].vbl_length=0) then begin apu_square:=0; exit; end; // freqsweeps if (((self.apu.squ[chan].regs[1] and $80)<>0) and ((self.apu.squ[chan].regs[1] and 7)<>0)) then begin sweep_delay:=self.sync_times1[(self.apu.squ[chan].regs[1] shr 4) and 7]; self.apu.squ[chan].sweep_phase:=self.apu.squ[chan].sweep_phase-2; while (self.apu.squ[chan].sweep_phase<0) do begin self.apu.squ[chan].sweep_phase:=self.apu.squ[chan].sweep_phase+sweep_delay; if (self.apu.squ[chan].regs[1] and 8)<>0 then self.apu.squ[chan].freq:=self.apu.squ[chan].freq-sshr(self.apu.squ[chan].freq,(self.apu.squ[chan].regs[1] and 7)) else self.apu.squ[chan].freq:=self.apu.squ[chan].freq+sshr(self.apu.squ[chan].freq,(self.apu.squ[chan].regs[1] and 7)); end; end; if ((((self.apu.squ[chan].regs[1] and 8)=0) and (sshr(self.apu.squ[chan].freq,16)>freq_limit[self.apu.squ[chan].regs[1] and 7])) or (sshr(self.apu.squ[chan].freq,16)<4)) then begin apu_square:=0; exit; end; self.apu.squ[chan].phaseacc:=self.apu.squ[chan].phaseacc-4; // # of cycles per sample while (self.apu.squ[chan].phaseacc<0) do begin self.apu.squ[chan].phaseacc:=self.apu.squ[chan].phaseacc+sshr(self.apu.squ[chan].freq,16); self.apu.squ[chan].adder:=(self.apu.squ[chan].adder+1) and $0F; end; if (self.apu.squ[chan].regs[0] and $10)<>0 then output_:=self.apu.squ[chan].regs[0] and $0F else output_:=$0F-self.apu.squ[chan].env_vol; if (self.apu.squ[chan].adder<(duty_lut[self.apu.squ[chan].regs[0] shr 6])) then output_:=-output_; apu_square:=shortint(output_); end; // OUTPUT TRIANGLE WAVE SAMPLE (VALUES FROM -16 to +15) function cpu_n2a03.apu_triangle:integer; var freq:word; output_:integer; begin { reg0: 7=holdnote, 6-0=linear length counter ** reg2: low 8 bits of frequency ** reg3: 7-3=length counter, 2-0=high 3 bits of frequency} apu_triangle:=0; if not(self.apu.tri.enabled) then exit; if (not(self.apu.tri.counter_started) and ((self.apu.tri.regs[0] and $80)=0)) then begin if (self.apu.tri.write_latency)<>0 then self.apu.tri.write_latency:=self.apu.tri.write_latency-1; if (self.apu.tri.write_latency=0) then self.apu.tri.counter_started:=true; end; if (self.apu.tri.counter_started) then begin if (self.apu.tri.linear_length>0) then self.apu.tri.linear_length:=self.apu.tri.linear_length-1; if ((self.apu.tri.vbl_length<>0) and ((self.apu.tri.regs[0] and $80)=0)) then self.apu.tri.vbl_length:=self.apu.tri.vbl_length-1; if (self.apu.tri.vbl_length=0) then exit; end; if (self.apu.tri.linear_length=0) then exit; freq:=(((self.apu.tri.regs[3] and 7) shl 8)+self.apu.tri.regs[2])+1; if (freq<4) then exit; // inaudible self.apu.tri.phaseacc:=self.apu.tri.phaseacc-4; // # of cycles per sample while (self.apu.tri.phaseacc<0) do begin self.apu.tri.phaseacc:=self.apu.tri.phaseacc+freq; self.apu.tri.adder:=(self.apu.tri.adder+1) and $1f; output_:=(self.apu.tri.adder and 7) shl 1; if (self.apu.tri.adder and 8)<>0 then output_:=$10-output_; if (self.apu.tri.adder and $10)<>0 then output_:=-output_; self.apu.tri.output_vol:=output_; end; apu_triangle:=self.apu.tri.output_vol; end; // OUTPUT NOISE WAVE SAMPLE (VALUES FROM -16 to +15) function cpu_n2a03.apu_noise:integer; var freq,env_delay:integer; outvol,output_:byte; begin {reg0: 0-3=volume, 4=envelope, 5=hold ** reg2: 7=small(93 byte) sample,3-0=freq lookup ** reg3: 7-4=vbl length counter} if not(self.apu.noi.enabled) then begin apu_noise:=0; exit; end; // enveloping */ env_delay:=self.sync_times1[self.apu.noi.regs[0] and $0f]; // decay is at a rate of (env_regs + 1) / 240 secs self.apu.noi.env_phase:=self.apu.noi.env_phase-4; while (self.apu.noi.env_phase<0) do begin self.apu.noi.env_phase:=self.apu.noi.env_phase+env_delay; if (self.apu.noi.regs[0] and $20)<>0 then self.apu.noi.env_vol:=(self.apu.noi.env_vol+1) and 15 else if (self.apu.noi.env_vol<15) then self.apu.noi.env_vol:=self.apu.noi.env_vol+1; end; // length counter if (self.apu.noi.regs[0] and $20)=0 then begin if (self.apu.noi.vbl_length>0) then self.apu.noi.vbl_length:=self.apu.noi.vbl_length-1; end; if self.apu.noi.vbl_length=0 then begin apu_noise:=0; exit; end; freq:=noise_freq[self.apu.noi.regs[2] and $0f]; self.apu.noi.phaseacc:=self.apu.noi.phaseacc-4; // # of cycles per sample while (self.apu.noi.phaseacc<0) do begin self.apu.noi.phaseacc:=self.apu.noi.phaseacc+freq; if (self.apu.noi.regs[2] and $80)<>0 then self.apu.noi.seed:=(self.apu.noi.seed shr 1) or ((BIT_n(self.apu.noi.seed,0) xor BIT_n(self.apu.noi.seed,6)) shl 14) else self.apu.noi.seed:= (self.apu.noi.seed shr 1) or ((BIT_n(self.apu.noi.seed,0) xor BIT_n(self.apu.noi.seed, 1)) shl 14); end; if (self.apu.noi.regs[0] and $10)<>0 then outvol:=self.apu.noi.regs[0] and $f else outvol:=$0F-self.apu.noi.env_vol; output_:=self.apu.noi.seed and $ff; if (output_>outvol) then output_:=outvol; if (self.apu.noi.seed and $80)<>0 then apu_noise:=-output_ else apu_noise:=output_; end; // OUTPUT DPCM WAVE SAMPLE function cpu_n2a03.apu_dpcm:integer; var freq:integer; begin if not(self.apu.dpcm.enabled) then begin apu_dpcm:=0; exit; end; freq:=dpcm_clocks[self.apu.dpcm.regs[0] and $0f]; self.apu.dpcm.phaseacc:=self.apu.dpcm.phaseacc-4; // # of cycles per sample while (self.apu.dpcm.phaseacc<0) do begin self.apu.dpcm.phaseacc:=self.apu.dpcm.phaseacc+freq; if (self.apu.dpcm.bits_left=0) then begin self.apu.dpcm.bits_left:=8; self.apu.dpcm.cur_byte:=self.apu.dpcm.getbyte(self.apu.dpcm.address); if self.apu.dpcm.address=$ffff then self.apu.dpcm.address:=$8000 else self.apu.dpcm.address:=self.apu.dpcm.address+1; self.apu.dpcm.length:=self.apu.dpcm.length-1; end; self.apu.dpcm.bits_left:=self.apu.dpcm.bits_left-1; if (self.apu.dpcm.cur_byte and (1 shl self.apu.dpcm.bits_left))<>0 then begin if (self.apu.dpcm.output<126) then self.apu.dpcm.output:=self.apu.dpcm.output+2; end else begin if (self.apu.dpcm.output>1) then self.apu.dpcm.output:=self.apu.dpcm.output-2; end; if (self.apu.dpcm.length=0) then begin self.apu.dpcm.enabled:=false; // Fixed * Proper DPCM channel ENABLE/DISABLE flag behaviour //self.apu.dpcm.output:=0; // Fixed * DPCM DAC resets itself when restarted if (self.apu.dpcm.regs[0] and $40)<>0 then begin //Loop apu_dpcmreset(self.apu.dpcm); end else begin // Final - IRQ Generator if self.apu.dpcm.irq then n2a03_0.m6502.change_irq(HOLD_LINE); break; end; end; end; //while apu_dpcm:=self.apu.dpcm.output; end; procedure cpu_n2a03.sound_advance; var tnd_out,pulse_out:single; begin pulse_out:=0.00752*(self.apu_square(0)+self.apu_square(1)); tnd_out:=0.00851*self.apu_triangle+0.00494*self.apu_noise+0.00335*self.apu_dpcm; self.buffer[self.buffer_pos]:=trunc((pulse_out+tnd_out)*255) shl 7; self.buffer_pos:=self.buffer_pos+1; end; procedure cpu_n2a03.sound_update; var f:byte; res:integer; begin //Resample from 447443hz to 44100hz res:=0; if self.buffer_pos>11 then begin for f:=1 to 11 do res:=res+self.buffer[f]; res:=res div 11; for f:=12 to self.buffer_pos do self.buffer[f-11]:=self.buffer[f]; self.buffer_pos:=self.buffer_pos-11; end else res:=self.old_res; tsample[self.num_sample,sound_status.posicion_sonido]:=res; self.old_res:=res; if @self.additional_sound<>nil then self.additional_sound; end; procedure n2a03_update_sound_0; begin n2a03_0.sound_update; end; procedure n2a03_update_sound(index:byte); begin case index of 1:n2a03_1.sound_update; end; end; procedure n2a03_sound_advance(index:byte); begin case index of 0:n2a03_0.sound_advance; 1:n2a03_1.sound_advance; end; end; procedure n2a03_irq_call(index:byte); begin case index of 0:if n2a03_0.frame_irq then n2a03_0.m6502.change_irq(HOLD_LINE); 1:if n2a03_1.frame_irq then n2a03_1.m6502.change_irq(HOLD_LINE); end; end; end.
unit vulkan_win32; (* ** Copyright 2015-2021 The Khronos Group Inc. ** ** SPDX-License-Identifier: Apache-2.0 *) (* ** This header is generated from the Khronos Vulkan XML API Registry. ** *) interface //#################################################################### ■ uses LUX.Code.C, vulkan_core; const VK_KHR_win32_surface = 1; const VK_KHR_WIN32_SURFACE_SPEC_VERSION = 6; const VK_KHR_WIN32_SURFACE_EXTENSION_NAME = 'VK_KHR_win32_surface'; type P_VkWin32SurfaceCreateFlagsKHR = ^VkWin32SurfaceCreateFlagsKHR; VkWin32SurfaceCreateFlagsKHR = VkFlags; type P_VkWin32SurfaceCreateInfoKHR = ^VkWin32SurfaceCreateInfoKHR; VkWin32SurfaceCreateInfoKHR = record sType :VkStructureType; pNext :P_void; flags :VkWin32SurfaceCreateFlagsKHR; hinstance :T_HINSTANCE; hwnd :T_HWND; end; type PFN_vkCreateWin32SurfaceKHR = function( instance_:VkInstance; const pCreateInfo_:P_VkWin32SurfaceCreateInfoKHR; const pAllocator_:P_VkAllocationCallbacks; pSurface_:P_VkSurfaceKHR ) :VkResult; type PFN_vkGetPhysicalDeviceWin32PresentationSupportKHR = function( physicalDevice_:VkPhysicalDevice; queueFamilyIndex_:T_uint32_t ) :VkBool32; {$IFNDEF VK_NO_PROTOTYPES } function vkCreateWin32SurfaceKHR( instance_ :VkInstance; const pCreateInfo_ :P_VkWin32SurfaceCreateInfoKHR; const pAllocator_ :P_VkAllocationCallbacks; pSurface_ :P_VkSurfaceKHR ) :VkResult; stdcall; external DLLNAME; function vkGetPhysicalDeviceWin32PresentationSupportKHR( physicalDevice_ :VkPhysicalDevice; queueFamilyIndex_ :T_uint32_t ) :VkBool32; stdcall; external DLLNAME; {$ENDIF} const VK_KHR_external_memory_win32 = 1; const VK_KHR_EXTERNAL_MEMORY_WIN32_SPEC_VERSION = 1; const VK_KHR_EXTERNAL_MEMORY_WIN32_EXTENSION_NAME = 'VK_KHR_external_memory_win32'; type P_VkImportMemoryWin32HandleInfoKHR = ^VkImportMemoryWin32HandleInfoKHR; VkImportMemoryWin32HandleInfoKHR = record sType :VkStructureType; pNext :P_void; handleType :VkExternalMemoryHandleTypeFlagBits; handle :T_HANDLE; name :T_LPCWSTR; end; type P_VkExportMemoryWin32HandleInfoKHR = ^VkExportMemoryWin32HandleInfoKHR; VkExportMemoryWin32HandleInfoKHR = record sType :VkStructureType; pNext :P_void; pAttributes :P_SECURITY_ATTRIBUTES; dwAccess :T_DWORD; name :T_LPCWSTR; end; type P_VkMemoryWin32HandlePropertiesKHR = ^VkMemoryWin32HandlePropertiesKHR; VkMemoryWin32HandlePropertiesKHR = record sType :VkStructureType; pNext :P_void; memoryTypeBits :T_uint32_t; end; type P_VkMemoryGetWin32HandleInfoKHR = ^VkMemoryGetWin32HandleInfoKHR; VkMemoryGetWin32HandleInfoKHR = record sType :VkStructureType; pNext :P_void; memory :VkDeviceMemory; handleType :VkExternalMemoryHandleTypeFlagBits; end; type PFN_vkGetMemoryWin32HandleKHR = function( device_:VkDevice; const pGetWin32HandleInfo_:P_VkMemoryGetWin32HandleInfoKHR; pHandle_:P_HANDLE ) :VkResult; type PFN_vkGetMemoryWin32HandlePropertiesKHR = function( device_:VkDevice; handleType_:VkExternalMemoryHandleTypeFlagBits; handle_:T_HANDLE; pMemoryWin32HandleProperties_:P_VkMemoryWin32HandlePropertiesKHR ) :VkResult; {$IFNDEF VK_NO_PROTOTYPES } function vkGetMemoryWin32HandleKHR( device_ :VkDevice; const pGetWin32HandleInfo_ :P_VkMemoryGetWin32HandleInfoKHR; pHandle_ :P_HANDLE ) :VkResult; stdcall; external DLLNAME; function vkGetMemoryWin32HandlePropertiesKHR( device_ :VkDevice; handleType_ :VkExternalMemoryHandleTypeFlagBits; handle_ :T_HANDLE; pMemoryWin32HandleProperties_ :P_VkMemoryWin32HandlePropertiesKHR ) :VkResult; stdcall; external DLLNAME; {$ENDIF} const VK_KHR_win32_keyed_mutex = 1; const VK_KHR_WIN32_KEYED_MUTEX_SPEC_VERSION = 1; const VK_KHR_WIN32_KEYED_MUTEX_EXTENSION_NAME = 'VK_KHR_win32_keyed_mutex'; type P_VkWin32KeyedMutexAcquireReleaseInfoKHR = ^VkWin32KeyedMutexAcquireReleaseInfoKHR; VkWin32KeyedMutexAcquireReleaseInfoKHR = record sType :VkStructureType; pNext :P_void; acquireCount :T_uint32_t; pAcquireSyncs :P_VkDeviceMemory; pAcquireKeys :P_uint64_t; pAcquireTimeouts :P_uint32_t; releaseCount :T_uint32_t; pReleaseSyncs :P_VkDeviceMemory; pReleaseKeys :P_uint64_t; end; const VK_KHR_external_semaphore_win32 = 1; const VK_KHR_EXTERNAL_SEMAPHORE_WIN32_SPEC_VERSION = 1; const VK_KHR_EXTERNAL_SEMAPHORE_WIN32_EXTENSION_NAME = 'VK_KHR_external_semaphore_win32'; type P_VkImportSemaphoreWin32HandleInfoKHR = ^VkImportSemaphoreWin32HandleInfoKHR; VkImportSemaphoreWin32HandleInfoKHR = record sType :VkStructureType; pNext :P_void; semaphore :VkSemaphore; flags :VkSemaphoreImportFlags; handleType :VkExternalSemaphoreHandleTypeFlagBits; handle :T_HANDLE; name :T_LPCWSTR; end; type P_VkExportSemaphoreWin32HandleInfoKHR = ^VkExportSemaphoreWin32HandleInfoKHR; VkExportSemaphoreWin32HandleInfoKHR = record sType :VkStructureType; pNext :P_void; pAttributes :P_SECURITY_ATTRIBUTES; dwAccess :T_DWORD; name :T_LPCWSTR; end; type P_VkD3D12FenceSubmitInfoKHR = ^VkD3D12FenceSubmitInfoKHR; VkD3D12FenceSubmitInfoKHR = record sType :VkStructureType; pNext :P_void; waitSemaphoreValuesCount :T_uint32_t; pWaitSemaphoreValues :P_uint64_t; signalSemaphoreValuesCount :T_uint32_t; pSignalSemaphoreValues :P_uint64_t; end; type P_VkSemaphoreGetWin32HandleInfoKHR = ^VkSemaphoreGetWin32HandleInfoKHR; VkSemaphoreGetWin32HandleInfoKHR = record sType :VkStructureType; pNext :P_void; semaphore :VkSemaphore; handleType :VkExternalSemaphoreHandleTypeFlagBits; end; type PFN_vkImportSemaphoreWin32HandleKHR = function( device_:VkDevice; const pImportSemaphoreWin32HandleInfo_:P_VkImportSemaphoreWin32HandleInfoKHR ) :VkResult; type PFN_vkGetSemaphoreWin32HandleKHR = function( device_:VkDevice; const pGetWin32HandleInfo_:P_VkSemaphoreGetWin32HandleInfoKHR; pHandle_:P_HANDLE ) :VkResult; {$IFNDEF VK_NO_PROTOTYPES } function vkImportSemaphoreWin32HandleKHR( device_ :VkDevice; const pImportSemaphoreWin32HandleInfo_ :P_VkImportSemaphoreWin32HandleInfoKHR ) :VkResult; stdcall; external DLLNAME; function vkGetSemaphoreWin32HandleKHR( device_ :VkDevice; const pGetWin32HandleInfo_ :P_VkSemaphoreGetWin32HandleInfoKHR; pHandle_ :P_HANDLE ) :VkResult; stdcall; external DLLNAME; {$ENDIF} const VK_KHR_external_fence_win32 = 1; const VK_KHR_EXTERNAL_FENCE_WIN32_SPEC_VERSION = 1; const VK_KHR_EXTERNAL_FENCE_WIN32_EXTENSION_NAME = 'VK_KHR_external_fence_win32'; type P_VkImportFenceWin32HandleInfoKHR = ^VkImportFenceWin32HandleInfoKHR; VkImportFenceWin32HandleInfoKHR = record sType :VkStructureType; pNext :P_void; fence :VkFence; flags :VkFenceImportFlags; handleType :VkExternalFenceHandleTypeFlagBits; handle :T_HANDLE; name :T_LPCWSTR; end; type P_VkExportFenceWin32HandleInfoKHR = ^VkExportFenceWin32HandleInfoKHR; VkExportFenceWin32HandleInfoKHR = record sType :VkStructureType; pNext :P_void; pAttributes :P_SECURITY_ATTRIBUTES; dwAccess :T_DWORD; name :T_LPCWSTR; end; type P_VkFenceGetWin32HandleInfoKHR = ^VkFenceGetWin32HandleInfoKHR; VkFenceGetWin32HandleInfoKHR = record sType :VkStructureType; pNext :P_void; fence :VkFence; handleType :VkExternalFenceHandleTypeFlagBits; end; type PFN_vkImportFenceWin32HandleKHR = function( device_:VkDevice; const pImportFenceWin32HandleInfo_:P_VkImportFenceWin32HandleInfoKHR ) :VkResult; type PFN_vkGetFenceWin32HandleKHR = function( device_:VkDevice; const pGetWin32HandleInfo_:P_VkFenceGetWin32HandleInfoKHR; pHandle_:P_HANDLE ) :VkResult; {$IFNDEF VK_NO_PROTOTYPES } function vkImportFenceWin32HandleKHR( device_ :VkDevice; const pImportFenceWin32HandleInfo_ :P_VkImportFenceWin32HandleInfoKHR ) :VkResult; stdcall; external DLLNAME; function vkGetFenceWin32HandleKHR( device_ :VkDevice; const pGetWin32HandleInfo_ :P_VkFenceGetWin32HandleInfoKHR; pHandle_ :P_HANDLE ) :VkResult; stdcall; external DLLNAME; {$ENDIF} const VK_NV_external_memory_win32 = 1; const VK_NV_EXTERNAL_MEMORY_WIN32_SPEC_VERSION = 1; const VK_NV_EXTERNAL_MEMORY_WIN32_EXTENSION_NAME = 'VK_NV_external_memory_win32'; type P_VkImportMemoryWin32HandleInfoNV = ^VkImportMemoryWin32HandleInfoNV; VkImportMemoryWin32HandleInfoNV = record sType :VkStructureType; pNext :P_void; handleType :VkExternalMemoryHandleTypeFlagsNV; handle :T_HANDLE; end; type P_VkExportMemoryWin32HandleInfoNV = ^VkExportMemoryWin32HandleInfoNV; VkExportMemoryWin32HandleInfoNV = record sType :VkStructureType; pNext :P_void; pAttributes :P_SECURITY_ATTRIBUTES; dwAccess :T_DWORD; end; type PFN_vkGetMemoryWin32HandleNV = function( device_:VkDevice; memory_:VkDeviceMemory; handleType_:VkExternalMemoryHandleTypeFlagsNV; pHandle_:P_HANDLE ) :VkResult; {$IFNDEF VK_NO_PROTOTYPES } function vkGetMemoryWin32HandleNV( device_ :VkDevice; memory_ :VkDeviceMemory; handleType_ :VkExternalMemoryHandleTypeFlagsNV; pHandle_ :P_HANDLE ) :VkResult; stdcall; external DLLNAME; {$ENDIF} const VK_NV_win32_keyed_mutex = 1; const VK_NV_WIN32_KEYED_MUTEX_SPEC_VERSION = 2; const VK_NV_WIN32_KEYED_MUTEX_EXTENSION_NAME = 'VK_NV_win32_keyed_mutex'; type P_VkWin32KeyedMutexAcquireReleaseInfoNV = ^VkWin32KeyedMutexAcquireReleaseInfoNV; VkWin32KeyedMutexAcquireReleaseInfoNV = record sType :VkStructureType; pNext :P_void; acquireCount :T_uint32_t; pAcquireSyncs :P_VkDeviceMemory; pAcquireKeys :P_uint64_t; pAcquireTimeoutMilliseconds :P_uint32_t; releaseCount :T_uint32_t; pReleaseSyncs :P_VkDeviceMemory; pReleaseKeys :P_uint64_t; end; const VK_EXT_full_screen_exclusive = 1; const VK_EXT_FULL_SCREEN_EXCLUSIVE_SPEC_VERSION = 4; const VK_EXT_FULL_SCREEN_EXCLUSIVE_EXTENSION_NAME = 'VK_EXT_full_screen_exclusive'; type VkFullScreenExclusiveEXT = ( VK_FULL_SCREEN_EXCLUSIVE_DEFAULT_EXT = 0, VK_FULL_SCREEN_EXCLUSIVE_ALLOWED_EXT = 1, VK_FULL_SCREEN_EXCLUSIVE_DISALLOWED_EXT = 2, VK_FULL_SCREEN_EXCLUSIVE_APPLICATION_CONTROLLED_EXT = 3, VK_FULL_SCREEN_EXCLUSIVE_MAX_ENUM_EXT = $7FFFFFFF ); type P_VkSurfaceFullScreenExclusiveInfoEXT = ^VkSurfaceFullScreenExclusiveInfoEXT; VkSurfaceFullScreenExclusiveInfoEXT = record sType :VkStructureType; pNext :P_void; fullScreenExclusive :VkFullScreenExclusiveEXT; end; type P_VkSurfaceCapabilitiesFullScreenExclusiveEXT = ^VkSurfaceCapabilitiesFullScreenExclusiveEXT; VkSurfaceCapabilitiesFullScreenExclusiveEXT = record sType :VkStructureType; pNext :P_void; fullScreenExclusiveSupported :VkBool32; end; type P_VkSurfaceFullScreenExclusiveWin32InfoEXT = ^VkSurfaceFullScreenExclusiveWin32InfoEXT; VkSurfaceFullScreenExclusiveWin32InfoEXT = record sType :VkStructureType; pNext :P_void; hmonitor :T_HMONITOR; end; type PFN_vkGetPhysicalDeviceSurfacePresentModes2EXT = function( physicalDevice_:VkPhysicalDevice; const pSurfaceInfo_:P_VkPhysicalDeviceSurfaceInfo2KHR; pPresentModeCount_:P_uint32_t; pPresentModes_:P_VkPresentModeKHR ) :VkResult; type PFN_vkAcquireFullScreenExclusiveModeEXT = function( device_:VkDevice; swapchain_:VkSwapchainKHR ) :VkResult; type PFN_vkReleaseFullScreenExclusiveModeEXT = function( device_:VkDevice; swapchain_:VkSwapchainKHR ) :VkResult; type PFN_vkGetDeviceGroupSurfacePresentModes2EXT = function( device_:VkDevice; const pSurfaceInfo_:P_VkPhysicalDeviceSurfaceInfo2KHR; pModes_:P_VkDeviceGroupPresentModeFlagsKHR ) :VkResult; {$IFNDEF VK_NO_PROTOTYPES } function vkGetPhysicalDeviceSurfacePresentModes2EXT( physicalDevice_ :VkPhysicalDevice; const pSurfaceInfo_ :P_VkPhysicalDeviceSurfaceInfo2KHR; pPresentModeCount_ :P_uint32_t; pPresentModes_ :P_VkPresentModeKHR ) :VkResult; stdcall; external DLLNAME; function vkAcquireFullScreenExclusiveModeEXT( device_ :VkDevice; swapchain_ :VkSwapchainKHR ) :VkResult; stdcall; external DLLNAME; function vkReleaseFullScreenExclusiveModeEXT( device_ :VkDevice; swapchain_ :VkSwapchainKHR ) :VkResult; stdcall; external DLLNAME; function vkGetDeviceGroupSurfacePresentModes2EXT( device_ :VkDevice; const pSurfaceInfo_ :P_VkPhysicalDeviceSurfaceInfo2KHR; pModes_ :P_VkDeviceGroupPresentModeFlagsKHR ) :VkResult; stdcall; external DLLNAME; {$ENDIF} implementation //############################################################### ■ end. //######################################################################### ■
unit alcuChangeDateDlg; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, alcuMsgDlg, StdCtrls, ComCtrls; type TalcuChangeDateDialog = class(TForm) Button1: TButton; Button2: TButton; dtFrom: TDateTimePicker; dtTo: TDateTimePicker; Label1: TLabel; Label2: TLabel; lblTaskCaption: TLabel; public function Execute(const aCaption: String; const aFromDate: TDateTime; out aToDate: TDateTime): Boolean; end; var alcuChangeDateDialog: TalcuChangeDateDialog; implementation {$R *.dfm} { TForm1 } { **************************** TalcuChangeDateDialog ***************************** } function TalcuChangeDateDialog.Execute(const aCaption: String; const aFromDate: TDateTime; out aToDate: TDateTime): Boolean; begin lblTaskCaption.Caption:= aCaption; dtFrom.Date:= aFromDate; dtTo.Date:= aFromDate; if ShowModal = mrOk then begin Result:= true; aToDate:= dtTo.date; end else begin Result:= False; aToDate:= aFromDate; end end; end.
{ Типы. } unit uTypes; interface uses OpenGL, uGlobal; type PPoint3f = ^TPoint3f; TPoint3f = record x,y,z:single; end; PPoint2f = ^TPoint2f; TPoint2f = record x,z:Single; end; PVector3f = ^TVector3f; {TVector3f = record nx,ny,nz:single; end;} PVector2f = ^TVector2f; TVector2f = record x,z : Single; end; PVectorA2f = ^TVectorA2f; TVectorA2f = record ang : GLfloat; v : GLfloat; end; TRect4f = record x1,z1,x2,z2:GLfloat; end; TVector3f=record x:glfloat; y:glfloat; z:glfloat; end; rTriangle=record V:array [0..2] of TVector3f; end; procedure Normalize3f (var a:TVector3f); function Distance3f(P1,P2:TPoint3f) :glfloat; procedure GenVector(xang : PGLfloat; vec : PVector2f); procedure NormalizeVector(vec : PVector2f); function lineln(d1,d2:PPoint2f):GLfloat; function AngbPoints(x0,y0,x1,y1:GLfloat):GLfloat; procedure vGen3fv(dest:PPoint3f; src : Pointer); function cwCos(a:GLfloat):GLfloat; function cwSin(a:GLfloat):GLfloat; function FPSsynSpeed(mps : GLfloat):GLfloat; function Signf(n:Single):Shortint; function KphToFPS(kph : GLfloat):GLfloat; function Chetvert(var ang : GLfloat):Byte; function DoTheNormal(A, B, C : TVector3f):TVector3f; implementation procedure Normalize3f(var a:TVector3f); var d:glfloat; begin d:=sqrt(sqr(a.x)+sqr(a.y)+sqr(a.z)); if d = 0 then d :=1; a.x:=a.x/d; a.y:=a.y/d; a.z:=a.z/d; end; function DoTheNormal(A, B, C : TVector3f):TVector3f; var vx1,vy1,vz1,vx2,vy2,vz2:GLfloat; begin { vx1 = A.x - B.x vy1 = A.y - B.y vz1 = A.z - B.z vx2 = B.x - C.x vy2 = B.y - C.y vz2 = B.z - C.z Пусть координаты интересующего нас вектора (ну он же нормаль) будут N.x, N.y и N.z, тогда их можно посчитать так: N.x = (vy1 * vz2 - vz1 * vy2) N.y = (vz1 * vx2 - vx1 * vz2) N.z = (vx1 * vy2 - vy1 * vx2) } vx1 := A.x - B.x; vy1 := A.y - B.y; vz1 := A.z - B.z; vx2 := B.x - C.x; vy2 := B.y - C.y; vz2 := B.z - C.z; Result.x := vy1 * vz2 - vz1 * vy2; Result.y := vz1 * vx2 - vx1 * vz2; Result.z := vx1 * vy2 - vy1 * vx2; Normalize3f(Result); end; function Distance3f(P1,P2:TPoint3f):GLfloat; begin Result := sqrt(sqr(P2.x-P1.x)+sqr(p2.y-p1.y)+sqr(p2.z-p1.z)); end; function Chetvert(var ang : GLfloat):Byte; begin Result := 1; if ang<0 then ang := 360+ang; if ang>360 then ang := 0; if (ang>=0) and (ang<90) then Result := 1; if (ang>=90) and (ang<180) then Result := 2; if (ang>=180)and (ang<270) then Result := 3; if (ang>=270)and(ang<=360) then Result := 4; end; function Signf(n:Single):Shortint; begin if n=0 then Result := 1 else Result := Trunc(n) div abs(Trunc(n)); end; function FPSsynSpeed(mps : GLfloat):GLfloat; begin Result := mps/64; end; function KphToFPS(kph : GLfloat):GLfloat; var a:GLfloat; begin a := ((kph*1000)/60/60)/64; Result :=a; end; procedure vGen3fv(dest:PPoint3f; src : Pointer); begin dest^ := TPoint3f(src^); end; function cwSin(a:GLfloat):GLfloat; begin Result := Sin(a/RAD); end; function cwCos(a:GLfloat):GLfloat; begin Result := Cos(a/RAD); end; function Squer(x:GLfloat):GLfloat; begin Result := x*x; end; procedure GenVector(xang : PGLfloat; vec : PVector2f); begin vec^.x := sin(xang^/(180/pi)); vec^.z := cos(xang^/(180/pi)); end; procedure NormalizeVector(vec : PVector2f); var n:single; begin n := sqrt(sqr(vec.x)+sqr(vec.z)); vec.x := vec.x/n; vec.z := vec.z/n; end; function lineln(d1,d2:PPoint2f):GLfloat; begin Result := Sqrt(squer(d2^.x-d1^.x)+squer(d2.z-d1.z)); end; function AngbPoints(x0,y0,x1,y1:GLfloat):GLfloat; var a:glfloat; begin x1 := x1-x0; y1 := y1-y0; if(x1=0)then begin if y1>0 then a:=90; if y1<0 then a:=270; end else begin a := (y1/x1); a := abs(arctan(a))*(180/pi); end; if (x1<0)and(y1>0)then a:=180-a; if (x1<0)and(y1<0)then a:=180+a; if (x1>0)and(y1<0)then a:=360-a; Result := a; end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clRegex; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, {$IFDEF DELPHIXE} RegularExpressions {$ELSE} clPCRE, clWUtils{$ENDIF}; {$ELSE} System.Classes, {$IFDEF DELPHIXE} System.RegularExpressions {$ELSE} clPCRE{$ENDIF}; {$ENDIF} type TclRegExOption = (rxoNone, rxoIgnoreCase, rxoMultiLine); TclRegExOptions = set of TclRegExOption; TclRegEx = class private {$IFDEF DELPHIXE} class function GetOptions(AOpts: TclRegExOptions): TRegExOptions; {$ELSE} class function GetOptions(AOpts: TclRegExOptions): Integer; {$ENDIF} public class function IsMatch(const AText, ARegEx: string; AOpts: TclRegExOptions): Boolean; class function ExactMatch(const AText, ARegEx: string; AOpts: TclRegExOptions): Boolean; class function Escape(const Str: string): string; end; implementation { TclRegEx } {$IFDEF DELPHIXE} class function TclRegEx.GetOptions(AOpts: TclRegExOptions): TRegExOptions; begin Result := []; if (rxoIgnoreCase in AOpts) then begin Result := Result + [roIgnoreCase]; end; if (rxoMultiLine in AOpts) then begin Result := Result + [roMultiLine]; end; end; {$ELSE} class function TclRegEx.GetOptions(AOpts: TclRegExOptions): Integer; begin Result := 0; if (rxoIgnoreCase in AOpts) then begin Result := Result + PCRE_CASELESS; end; if (rxoMultiLine in AOpts) then begin Result := Result + PCRE_MULTILINE; end; end; {$ENDIF} class function TclRegEx.ExactMatch(const AText, ARegEx: string; AOpts: TclRegExOptions): Boolean; {$IFDEF DELPHIXE} var match: TMatch; begin match := TRegEx.Match(AText, ARegEx, GetOptions(AOpts)); Result := match.Success and (match.Index = 1) and (match.Length = Length(AText)); end; {$ELSE} var RE: TPCRE; begin RE := TPCRE.Create(False, GetOptions(AOpts)); try Result := RE.Match(PclChar(GetTclString(ARegEx)), PclChar(GetTclString(AText))); Result := Result and (RE.MatchCount > 0) and (RE.MatchOffset[0] = 0) and (RE.MatchLength[0] = Length(AText)) finally RE.Free(); end; end; {$ENDIF} class function TclRegEx.IsMatch(const AText, ARegEx: string; AOpts: TclRegExOptions): Boolean; begin {$IFDEF DELPHIXE} Result := TRegEx.IsMatch(AText, ARegEx, GetOptions(AOpts)); {$ELSE} Result := RE_Match(AText, ARegEx, GetOptions(AOpts)); {$ENDIF} end; class function TclRegEx.Escape(const Str: string): string; begin {$IFDEF DELPHIXE} Result := TRegEx.Escape(Str); {$ELSE} Result := EscRegex(Str); {$ENDIF} end; end.
unit Icons; // Copyright (c) 1996 Jorge Romero Gomez, Merchise. interface uses Windows, SysUtils, ShellAPI; function GetIconFromPathIndx( const PathIndx : string ) : HICON; function GetSmallIconFromFile( const FileName : string ) : HICON; function GetSmallIconFromResource( const ResName : string ) : HICON; function GetLargeIconFromFile( const FileName : string ) : HICON; function GetLargeIconFromResource( const ResName : string ) : HICON; // procedure GetSmallIconSize( var Width, Height : integer ); procedure GetLargeIconSize( var Width, Height : integer ); implementation uses StrUtils; procedure GetSmallIconSize( var Width, Height : integer ); begin Width := GetSystemMetrics( SM_CXSMICON ); Height := GetSystemMetrics( SM_CYSMICON ); end; procedure GetLargeIconSize( var Width, Height : integer ); begin Width := GetSystemMetrics( SM_CXICON ); Height := GetSystemMetrics( SM_CYICON ); end; // function GetIconFromPathIndx( const PathIndx : string ) : HICON; var Pos : integer; Indx : integer; hInst : integer; begin if (PathIndx <> '%1') and (PathIndx <> '') then try Pos := BackPos( ',', PathIndx, 0 ); if Pos <> 0 then begin try Indx := StrToInt( RightStr( PathIndx, Length(PathIndx) - Pos )); except Indx := 0; end; if Indx < 0 then begin hInst := LoadLibrary( pchar(copy( PathIndx, 1, Pos - 1 )) ); if hInst <> 0 then begin Result := LoadIcon( hInst, MAKEINTRESOURCE( -Indx ) ); FreeLibrary( hInst ); end else Result := 0; end else Result := ExtractIcon( hInstance, pchar(copy( PathIndx, 1, Pos - 1 )), Indx ); end else Result := ExtractIcon( hInstance, pchar(PathIndx), 0 ); except Result := 0; end else Result := 0; end; // function GetSmallIconFromFile( const FileName : string ) : HICON; var Width, Height : integer; begin GetSmallIconSize( Width, Height ); Result := LoadImage( hInstance, pchar(FileName), IMAGE_ICON, Width, Height, LR_DEFAULTCOLOR or LR_LOADFROMFILE ); end; function GetSmallIconFromResource( const ResName : string ) : HICON; var Width, Height : integer; begin GetSmallIconSize( Width, Height ); Result := LoadImage( hInstance, pchar(ResName), IMAGE_ICON, Width, Height, LR_DEFAULTCOLOR ); end; function GetLargeIconFromFile( const FileName : string ) : HICON; var Width, Height : integer; begin GetLargeIconSize( Width, Height ); Result := LoadImage( hInstance, pchar(FileName), IMAGE_ICON, Width, Height, LR_DEFAULTCOLOR or LR_LOADFROMFILE); end; function GetLargeIconFromResource( const ResName : string ) : HICON; var Width, Height : integer; begin GetLargeIconSize( Width, Height ); Result := LoadImage( hInstance, pchar(ResName), IMAGE_ICON, Width, Height, LR_DEFAULTCOLOR ); end; end.
unit DAO.Parametros; interface uses FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Model.Parametros, Control.Sistema; type TParametrosDAO = class private FConexao : TConexao; public constructor Create; function Inserir(AParametros: TParametros): Boolean; function Alterar(AParametros: TParametros): Boolean; function Excluir(AParametros: TParametros): Boolean; function Pesquisar(aParam: array of variant): TFDQuery; end; const TABLENAME = 'financeiro_parametros'; implementation { TParametrosDAO } function TParametrosDAO.Alterar(AParametros: TParametros): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('UPDATE ' + TABLENAME + 'SET num_quinzena = :num_quinzena, dia_inicio_quinzena = :dia_inicio_quinzena, ' + 'dia_final_quinzena = :dia_final_quinzena, qtd_raio_x = :qtd_raio_x ' + 'WHERE id_parametro = :id_parametro;', [AParametros.Quinzena, AParametros.DiaInicio, AParametros.DiaFinal, AParametros.RaioX, AParametros.ID]); Result := True; finally FDQuery.Free; end; end; constructor TParametrosDAO.Create; begin FConexao := TSistemaControl.GetInstance().Conexao; end; function TParametrosDAO.Excluir(AParametros: TParametros): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('delete from ' + TABLENAME + ' where WHERE id_parametro = :id_parametro', [AParametros.ID]); Result := True; finally FDquery.Free; end; end; function TParametrosDAO.Inserir(AParametros: TParametros): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('insert into ' + TABLENAME + '(id_parametro, num_quinzena, dia_inicio_quinzena, dia_final_quinzena, ' + 'qtd_raio_x) ' + 'values ' + '(:id_parametro, :num_quinzena, :, :dia_final_quinzena, :qtd_raio_x);', [AParametros.Quinzena, AParametros.DiaInicio, AParametros.DiaFinal, AParametros.RaioX]); Result := True; finally FDQuery.Free; end; end; function TParametrosDAO.Pesquisar(aParam: array of variant): TFDQuery; var FDQuery: TFDQuery; begin FDQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FDQuery.SQL.Clear; FDQuery.SQL.Add('select * from ' + TABLENAME); if aParam[0] = 'ID' then begin FDQuery.SQL.Add('WHERE id_parametro = :id_parametro'); FDQuery.ParamByName('id_parametro').AsInteger := aParam[1]; end; if aParam[0] = 'QUINZENA' then begin FDQuery.SQL.Add('WHERE num_quinzena = :num_quinzena'); FDQuery.ParamByName('num_quinzena').AsInteger := aParam[1]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('WHERE ' + aParam[1]); end; if aParam[0] = 'APOIO' then begin FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT ' + aParam[1] + ' FROM ' + TABLENAME + ' ' + aParam[2]); end; FDQuery.Open; Result := FDQuery; end; end.
unit DW.Androidapi.JNI.LocalBroadcastManager; {*******************************************************} { } { Kastri Free } { } { DelphiWorlds Cross-Platform Library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface uses // Android Androidapi.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.GraphicsContentViewText; type JLocalBroadcastManager = interface; JLocalBroadcastManagerClass = interface(JObjectClass) ['{5CCF81B2-E170-47C4-873E-32E644085880}'] {class} function getInstance(context: JContext): JLocalBroadcastManager; cdecl; end; [JavaSignature('android/support/v4/content/LocalBroadcastManager')] JLocalBroadcastManager = interface(JObject) ['{B5D9B2DA-E150-4CC5-BBDA-58FCD42C6C1E}'] procedure registerReceiver(receiver: JBroadcastReceiver; filter: JIntentFilter); cdecl; function sendBroadcast(intent: JIntent): Boolean; cdecl; procedure sendBroadcastSync(intent: JIntent); cdecl; procedure unregisterReceiver(receiver: JBroadcastReceiver); cdecl; end; TJLocalBroadcastManager = class(TJavaGenericImport<JLocalBroadcastManagerClass, JLocalBroadcastManager>) end; implementation end.
{ Subroutine SST_SET_ELE_FIND (VAL,ELE,P,MASK) * * Find the bit representing a particular set element in the constant descriptor * for a set value. The calling program can then easily read or write the bit. * * VAL - Constant value descriptor. It is an error if its data type * is not SET. * * ELE - The element number within the set. Elements are numbered from 0 to * (number of elements - 1). * * P - Returned pointing to the integer word containing the particular * requested set bit. * * MASK - Returned mask word that selects only the particular set element * bit. All bits are zero, except for the bit corresponding to the set * element in P^. } module sst_SET_ELE_FIND; define sst_set_ele_find; %include 'sst2.ins.pas'; procedure sst_set_ele_find ( {get handle to bit for particular set element} in val: sst_var_value_t; {constant set expression value descriptor} in ele: sys_int_machine_t; {set element number, 0 - N_ELE-1} out p: sys_int_conv32_p_t; {points to word containing set element} out mask: sys_int_conv32_t); {mask word for this set element bit} const max_msg_parms = 2; {max parameters we can pass to a message} var dt_p: sst_dtype_p_t; {points to base data type descriptor of set} ind: sys_int_machine_t; {set elements array index for word with ele} bit: sys_int_machine_t; {number of element bit within its word} msg_parm: {references parameters for messages} array[1..max_msg_parms] of sys_parm_msg_t; begin if val.dtype <> sst_dtype_set_k then begin {value descriptor is not for a set ?} sys_message_bomb ('sst', 'value_not_a_set', nil, 0); end; dt_p := val.set_dtype_p; {init pointer to base data type descriptor} while dt_p^.dtype = sst_dtype_copy_k do begin {resolve copied data type} dt_p := dt_p^.copy_dtype_p; end; if (ele < 0) or (ele >= dt_p^.bits_min) then begin {ELE out of range ?} sys_msg_parm_int (msg_parm[1], ele); sys_msg_parm_int (msg_parm[2], dt_p^.bits_min-1); sys_message_bomb ('sst', 'set_ele_out_of_range', msg_parm, 2); end; ind := ele div sst_set_ele_per_word; {find which word the element bit is in} bit := ele - (sst_set_ele_per_word * ind); {number of bit within word} ind := dt_p^.set_n_ent - 1 - ind; {make array index for this word} p := addr(val.set_val_p^[ind]); {make pointer to word containing ele bit} mask := lshft(1, bit); {make mask for this element bit} end;
unit ExtAIMaster; interface uses Classes, Windows, Math, System.SysUtils, Generics.Collections, ExtAI_DLLs, ExtAINetServer, ExtAIInfo, KM_CommonTypes, ExtAILog; type // Manages external AI (list of available AIs and communication) TExtAIMaster = class private fNetServer: TExtAINetServer; fExtAIs: TObjectList<TExtAIInfo>; fDLLs: TExtAIDLLs; fIDCounter: Word; // Callbacks fOnAIConnect: TExtAIStatusEvent; fOnAIConfigured: TExtAIStatusEvent; fOnAIDisconnect: TExtAIStatusEvent; procedure ConnectExtAIWithID(aServerClient: TExtAIServerClient; aID: Word); procedure DisconnectClient(aServerClient: TExtAIServerClient); function CreateNewExtAI(aID: Word; aServerClient: TExtAIServerClient): TExtAIInfo; procedure ConfiguredExtAI(aExtAIInfo: TExtAIInfo); function GetExtAI(aID: Word): TExtAIInfo; overload; function GetExtAI(aServerClient: TExtAIServerClient): TExtAIInfo; overload; public constructor Create(aDLLPaths: TStringList = nil); destructor Destroy; override; property OnAIConnect: TExtAIStatusEvent write fOnAIConnect; property OnAIConfigured: TExtAIStatusEvent write fOnAIConfigured; property OnAIDisconnect: TExtAIStatusEvent write fOnAIDisconnect; property Net: TExtAINetServer read fNetServer; property AIs: TObjectList<TExtAIInfo> read fExtAIs; property DLLs: TExtAIDLLs read fDLLs; procedure UpdateState(); function GetExtAIClientNames(): TStringArray; function GetExtAIDLLNames(): TStringArray; function GetNewID(): Word; function ConnectNewExtAI(aIdxDLL: Word): Word; end; implementation { TExtAIMaster } constructor TExtAIMaster.Create(aDLLPaths: TStringList = nil); begin fIDCounter := 0; fNetServer := TExtAINetServer.Create(); fExtAIs := TObjectList<TExtAIInfo>.Create(); fDLLs := TExtAIDLLs.Create(aDLLPaths); fNetServer.OnStatusMessage := gLog.Log; fNetServer.OnClientConnect := nil; // Ignore incoming client untill we receive config fNetServer.OnClientNewID := ConnectExtAIWithID; fNetServer.OnClientDisconnect := DisconnectClient; end; destructor TExtAIMaster.Destroy(); begin fNetServer.Free; fExtAIs.Free; fDLLs.Free; Inherited; end; function TExtAIMaster.GetNewID(): Word; begin Inc(fIDCounter); Result := fIDCounter; end; procedure TExtAIMaster.ConnectExtAIWithID(aServerClient: TExtAIServerClient; aID: Word); var ExtAI: TExtAIInfo; begin // Try to find AI according to ID (DLL creates class of ExtAI before the AI is connected) ExtAI := GetExtAI(aID); if (ExtAI <> nil) then ExtAI.ServerClient := aServerClient // Try to find AI according to pointer to client class else begin ExtAI := GetExtAI(aServerClient); // AI was not found -> create new TExtAIInfo class if (ExtAI = nil) then CreateNewExtAI(aID, aServerClient); end; if Assigned(fOnAIConnect) then fOnAIConnect(ExtAI); end; procedure TExtAIMaster.ConfiguredExtAI(aExtAIInfo: TExtAIInfo); begin if Assigned(fOnAIConfigured) then fOnAIConfigured(aExtAIInfo); fIDCounter := Max(fIDCounter+1,aExtAIInfo.ID); end; function TExtAIMaster.ConnectNewExtAI(aIdxDLL: Word): Word; begin Result := GetNewID(); CreateNewExtAI(Result, nil); DLLs[aIdxDLL].CreateNewExtAI(Result, Net.Server.Socket.PortNum, '127.0.0.1');// DLLs use localhost end; procedure TExtAIMaster.DisconnectClient(aServerClient: TExtAIServerClient); var ExtAI: TExtAIInfo; begin //{ ExtAI := GetExtAI(aServerClient); if (ExtAI <> nil)then begin if Assigned(fOnAIDisconnect) then fOnAIDisconnect(ExtAI); ExtAI.ServerClient := nil; //fExtAIs.Remove(ExtAI); // Remove and free the object (TObjectList) end; //} end; function TExtAIMaster.CreateNewExtAI(aID: Word; aServerClient: TExtAIServerClient): TExtAIInfo; begin Result := TExtAIInfo.Create(aID, aServerClient); Result.OnAIConfigured := ConfiguredExtAI; fExtAIs.Add(Result); end; function TExtAIMaster.GetExtAI(aID: Word): TExtAIInfo; var K: Integer; begin Result := nil; for K := 0 to fExtAIs.Count - 1 do if (fExtAIs[K].ID = aID) then Exit(fExtAIs[K]); end; function TExtAIMaster.GetExtAI(aServerClient: TExtAIServerClient): TExtAIInfo; var K: Integer; begin Result := nil; for K := 0 to fExtAIs.Count-1 do if (fExtAIs[K].ServerClient = aServerClient) then Exit(fExtAIs[K]); end; procedure TExtAIMaster.UpdateState(); begin if (fNetServer <> nil) AND (fNetServer.Listening) then fNetServer.UpdateState(); end; // Get names of connected clients function TExtAIMaster.GetExtAIClientNames(): TStringArray; var K, Cnt: Integer; begin Cnt := 0; SetLength(Result, fExtAIs.Count); for K := 0 to fExtAIs.Count-1 do if AIs[K].ReadyForGame then begin Result[Cnt] := AIs[K].Name; Cnt := Cnt + 1; end; SetLength(Result, Cnt); end; // Get name of available DLLs (DLL can generate infinite amount of ExtAIs) function TExtAIMaster.GetExtAIDLLNames(): TStringArray; var K: Integer; begin SetLength(Result, fDLLs.Count); for K := 0 to fDLLs.Count-1 do Result[K] := fDLLs[K].Name; end; end.
{ Subroutine SST_W_C_ARG (ARG_P, ARGT_P, DONE) * * Write a call argument in a subroutine or function call. ARG_P is pointing * to the calling argument descriptor, and ARGT_P is pointing to the argument * template descriptor. Both will be advanced to the next argument upon return. * There are no more arguments when both ARG_P and ARGT_P are returned NIL. } module sst_w_c_ARG; define sst_w_c_arg; %include 'sst_w_c.ins.pas'; var star: string_var4_t := {"*" pointer data type operator} [str := '*', len := 1, max := sizeof(star.str)]; procedure sst_w_c_arg ( {write argument in function/subroutine call} in out arg_p: sst_proc_arg_p_t; {points to arg descriptor, will be advanced} in out argt_p: sst_proc_arg_p_t); {points to arg template, will be advanced} const max_msg_parms = 1; {max parameters we can pass to a message} var at_p: sst_proc_arg_p_t; {points to descriptor to use as the template} ac_p: sst_proc_arg_p_t; {points to descriptor to for actual call} dt_force_p: sst_dtype_p_t; {points to dtype to force arg into} dt_temp_p: sst_dtype_p_t; {base data type of argument template} dt_arg_p: sst_dtype_p_t; {base data type of argument} dt_p: sst_dtype_p_t; {scratch data type pointer} exp_p: sst_exp_p_t; {pointer to argument value expression} adr_cnt: sys_int_machine_t; {number of times to take "address of" arg} enc: enclose_k_t; {enclose in parentheses yes/no flag} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; label done_univ; begin enc := enclose_no_k; {init to don't need to enclose arg in ()} if argt_p = nil {arg template descriptor exists ?} then at_p := arg_p {no it doesn't, use arg as template} else at_p := argt_p; {yes it does, use the template as template} if arg_p = nil {call descriptor exists ?} then ac_p := argt_p {no it doesn't, use template} else ac_p := arg_p; {yes it does, use ARG_P directly} exp_p := ac_p^.exp_p; {get pointer to argument value expression} dt_temp_p := at_p^.dtype_p; {init template data type} while dt_temp_p^.dtype = sst_dtype_copy_k {resolve base template data type} do dt_temp_p := dt_temp_p^.copy_dtype_p; dt_arg_p := ac_p^.dtype_p; {init argument data type} while dt_arg_p^.dtype = sst_dtype_copy_k {resolve base argument data type} do dt_arg_p := dt_arg_p^.copy_dtype_p; case at_p^.pass of {what is argument passing method ?} sst_pass_ref_k: begin {argument is passed by reference} adr_cnt := 1; end; sst_pass_val_k: begin {argument is passed by value} adr_cnt := 0; end; otherwise sys_msg_parm_int (msg_parm[1], ord(ac_p^.pass)); sys_message_bomb ('sst_c_write', 'ac_pass_method_bad', msg_parm, 1); end; dt_force_p := dt_temp_p; {init to force arg to be template data type} if (at_p^.univ or ( {allowed to match any data type ?} (dt_temp_p^.dtype = sst_dtype_pnt_k) and {allowed to match any pointer ?} (dt_temp_p^.pnt_dtype_p = nil))) and (exp_p^.dtype_hard or {argument data type is absolutely certain ?} not sst_dtype_convertable(dt_arg_p^, dt_temp_p^)) {arg can't be converted ?} then begin dt_force_p := nil; {don't try to alter argument data type} if {passing CHAR to a STRING ?} (dt_temp_p^.dtype = sst_dtype_array_k) and dt_temp_p^.ar_string and (dt_arg_p^.dtype = sst_dtype_char_k) then begin goto done_univ; {no need for type casting function} end; if dt_arg_p <> dt_temp_p then begin {argument doesn't match template data type ?} sst_w.appendn^ ('(', 1); {start of type casting operator} if dt_temp_p^.dtype = sst_dtype_array_k then begin {we are passing a UNIV array by reference} if dt_temp_p^.ar_dtype_rem_p = nil {resolve data type of array elements} then dt_p := dt_temp_p^.ar_dtype_ele_p else dt_p := dt_temp_p^.ar_dtype_rem_p; sst_w_c_dtype_simple (dt_p^, star, false); {write array elements data type} end else begin {we are passing a UNIV non-array by reference} sst_w_c_dtype_simple (at_p^.dtype_p^, star, false); {write target dtype} end ; sst_w.appendn^ (')', 1); {done writing type casting operator} enc := enclose_yes_k; {arg must now be enclosed in () if not simple} end; end; {done handling data type issues} done_univ: {done handling UNIV argument template} if {template data type is UNIVERSAL POINTER ?} (dt_temp_p^.dtype = sst_dtype_pnt_k) and (dt_temp_p^.pnt_dtype_p = nil) then begin dt_force_p := nil; {don't force argument's data type to match} end; if sst_rwflag_write_k in at_p^.rwflag_ext then begin {value being passed back ?} dt_force_p := nil; {don't force expression data type to match} end; sst_w_c_armode_push {array names will act like pointers to array} (array_pnt_whole_k); sst_w_c_exp ( {write this argument value} exp_p^, {argument value expression} adr_cnt, {number of times to take "address of"} dt_force_p, {pointer to mandatory expression data type} enc); {enclose in parentheses yes/no flag} sst_w_c_armode_pop; if arg_p <> nil {advance to next call argument descriptor} then arg_p := arg_p^.next_p; if argt_p <> nil {advance to next argument template} then argt_p := argt_p^.next_p; end;
unit TrackingActionsUnit; interface uses SysUtils, BaseActionUnit, DataObjectUnit, GPSParametersUnit, EnumsUnit, GenericParametersUnit, TrackingHistoryUnit, TrackingHistoryResponseUnit, TrackingDataUnit; type TTrackingActions = class(TBaseAction) public function GetLastLocation(RouteId: String; out ErrorString: String): TDataObjectRoute; function GetLocationHistory(RouteId: String; Period: TPeriod; LastPositionOnly: boolean; out ErrorString: String): TTrackingHistoryResponse; overload; function GetLocationHistory(RouteId: String; StartDate, EndDate: TDateTime; LastPositionOnly: boolean; out ErrorString: String): TTrackingHistoryResponse; overload; function GetAssetTrackingData(TrackingNumber: String; out ErrorString: String): TTrackingData; procedure SetGPS(Parameters: TGPSParameters; out ErrorString: String); end; implementation uses SettingsUnit, StatusResponseUnit, TrackingHistoryRequestUnit, UtilsUnit; function TTrackingActions.GetAssetTrackingData(TrackingNumber: String; out ErrorString: String): TTrackingData; var Parameters: TGenericParameters; begin Parameters := TGenericParameters.Create; try Parameters.AddParameter('tracking', TrackingNumber); Result := FConnection.Get(TSettings.EndPoints.TrackingStatus, Parameters, TTrackingData, ErrorString) as TTrackingData; finally FreeAndNil(Parameters); end; end; function TTrackingActions.GetLastLocation(RouteId: String; out ErrorString: String): TDataObjectRoute; var Parameters: TGenericParameters; begin Parameters := TGenericParameters.Create; try Parameters.AddParameter('route_id', RouteId); Parameters.AddParameter('device_tracking_history', '1'); Result := FConnection.Get(TSettings.EndPoints.Route, Parameters, TDataObjectRoute, ErrorString) as TDataObjectRoute; finally FreeAndNil(Parameters); end; end; function TTrackingActions.GetLocationHistory(RouteId: String; Period: TPeriod; LastPositionOnly: boolean; out ErrorString: String): TTrackingHistoryResponse; var Parameters: TTrackingHistoryRequest; begin Parameters := TTrackingHistoryRequest.Create(RouteId); try Parameters.TimePeriod := TPeriodDescription[Period]; Parameters.LastPosition := LastPositionOnly; Parameters.Format := 'json'; Result := FConnection.Get(TSettings.EndPoints.GetDeviceLocation, Parameters, TTrackingHistoryResponse, ErrorString) as TTrackingHistoryResponse; if (Result <> nil) and (ErrorString = EmptyStr) and (Length(Result.TrackingHistories) = 0) and (Result.Mmd = nil) then begin FreeAndNil(Result); ErrorString := 'GetLocationHistory was failed' end; finally FreeAndNil(Parameters); end; end; function TTrackingActions.GetLocationHistory(RouteId: String; StartDate, EndDate: TDateTime; LastPositionOnly: boolean; out ErrorString: String): TTrackingHistoryResponse; var Parameters: TTrackingHistoryRequest; begin Parameters := TTrackingHistoryRequest.Create(RouteId); try Parameters.TimePeriod := 'custom'; Parameters.LastPosition := LastPositionOnly; Parameters.StartDate := IntToStr(TUtils.ConvertToUnixTimestamp(StartDate)); Parameters.EndDate := IntToStr(TUtils.ConvertToUnixTimestamp(EndDate)); Parameters.Format := 'json'; Result := FConnection.Get(TSettings.EndPoints.GetDeviceLocation, Parameters, TTrackingHistoryResponse, ErrorString) as TTrackingHistoryResponse; if (Result <> nil) and (ErrorString = EmptyStr) and (Length(Result.TrackingHistories) = 0) and (Result.Mmd = nil) then begin FreeAndNil(Result); ErrorString := 'GetLocationHistory was failed' end; finally FreeAndNil(Parameters); end; end; procedure TTrackingActions.SetGPS(Parameters: TGPSParameters; out ErrorString: String); var Response: TStatusResponse; begin ErrorString := EmptyStr; Response := FConnection.Get(TSettings.EndPoints.SetGps, Parameters, TStatusResponse, ErrorString) as TStatusResponse; try if ((Response = nil) and (ErrorString = EmptyStr)) or ((Response <> nil) and (not Response.Status) and (ErrorString = EmptyStr)) then ErrorString := 'SetGPS fault'; finally FreeAndNil(Response); end; end; end.
{ Ultibo QEMU VersatilePB unit. Copyright (C) 2016 - SoftOz Pty Ltd. Arch ==== ARMv7 (Cortex A8) Boards ====== QEMU - VersatilePB Licence ======= LGPLv2.1 with static linking exception (See COPYING.modifiedLGPL.txt) Credits ======= Information for this unit was obtained from: References ========== QEMU VersatilePB ================ This unit serves to include all units relevant to the QEMU VersatilePB and to register the drivers that are appropriate to the configuration. This includes standard interfaces such as network, filesystem and storage as well as drivers that are specific to the VersatilePB and may or may not be included by anything else. The unit also provides a very simple clock device driver for the 24MHz clock included in the Versatile PB System Control registers. This clock is 32bit only, runs at a fixed rate of 24MHz and cannot be stopped or reset. Additional units can be included anywhere within a program and they will be linked during the compile process. This unit simply provides a convenient way to ensure all relevant units have been included and the standard drivers registered. } {$mode delphi} {Default to Delphi compatible syntax} {$H+} {Default to AnsiString} {$inline on} {Allow use of Inline procedures} unit QEMUVersatilePBWithoutServices; interface uses GlobalConfig, GlobalConst, GlobalTypes, VersatilePB, Platform, Threads, PlatformQEMUVPB, Devices, DMA, //PL08X, {ARM PrimeCell PL080/PL081 DMA driver} //To Do //Continuing Serial, UART, PL011, {ARM PrimeCell PL011 UART driver} RTC, PL031, {ARM PrimeCell PL031 Real Time Clock driver} MMC, PL18X, {ARM PrimeCell PL181 SDHCI driver} USB, //OHCI, {USB OHCI Controller driver} //To Do //Continuing Network, SMC91X, {SMC LAN91C11 Network driver} Framebuffer, PL110, {ARM PrimeCell PL110 Color LCD driver} Console, Keyboard, Mouse, PS2, PL050, {ARM PrimeCell PL050 PS2 Keyboard/Mouse driver} Filesystem, EXTFS, FATFS, NTFS, CDFS, VirtualDisk, Logging, Sockets, Winsock2, //Services, SysUtils; {==============================================================================} {Global definitions} //{$INCLUDE ..\core\GlobalDefines.inc} {==============================================================================} const {QEMUVersatilePB specific constants} VERSATILEPB_CLOCK_DESCRIPTION = 'VersatilePB 24MHz Clock'; {Description of 24MHz clock device} {==============================================================================} {var} {QEMUVersatilePB specific variables} {==============================================================================} {Initialization Functions} procedure QEMUVersatilePBInit; {==============================================================================} {QEMUVersatilePB Functions} {==============================================================================} {QEMUVersatilePB Clock Functions} function VersatilePBClockRead(Clock:PClockDevice):LongWord; function VersatilePBClockRead64(Clock:PClockDevice):Int64; {==============================================================================} {==============================================================================} implementation {==============================================================================} {==============================================================================} var {QEMUVersatilePB specific variables} QEMUVersatilePBInitialized:Boolean; {==============================================================================} {==============================================================================} {QEMUVersatilePB forward declarations} function MMCIGetCardDetect(MMC:PMMCDevice):LongWord; forward; function MMCIGetWriteProtect(MMC:PMMCDevice):LongWord; forward; {==============================================================================} {==============================================================================} {Initialization Functions} procedure QEMUVersatilePBInit; {Initialize the QEMUVersatilePB unit and parameters} {Note: Called only during system startup} var Status:LongWord; VersatilePBClock:PClockDevice; begin {} {Check Initialized} if QEMUVersatilePBInitialized then Exit; {Initialize Peripherals (Using information from QEMUVPBPeripheralInit)} //PL08XDMA_ALIGNMENT:=DMA_ALIGNMENT; //To Do //Continuing //PL08XDMA_MULTIPLIER:=DMA_MULTIPLIER; //PL08XDMA_SHARED_MEMORY:=DMA_SHARED_MEMORY; //PL08XDMA_NOCACHE_MEMORY:=DMA_NOCACHE_MEMORY; //PL08XDMA_BUS_ADDRESSES:=DMA_BUS_ADDRESSES; //PL08XDMA_CACHE_COHERENT:=DMA_CACHE_COHERENT; {Initialize Peripherals} PL18X_MMCI_FIQ_ENABLED:=False; PL18X_MMCI_MAX_FREQ:=VERSATILEPB_SYS_24MHZ_FREQUENCY; {Connected to the 24MHz reference clock} {Check Environment Variables} //To Do //Continuing {Check DMA} if QEMUVPB_REGISTER_DMA then begin {Create DMA} //PL080DMACreate(VERSATILEPB_DMAC_REGS_BASE,'',VERSATILEPB_IRQ_DMA); //To Do //Continuing end; {Check UART0} if QEMUVPB_REGISTER_UART0 then begin {Create UART0} PL011UARTCreate(VERSATILEPB_UART0_REGS_BASE,PL011_UART_DESCRIPTION + ' (UART0)',VERSATILEPB_IRQ_UART0,PL011_UART_CLOCK_RATE); end; {Check UART1} if QEMUVPB_REGISTER_UART1 then begin {Create UART1} PL011UARTCreate(VERSATILEPB_UART1_REGS_BASE,PL011_UART_DESCRIPTION + ' (UART1)',VERSATILEPB_IRQ_UART1,PL011_UART_CLOCK_RATE); end; {Check UART2} if QEMUVPB_REGISTER_UART2 then begin {Create UART2} PL011UARTCreate(VERSATILEPB_UART2_REGS_BASE,PL011_UART_DESCRIPTION + ' (UART2)',VERSATILEPB_IRQ_UART2,PL011_UART_CLOCK_RATE); end; {Check UART3} if QEMUVPB_REGISTER_UART3 then begin {Create UART3} PL011UARTCreate(VERSATILEPB_UART3_REGS_BASE,PL011_UART_DESCRIPTION + ' (UART3)',VERSATILEPB_IRQ_SIC_UART3,PL011_UART_CLOCK_RATE); end; {Check RTC} if QEMUVPB_REGISTER_RTC then begin {Create RTC} PL031RTCCreate(VERSATILEPB_RTC_REGS_BASE,'',VERSATILEPB_IRQ_RTC); end; {Check Clock} if QEMUVPB_REGISTER_CLOCK then begin {Create Clock} VersatilePBClock:=PClockDevice(ClockDeviceCreateEx(SizeOf(TClockDevice))); if VersatilePBClock <> nil then begin {Update Clock} {Device} VersatilePBClock.Device.DeviceBus:=DEVICE_BUS_MMIO; VersatilePBClock.Device.DeviceType:=CLOCK_TYPE_HARDWARE; VersatilePBClock.Device.DeviceFlags:=CLOCK_FLAG_NONE; VersatilePBClock.Device.DeviceData:=nil; VersatilePBClock.Device.DeviceDescription:=VERSATILEPB_CLOCK_DESCRIPTION; {Clock} VersatilePBClock.ClockState:=CLOCK_STATE_DISABLED; VersatilePBClock.DeviceRead:=VersatilePBClockRead; VersatilePBClock.DeviceRead64:=VersatilePBClockRead64; {Driver} VersatilePBClock.Address:=Pointer(VERSATILEPB_SYS_24MHZ); VersatilePBClock.Rate:=VERSATILEPB_SYS_24MHZ_FREQUENCY; VersatilePBClock.MinRate:=VERSATILEPB_SYS_24MHZ_FREQUENCY; VersatilePBClock.MaxRate:=VERSATILEPB_SYS_24MHZ_FREQUENCY; {Register Clock} Status:=ClockDeviceRegister(VersatilePBClock); if Status = ERROR_SUCCESS then begin {Start Clock} Status:=ClockDeviceStart(VersatilePBClock); if Status <> ERROR_SUCCESS then begin if DEVICE_LOG_ENABLED then DeviceLogError(nil,'QEMUVPB: Failed to start new clock device: ' + ErrorToString(Status)); end; end else begin if DEVICE_LOG_ENABLED then DeviceLogError(nil,'QEMUVPB: Failed to register new clock device: ' + ErrorToString(Status)); end; end else begin if DEVICE_LOG_ENABLED then DeviceLogError(nil,'QEMUVPB: Failed to create new clock device'); end; end; //To Do //Continuing //Timer devices {Check MMC0} if QEMUVPB_REGISTER_MMC0 then begin PL181SDHCICreate(VERSATILEPB_MMCI0_REGS_BASE,PL181_MMCI_DESCRIPTION + ' (MMC0)',VERSATILEPB_IRQ_MMCI0A,VERSATILEPB_IRQ_SIC_MMCI0B,PL18X_MMCI_MIN_FREQ,PL18X_MMCI_MAX_FREQ); end; {Check MMC1} if QEMUVPB_REGISTER_MMC1 then begin PL181SDHCICreate(VERSATILEPB_MMCI1_REGS_BASE,PL181_MMCI_DESCRIPTION + ' (MMC1)',VERSATILEPB_IRQ_MMCI1A,VERSATILEPB_IRQ_SIC_MMCI1B,PL18X_MMCI_MIN_FREQ,PL18X_MMCI_MAX_FREQ); end; {Check Network} if QEMUVPB_REGISTER_NETWORK then begin {Create Network} SMC91XNetworkCreate(VERSATILEPB_ETH_REGS_BASE,'',VERSATILEPB_IRQ_ETH); end; {Check Keyboard} if QEMUVPB_REGISTER_KEYBOARD then begin {Create Keyboard} PL050KeyboardCreate(VERSATILEPB_KMI0_REGS_BASE,'',VERSATILEPB_IRQ_SIC_KMI0,PL050_KEYBOARD_CLOCK_RATE); end; {Check Mouse} if QEMUVPB_REGISTER_MOUSE then begin {Create Mouse} PL050MouseCreate(VERSATILEPB_KMI1_REGS_BASE,'',VERSATILEPB_IRQ_SIC_KMI1,PL050_MOUSE_CLOCK_RATE); end; {$IFNDEF CONSOLE_EARLY_INIT} {Check Framebuffer} if QEMUVPB_REGISTER_FRAMEBUFFER then begin {Check Defaults} if (FRAMEBUFFER_DEFAULT_WIDTH = 0) or (FRAMEBUFFER_DEFAULT_HEIGHT = 0) then begin FRAMEBUFFER_DEFAULT_WIDTH:=1024; FRAMEBUFFER_DEFAULT_HEIGHT:=768; end; {Check Defaults} if (FRAMEBUFFER_DEFAULT_DEPTH <> FRAMEBUFFER_DEPTH_16) and (FRAMEBUFFER_DEFAULT_DEPTH <> FRAMEBUFFER_DEPTH_32) then begin FRAMEBUFFER_DEFAULT_DEPTH:=FRAMEBUFFER_DEPTH_16; end; {Memory Barrier} DataMemoryBarrier; {Before the First Write} {Setup CLCD Mode} PLongWord(VERSATILEPB_SYS_CLCD)^:=(PLongWord(VERSATILEPB_SYS_CLCD)^ and not(VERSATILEPB_SYS_CLCD_MODEMASK)) or VERSATILEPB_SYS_CLCD_MODE565RGB; {Start CLCD Clock} //To Do //Continuing {Memory Barrier} DataMemoryBarrier; {After the Last Read} {Create Framebuffer} PL110FramebufferCreateSVGA(VERSATILEPB_CLCD_REGS_BASE,'',FRAMEBUFFER_DEFAULT_ROTATION,FRAMEBUFFER_DEFAULT_WIDTH,FRAMEBUFFER_DEFAULT_HEIGHT,FRAMEBUFFER_DEFAULT_DEPTH); end; {$ENDIF} {Create Timer for ClockGetTotal (Every 60 seconds)} ClockGetTimer:=TimerCreateEx(60000,TIMER_STATE_ENABLED,TIMER_FLAG_RESCHEDULE,TTimerEvent(QEMUVPBClockGetTimer),nil); {Rescheduled Automatically} QEMUVersatilePBInitialized:=True; end; {==============================================================================} {==============================================================================} {QEMUVersatilePB Functions} {==============================================================================} {==============================================================================} {QEMUVersatilePB MMCI Functions} function MMCIGetCardDetect(MMC:PMMCDevice):LongWord; {Implementation of MMCDeviceGetCardDetect API for QEMUVPB MMCI} {Note: Not intended to be called directly by applications, use MMCDeviceGetCardDetect instead} {Note: Not currently used as the VERSATILEPB_SYS_MCI register is not connected in QEMUVPB} var Mask:LongWord; SDHCI:PSDHCIHost; begin {} Result:=MMC_STATUS_INVALID_PARAMETER; {Check MMC} if MMC = nil then Exit; {$IF DEFINED(PL18X_DEBUG) or DEFINED(MMC_DEBUG)} if MMC_LOG_ENABLED then MMCLogDebug(nil,'QEMUVPB: MMC Device Get Card Detect'); {$ENDIF} {Get SDHCI} SDHCI:=PSDHCIHost(MMC.Device.DeviceData); if SDHCI = nil then Exit; {Check MMC State} if MMC.MMCState = MMC_STATE_INSERTED then begin {Get Card Status} if MMCDeviceSendCardStatus(MMC) <> MMC_STATUS_SUCCESS then begin {Update Flags} MMC.Device.DeviceFlags:=MMC.Device.DeviceFlags and not(MMC_FLAG_CARD_PRESENT); {$IF DEFINED(PL18X_DEBUG) or DEFINED(MMC_DEBUG)} if MMC_LOG_ENABLED then MMCLogDebug(nil,'QEMUVPB: Get Card Detect (Flags=not MMC_FLAG_CARD_PRESENT)'); {$ENDIF} end; end else begin {Check Address} if PtrUInt(SDHCI.Address) = VERSATILEPB_MMCI0_REGS_BASE then begin Mask:=VERSATILEPB_SYS_MCI_CD0; end else if PtrUInt(SDHCI.Address) = VERSATILEPB_MMCI1_REGS_BASE then begin Mask:=VERSATILEPB_SYS_MCI_CD1; end else begin Mask:=0; end; {$IF DEFINED(PL18X_DEBUG) or DEFINED(MMC_DEBUG)} if MMC_LOG_ENABLED then MMCLogDebug(nil,'QEMUVPB: VERSATILEPB_SYS_MCI=' + IntToHex(PLongWord(VERSATILEPB_SYS_MCI)^,8)); {$ENDIF} {Read Status} if (PLongWord(VERSATILEPB_SYS_MCI)^ and Mask) <> 0 then begin {Update Flags} MMC.Device.DeviceFlags:=(MMC.Device.DeviceFlags or MMC_FLAG_CARD_PRESENT); {$IF DEFINED(PL18X_DEBUG) or DEFINED(MMC_DEBUG)} if MMC_LOG_ENABLED then MMCLogDebug(nil,'QEMUVPB: Get Card Detect (Flags=MMC_FLAG_CARD_PRESENT)'); {$ENDIF} end else begin {Update Flags} MMC.Device.DeviceFlags:=MMC.Device.DeviceFlags and not(MMC_FLAG_CARD_PRESENT); {$IF DEFINED(PL18X_DEBUG) or DEFINED(MMC_DEBUG)} if MMC_LOG_ENABLED then MMCLogDebug(nil,'QEMUVPB: Get Card Detect (Flags=not MMC_FLAG_CARD_PRESENT)'); {$ENDIF} end; {Memory Barrier} DataMemoryBarrier; {After the Last Read} end; Result:=MMC_STATUS_SUCCESS; end; {==============================================================================} function MMCIGetWriteProtect(MMC:PMMCDevice):LongWord; {Implementation of MMCDeviceGetWriteProtect API for QEMUVPB MMCI} {Note: Not intended to be called directly by applications, use MMCDeviceGetWriteProtect instead} {Note: Not currently used as the VERSATILEPB_SYS_MCI register is not connected in QEMUVPB} var Mask:LongWord; SDHCI:PSDHCIHost; begin {} Result:=MMC_STATUS_INVALID_PARAMETER; {Check MMC} if MMC = nil then Exit; {$IF DEFINED(PL18X_DEBUG) or DEFINED(MMC_DEBUG)} if MMC_LOG_ENABLED then MMCLogDebug(nil,'QEMUVPB: MMC Device Get Write Protect'); {$ENDIF} {Get SDHCI} SDHCI:=PSDHCIHost(MMC.Device.DeviceData); if SDHCI = nil then Exit; {Check MMC State} if MMC.MMCState = MMC_STATE_INSERTED then begin {Check Address} if PtrUInt(SDHCI.Address) = VERSATILEPB_MMCI0_REGS_BASE then begin Mask:=VERSATILEPB_SYS_MCI_WP0; end else if PtrUInt(SDHCI.Address) = VERSATILEPB_MMCI1_REGS_BASE then begin Mask:=VERSATILEPB_SYS_MCI_WP1; end else begin Mask:=0; end; {$IF DEFINED(PL18X_DEBUG) or DEFINED(MMC_DEBUG)} if MMC_LOG_ENABLED then MMCLogDebug(nil,'QEMUVPB: VERSATILEPB_SYS_MCI=' + IntToHex(PLongWord(VERSATILEPB_SYS_MCI)^,8)); {$ENDIF} {Read Status} if (PLongWord(VERSATILEPB_SYS_MCI)^ and Mask) <> 0 then begin {Update Flags} MMC.Device.DeviceFlags:=(MMC.Device.DeviceFlags or MMC_FLAG_WRITE_PROTECT); {$IF DEFINED(PL18X_DEBUG) or DEFINED(MMC_DEBUG)} if MMC_LOG_ENABLED then MMCLogDebug(nil,'QEMUVPB: Get Card Detect (Flags=MMC_FLAG_WRITE_PROTECT)'); {$ENDIF} end else begin {Update Flags} MMC.Device.DeviceFlags:=MMC.Device.DeviceFlags and not(MMC_FLAG_WRITE_PROTECT); {$IF DEFINED(PL18X_DEBUG) or DEFINED(MMC_DEBUG)} if MMC_LOG_ENABLED then MMCLogDebug(nil,'QEMUVPB: Get Card Detect (Flags=not MMC_FLAG_WRITE_PROTECT)'); {$ENDIF} end; {Memory Barrier} DataMemoryBarrier; {After the Last Read} end; Result:=MMC_STATUS_SUCCESS; end; {==============================================================================} {==============================================================================} {QEMUVersatilePB Clock Functions} function VersatilePBClockRead(Clock:PClockDevice):LongWord; {Implementation of ClockDeviceRead API for the 24MHz Clock} {Note: Not intended to be called directly by applications, use ClockDeviceRead instead} begin {} Result:=0; {Check Clock} if Clock = nil then Exit; if Clock.Address = nil then Exit; if MutexLock(Clock.Lock) <> ERROR_SUCCESS then Exit; {Read Clock} Result:=PLongWord(Clock.Address)^; {Memory Barrier} DataMemoryBarrier; {After the Last Read} {Update Statistics} Inc(Clock.ReadCount); MutexUnlock(Clock.Lock); end; {==============================================================================} function VersatilePBClockRead64(Clock:PClockDevice):Int64; {Implementation of ClockDeviceRead64 API for the 24MHz Clock} {Note: Not intended to be called directly by applications, use ClockDeviceRead64 instead} begin {} Result:=0; {Check Clock} if Clock = nil then Exit; if Clock.Address = nil then Exit; if MutexLock(Clock.Lock) <> ERROR_SUCCESS then Exit; {Read Clock} Result:=PLongWord(Clock.Address)^; {Memory Barrier} DataMemoryBarrier; {After the Last Read} {Update Statistics} Inc(Clock.ReadCount); MutexUnlock(Clock.Lock); end; {==============================================================================} {==============================================================================} initialization QEMUVersatilePBInit; {==============================================================================} {finalization} {Nothing} {==============================================================================} {==============================================================================} end.
unit ResPubUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, ADODB, Grids, DBGridEh, ImgList,GridsEh,EhLibBDE; type TResPubFrm = class(TForm) private { Private declarations } FSortDrict: Boolean; public { Public declarations } procedure DBGridEhSortSupport(DBGridEh: TDBGridEh); procedure DBGridEhTitleSort(Column: TColumnEh); published procedure DBGridEhDrawRec(const Rect: TRect; DataCol: Integer; Column: TColumnEh; State: TGridDrawState; DBGridEh: TDBGridEh); function CompactACCESSDatabase(const AFileName, APassWord: string): Boolean; function GetTempPathFileName(): string; end; resourcestring Demo = 'Demo'; CompactOK = '压缩成功'; payout = '支出'; Incom = '收入'; InComeTypeEdit ='收入类型'; ConsumeType ='消费类型'; var ResPubFrm: TResPubFrm; implementation {$R *.dfm} uses comobj, PayOutUnit; //原作者 procedure TResPubFrm.DBGridEhSortSupport(DBGridEh: TDBGridEh); var i: integer; begin for i := 0 to DBGridEh.Columns.Count - 1 do // 排序支持 DBGridEh.Columns.Items[i].Title.TitleButton := true; end; procedure TResPubFrm.DBGridEhTitleSort(Column: TColumnEh); var FadoQry: TADOQuery; begin try FadoQry := Column.Field.DataSet as TADOQuery; if FSortDrict = True then //当前是升序 begin FadoQry.Sort := Column.FieldName + ' DESC'; //Attion Add Space Chart FSortDrict := false; end else if FSortDrict = false then //当前是降序 begin FadoQry.Sort := Column.FieldName + ' ASC'; FSortDrict := true; end; except end end; //------------------------------------------------------------------------------------------------- procedure TResPubFrm.DBGridEhDrawRec(const Rect: TRect; DataCol: Integer; Column: TColumnEh; State: TGridDrawState; DBGridEh: TDBGridEh); begin if DBGridEh.DataSource.Dataset.RecNo mod 2 = 0 then // DBGridEh.Canvas.Brush.Color := clCream //定义背景颜色 DBGridEh.Canvas.Brush.Color := $00FAE3D3 //定义背景颜色 else DBGridEh.Canvas.Brush.Color := clWhite; //定义背景颜色 // DBGridEh.Canvas.Brush.Color := clblue; //定义背景颜色 if (gdSelected in State) and (gdFocused in State) then DBGridEh.Canvas.Font.Color := clBlue else DBGridEh.Canvas.Font.Color := clBlack; DBGridEh.DefaultDrawColumnCell(Rect, DataCol, Column, State); end; //------------------------------------------------------------------------------------------------- function TResPubFrm.GetTempPathFileName(): string; //取得临时文件名 var SPath, SFile: array[0..254] of char; begin GetTempPath(254, SPath); GetTempFileName(SPath, '~SM', 0, SFile); result := SFile; DeleteFile(result); end; //------------------------------------------------------------------------------ function TResPubFrm.CompactACCESSDatabase(const AFileName, APassWord: string): Boolean; const SConnectionString = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s;' + 'Jet OLEDB:Database Password=gigi2009;'; var SPath: string; SFile: array[0..254] of Char; STempFileName: string; JE: OleVariant; function GetTempDir: string; var Buffer: array[0..MAX_PATH] of Char; begin ZeroMemory(@Buffer, MAX_PATH); GetTempPath(MAX_PATH, Buffer); Result := IncludeTrailingBackslash(StrPas(Buffer)); end; begin Result := False; SPath := GetTempDir; //取得Windows的Temp路径 GetTempFileName(PChar(SPath), '~ACP', 0, SFile); //取得Temp文件名,Windows将自动建立0字节文件 STempFileName := SFile; //PChar->String if not DeleteFile(STempFileName) then Exit; //删除Windows建立的0字节文件 try JE := CreateOleObject('JRO.JetEngine'); //建立OLE对象,函数结束OLE对象超过作用域自动释放 OleCheck(JE.CompactDatabase(Format(SConnectionString, [AFileName, APassWord]), Format(SConnectionString, [STempFileName, APassWord]))); //压缩数据库 Result := CopyFile(PChar(STempFileName), PChar(AFileName), False); //复制并覆盖源数据库文件,如果复制失败则函数返回假,压缩成功但没有到函数的功能 DeleteFile(STempFileName); //删除临时文件 except //压缩失败 end; ShowMessage(CompactOK); end; //------------------------------------------------------------------------------------------------- end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { { Rev 1.3 1/21/2004 2:12:40 PM JPMugaas { InitComponent } { { Rev 1.2 12/8/2002 07:26:30 PM JPMugaas { Added published host and port properties. } { { Rev 1.1 12/6/2002 05:29:28 PM JPMugaas { Now decend from TIdTCPClientCustom instead of TIdTCPClient. } { { Rev 1.0 11/14/2002 02:17:02 PM JPMugaas } unit IdDayTime; {*******************************************************} { } { Indy QUOTD Client TIdDayTime } { } { Copyright (C) 2000 Winshoes WOrking Group } { Started by J. Peter Mugaas } { 2000-April-23 } { } {*******************************************************} {2000-April-30 J. Peter Mugaas changed to drop control charactors and spaces from result to ease parsing} interface uses IdAssignedNumbers, IdTCPClient; type TIdDayTime = class(TIdTCPClientCustom) protected Function GetDayTimeStr : String; procedure InitComponent; override; public Property DayTimeStr : String read GetDayTimeStr; published property Port default IdPORT_DAYTIME; property Host; end; implementation uses IdGlobal, IdSys; { TIdDayTime } procedure TIdDayTime.InitComponent; begin inherited InitComponent; Port := IdPORT_DAYTIME; end; function TIdDayTime.GetDayTimeStr: String; begin Result := Sys.Trim ( ConnectAndGetAll ); end; end.
unit VideoICM; // Copyright (c) 1996 Jorge Romero Gomez, Merchise interface uses Windows, MMSystem, Dibs; type HIC = type THandle; const ICTYPE_VIDEO = $63646976; // 'vidc': Video compressor/decompressor ICTYPE_AUDIO = $63647561; // 'audc': Audio compressor/decompressor const COMP_MSVIDEO1 = $6376736D; // 'msvc': Microsoft Video 1 COMP_MSRLE = $656C726D; // 'mrle': Microsoft RLE COMP_JPEG = $6765706A; // 'jpeg': Texas Instruments JPEG COMP_CINEPAK = $64697663; // 'cvid': Supermac Cinepak COMP_YUV9 = $39767579; // 'yuv9': Intel 411 YUV format COMP_RT21 = $31327472; // 'rt21': Intel Indeo 2.1 format COMP_IV31 = $31337669; // 'iv31': Intel Indeo 3.0 format COMP_IV41 = $31347669; // 'iv41': Intel Indeo Interactive format function StrToFourCC( const FourCC : string ) : dword; function FourCC( ch1, ch2, ch3, ch4 : char ) : dword; function FourCCToStr( FourCC : dword ) : string; function ICCompressDecompressImage( // Compresses or decompresses a given image. ic : HIC; // compressor (NULL if any will do) uiFlags : uint; // silly flags lpbiIn : PBitmapInfoHeader; // input DIB format lpBits : pointer; // input DIB bits lpbiOut : PBitmapInfoHeader; // output format (NULL => default) lQuality : longint // the reqested quality ) : PDib; // input: // hic compressor to use, if NULL is specifed a // compressor will be located that can handle the conversion. // uiFlags flags (not used, must be 0) // lpbiIn input DIB format // lpBits input DIB bits // lpbiOut output format, if NULL is specifed the default // format choosen be the compressor will be used. // lQuality the reqested compression quality function ICCompressImage( // Compresses a given image. ic : HIC; // compressor (NULL if any will do) uiFlags : uint; // silly flags lpbiIn : PBitmapInfoHeader; // input DIB format lpBits : pointer; // input DIB bits lpbiOut : PBitmapInfoHeader; // output format (NULL => default) lQuality : longint // the reqested quality ) : PDib; // input: // hic compressor to use, if NULL is specifed a // compressor will be located that can handle the conversion. // uiFlags flags (not used, must be 0) // lpbiIn input DIB format // lpBits input DIB bits // lpbiOut output format, if NULL is specifed the default // format choosen be the compressor will be used. // lQuality the reqested compression quality function ICDecompressImage( // Decompresses a given image. ic : HIC; // compressor (NULL if any will do) uiFlags : uint; // silly flags lpbiIn : PBitmapInfoHeader; // input DIB format lpBits : pointer; // input DIB bits lpbiOut : PBitmapInfoHeader // output format (NULL => default) ) : PDib; // input: // hic compressor to use, if NULL is specifed a // compressor will be located that can handle the conversion. // uiFlags flags (not used, must be 0) // lpbiIn input DIB format // lpBits input DIB bits // lpbiOut output format, if NULL is specifed the default // format choosen be the compressor will be used. // lQuality the reqested compression quality //============================================================================ const // this code in biCompression means the DIB must be accesed via // 48 bit pointers! using *ONLY* the selector given. BI_1632 = $32333631; // '1632' const // Error conditions ICERR_OK = 00; ICERR_DONTDRAW = 01; ICERR_NEWPALETTE = 02; ICERR_GOTOKEYFRAME = 03; ICERR_STOPDRAWING = 04; ICERR_UNSUPPORTED = -1; ICERR_BADFORMAT = -2; ICERR_MEMORY = -3; ICERR_INTERNAL = -4; ICERR_BADFLAGS = -5; ICERR_BADPARAM = -6; ICERR_BADSIZE = -7; ICERR_BADHANDLE = -8; ICERR_CANTUPDATE = -9; ICERR_ABORT = -10; ICERR_ERROR = -100; ICERR_BADBITDEPTH = -200; ICERR_BADIMAGESIZE = -201; ICERR_CUSTOM = -400; // errors less than ICERR_CUSTOM... const // Values for dwFlags of ICOpen() ICMODE_COMPRESS = 1; ICMODE_DECOMPRESS = 2; ICMODE_FASTDECOMPRESS = 3; ICMODE_QUERY = 4; ICMODE_FASTCOMPRESS = 5; ICMODE_DRAW = 8; const // Flags for AVI file index AVIIF_LIST = $00000001; AVIIF_TWOCC = $00000002; AVIIF_KEYFRAME = $00000010; const // quality flags ICQUALITY_LOW = 0; ICQUALITY_HIGH = 10000; ICQUALITY_DEFAULT = -1; const // ICM specific messages. ICM_USER = DRV_USER + $0000; ICM_COMPRESS_GET_FORMAT = ICM_USER + 4; // get compress format or size ICM_COMPRESS_GET_SIZE = ICM_USER + 5; // get output size ICM_COMPRESS_QUERY = ICM_USER + 6; // query support for compress ICM_COMPRESS_BEGIN = ICM_USER + 7; // begin a series of compress calls. ICM_COMPRESS = ICM_USER + 8; // compress a frame ICM_COMPRESS_END = ICM_USER + 9; // end of a series of compress calls. ICM_DECOMPRESS_GET_FORMAT = ICM_USER + 10; // get decompress format or size ICM_DECOMPRESS_QUERY = ICM_USER + 11; // query support for dempress ICM_DECOMPRESS_BEGIN = ICM_USER + 12; // start a series of decompress calls ICM_DECOMPRESS = ICM_USER + 13; // decompress a frame ICM_DECOMPRESS_END = ICM_USER + 14; // end a series of decompress calls ICM_DECOMPRESS_SET_PALETTE = ICM_USER + 29; // fill in the DIB color table ICM_DECOMPRESS_GET_PALETTE = ICM_USER + 30; // fill in the DIB color table ICM_DRAW_QUERY = ICM_USER + 31; // query support for dempress ICM_DRAW_BEGIN = ICM_USER + 15; // start a series of draw calls ICM_DRAW_GET_PALETTE = ICM_USER + 16; // get the palette needed for drawing ICM_DRAW_START = ICM_USER + 18; // start decompress clock ICM_DRAW_STOP = ICM_USER + 19; // stop decompress clock ICM_DRAW_END = ICM_USER + 21; // end a series of draw calls ICM_DRAW_GETTIME = ICM_USER + 32; // get value of decompress clock ICM_DRAW = ICM_USER + 33; // generalized "render" message ICM_DRAW_WINDOW = ICM_USER + 34; // drawing window has moved or hidden ICM_DRAW_SETTIME = ICM_USER + 35; // set correct value for decompress clock ICM_DRAW_REALIZE = ICM_USER + 36; // realize palette for drawing ICM_DRAW_FLUSH = ICM_USER + 37; // clear out buffered frames ICM_DRAW_RENDERBUFFER = ICM_USER + 38; // draw undrawn things in queue ICM_DRAW_START_PLAY = ICM_USER + 39; // start of a play ICM_DRAW_STOP_PLAY = ICM_USER + 40; // end of a play ICM_DRAW_SUGGESTFORMAT = ICM_USER + 50; // Like ICGetDisplayFormat ICM_DRAW_CHANGEPALETTE = ICM_USER + 51; // for animating palette ICM_GETBUFFERSWANTED = ICM_USER + 41; // ask about prebuffering ICM_GETDEFAULTKEYFRAMERATE = ICM_USER + 42; // get the default value for key frames ICM_DECOMPRESSEX_BEGIN = ICM_USER + 60; // start a series of decompress calls ICM_DECOMPRESSEX_QUERY = ICM_USER + 61; // start a series of decompress calls ICM_DECOMPRESSEX = ICM_USER + 62; // decompress a frame ICM_DECOMPRESSEX_END = ICM_USER + 63; // end a series of decompress calls ICM_COMPRESS_FRAMES_INFO = ICM_USER + 70; // tell about compress to come ICM_SET_STATUS_PROC = ICM_USER + 72; // set status callback const // Messages ======================== ICM_RESERVED_LOW = DRV_USER + $1000; ICM_RESERVED_HIGH = DRV_USER + $2000; ICM_RESERVED = ICM_RESERVED_LOW; ICM_GETSTATE = ICM_RESERVED + 0; // Get compressor state ICM_SETSTATE = ICM_RESERVED + 1; // Set compressor state ICM_GETINFO = ICM_RESERVED + 2; // Query info about the compressor ICM_CONFIGURE = ICM_RESERVED + 10; // show the configure dialog ICM_ABOUT = ICM_RESERVED + 11; // show the about box ICM_GETDEFAULTQUALITY = ICM_RESERVED + 30; // get the default value for quality ICM_GETQUALITY = ICM_RESERVED + 31; // get the current value for quality ICM_SETQUALITY = ICM_RESERVED + 32; // set the default value for quality ICM_SET = ICM_RESERVED + 40; // Tell the driver something ICM_GET = ICM_RESERVED + 41; // Ask the driver something const // Constants for ICM_SET: ICM_FRAMERATE : array[0..3] of char = ('F','r','m','R'); ICM_KEYFRAMERATE : array[0..3] of char = ('K','e','y','R'); type TIcOpen = packed record dwSize : dword; // sizeof(ICOPEN) fccType : dword; // 'vidc' fccHandler : dword; // dwVersion : dword; // version of compman opening you dwFlags : dword; // LOWORD is type specific dwError : LRESULT; // error return. pV1Reserved : pointer; // Reserved pV2Reserved : pointer; // Reserved dnDevNode : dword; // Devnode for PnP devices end; const // Flags for the <dwFlags> field of the <ICINFO> structure VIDCF_QUALITY = $0001; // supports quality VIDCF_CRUNCH = $0002; // supports crunching to a frame size VIDCF_TEMPORAL = $0004; // supports inter-frame compress VIDCF_COMPRESSFRAMES = $0008; // wants the compress all frames message VIDCF_DRAW = $0010; // supports drawing VIDCF_FASTTEMPORALC = $0020; // does not need prev frame on compress VIDCF_FASTTEMPORALD = $0080; // does not need prev frame on decompress VIDCF_QUALITYTIME = $0040; // supports temporal quality VIDCF_FASTTEMPORAL = VIDCF_FASTTEMPORALC or VIDCF_FASTTEMPORALD; type TIcInfo = packed record dwSize : dword; // sizeof(ICINFO) fccType : dword; // compressor type 'vidc' 'audc' fccHandler : dword; // compressor sub-type 'rle ' 'jpeg' 'pcm ' dwFlags : dword; // flags LOWORD is type specific dwVersion : dword; // version of the driver dwVersionICM : dword; // version of the ICM used // under Win32, the driver always returns UNICODE strings. szName : array[0..15] of WideChar; // short name szDescription : array[0..127] of WideChar; // long name szDriver : array[0..127] of WideChar; // driver that contains compressor end; const ICCOMPRESS_KEYFRAME = $00000001; type TIcCompress = packed record dwFlags : dword; // flags lpbiOutput : PBitmapInfoHeader; // output format lpOutput : pointer; // output data lpbiInput : PBitmapInfoHeader; // format of frame to compress lpInput : pointer; // frame data to compress lpckid : pdword; // ckid for data in AVI file lpdwFlags : pdword; // flags in the AVI index. lFrameNum : longint; // frame number of seq. dwFrameSize : longint; // reqested size in bytes. (if non zero) dwQuality : dword; // quality // these are new fields lpbiPrev : PBitmapInfoHeader; // format of previous frame lpPrev : pointer; // previous frame end; const ICCOMPRESSFRAMES_PADDING = $00000001; type TGetDataProc = function ( lInput : LPARAM; lFrame : longint; lpBits : pointer; len : longint ) : longint; TPutDataProc = function ( lInput : LPARAM; lFrame : longint; lpBits : pointer; len : longint ) : longint; type TIcCompressFrames = packed record dwFlags : dword; // flags lpbiOutput : PBitmapInfoHeader; // output format lOutput : LPARAM; // output data lpbiInput : PBitmapInfoHeader; // format of frame to compress lInput : LPARAM; // frame data to compress lStartFrame : longint; // start frame lFrameCount : longint; // # of frames lQuality : longint; // quality lDataRate : longint; // data rate lKeyRate : longint; // key frame rate dwRate : dword; // frame rate, as always dwScale : dword; dwOverheadPerFrame : dword; dwReserved2 : dword; GetData : TGetDataProc; PutData : TPutDataProc; end; const // messages for Status callback ICSTATUS_START = 0; ICSTATUS_STATUS = 1; // l == % done ICSTATUS_END = 2; ICSTATUS_ERROR = 3; // l == error string (LPSTR) ICSTATUS_YIELD = 4; type TStatusProc = function ( lParam : LPARAM; Msg : uint; l : longint ) : LRESULT; type TIcSetStatusProc = packed record dwFlags : dword; Param : LPARAM; Status : TStatusProc; // return nonzero means abort operation in progress end; const ICDECOMPRESS_HURRYUP = $80000000; // don't draw just buffer (hurry up!) ICDECOMPRESS_UPDATE = $40000000; // don't draw just update screen ICDECOMPRESS_PREROLL = $20000000; // this frame is before real start ICDECOMPRESS_NULLFRAME = $10000000; // repeat last frame ICDECOMPRESS_NOTKEYFRAME = $08000000; // this frame is not a key frame type TIcDecompress = packed record dwFlags : dword; // flags (from AVI index...) lpbiInput : PBitmapInfoHeader; // BITMAPINFO of compressed data, biSizeImage has the chunk size lpInput : pointer; // compressed data lpbiOutput : PBitmapInfoHeader; // DIB to decompress to lpOutput : pointer; // lpckid : pdword; // ckid from AVI file end; type TIcDecompressEx = packed record dwFlags : dword; // flags (from AVI index...) lpbiSrc : PBitmapInfoHeader; // BITMAPINFO of compressed data lpSrc : pointer; // compressed data lpbiDst : PBitmapInfoHeader; // DIB to decompress to lpDst : pointer; // output data xDst : integer; // destination rectangle yDst : integer; dxDst : integer; dyDst : integer; xSrc : integer; // source rectangle ySrc : integer; dxSrc : integer; dySrc : integer; end; const ICDRAW_QUERY = $00000001; // test for support ICDRAW_FULLSCREEN = $00000002; // draw to full screen ICDRAW_HDC = $00000004; // draw to a HDC/HWND ICDRAW_ANIMATE = $00000008; // expect palette animation ICDRAW_CONTINUE = $00000010; // draw is a continuation of previous draw ICDRAW_MEMORYDC = $00000020; // DC is offscreen, by the way ICDRAW_UPDATING = $00000040; // We're updating, as opposed to playing ICDRAW_RENDER = $00000080; // used to render data not draw it ICDRAW_BUFFER = $00000100; // please buffer this data offscreen, we will need to update it type TIcDrawBegin = packed record dwFlags : dword; // flags hpal : HPALETTE; // palette to draw with wnd : HWND; // window to draw to dc : HDC; // HDC to draw to xDst : integer; // destination rectangle yDst : integer; dxDst : integer; dyDst : integer; lpbi : PBitmapInfoHeader; // format of frame to draw xSrc : integer; // source rectangle ySrc : integer; dxSrc : integer; dySrc : integer; dwRate : dword; // frames/second = (dwRate/dwScale) dwScale : dword; end; const ICDRAW_HURRYUP = $80000000; // don't draw just buffer (hurry up!) ICDRAW_UPDATE = $40000000; // don't draw just update screen ICDRAW_PREROLL = $20000000; // this frame is before real start ICDRAW_NULLFRAME = $10000000; // repeat last frame ICDRAW_NOTKEYFRAME = $08000000; // this frame is not a key frame type TIcDraw = packed record dwFlags : dword; // flags lpFormat : pointer; // format of frame to decompress lpData : pointer; // frame data to decompress cbData : dword; lTime : longint; // time in drawbegin units (see dwRate and dwScale) end; type TIcDrawSuggest = packed record lpbiIn : PBitmapInfoHeader; // format to be drawn lpbiSuggest : PBitmapInfoHeader; // location for suggested format (or NULL to get size) dxSrc : integer; // source extent or 0 dySrc : integer; dxDst : integer; // dest extent or 0 dyDst : integer; hicDecompressor : HIC; // decompressor you can talk to end; type TIcPalette = packed record dwFlags : dword; // flags (from AVI index...) iStart : integer; // first palette to change iLen : integer; // count of entries to change. lppe : pointer; // palette end; // ICM function declarations ===================================================== function ICInfo( fccType : dword; fccHandler : dword; var Info : TICInfo ) : BOOL; stdcall; function ICGetInfo( ic : HIC; var Info : TICInfo; cb : dword ) : BOOL; stdcall; function ICOpen( fccType : dword; fccHandler : dword; wMode : uint ) : HIC; stdcall; function ICOpenFunction( fccType : dword; fccHandler : dword; wMode : uint; HandlerProc : pointer ) : HIC; stdcall; function ICClose( ic : HIC ) : LRESULT; stdcall; function ICSendMessage( ic : HIC; msg : UINT; dw1, dw2 : dword ) : LRESULT; stdcall; const // Values for wFlags of ICInstall() ICINSTALL_UNICODE = $8000; ICINSTALL_FUNCTION = $0001; // lParam is a DriverProc (function ptr) ICINSTALL_DRIVER = $0002; // lParam is a driver name (string) ICINSTALL_HDRV = $0004; // lParam is a HDRVR (driver handle) ICINSTALL_DRIVERW = $8002; // lParam is a unicode driver name function ICInstall( fccType : dword; fccHandler : dword; Param : LPARAM; szDesc : pchar; wFlags : uint ) : BOOL; stdcall; function ICRemove( fccType : dword; fccHandler : dword; wFlags : uint ) : BOOL; stdcall; // Query macros const ICMF_CONFIGURE_QUERY = $00000001; ICMF_ABOUT_QUERY = $00000001; function ICQueryAbout( ic : HIC ) : boolean; function ICAbout( ic : HIC; Wnd : HWND ) : LRESULT; function ICQueryConfigure( ic : HIC ) : boolean; function ICConfigure( ic : HIC; Wnd : HWND ) : LRESULT; // Get/Set state macros function ICGetState( ic : HIC; info : pointer; size : dword ) : dword; function ICSetState( ic : HIC; info : pointer; size : dword ) : dword; function ICGetStateSize( ic : HIC ) : integer; // Get value macros function ICGetDefaultQuality( ic : HIC ) : integer; function ICGetDefaultKeyFrameRate( ic : HIC ) : integer; // Draw Window macro function ICDrawWindow( ic : HIC; Dest : PRect ) : dword; // Compression functions ============================================================================= // Compress a single frame function ICCompress( ic : HIC; dwFlags : dword; // flags lpbiOutput : PBitmapInfoHeader; // output format lpData : pointer; // output data lpbiInput : PBitmapInfoHeader; // format of frame to compress lpBits : pointer; // frame data to compress lpckid : pdword; // ckid for data in AVI file lpdwFlags : pdword; // flags in the AVI index. lFrameNum : longint; // frame number of seq. dwFrameSize : dword; // reqested size in bytes. (if non zero) dwQuality : dword; // quality within one frame lpbiPrev : PBitmapInfoHeader; // format of previous frame lpPrev : pointer // previous frame ) : dword; stdcall; // Start compression from a source format (lpbiInput) to a dest format (lpbiOuput) if supported. function ICCompressBegin( ic : HIC; lpbiInput : PBitmapInfoHeader; lpbiOutput : PBitmapInfoHeader ) : LRESULT; function ICCompressEnd( ic : HIC ) : LRESULT; // determines if compression from a source format (lpbiInput) to a dest format (lpbiOuput) is supported. function ICCompressQuery( ic : HIC; lpbiInput : PBitmapInfoHeader; lpbiOutput : PBitmapInfoHeader ) : LRESULT; // get the output format, (format of compressed data), if lpbiOutput is NULL return the size in bytes needed for format function ICCompressGetFormat( ic : HIC; lpbiInput : PBitmapInfoHeader; lpbiOutput : PBitmapInfoHeader ) : LRESULT; function ICCompressGetFormatSize( ic : HIC; lpbiInput : PBitmapInfoHeader ) : dword; // return the maximal size of a compressed frame function ICCompressGetSize( ic : HIC; lpbiInput : PBitmapInfoHeader; lpbiOutput : PBitmapInfoHeader ) : dword; // Decompression functions ============================================================================= function ICDecompress( // decompress a single frame ic : HIC; dwFlags : dword; // flags (from AVI index...) lpbiFormat : PBitmapInfoHeader; // BITMAPINFO of compressed data, biSizeImage has the chunk size lpData : pointer; // data lpbi : PBitmapInfoHeader; // DIB to decompress to lpBits : pointer ) : LRESULT; stdcall; function ICDecompressBegin( ic : HIC; lpbiInput : PBitmapInfoHeader; lpbiOutput : PBitmapInfoHeader ) : LRESULT; function ICDecompressEnd( ic : HIC ) : LRESULT; function ICDecompressQuery( ic : HIC; lpbiInput : PBitmapInfoHeader; lpbiOutput : PBitmapInfoHeader ) : LRESULT; function ICDecompressGetFormat( ic : HIC; lpbiInput : PBitmapInfoHeader; lpbiOutput : PBitmapInfoHeader ) : LRESULT; function ICDecompressGetFormatSize( ic : HIC; lpbiInput : PBitmapInfoHeader ) : dword; // Get the output palette in lpbiOutput function ICDecompressGetPalette( ic : HIC; lpbiInput : PBitmapInfoHeader; lpbiOutput : PBitmapInfoHeader ) : LRESULT; function ICDecompressSetPalette( ic : HIC; lpbiPalette : PBitmapInfoHeader ) : LRESULT; // Decompression (ex) functions ========================================================================= function ICDecompressEx( // Decompress a single frame ic : HIC; dwFlags : dword; lpbiSrc : PBitmapInfoHeader; lpSrc : pointer; xSrc, ySrc : integer; dxSrc, dySrc : integer; lpbiDst : PBitmapInfoHeader; lpDst : pointer; xDst, yDst : integer; dxDst, dyDst : integer ) : LRESULT; function ICDecompressExBegin( // Start compression from a source format (lpbiInput) to a dest format (lpbiOutput) is supported. ic : HIC; dwFlags : dword; lpbiSrc : PBitmapInfoHeader; lpSrc : pointer; xSrc, ySrc : integer; dxSrc, dySrc : integer; lpbiDst : PBitmapInfoHeader; lpDst : pointer; xDst, yDst : integer; dxDst, dyDst : integer ) : LRESULT; function ICDecompressExQuery( ic : HIC; dwFlags : dword; lpbiSrc : PBitmapInfoHeader; lpSrc : pointer; xSrc, ySrc : integer; dxSrc, dySrc : integer; lpbiDst : PBitmapInfoHeader; lpDst : pointer; xDst, yDst : integer; dxDst, dyDst : integer ) : LRESULT; function ICDecompressExEnd( ic : HIC ) : LRESULT; // Higher level functions ============================================================================ function ICImageCompress( ic : HIC; // compressor to use uiFlags : uint; // flags (none yet) lpbiIn : PBitmapInfo; // format to compress from lpBits : pointer; // data to compress lpbiOut : PBitmapInfo; // compress to this (NULL ==> default) lQuality : longint; // quality to use var lSize : longint // compress to this size (0=whatever) ) : PDib; stdcall; function ICImageDecompress( ic : HIC; // compressor to use uiFlags : uint; // flags (none yet) lpbiIn : PBitmapInfo; // format to decompress from lpBits : pointer; // data to decompress lpbiOut : PBitmapInfo // decompress to this (NULL ==> default) ) : PDib; stdcall; // Drawing functions ========================================================================= function ICDrawBegin( // Start decompressing data with format (lpbiInput) directly to the screen, return zero if the decompressor supports drawing. ic : HIC; dwFlags : dword; hpal : HPALETTE; dc : HDC; xDst, yDst : integer; // source rectangle dxDst, dyDst : integer; lpbi : PBitmapInfoHeader; xSrc, ySrc : integer; dxSrc, dySrc : integer; dwRate : dword; // frames/second = (dwRate/dwScale) dwScale : dword ) : dword; stdcall; function ICDraw( // Decompress data directly to the screen ic : HIC; dwFlags : dword; // flags lpFormat : pointer; // format of frame to decompress lpData : pointer; // frame data to decompress cbData : dword; // size of data lTime : longint // time to draw this frame ) : dword; stdcall; function ICDrawSuggestFormat( ic : HIC; lpbiIn : PBitmapInfoHeader; lpbiOut : PBitmapInfoHeader; dxSrc, dySrc : integer; dxDst, dyDst : integer; icDecomp : HIC ) : LRESULT; function ICDrawQuery( // Determines if the compressor is willing to render the specified format. ic : HIC; lpbiInput : PBitmapInfoHeader ) : dword; function ICDrawChangePalette( ic : HIC; lpbiInput : PBitmapInfoHeader ) : dword; function ICGetBuffersWanted( ic : HIC; var Buffers : dword ) : LRESULT; function ICDrawStart( ic : HIC ) : LRESULT; function ICDrawEnd( ic : HIC ) : LRESULT; function ICDrawStartPlay( ic : HIC; lFrom, lTo : longint ) : LRESULT; function ICDrawStop( ic : HIC ) : LRESULT; function ICDrawStopPlay( ic : HIC ) : LRESULT; function ICDrawGetTime( ic : HIC; var lTime : longint ) : LRESULT; function ICDrawSetTime( ic : HIC; lTime : longint ) : LRESULT; function ICDrawRealize( ic : HIC; dc : HDC; fBackground : BOOL ) : LRESULT; function ICDrawFlush( ic : HIC ) : LRESULT; function ICDrawRenderBuffer( ic : HIC ) : LRESULT; // Status callback functions ========================================================================= function ICSetStatusProc( // Set the status callback function ic : HIC; dwFlags : dword; Param : LPARAM; StatusProc : TStatusProc ) : LRESULT; // Helper routines for DrawDib and MCIAVI =========================================================== function ICDecompressOpen( fccType : dword; fccHandler : dword; lpbiIn, lpbiOut : PBitmapInfoHeader ) : HIC; function ICDrawOpen( fccType : dword; fccHandler : dword; lpbiIn : PBitmapInfoHeader ) : HIC; function ICLocate( fccType : dword; fccHandler : dword; lpbiIn, lpbiOut : PBitmapInfoHeader; wFlags : word ) : HIC; stdcall; function ICGetDisplayFormat( ic : HIC; lpbiIn, lpbiOut : PBitmapInfoHeader; BitDepth : integer; dx, dy : integer ) : HIC; stdcall; // Structure used by ICSeqCompressFrame and ICCompressorChoose routines type PCompVars = ^TCompVars; TCompVars = packed record cbSize : longint; // set to sizeof(COMPVARS) before calling ICCompressorChoose dwFlags : dword; // see below... ic : HIC; // HIC of chosen compressor fccType : dword; // basically ICTYPE_VIDEO fccHandler : dword; // handler of chosen compressor or // "" or "DIB " lpbiIn : PBitmapInfo; // input format lpbiOut : PBitmapInfo; // output format - will compress to this lpBitsOut : pointer; lpBitsPrev : pointer; lFrame : longint; lKey : longint; // key frames how often? lDataRate : longint; // desired data rate KB/Sec lQ : longint; // desired quality lKeyCount : longint; lpState : pointer; // state of compressor cbState : longint; // size of the state end; const // FLAGS for dwFlags element of COMPVARS structure: // set this flag if you initialize COMPVARS before calling ICCompressorChoose ICMF_COMPVARS_VALID = $00000001; // COMPVARS contains valid data function ICCompressorChoose( // allows user to choose compressor, quality etc... WinHandle : HWND; // parent window for dialog uiFlags : uint; // flags pvIn : pointer; // input format (optional) lpData : pointer; // input data (optional) var cv : TCompVars; // data about the compressor/dlg lpszTitle : pchar // dialog title (optional) ) : BOOL; stdcall; const // defines for uiFlags ICMF_CHOOSE_KEYFRAME = $0001; // show KeyFrame Every box ICMF_CHOOSE_DATARATE = $0002; // show DataRate box ICMF_CHOOSE_PREVIEW = $0004; // allow expanded preview dialog ICMF_CHOOSE_ALLCOMPRESSORS = $0008; // don't only show those that can handle the input format or input data function ICSeqCompressFrameStart( pc : PCompVars; lpbiIn : PBitmapInfo ) : BOOL; stdcall; procedure ICSeqCompressFrameEnd( pc : PCompVars ); stdcall; function ICSeqCompressFrame( pc : PCompVars; // set by ICCompressorChoose uiFlags : uint; // flags lpBits : pointer; // input DIB bits var Key : boolean; // did it end up being a key frame? var lSize : longint // size to compress to/of returned image ) : pointer; stdcall; procedure ICCompressorFree( pc : PCompVars ); stdcall; implementation uses NumUtils; function StrToFourCC( const FourCC : string ) : dword; begin Result := VideoICM.FourCC( FourCC[1], FourCC[2], FourCC[3], FourCC[4] ); end; function FourCC( ch1, ch2, ch3, ch4 : char ) : dword; begin Result := ( byte( ch4 ) shl 24 ) or ( byte( ch3 ) shl 16 ) or ( byte( ch2 ) shl 8 ) or byte( ch1 ); end; function FourCCToStr( FourCC : dword ) : string; begin SetLength( Result, 4 ); pdword( Result )^ := FourCC; end; function ICInfo; external 'MSVFW32.DLL'; function ICGetInfo; external 'MSVFW32.DLL'; function ICOpen; external 'MSVFW32.DLL'; function ICOpenFunction; external 'MSVFW32.DLL'; function ICClose; external 'MSVFW32.DLL'; function ICSendMessage; external 'MSVFW32.DLL'; function ICInstall; external 'MSVFW32.DLL'; function ICRemove; external 'MSVFW32.DLL'; function ICCompress; external 'MSVFW32.DLL'; function ICDecompress; external 'MSVFW32.DLL'; function ICDrawBegin; external 'MSVFW32.DLL'; function ICDraw; external 'MSVFW32.DLL'; function ICLocate; external 'MSVFW32.DLL'; function ICGetDisplayFormat; external 'MSVFW32.DLL'; function ICImageCompress; external 'MSVFW32.DLL'; function ICImageDecompress; external 'MSVFW32.DLL'; function ICCompressorChoose; external 'MSVFW32.DLL'; function ICSeqCompressFrameStart; external 'MSVFW32.DLL'; procedure ICSeqCompressFrameEnd; external 'MSVFW32.DLL'; function ICSeqCompressFrame; external 'MSVFW32.DLL'; procedure ICCompressorFree; external 'MSVFW32.DLL'; // Query macros function ICQueryAbout( ic : HIC ) : boolean; begin Result := ICSendMessage( ic, ICM_ABOUT, -1, ICMF_ABOUT_QUERY ) = ICERR_OK; end; function ICAbout( ic : HIC; Wnd : HWND ) : LRESULT; begin Result := ICSendMessage( ic, ICM_ABOUT, Wnd, 0 ); end; function ICQueryConfigure( ic : HIC ) : boolean; begin Result := ICSendMessage( ic, ICM_CONFIGURE, -1, ICMF_CONFIGURE_QUERY ) = ICERR_OK; end; function ICConfigure( ic : HIC; Wnd : HWND ) : LRESULT; begin Result := ICSendMessage( ic, ICM_CONFIGURE, Wnd, 0 ); end; // Get/Set state macros function ICGetState( ic : HIC; info : pointer; size : dword ) : dword; begin Result := ICSendMessage( ic, ICM_GETSTATE, integer( info ), size ); end; function ICSetState( ic : HIC; info : pointer; size : dword ) : dword; begin Result := ICSendMessage( ic, ICM_SETSTATE, integer( info ), size ); end; function ICGetStateSize( ic : HIC ) : integer; begin Result := ICGetState( ic, nil, 0 ); end; // Get value macros function ICGetDefaultQuality( ic : HIC ) : integer; begin ICSendMessage( ic, ICM_GETDEFAULTQUALITY, integer( @Result ), sizeof( Result ) ); end; function ICGetDefaultKeyFrameRate( ic : HIC ) : integer; begin ICSendMessage( ic, ICM_GETDEFAULTKEYFRAMERATE, integer( @Result ), sizeof( Result ) ); end; // Draw Window macro function ICDrawWindow( ic : HIC; Dest : PRect ) : dword; begin Result := ICSendMessage( ic, ICM_DRAW_WINDOW, integer( Dest ), sizeof( TRect ) ); end; // Compression functions ============================================================================= function ICCompressBegin( ic : HIC; lpbiInput : PBitmapInfoHeader; lpbiOutput : PBitmapInfoHeader ) : LRESULT; begin Result := ICSendMessage( IC, ICM_COMPRESS_BEGIN, integer(lpbiInput), integer(lpbiOutput) ); end; function ICCompressQuery( ic : HIC; lpbiInput : PBitmapInfoHeader; lpbiOutput : PBitmapInfoHeader ) : LRESULT; begin Result := ICSendMessage( IC, ICM_COMPRESS_QUERY, integer(lpbiInput), integer(lpbiOutput) ); end; function ICCompressGetFormat( ic : HIC; lpbiInput : PBitmapInfoHeader; lpbiOutput : PBitmapInfoHeader ) : LRESULT; begin Result := ICSendMessage( ic, ICM_COMPRESS_GET_FORMAT, integer(lpbiInput), integer(lpbiOutput) ); end; function ICCompressGetFormatSize( ic : HIC; lpbiInput : PBitmapInfoHeader ) : dword; begin Result := ICCompressGetFormat( ic, lpbiInput, nil ); end; function ICCompressGetSize( ic : HIC; lpbiInput : PBitmapInfoHeader; lpbiOutput : PBitmapInfoHeader ) : dword; begin Result := ICSendMessage( ic, ICM_COMPRESS_GET_SIZE, integer(lpbiInput), integer(lpbiOutput) ); end; function ICCompressEnd( ic : HIC ) : LRESULT; begin Result := ICSendMessage( ic, ICM_COMPRESS_END, 0, 0 ); end; // Decompression functions ============================================================================= function ICDecompressBegin( ic : HIC; lpbiInput : PBitmapInfoHeader; lpbiOutput : PBitmapInfoHeader ) : LRESULT; begin Result := ICSendMessage( ic, ICM_DECOMPRESS_BEGIN, integer(lpbiInput), integer(lpbiOutput) ); end; function ICDecompressQuery( ic : HIC; lpbiInput : PBitmapInfoHeader; lpbiOutput : PBitmapInfoHeader ) : LRESULT; begin Result := ICSendMessage( IC, ICM_DECOMPRESS_QUERY, integer(lpbiInput), integer(lpbiOutput) ); end; function ICDecompressGetFormat( ic : HIC; lpbiInput : PBitmapInfoHeader; lpbiOutput : PBitmapInfoHeader ) : LRESULT; begin Result := ICSendMessage( ic, ICM_DECOMPRESS_GET_FORMAT, integer(lpbiInput), integer(lpbiOutput) ); end; function ICDecompressGetFormatSize( ic : HIC; lpbiInput : PBitmapInfoHeader ) : dword; begin Result := ICDecompressGetFormat( ic, lpbiInput, nil ); end; function ICDecompressEnd( ic : HIC ) : LRESULT; begin Result := ICSendMessage( ic, ICM_DECOMPRESS_END, 0, 0 ); end; function ICDecompressGetPalette( ic : HIC; lpbiInput : PBitmapInfoHeader; lpbiOutput : PBitmapInfoHeader ) : LRESULT; begin Result := ICSendMessage( ic, ICM_DECOMPRESS_GET_PALETTE, integer(lpbiInput), integer(lpbiOutput) ); end; function ICDecompressSetPalette( ic : HIC; lpbiPalette : PBitmapInfoHeader ) : LRESULT; begin Result := ICSendMessage( ic, ICM_DECOMPRESS_SET_PALETTE, integer(lpbiPalette), 0 ); end; // Decompression (ex) functions ========================================================================= function ICDecompressEx( // Decompress a single frame ic : HIC; dwFlags : dword; lpbiSrc : PBitmapInfoHeader; lpSrc : pointer; xSrc, ySrc : integer; dxSrc, dySrc : integer; lpbiDst : PBitmapInfoHeader; lpDst : pointer; xDst, yDst : integer; dxDst, dyDst : integer ) : LRESULT; var ICData : TICDecompressEx; begin ICData.dwFlags := dwFlags; ICData.lpbiSrc := lpbiSrc; ICData.lpSrc := lpSrc; ICData.xSrc := xSrc; ICData.ySrc := ySrc; ICData.dxSrc := dxSrc; ICData.dySrc := dySrc; ICData.lpbiDst := lpbiDst; ICData.lpDst := lpDst; ICData.xDst := xDst; ICData.yDst := yDst; ICData.dxDst := dxDst; ICData.dyDst := dyDst; // Note that ICM swaps round the length and pointer length in lparam2, pointer in lparam1 Result := ICSendMessage( ic, ICM_DECOMPRESSEX, integer( @ICData ), sizeof( ICData ) ) ; end; function ICDecompressExBegin( // Start compression from a source format (lpbiInput) to a dest format (lpbiOutput) is supported. ic : HIC; dwFlags : dword; lpbiSrc : PBitmapInfoHeader; lpSrc : pointer; xSrc, ySrc : integer; dxSrc, dySrc : integer; lpbiDst : PBitmapInfoHeader; lpDst : pointer; xDst, yDst : integer; dxDst, dyDst : integer ) : LRESULT; var ICData : TICDecompressEx; begin ICData.dwFlags := dwFlags; ICData.lpbiSrc := lpbiSrc; ICData.lpSrc := lpSrc; ICData.xSrc := xSrc; ICData.ySrc := ySrc; ICData.dxSrc := dxSrc; ICData.dySrc := dySrc; ICData.lpbiDst := lpbiDst; ICData.lpDst := lpDst; ICData.xDst := xDst; ICData.yDst := yDst; ICData.dxDst := dxDst; ICData.dyDst := dyDst; // Note that ICM swaps round the length and pointer length in lparam2, pointer in lparam1 Result := ICSendMessage( ic, ICM_DECOMPRESSEX_BEGIN, integer( @ICData ), sizeof( ICData ) ) ; end; function ICDecompressExQuery( ic : HIC; dwFlags : dword; lpbiSrc : PBitmapInfoHeader; lpSrc : pointer; xSrc, ySrc : integer; dxSrc, dySrc : integer; lpbiDst : PBitmapInfoHeader; lpDst : pointer; xDst, yDst : integer; dxDst, dyDst : integer ) : LRESULT; var ICData : TICDecompressEx; begin ICData.dwFlags := dwFlags; ICData.lpbiSrc := lpbiSrc; ICData.lpSrc := lpSrc; ICData.xSrc := xSrc; ICData.ySrc := ySrc; ICData.dxSrc := dxSrc; ICData.dySrc := dySrc; ICData.lpbiDst := lpbiDst; ICData.lpDst := lpDst; ICData.xDst := xDst; ICData.yDst := yDst; ICData.dxDst := dxDst; ICData.dyDst := dyDst; // Note that ICM swaps round the length and pointer length in lparam2, pointer in lparam1 Result := ICSendMessage( ic, ICM_DECOMPRESSEX_QUERY, integer( @ICData ), sizeof( ICData ) ) ; end; function ICDecompressExEnd( ic : HIC ) : LRESULT; begin Result := ICSendMessage( ic, ICM_DECOMPRESSEX_END, 0, 0 ); end; // Drawing functions ========================================================================= function ICDrawSuggestFormat( ic : HIC; lpbiIn : PBitmapInfoHeader; lpbiOut : PBitmapInfoHeader; dxSrc, dySrc : integer; dxDst, dyDst : integer; icDecomp : HIC ) : LRESULT; var ICData : TICDrawSuggest; begin ICData.hicDecompressor := icDecomp; ICData.lpbiIn := lpbiIn; ICData.lpbiSuggest := lpbiOut; ICData.dxSrc := dxSrc; ICData.dySrc := dySrc; ICData.dxDst := dxDst; ICData.dyDst := dyDst; // Note that ICM swaps round the length and pointer length in lparam2, pointer in lparam1 Result := ICSendMessage( ic, ICM_DRAW_SUGGESTFORMAT, integer( @ICData ), sizeof( ICData ) ) ; end; function ICDrawQuery( // Determines if the compressor is willing to render the specified format. ic : HIC; lpbiInput : PBitmapInfoHeader ) : dword; begin Result := ICSendMessage( ic, ICM_DRAW_QUERY, dword( lpbiInput ), 0 ); end; function ICDrawChangePalette( ic : HIC; lpbiInput : PBitmapInfoHeader ) : dword; begin Result := ICSendMessage( ic, ICM_DRAW_CHANGEPALETTE, dword( lpbiInput ), 0 ); end; function ICGetBuffersWanted( ic : HIC; var Buffers : dword ) : LRESULT; begin Result := ICSendMessage( ic, ICM_DRAW_CHANGEPALETTE, dword( @Buffers ), 0 ); end; function ICDrawStart( ic : HIC ) : LRESULT; begin Result := ICSendMessage( ic, ICM_DRAW_START, 0, 0 ); end; function ICDrawEnd( ic : HIC ) : LRESULT; begin Result := ICSendMessage( ic, ICM_DRAW_END, 0, 0 ); end; function ICDrawStartPlay( ic : HIC; lFrom, lTo : longint ) : LRESULT; begin Result := ICSendMessage( ic, ICM_DRAW_START_PLAY, lFrom, lTo ); end; function ICDrawStop( ic : HIC ) : LRESULT; begin Result := ICSendMessage( ic, ICM_DRAW_STOP, 0, 0 ); end; function ICDrawStopPlay( ic : HIC ) : LRESULT; begin Result := ICSendMessage( ic, ICM_DRAW_STOP_PLAY, 0, 0 ); end; function ICDrawGetTime( ic : HIC; var lTime : longint ) : LRESULT; begin Result := ICSendMessage( ic, ICM_DRAW_GETTIME, dword( @lTime ), 0 ); end; function ICDrawSetTime( ic : HIC; lTime : longint ) : LRESULT; begin Result := ICSendMessage( ic, ICM_DRAW_SETTIME, dword( lTime ), 0 ); end; function ICDrawRealize( ic : HIC; dc : HDC; fBackground : BOOL ) : LRESULT; begin Result := ICSendMessage( ic, ICM_DRAW_REALIZE, dword( dc ), dword( fBackground ) ); end; function ICDrawFlush( ic : HIC ) : LRESULT; begin Result := ICSendMessage( ic, ICM_DRAW_FLUSH, 0, 0 ); end; function ICDrawRenderBuffer( ic : HIC ) : LRESULT; begin Result := ICSendMessage( ic, ICM_DRAW_RENDERBUFFER, 0, 0 ); end; // Status callback functions ========================================================================= function ICSetStatusProc( // Set the status callback function ic : HIC; dwFlags : dword; Param : LPARAM; StatusProc : TStatusProc ) : LRESULT; var ICData : TICSetStatusProc; begin ICData.dwFlags := dwFlags; ICData.Param := Param; ICData.Status := StatusProc; // Note that ICM swaps round the length and pointer length in lparam2, pointer in lparam1 Result := ICSendMessage( ic, ICM_SET_STATUS_PROC, integer( @ICData ), sizeof( ICData ) ) ; end; // Helper routines for DrawDib and MCIAVI =========================================================== function ICDecompressOpen( fccType : dword; fccHandler : dword; lpbiIn, lpbiOut : PBitmapInfoHeader ) : HIC; begin Result := ICLocate( fccType, fccHandler, lpbiIn, lpbiOut, ICMODE_DECOMPRESS ); end; function ICDrawOpen( fccType : dword; fccHandler : dword; lpbiIn : PBitmapInfoHeader ) : HIC; begin Result := ICLocate( fccType, fccHandler, lpbiIn, nil, ICMODE_DRAW ); end; function ICCompressDecompressImage( ic : HIC; // compressor (NULL if any will do) uiFlags : uint; // silly flags lpbiIn : PBitmapInfoHeader; // input DIB format lpBits : pointer; // input DIB bits lpbiOut : PBitmapInfoHeader; // output format (NULL => default) lQuality : longint // the reqested quality ) : PDib; begin if lpbiIn.biCompression = 0 then begin Result := ICCompressImage( ic, uiFlags, lpbiIn, lpBits, lpbiOut, lQuality ); if Result = nil then Result := ICDecompressImage( ic, uiFlags, lpbiIn, lpBits, lpbiOut ); end else begin Result := ICDecompressImage( ic, uiFlags, lpbiIn, lpBits, lpbiOut ); if Result = nil then Result := ICCompressImage( ic, uiFlags, lpbiIn, lpBits, lpbiOut, lQuality ); end end; function ICCompressImage( ic : HIC; // compressor (NULL if any will do) uiFlags : uint; // silly flags lpbiIn : PBitmapInfoHeader; // input DIB format lpBits : pointer; // input DIB bits lpbiOut : PBitmapInfoHeader; // output format (NULL => default) lQuality : longint // the reqested quality ) : PDib; var l : longint; UseDefaultIC : boolean; SourceTopDown : boolean; dwFlags : dword; ckid : dword; lpbi : PDib; begin dwFlags := 0; ckid := 0; lpbi := nil; Result := nil; UseDefaultIC := false; SourceTopDown := false; try SourceTopDown := ( lpbiIn.biHeight < 0 ); // This ICM thing can't handle top-down DIBs!! Can you believe it? if SourceTopDown then begin lpbiIn := DibInvert( lpbiIn, lpBits ); lpBits := DibPtr( lpbiIn ); end; UseDefaultIC := ( ic = 0 ); if UseDefaultIC then // either locate a compressor or use the one supplied ic := ICLocate( ICTYPE_VIDEO, 0, lpbiIn, lpbiOut, ICMODE_COMPRESS ); if ic <> 0 then // make sure the found compressor can handle this format. if ICCompressQuery( ic, lpbiIn, nil ) = ICERR_OK then // now make a DIB header big enough to hold the ouput format begin l := ICCompressGetFormatSize( ic, lpbiIn ); if l > 0 then begin getmem( lpbi, l + 256 * sizeof( TRGBQuad ) ); // if the compressor likes the passed format, use it else use the default // format of the compressor. if (lpbiOut = nil) or ( ICCompressQuery( ic, lpbiIn, lpbiOut ) <> ICERR_OK ) then ICCompressGetFormat( ic, lpbiIn, lpbi ) else move( lpbiOut^, lpbi^, lpbiOut.biSize + lpbiOut.biClrUsed * sizeof(TRGBQuad) ); with lpbi^ do begin biSizeImage := ICCompressGetSize( ic, lpbiIn, lpbi ); biClrUsed := DibNumColors( lpbi ); end; // now resize the DIB to be the maximal size. ReallocMem( lpbi, DibSize( lpbi ) ); if ICCompressBegin( ic, lpbiIn, lpbi ) = ICERR_OK // now compress it. then begin if lpBits = nil then lpBits := DibPtr( lpbiIn ); if lQuality = ICQUALITY_DEFAULT then lQuality := ICGetDefaultQuality( ic ); l := ICCompress( ic, 0, // flags lpbi, // output format DibPtr( lpbi ), // output data lpbiIn, // format of frame to compress lpBits, // frame data to compress @ckid, // ckid for data in AVI file @dwFlags, // flags in the AVI index. 0, // frame number of seq. 0, // reqested size in bytes. (if non zero) lQuality, // quality nil, // format of previous frame nil ); // previous frame if ( l >= ICERR_OK ) and ( ICCompressEnd( ic ) = ICERR_OK ) then // now resize the DIB to be the real size. begin ReallocMem( lpbi, DibSize( lpbi ) ); Result := lpbi; end; end; end; end; except Result := nil; end; if UseDefaultIC and ( ic <> 0 ) then ICClose( ic ); if SourceTopDown then DibFree( lpbiIn ); if ( Result = nil ) and ( lpbi <> nil ) // There was an error... then freemem( lpbi ); end; function ICDecompressImage( ic : HIC; // compressor (NULL if any will do) uiFlags : uint; // silly flags lpbiIn : PBitmapInfoHeader; // input DIB format lpBits : pointer; // input DIB bits lpbiOut : PBitmapInfoHeader // output format (NULL => default) ) : PDib; var l : longint; UseDefaultIC : boolean; lpbi : PBitmapInfoHeader; begin lpbi := nil; Result := nil; UseDefaultIC := false; try UseDefaultIC := ( ic = 0 ); if UseDefaultIC then // either locate a compressor or use the one supplied. ic := ICLocate( ICTYPE_VIDEO, 0, lpbiIn, lpbiOut, ICMODE_DECOMPRESS ); if ic <> 0 then // make sure the found compressor can handle this format. if ICDecompressQuery( ic, lpbiIn, nil ) = ICERR_OK then // now make a DIB header big enought to hold the ouput format begin l := ICDecompressGetFormatSize( ic, lpbiIn ); if l > 0 then begin getmem( lpbi, l + 256 * sizeof( TRGBQuad ) ); // if the compressor likes the passed format, use it else use the default // format of the compressor. if ( lpbiOut = nil ) or ( ICDecompressQuery( ic, lpbiIn, lpbiOut ) <> ICERR_OK ) then ICDecompressGetFormat( ic, lpbiIn, lpbi ) else move( lpbiOut^, lpbi^, lpbiOut.biSize + lpbiOut.biClrUsed * sizeof(TRGBQuad) ); with lpbi^ do begin biSizeImage := DibSize( lpbi ); //ICDecompressGetSize( ic, lpbi ); biClrUsed := DibNumColors( lpbi ); end; // for decompress make sure the palette (ie color table) is correct if lpbi.biBitCount <= 8 then ICDecompressGetPalette( ic, lpbiIn, lpbi ); // now resize the DIB to be the maximal size. ReallocMem( lpbi, DibSize( lpbi ) ); if ICDecompressBegin( ic, lpbiIn, lpbi ) = ICERR_OK // now deccompress it. then begin if lpBits = nil then lpBits := DibPtr( lpbiIn ); l := ICDecompress( ic, 0, // flags lpbiIn, // format of frame to decompress lpBits, // frame data to decompress lpbi, // output format DibPtr( lpbi ) ); // output data if ( l >= ICERR_OK ) and ( ICDecompressEnd( ic ) = ICERR_OK ) then Result := lpbi; end; end; end; except Result := nil; end; if UseDefaultIC and ( ic <> 0 ) then ICClose( ic ); if ( Result = nil ) and ( lpbi <> nil ) // There was an error... then freemem( lpbi ); end; end.
(* * Copyright (c) 2010-2020, Alexandru Ciobanu (alex+git@ciobanu.org) * 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 this library 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 AUTHOR ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) {$INCLUDE '../TZDBPK/Version.inc'} unit TZStrs; interface procedure CLIError(const AMessage: string); procedure CLIFatal(const AMessage: string); procedure CLIMessage(const AMessage: string); { File format constants } const CAbbDayNames: array[1..7] of string = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'); CAbbMonthNames: array[1..12] of string = ( 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'); CLastDoW = 'last'; CNthDoW = '>='; CPreDoW = '<='; CMinDate = 'min'; CMaxDate = 'max'; COnlyDate = 'only'; CCommentChar = '#'; CLinkId = 'Link'; CRuleId = 'Rule'; CZoneId = 'Zone'; resourcestring CCLIHeader = 'TZ Compiler. (c) 2010-2019 Alexandru Ciobanu (alex+git@ciobanu.org). Part of TZDB project.'; CCLIUsage = 'USAGE: <TZCompile> input-dir output-file iana_db_version' + sLineBreak + ' input-dir : The path to the directory containing tzinfo database files.' + sLineBreak + ' output-file : The path to the INC file that will contain the converted data.' + sLineBreak + ' iana_db_version: The version of the IANA DB that is being compiled (e.g. 2019b).'; CCLIError_Prefix = 'ERROR:'; CCLIFatal_Prefix = 'FATAL:'; CCLIMessage_Prefix = 'NOTE:'; { Main messages } CCLIBadInputDir = 'Input directory "%s" does not exist or is inaccessible.'; CCLIBadOutputDir = 'Output file''s directory "%s" does not exist or is inaccessible.'; CCLIBadVersion = 'The supplied version string "%s" is invalid.'; CCLIGlobalException = 'An unhandled exception was raised while processing files. Exception type is %s; and message is "%s".'; { Processing messages } CPMBadMonthIdentifier = 'Found an invalid month identifier "%s".'; CPMBadDoWIdentifier = 'Found an invalid "day of week" identifier "%s".'; CPMBadTimeOfDay = 'Found an invalid "time of day" identifier "%s".'; CPMBadHour = 'Found an invalid hour value "%s" (in "time of day").'; CPMBadMinute = 'Found an invalid minute value "%s" (in "time of day").'; CPMBadSecond = 'Found an invalid second value "%s" (in "time of day").'; CPMBadDoWInLast = 'Found an invalid "day of week" "%s" (in "last occurence of" mode).'; CPMBadDoWInNth = 'Found an invalid "day of week" "%s" (in "Nth occurence of" mode).'; CPMBadIndexInNth = 'Found an invalid "after day index" "%s" (in "Nth occurence of" mode).'; CPMBadIndexInFixed = 'Found an invalid "day index" "%s" (in "fixed day" mode).'; CPMBadRuleSplitCount = 'Found a rule line with an invalid number of elements: %d.'; CPMBadRuleFROMField = 'Found an invalid FROM field (parse message was "%s") in rule [%s].'; CPMBadRuleTOField = 'Found an invalid TO field (parse message was "%s") in rule [%s].'; CPMBadRuleINField = 'Found an invalid IN field (parse message was "%s") in rule [%s].'; CPMBadRuleONField = 'Found an invalid ON field (parse message was "%s") in rule [%s].'; CPMBadRuleATField = 'Found an invalid AT field (parse message was "%s") in rule [%s].'; CPMBadRuleSAVEField = 'Found an invalid SAVE field (parse message was "%s") in rule [%s].'; CPMBadZoneSplitCount = 'Found a zone line with an invalid number of elements: %d.'; CPMBadZoneGMTOFFField = 'Found an invalid GMTOFF field (parse message was "%s") in zone [%s].'; CPMBadZoneUNTILFieldYear = 'Found an invalid UNTIL/year field (parse message was "%s") in zone [%s].'; CPMBadZoneUNTILFieldMonth = 'Found an invalid UNTIL/year field (parse message was "%s") in zone [%s].'; CPMBadZoneUNTILFieldDay = 'Found an invalid UNTIL/year field (parse message was "%s") in zone [%s].'; CPMBadZoneUNTILFieldTime = 'Found an invalid UNTIL/year field (parse message was "%s") in zone [%s].'; CPMBadLineSplitCount = 'Found a link line with an invalid number of elements: %d.'; CPMBadLineFROM = 'Found an invalid FROM field (empty or bad format).'; CPMBadLineTO = 'Found an invalid TO field (empty or bad format).'; CPMAliasExists = 'Alias "%s" already points to zone "%s". Cannot reassign to zone "%s".'; CPMAddedAlias = 'Added new alias "%s" for zone "%s".'; CPMAliasFailed = 'Failed to add alias "%s". The referenced time zone "%s" does not exist.'; CPMAddedZone = 'Added new zone "%s".'; CPMAddedRuleFamily = 'Added new rule family "%s".'; CPMAddedRule = 'Added new rule for month %d, day [%d/%d/%d/%d], at %d, char "%s", offset %d and letters "%s".'; CPMBadFile = 'Unable to parse "%s" line in file (%s). Skipping!'; CPMStartedFile = 'Processing file "%s" ...'; CPMStats = 'Processed %d rules; %d zones; %d day parts; %d unique rules; %d unique rule families; %d aliases.'; CPMStartDump = 'Dumping parsed contents to "%s" ...'; implementation procedure CLIFatal(const AMessage: string); begin Write(CCLIFatal_Prefix, ' '); WriteLn(AMessage); Halt(1); end; procedure CLIError(const AMessage: string); begin Write(CCLIError_Prefix, ' '); WriteLn(AMessage); end; procedure CLIMessage(const AMessage: string); begin Write(CCLIMessage_Prefix, ' '); WriteLn(AMessage); end; end.
unit DDrawErrors; interface uses Windows; function GetErrorAsText(Error : HResult) : string; implementation const cMaxErrors = 111; type TDirectDrawError = record Code : HResult; Text : string; end; const DDrawErrors : array [0 .. pred(cMaxErrors)] of TDirectDrawError = ( (Code : DD_OK; Text : 'DD_OK'), (Code : DDERR_ALREADYINITIALIZED; Text : 'DDERR_ALREADYINITIALIZED'), (Code : DDERR_BLTFASTCANTCLIP; Text : 'DDERR_BLTFASTCANTCLIP'), (Code : DDERR_CANNOTATTACHSURFACE; Text : 'DDERR_CANNOTATTACHSURFACE'), (Code : DDERR_CANNOTDETACHSURFACE; Text : 'DDERR_CANNOTDETACHSURFACE'), (Code : DDERR_CANTCREATEDC; Text : 'DDERR_CANTCREATEDC'), (Code : DDERR_CANTDUPLICATE; Text : 'DDERR_CANTDUPLICATE'), (Code : DDERR_CANTLOCKSURFACE; Text : 'DDERR_CANTLOCKSURFACE'), (Code : DDERR_CANTPAGELOCK; Text : 'DDERR_CANTPAGELOCK'), (Code : DDERR_CANTPAGEUNLOCK; Text : 'DDERR_CANTPAGEUNLOCK'), (Code : DDERR_CLIPPERISUSINGHWND; Text : 'DDERR_CLIPPERISUSINGHWND'), (Code : DDERR_COLORKEYNOTSET; Text : 'DDERR_COLORKEYNOTSET'), (Code : DDERR_CURRENTLYNOTAVAIL; Text : 'DDERR_CURRENTLYNOTAVAIL'), (Code : DDERR_DCALREADYCREATED; Text : 'DDERR_DCALREADYCREATED'), (Code : DDERR_DEVICEDOESNTOWNSURFACE; Text : 'DDERR_DEVICEDOESNTOWNSURFACE'), (Code : DDERR_DIRECTDRAWALREADYCREATED; Text : 'DDERR_DIRECTDRAWALREADYCREATED'), (Code : DDERR_EXCEPTION; Text : 'DDERR_EXCEPTION'), (Code : DDERR_EXCLUSIVEMODEALREADYSET; Text : 'DDERR_EXCLUSIVEMODEALREADYSET'), (Code : DDERR_EXPIRED; Text : 'DDERR_EXPIRED'), (Code : DDERR_GENERIC; Text : 'DDERR_GENERIC'), (Code : DDERR_HEIGHTALIGN; Text : 'DDERR_HEIGHTALIGN'), (Code : DDERR_HWNDALREADYSET; Text : 'DDERR_HWNDALREADYSET'), (Code : DDERR_HWNDSUBCLASSED; Text : 'DDERR_HWNDSUBCLASSED'), (Code : DDERR_IMPLICITLYCREATED; Text : 'DDERR_IMPLICITLYCREATED'), (Code : DDERR_INCOMPATIBLEPRIMARY; Text : 'DDERR_INCOMPATIBLEPRIMARY'), (Code : DDERR_INVALIDCAPS; Text : 'DDERR_INVALIDCAPS'), (Code : DDERR_INVALIDCLIPLIST; Text : 'DDERR_INVALIDCLIPLIST'), (Code : DDERR_INVALIDDIRECTDRAWGUID; Text : 'DDERR_INVALIDDIRECTDRAWGUID'), (Code : DDERR_INVALIDMODE; Text : 'DDERR_INVALIDMODE'), (Code : DDERR_INVALIDOBJECT; Text : 'DDERR_INVALIDOBJECT'), (Code : DDERR_INVALIDPARAMS; Text : 'DDERR_INVALIDPARAMS'), (Code : DDERR_INVALIDPIXELFORMAT; Text : 'DDERR_INVALIDPIXELFORMAT'), (Code : DDERR_INVALIDPOSITION; Text : 'DDERR_INVALIDPOSITION'), (Code : DDERR_INVALIDRECT; Text : 'DDERR_INVALIDRECT'), (Code : DDERR_INVALIDSTREAM; Text : 'DDERR_INVALIDSTREAM'), (Code : DDERR_INVALIDSURFACETYPE; Text : 'DDERR_INVALIDSURFACETYPE'), (Code : DDERR_LOCKEDSURFACES; Text : 'DDERR_LOCKEDSURFACES'), (Code : DDERR_MOREDATA; Text : 'DDERR_MOREDATA'), (Code : DDERR_NO3D; Text : 'DDERR_NO3D'), (Code : DDERR_NOALPHAHW; Text : 'DDERR_NOALPHAHW'), (Code : DDERR_NOBLTHW; Text : 'DDERR_NOBLTHW'), (Code : DDERR_NOCLIPLIST; Text : 'DDERR_NOCLIPLIST'), (Code : DDERR_NOCLIPPERATTACHED; Text : 'DDERR_NOCLIPPERATTACHED'), (Code : DDERR_NOCOLORCONVHW; Text : 'DDERR_NOCOLORCONVHW'), (Code : DDERR_NOCOLORKEY; Text : 'DDERR_NOCOLORKEY'), (Code : DDERR_NOCOLORKEYHW; Text : 'DDERR_NOCOLORKEYHW'), (Code : DDERR_NOCOOPERATIVELEVELSET; Text : 'DDERR_NOCOOPERATIVELEVELSET'), (Code : DDERR_NODC; Text : 'DDERR_NODC'), (Code : DDERR_NODDROPSHW; Text : 'DDERR_NODDROPSHW'), (Code : DDERR_NODIRECTDRAWHW; Text : 'DDERR_NODIRECTDRAWHW'), (Code : DDERR_NODIRECTDRAWSUPPORT; Text : 'DDERR_NODIRECTDRAWSUPPORT'), (Code : DDERR_NOEMULATION; Text : 'DDERR_NOEMULATION'), (Code : DDERR_NOEXCLUSIVEMODE; Text : 'DDERR_NOEXCLUSIVEMODE'), (Code : DDERR_NOFLIPHW; Text : 'DDERR_NOFLIPHW'), (Code : DDERR_NOFOCUSWINDOW; Text : 'DDERR_NOFOCUSWINDOW'), (Code : DDERR_NOGDI; Text : 'DDERR_NOGDI'), (Code : DDERR_NOHWND; Text : 'DDERR_NOHWND'), (Code : DDERR_NOMIPMAPHW; Text : 'DDERR_NOMIPMAPHW'), (Code : DDERR_NOMIRRORHW; Text : 'DDERR_NOMIRRORHW'), (Code : DDERR_NONONLOCALVIDMEM; Text : 'DDERR_NONONLOCALVIDMEM'), (Code : DDERR_NOOPTIMIZEHW; Text : 'DDERR_NOOPTIMIZEHW'), (Code : DDERR_NOOVERLAYDEST; Text : 'DDERR_NOOVERLAYDEST'), (Code : DDERR_NOOVERLAYHW; Text : 'DDERR_NOOVERLAYHW'), (Code : DDERR_NOPALETTEATTACHED; Text : 'DDERR_NOPALETTEATTACHED'), (Code : DDERR_NOPALETTEHW; Text : 'DDERR_NOPALETTEHW'), (Code : DDERR_NORASTEROPHW; Text : 'DDERR_NORASTEROPHW'), (Code : DDERR_NOROTATIONHW; Text : 'DDERR_NOROTATIONHW'), (Code : DDERR_NOSTRETCHHW; Text : 'DDERR_NOSTRETCHHW'), (Code : DDERR_NOT4BITCOLOR; Text : 'DDERR_NOT4BITCOLOR'), (Code : DDERR_NOT4BITCOLORINDEX; Text : 'DDERR_NOT4BITCOLORINDEX'), (Code : DDERR_NOT8BITCOLOR; Text : 'DDERR_NOT8BITCOLOR'), (Code : DDERR_NOTAOVERLAYSURFACE; Text : 'DDERR_NOTAOVERLAYSURFACE'), (Code : DDERR_NOTEXTUREHW; Text : 'DDERR_NOTEXTUREHW'), (Code : DDERR_NOTFLIPPABLE; Text : 'DDERR_NOTFLIPPABLE'), (Code : DDERR_NOTFOUND; Text : 'DDERR_NOTFOUND'), (Code : DDERR_NOTINITIALIZED; Text : 'DDERR_NOTINITIALIZED'), (Code : DDERR_NOTLOADED; Text : 'DDERR_NOTLOADED'), (Code : DDERR_NOTLOCKED; Text : 'DDERR_NOTLOCKED'), (Code : DDERR_NOTPAGELOCKED; Text : 'DDERR_NOTPAGELOCKED'), (Code : DDERR_NOTPALETTIZED; Text : 'DDERR_NOTPALETTIZED'), (Code : DDERR_NOVSYNCHW; Text : 'DDERR_NOVSYNCHW'), (Code : DDERR_NOZBUFFERHW; Text : 'DDERR_NOZBUFFERHW'), (Code : DDERR_NOZOVERLAYHW; Text : 'DDERR_NOZOVERLAYHW'), (Code : DDERR_OUTOFCAPS; Text : 'DDERR_OUTOFCAPS'), (Code : DDERR_OUTOFMEMORY; Text : 'DDERR_OUTOFMEMORY'), (Code : DDERR_OUTOFVIDEOMEMORY; Text : 'DDERR_OUTOFVIDEOMEMORY'), (Code : DDERR_OVERLAPPINGRECTS; Text : 'DDERR_OVERLAPPINGRECTS'), (Code : DDERR_OVERLAYCANTCLIP; Text : 'DDERR_OVERLAYCANTCLIP'), (Code : DDERR_OVERLAYCOLORKEYONLYONEACTIVE; Text : 'DDERR_OVERLAYCOLORKEYONLYONEACTIVE'), (Code : DDERR_OVERLAYNOTVISIBLE; Text : 'DDERR_OVERLAYNOTVISIBLE'), (Code : DDERR_PALETTEBUSY; Text : 'DDERR_PALETTEBUSY'), (Code : DDERR_PRIMARYSURFACEALREADYEXISTS; Text : 'DDERR_PRIMARYSURFACEALREADYEXISTS'), (Code : DDERR_REGIONTOOSMALL; Text : 'DDERR_REGIONTOOSMALL'), (Code : DDERR_SURFACEALREADYATTACHED; Text : 'DDERR_SURFACEALREADYATTACHED'), (Code : DDERR_SURFACEALREADYDEPENDENT; Text : 'DDERR_SURFACEALREADYDEPENDENT'), (Code : DDERR_SURFACEBUSY; Text : 'DDERR_SURFACEBUSY'), (Code : DDERR_SURFACEISOBSCURED; Text : 'DDERR_SURFACEISOBSCURED'), (Code : DDERR_SURFACELOST; Text : 'DDERR_SURFACELOST'), (Code : DDERR_SURFACENOTATTACHED; Text : 'DDERR_SURFACENOTATTACHED'), (Code : DDERR_TOOBIGHEIGHT; Text : 'DDERR_TOOBIGHEIGHT'), (Code : DDERR_TOOBIGSIZE; Text : 'DDERR_TOOBIGSIZE'), (Code : DDERR_TOOBIGWIDTH; Text : 'DDERR_TOOBIGWIDTH'), (Code : DDERR_UNSUPPORTED; Text : 'DDERR_UNSUPPORTED'), (Code : DDERR_UNSUPPORTEDFORMAT; Text : 'DDERR_UNSUPPORTEDFORMAT'), (Code : DDERR_UNSUPPORTEDMASK; Text : 'DDERR_UNSUPPORTEDMASK'), (Code : DDERR_UNSUPPORTEDMODE; Text : 'DDERR_UNSUPPORTEDMODE'), (Code : DDERR_VERTICALBLANKINPROGRESS; Text : 'DDERR_VERTICALBLANKINPROGRESS'), (Code : DDERR_VIDEONOTACTIVE; Text : 'DDERR_VIDEONOTACTIVE'), (Code : DDERR_WASSTILLDRAWING; Text : 'DDERR_WASSTILLDRAWING'), (Code : DDERR_WRONGMODE; Text : 'DDERR_WRONGMODE'), (Code : DDERR_XALIGN; Text : 'DDERR_XALIGN') ); function GetErrorAsText(Error : HResult) : string; var i : integer; begin i := 0; Found := false; while (i < cMaxErrors) and not Found do begin Found := DDrawErrors[i].Code = Error; if not Found then inc(i); end; if i < cMaxErrors then Result := DDrawError[i].Text else Result := 'Unknown error'; end; end.
program COPYTEIL ( INPFILE , OUTFILE ) ; //************************************************ // Programm kopiert Binaerdateien // verwendet CSP RDD //************************************************ // war in PCINT noch nicht implementiert (11.2019) // CSP RDD verwendet fread, fuellt allerdings // am Ende zu kurzen Buffer mit Hex Nullen auf // dadurch wird Zieldatei immer auf 1024 ohne // Rest teilbare Laenge verlaengert //************************************************ // eof erst, wenn fread Ergebnis 0 bringt. //************************************************ // Abhilfe: spaeter Funktion schreiben, die // tatsaechliche gelesene Laenge der Lesefunktion // abfragbar macht (Ergebnis von fread). // Das kann im letzten fread weniger als die // angeforderte Satzlaenge sein. //************************************************ const BUFSIZE = 1024 ; type BUFFER = CHAR ( BUFSIZE ) ; var INPFILE : FILE of BUFFER ; OUTFILE : FILE of BUFFER ; X : BUFFER ; SATZZAHL : INTEGER ; begin (* HAUPTPROGRAMM *) RESET ( INPFILE ) ; REWRITE ( OUTFILE ) ; SATZZAHL := 0 ; while not EOF ( INPFILE ) do begin READ ( INPFILE , X ) ; WRITE ( OUTFILE , X ) ; SATZZAHL := SATZZAHL + 1 ; if SATZZAHL MOD 100000 = 0 then WRITELN ( SATZZAHL , ' Buffer ausgegeben' ) ; end (* while *) ; WRITELN ( SATZZAHL , ' Buffer ausgegeben' ) ; end (* HAUPTPROGRAMM *) .
unit IntUseBar; interface uses DGLE, DGLE_Types, Engine; type TIntUseBar = class(TObject) private pUseBar: ITexture; FLeft: Integer; FTop: Integer; procedure SetLeft(const Value: Integer); procedure SetTop(const Value: Integer); public constructor Create; destructor Destroy; override; procedure Render(); function MouseOver(): Boolean; property Top: Integer read FTop write SetTop; property Left: Integer read FLeft write SetLeft; end; implementation { TIntUseBar } constructor TIntUseBar.Create; begin pResMan.Load('Resources\Sprites\Interface\UseBar.png', IEngineBaseObject(pUseBar), TEXTURE_LOAD_DEFAULT_2D); end; destructor TIntUseBar.Destroy; begin pUseBar := nil; inherited; end; function TIntUseBar.MouseOver: Boolean; begin Result := (MousePos.X > Left) and (MousePos.X < Left + 331) and (MousePos.Y > Top) and (MousePos.Y < Top + 35); end; procedure TIntUseBar.Render; begin Left := SCREEN_WIDTH div 2 - 165; Top := SCREEN_HEIGHT - 38; pRender2D.DrawTexture(pUseBar, Point2(Left, Top), Point2(331, 35)); end; procedure TIntUseBar.SetLeft(const Value: Integer); begin FLeft := Value; end; procedure TIntUseBar.SetTop(const Value: Integer); begin FTop := Value; end; end.
unit ZMBody; // ZMBody.pas - Properties and methods used by all 'operations' (* *************************************************************************** TZipMaster VCL originally by Chris Vleghert, Eric W. Engler. Present Maintainers and Authors Roger Aelbrecht and Russell Peters. Copyright (C) 1997-2002 Chris Vleghert and Eric W. Engler Copyright (C) 1992-2008 Eric W. Engler Copyright (C) 2009, 2010, 2011, 2012, 2013 Russell Peters and Roger Aelbrecht Copyright (C) 2014, 2015 Russell Peters and Roger Aelbrecht The MIT License (MIT) Copyright (c) 2014, 2015 delphizip Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. contact: problems AT delphizip DOT org updates: http://www.delphizip.org *************************************************************************** *) // modified 2015-07-23 interface {$INCLUDE '.\ZipVers.inc'} {.$DEFINE DEBUG_PROGRESS } uses {$IFDEF VERDXE2up} System.Classes, WinApi.Windows, System.SysUtils, VCL.Controls,// VCL.Forms, VCL.Dialogs, VCL.Graphics, {$ELSE} Classes, Windows, SysUtils, Controls, Dialogs, Graphics, IniFiles, {$ENDIF} ZipMstr, ZMHandler, ZMCore; type TZXtraProgress = (ZxArchive, ZxCopyZip, ZxSFX, ZxHeader, ZxFinalise, ZxCopying, ZxCentral, ZxChecking, ZxLoading, ZxJoining, ZxSplitting, ZxWriting, ZxPreCalc, ZxProcessing, ZxMerging); type TZMLoadOpts = (ZloNoLoad, ZloFull, ZloSilent); type TZipNumberScheme = (ZnsNone, ZnsVolume, ZnsName, ZnsExt); type TZMEncodingDir = (ZedFromInt, ZedToInt); TZipShowProgress = (ZspNone, ZspFull, ZspExtra); const EXT_EXE = '.EXE'; EXT_EXEL = '.exe'; EXT_ZIP = '.ZIP'; EXT_ZIPL = '.zip'; PRE_INTER = 'ZI$'; PRE_SFX = 'ZX$'; const ZPasswordFollows = '<'; ZSwitchFollows = '|'; ZForceNoRecurse = '|'; // leading ZForceRecurse = '>'; // leading const OUR_VEM = 20;//30; Def_VER = 20; type TZipNameType = (ZntExternal, ZntInternal); type TZCentralValues = (ZcvDirty, ZcvEmpty, ZcvError, ZcvBadStruct, ZcvBusy); TZCentralStatus = set of TZCentralValues; type TZMProgress = class(TZMProgressDetails) private FCore: TZMCore; FDelta: Int64; FInBatch: Boolean; FItemName: string; FItemNumber: Integer; FItemPosition: Int64; FItemSize: Int64; FOnChange: TNotifyEvent; FProgType: TZMProgressType; FStop: Boolean; FTotalCount: Int64; FTotalPosition: Int64; FTotalSize: Int64; FWritten: Int64; procedure GiveProgress(DoEvent: Boolean); procedure SetTotalCount(const Value: Int64); procedure SetTotalSize(const Value: Int64); protected function GetBytesWritten: Int64; override; function GetDelta: Int64; override; function GetItemName: string; override; function GetItemNumber: Integer; override; function GetItemPosition: Int64; override; function GetItemSize: Int64; override; function GetOrder: TZMProgressType; override; function GetStop: Boolean; override; function GetTotalCount: Int64; override; function GetTotalPosition: Int64; override; function GetTotalSize: Int64; override; procedure SetStop(const Value: Boolean); override; public constructor Create(TheCore: TZMCore); procedure Advance(Adv: Int64); procedure AdvanceXtra(Adv: Cardinal); procedure Clear; procedure EndBatch; procedure EndItem; procedure MoreWritten(More: Int64); procedure NewItem(const FName: string; FSize: Int64); procedure NewXtraItem(const Xmsg: string; FSize: Int64); overload; procedure NewXtraItem(Xtra: TZXtraProgress; XSize: Integer); overload; procedure Written(Bytes: Int64); property BytesWritten: Int64 read GetBytesWritten write FWritten; property InBatch: Boolean read FInBatch; property ItemName: string read GetItemName write FItemName; property ItemNumber: Integer read GetItemNumber write FItemNumber; property ItemPosition: Int64 read GetItemPosition write FItemPosition; property ItemSize: Int64 read GetItemSize write FItemSize; property Order: TZMProgressType read GetOrder write FProgType; property TotalCount: Int64 read GetTotalCount write SetTotalCount; property TotalPosition: Int64 read GetTotalPosition write FTotalPosition; property TotalSize: Int64 read GetTotalSize write SetTotalSize; property OnChange: TNotifyEvent read FOnChange write FOnChange; end; type TZMBody = class(TZMCore) private FActiveFlag: Integer; FProgress: TZMProgress; FShowProgress: TZipShowProgress; FTotalSizeToProcess: Int64; function GetTotalWritten: Int64; procedure LogGlobals; procedure SetTotalWritten(const Value: Int64); protected procedure ProgressChanged(Sender: TObject); public procedure AfterConstruction; override; procedure BeforeDestruction; override; procedure Clear; override; function IsActive: Boolean; procedure Start(TheOperation: TZMOperationRoot); procedure Started; override; procedure UpdateChanged(TheOperation: TZMOperationRoot); virtual; procedure UpdateCurrent(WasGood: Boolean); virtual; abstract; property ActiveFlag: Integer read FActiveFlag write FActiveFlag; property Progress: TZMProgress read FProgress; property ShowProgress: TZipShowProgress read FShowProgress write FShowProgress; property TotalSizeToProcess: Int64 read FTotalSizeToProcess; property TotalWritten: Int64 read GetTotalWritten write SetTotalWritten; end; type TZMBase = class private FBody: TZMBody; FErrors: TZMErrors; FExcludeSpecs: TStrings; FHowToDelete: TZMDeleteOpts; FIncludeSpecs: TStrings; FIsTrace: Boolean; FIsVerbose: Boolean; FMaster: TCustomZipMaster; FProblemList: TStrings; FProgress: TZMProgress; FSFX: TZMSFXParameters; FSpan: TZMSpanParameters; FTempDir: string; FUnattended: Boolean; FVerbosity: TZMVerbosity; FWriteOptions: TZMWriteOpts; function GetAnswerAll: Boolean; function GetCancel: Integer; function GetShowProgress: TZipShowProgress; function GetSuccessCnt: Integer; procedure SetAnswerAll(const Value: Boolean); procedure SetCancel(const Value: Integer); procedure SetShowProgress(const Value: TZipShowProgress); procedure SetSuccessCnt(const Value: Integer); public constructor Create(TheBody: TZMBody); procedure AfterConstruction; override; procedure CheckCancel; procedure Diag(Ident, XInfo: Integer); procedure DiagErr(Ident: Integer; const AnError: integer; XInfo: Integer); procedure DiagFmt(Ident: Integer; const Args: Array of Const; XInfo: Integer); procedure DiagInt(Ident: Integer; const AnInt: integer; XInfo: Integer); procedure DiagStr(Ident: Integer; const AStr: string; XInfo: Integer); function KeepAlive: Boolean; procedure ShowError(Error: Integer); procedure ShowExceptionError(const ZMExcept: Exception); procedure ShowMessage(Ident: Integer; const UserStr: string); function ZipFmtLoadStr(Id: Integer; const Args: array of const): string; function ZipLoadStr(Id: Integer): string; function ZipMessageDlgEx(const Title, Msg: string; Context: Integer; Btns: TMsgDlgButtons): TModalResult; property AnswerAll: Boolean read GetAnswerAll write SetAnswerAll; property Body: TZMBody read FBody; property Cancel: Integer read GetCancel write SetCancel; property Errors: TZMErrors read FErrors; property ExcludeSpecs: TStrings read FExcludeSpecs; property HowToDelete: TZMDeleteOpts read FHowToDelete; property IncludeSpecs: TStrings read FIncludeSpecs; property IsTrace: Boolean read FIsTrace; // property IsVerbose: Boolean read FIsVerbose; property Master: TCustomZipMaster read FMaster; property ProblemList: TStrings read FProblemList; property Progress: TZMProgress read FProgress; property SFX: TZMSFXParameters read FSFX; property ShowProgress: TZipShowProgress read GetShowProgress write SetShowProgress; property Span: TZMSpanParameters read FSpan; property SuccessCnt: Integer read GetSuccessCnt write SetSuccessCnt; property TempDir: string read FTempDir; property Unattended: Boolean read FUnattended; property Verbosity: TZMVerbosity read FVerbosity; property WriteOptions: TZMWriteOpts read FWriteOptions; end; implementation uses {$IFDEF VERDXE2up} VCL.Forms, {$ELSE} Forms, {$ENDIF} ZMUtils, ZMDlg, ZMCtx, ZMXcpt, ZMStructs, ZMMsg, ZMDiags, ZMMisc; const __UNIT__ = 5; const _U_ = (__UNIT__ shl ZERR_LINE_SHIFTS); { TZMProgress } constructor TZMProgress.Create(TheCore: TZMCore); begin inherited Create; FCore := TheCore; end; procedure TZMProgress.Advance(Adv: Int64); begin FDelta := Adv; FTotalPosition := FTotalPosition + Adv; FItemPosition := FItemPosition + Adv; FProgType := ProgressUpdate; {$IFDEF DEBUG_PROGRESS} TCore.DiagFmt(ZT_Progress, [Adv, ItemPosition, ItemSize, TotalPosition, TotalSize], _U_ + 415); {$ENDIF} GiveProgress(True); end; procedure TZMProgress.AdvanceXtra(Adv: Cardinal); begin FDelta := Adv; Inc(FItemPosition, Adv); FProgType := ExtraUpdate; {$IFDEF DEBUG_PROGRESS} FCore.DiagFmt(ZT_XProgress, [Adv, ItemPosition, ItemSize], _U_ + 426); {$ENDIF} GiveProgress(True); end; procedure TZMProgress.Clear; begin FProgType := EndOfBatch; FDelta := 0; FWritten := 0; FTotalCount := 0; FTotalSize := 0; FTotalPosition := 0; FItemSize := 0; FItemPosition := 0; FItemName := ''; FItemNumber := 0; FStop := False; end; procedure TZMProgress.EndBatch; begin {$IFDEF DEBUG_PROGRESS} if FCore.Verbosity >= ZvVerbose then begin if FInBatch then FCore.Diag(ZT_EndOfBatch, _U_ + 452) else FCore.Diag(ZT_EndOfBatchWithNoBatch, _U_ + 454); end; {$ENDIF} FItemName := ''; FItemSize := 0; FInBatch := False; FProgType := EndOfBatch; FStop := False; GiveProgress(True); end; procedure TZMProgress.EndItem; begin FProgType := EndOfItem; {$IFDEF DEBUG_PROGRESS} FCore.DiagStr(ZT_EndOfItem + DFQuote, ItemName, _U_ + 469); {$ENDIF} GiveProgress(True); end; function TZMProgress.GetBytesWritten: Int64; begin Result := FWritten; end; function TZMProgress.GetDelta: Int64; begin Result := FDelta; end; function TZMProgress.GetItemName: string; begin Result := FItemName; end; function TZMProgress.GetItemNumber: Integer; begin Result := FItemNumber; end; function TZMProgress.GetItemPosition: Int64; begin Result := FItemPosition; end; function TZMProgress.GetItemSize: Int64; begin Result := FItemSize; end; function TZMProgress.GetOrder: TZMProgressType; begin Result := FProgType; end; function TZMProgress.GetStop: Boolean; begin Result := FStop; end; function TZMProgress.GetTotalCount: Int64; begin Result := FTotalCount; end; function TZMProgress.GetTotalPosition: Int64; begin Result := FTotalPosition; end; function TZMProgress.GetTotalSize: Int64; begin Result := FTotalSize; end; procedure TZMProgress.GiveProgress(DoEvent: Boolean); begin if DoEvent and Assigned(OnChange) then OnChange(Self); end; procedure TZMProgress.MoreWritten(More: Int64); begin FWritten := FWritten + More; end; procedure TZMProgress.NewItem(const FName: string; FSize: Int64); begin if FSize >= 0 then begin Inc(FItemNumber); FItemName := FName; FItemSize := FSize; FItemPosition := 0; FProgType := NewFile; {$IFDEF DEBUG_PROGRESS} FCore.DiagFmt(ZT_Item, [ItemName, ItemSize], _U_ + 550); {$ENDIF} GiveProgress(True); end else EndItem; end; procedure TZMProgress.NewXtraItem(const Xmsg: string; FSize: Int64); begin FItemName := Xmsg; FItemSize := FSize; FItemPosition := 0; FProgType := NewExtra; {$IFDEF DEBUG_PROGRESS} FCore.DiagFmt(ZT_XItem, [ItemName, ItemSize], _U_ + 565); {$ENDIF} GiveProgress(True); end; procedure TZMProgress.NewXtraItem(Xtra: TZXtraProgress; XSize: Integer); begin NewXtraItem(FCore.ZipLoadStr(ZP_Archive + Ord(Xtra)), XSize); end; procedure TZMProgress.SetStop(const Value: Boolean); begin FStop := Value; end; procedure TZMProgress.SetTotalCount(const Value: Int64); begin Clear; FTotalCount := Value; FItemNumber := 0; FProgType := TotalFiles2Process; {$IFDEF DEBUG_PROGRESS} FCore.DiagFmt(ZT_Count, [TotalCount], _U_ + 587); {$ENDIF} GiveProgress(True); end; procedure TZMProgress.SetTotalSize(const Value: Int64); begin FStop := False; FTotalSize := Value; FTotalPosition := 0; FItemName := ''; FItemSize := 0; FItemPosition := 0; FProgType := TotalSize2Process; FWritten := 0; FInBatch := True; // start of batch {$IFDEF DEBUG_PROGRESS} if Verbosity >= ZvTrace then FCore.DiagStr(ZT_Size, IntToStr(TotalSize), _U_ + 605); {$ENDIF} GiveProgress(True); end; procedure TZMProgress.Written(Bytes: Int64); begin FWritten := Bytes; end; procedure TZMBody.AfterConstruction; begin inherited; FProgress := TZMProgress.Create(Self); FProgress.OnChange := ProgressChanged; end; procedure TZMBody.BeforeDestruction; begin FreeAndNil(FProgress); Inherited; end; procedure TZMBody.Clear; begin inherited; Progress.Clear; end; function TZMBody.GetTotalWritten: Int64; begin Result := Progress.BytesWritten; end; function TZMBody.IsActive: Boolean; begin Result := (ActiveFlag <> 0); if Result and ((CsDesigning in Master.ComponentState) or (CsLoading in Master.ComponentState)) then Result := False; // never Active while loading or designing end; function SetVal(Someset: Pointer): Integer; begin Result := PByte(Someset)^; end; procedure TZMBody.LogGlobals; var Msg: string; S: string; SpnOpts: TZMSpanOpts; SkpOpts: TZMSkipAborts; begin if Master.Owner <> nil then S := Master.Owner.Name else S := '<none>'; Logger.Log(ZMError(0, _U_ + 313), Format('Start logging %u.%u:%s.<%p>(%s)', [MainThreadID, GetCurrentThreadID, S, Pointer(Master), Master.Name])); Msg := Application.ExeName + ' -- ' + DateTimeToStr(Now) + ' -- '#13#10; SpnOpts := Master.SpanOptions; SkpOpts := Master.NoSkipping; Msg := Msg + Format('Add:%x Extr:%x Skip:%x Span:%x Write:%x'#13#10, [SetVal(@AddOptions), SetVal(@ExtrOptions), SetVal(@SkpOpts), SetVal(@SpnOpts), SetVal(@WriteOptions)]); Msg := Msg + Format('Platform:%d, Windows:%d.%d, Delphi:%g, ZipMaster:%d', [Win32Platform, Win32MajorVersion, Win32MinorVersion, {$IFDEF VERD7up}CompilerVersion{$ELSE}0.0{$ENDIF}, Master.Build]); Logger.Log(0, Msg); end; // does not get fired for 'Clear' procedure TZMBody.ProgressChanged(Sender: TObject); var TmpProgress: TZMProgressEvent; begin TmpProgress := Master.OnProgress; if Assigned(TmpProgress) then TmpProgress(Master, Progress); if Progress.Order = TotalSize2Process then FTotalSizeToProcess := Progress.TotalSize; // catch it KeepAlive; end; procedure TZMBody.SetTotalWritten(const Value: Int64); begin Progress.Written(Value); end; procedure TZMBody.Start(TheOperation: TZMOperationRoot); var LogLevel: Integer; begin if GetCurrentThreadID <> MainThreadID then NotMainThread := True; if ZorFSpecArgs in TheOperation.Needs then begin IncludeSpecs.Assign(Master.FSpecArgs); // lock contents ExcludeSpecs.Assign(Master.FSpecArgsExcl); // lock contents end; ProblemList.Clear; Errors.Clear; AnswerAll := False; SuccessCnt := 0; // 'lock' spec lists if Master.Trace then Verbosity := ZvTrace else if Master.Verbose then Verbosity := ZvVerbose else Verbosity := ZvOff; Logging := False; if Logger = nil then Logger := TZMLogger.Create(Self); LogLevel := Logger.StartLog; if LogLevel > 0 then begin Logging := True; if LogLevel > 3 then Verbosity := TZMVerbosity(LogLevel and 3); // force required level LogGlobals; end; if (Verbosity > ZvTrace) and not Logging then Verbosity := ZvTrace; if Verbosity >= ZvTrace then begin LoadTraceStrings; DiagStr(DFNoSpace + ZT_Operation, TheOperation.Name, _U_ + 613); end; if IsVerbose then LoadInformStrings; // DiagStr(DFNoSpace + ZI_Operation, TheOperation.Name, _U_ + 616); if ZorFSpecArgs in TheOperation.Needs then begin if Logging then Logging := Logger.LogStrings(' -- FSpecArgs', IncludeSpecs); if Logging then Logging := Logger.LogStrings(' -- FSpecArgsExcl', ExcludeSpecs); end; Started; end; procedure TZMBody.Started; begin inherited; FTotalSizeToProcess := 0; end; procedure TZMBody.UpdateChanged(TheOperation: TZMOperationRoot); begin if ZorFSpecArgs in TheOperation.Changes then begin // restore the 'locked' spec lists Master.FSpecArgs.Assign(IncludeSpecs); Master.FSpecArgsExcl.Assign(ProblemList); end; if (ZorZip in TheOperation.Changes) and not Errors.isFatal then UpdateCurrent(True); end; { TZMBase } constructor TZMBase.Create(TheBody: TZMBody); begin inherited Create; FBody := TheBody; end; procedure TZMBase.AfterConstruction; begin inherited; FMaster := Body.Master; FProblemList := Body.ProblemList; FIncludeSpecs := Body.IncludeSpecs; FExcludeSpecs := Body.ExcludeSpecs; FHowToDelete := Body.HowToDelete; FWriteOptions := Body.WriteOptions; FProgress := Body.Progress; FSpan := Body.Span; FSFX := Body.SFX; FErrors := Body.Errors; FUnattended := Body.Unattended; FVerbosity := Body.Verbosity; FIsVerbose := Body.Verbosity >= ZvVerbose; FIsTrace := Body.Verbosity >= ZvTrace; FTempDir := Body.TempDir; end; procedure TZMBase.CheckCancel; begin KeepAlive; if Body.Cancel <> 0 then raise EZipMaster.CreateMsg(Body, Cancel, _U_ + 990); end; procedure TZMBase.Diag(Ident, XInfo: Integer); begin Body.Diag(Ident, XInfo); end; procedure TZMBase.DiagErr(Ident: Integer; const AnError: integer; XInfo: Integer); begin Body.DiagErr(Ident, AnError, XInfo); end; procedure TZMBase.DiagFmt(Ident: Integer; const Args: array of Const; XInfo: Integer); begin Body.DiagFmt(Ident, Args, XInfo); end; procedure TZMBase.DiagInt(Ident: Integer; const AnInt: integer; XInfo: Integer); begin Body.DiagInt(Ident, AnInt, XInfo); end; procedure TZMBase.DiagStr(Ident: Integer; const AStr: string; XInfo: Integer); begin Body.DiagStr(Ident, AStr, XInfo); end; function TZMBase.GetAnswerAll: Boolean; begin Result := Body.AnswerAll; end; function TZMBase.GetCancel: Integer; begin Result := Body.Cancel; end; function TZMBase.GetShowProgress: TZipShowProgress; begin Result := Body.ShowProgress; end; function TZMBase.GetSuccessCnt: Integer; begin Result := Body.SuccessCnt; end; function TZMBase.KeepAlive: Boolean; begin Result := Body.KeepAlive; end; procedure TZMBase.SetAnswerAll(const Value: Boolean); begin Body.AnswerAll := Value; end; procedure TZMBase.SetCancel(const Value: Integer); begin Body.Cancel := Value; end; procedure TZMBase.SetShowProgress(const Value: TZipShowProgress); begin Body.ShowProgress := Value; end; procedure TZMBase.SetSuccessCnt(const Value: Integer); begin Body.SuccessCnt := Value; end; procedure TZMBase.ShowError(Error: Integer); begin Body.ShowError(Error); end; procedure TZMBase.ShowExceptionError(const ZMExcept: Exception); begin Body.ShowExceptionError(ZMExcept); end; procedure TZMBase.ShowMessage(Ident: Integer; const UserStr: string); begin Body.ShowMessage(Ident, UserStr); end; function TZMBase.ZipFmtLoadStr(Id: Integer; const Args: array of const): string; begin Result := Body.ZipFmtLoadStr(Id, Args); end; function TZMBase.ZipLoadStr(Id: Integer): string; begin Result := Body.ZipLoadStr(Id); end; function TZMBase.ZipMessageDlgEx(const Title, Msg: string; Context: Integer; Btns: TMsgDlgButtons): TModalResult; begin Result := Body.ZipMessageDlgEx(Title, Msg, Context, Btns); end; end.
unit SurfaceSpriteLoaders; interface uses Classes, Windows, SysUtils, SurfaceSpriteImages; procedure LoadSurfaceFrameImage(out anImage : TSurfaceFrameImage; Stream : TStream); procedure LoadSurfaceFrameImageFromFile(out anImage : TSurfaceFrameImage; const Filename : string); procedure LoadSurfaceFrameImageFromResName(out anImage : TSurfaceFrameImage; Instance : THandle; const ResourceName : string); procedure LoadSurfaceFrameImageFromResId(out anImage : TSurfaceFrameImage; Instance : THandle; ResourceId : Integer); implementation uses DirectDraw, ImageLoaders, GDI, Dibs, BitBlt, GifLoader, DDrawD3DManager{$IFDEF MEMREPORTS}, MemoryReports{$ENDIF}; type TDisposalMethod = (dmNone, dmDoNotDispose, dmRestToBckgrnd, dmRestToPrev); procedure LoadSurfaceFrameImage(out anImage : TSurfaceFrameImage; Stream : TStream); var Images : TImages; i : integer; buffsize : integer; buff1, buff2 : pchar; rgbpalette : array [0..255] of TRGBQuad; palentries : array [0..255] of TPaletteEntry; TransColor : integer; dispmeth : TDisposalMethod; begin Images := GetImageLoader( Stream, nil ); try if Assigned( Images ) then with Images, DibHeader^ do begin //assert( biBitCount = 8, 'Sprites must be 8-bit images in SpriteLoaders.LoadFrameImage!!' ); LoadImages; anImage := TSurfaceFrameImage.Create(biWidth, abs(biHeight)); with anImage do begin NewFrames(ImageCount); move(DibColors(DibHeader)^, rgbpalette[0], DibPaletteSize(DibHeader)); for i := 0 to pred(DibPaletteSize(DibHeader) div sizeof(TRGBQuad)) do begin palentries[i].peRed := rgbpalette[i].rgbRed; palentries[i].peGreen := rgbpalette[i].rgbGreen; palentries[i].peBlue := rgbpalette[i].rgbBlue; palentries[i].peFlags := 0; end; Palette := DDrawD3DMgr.CreatePalette(@palentries[0]); OwnsPalette := true; buffsize := anImage.ImageSize; {$IFDEF MEMREPORTS} //ReportMemoryAllocation(cSpriteAllocCause, 3*DibPaletteSize( DibHeader ) + sizeof(anImage) + sizeof(PalInfo)); {$ENDIF} getmem( buff1, buffsize ); try getmem( buff2, buffsize ); try TransColor := Image[0].Transparent; fillchar(buff1^, buffsize, TransColor); for i := 0 to ImageCount - 1 do begin //!!assert( TransparentIndx = Transparent, 'Image was authored with differing transparent colors per frame, which is unsupported by sprite engine!!' ); if LockFrame(i, true) then try FrameDelay[i] := Image[i].Delay*10; Image[i].Decode(PixelAddr[0, 0, i], StorageWidth[i]); if Image[i] is TGifImageData then dispmeth := TDisposalMethod(TGifImageData(Image[i]).Disposal) else dispmeth := dmNone; case dispmeth of dmNone,dmDoNotDispose: begin BltCopyTrans(PixelAddr[0, 0, i], @buff1[Width*Image[i].Origin.y + Image[i].Origin.x], Image[i].Width, Image[i].Height, Image[i].Transparent, StorageWidth[i], Width); BltCopyOpaque(buff1, PixelAddr[0, 0, i], Width, Height, Width, StorageWidth[i]); end; dmRestToBckgrnd: begin BltCopyTrans(PixelAddr[0, 0, i], @buff1[Width*Image[i].Origin.y + Image[i].Origin.x], Image[i].Width, Image[i].Height, TransColor, StorageWidth[i], Width); BltCopyOpaque(buff1, PixelAddr[0, 0, i], Width, Height, Width, StorageWidth[i]); fillchar(buff1^, buffsize, TransColor); end; dmRestToPrev: begin move(buff1^, buff2^, buffsize); BltCopyTrans(PixelAddr[0, 0, i], @buff1[Width*Image[i].Origin.y + Image[i].Origin.x], Image[i].Width, Image[i].Height, TransColor, StorageWidth[i], Width); BltCopyOpaque(buff1, PixelAddr[0, 0, i], Width, Height, Width, StorageWidth[i]); if i > 0 then move(buff2^, buff1^, buffsize); end; end; finally UnlockFrame(i); end; end; if TransColor = -1 // Assume a transparent color then begin if LockFrame(0, true) then begin TranspIndx := anImage.Pixel[0, 0, 0]; UnlockFrame(0); end; end else TranspIndx := TransColor; finally freemem(buff2); end; finally freemem( buff1 ); end; end; end else anImage := nil; finally Images.Free; end; end; procedure LoadSurfaceFrameImageFromFile(out anImage : TSurfaceFrameImage; const Filename : string); var Stream : TStream; begin Stream := TFileStream.Create( Filename, fmOpenRead or fmShareDenyWrite ); try LoadSurfaceFrameImage(anImage, Stream); finally Stream.Free; end; end; procedure LoadSurfaceFrameImageFromResName(out anImage : TSurfaceFrameImage; Instance : THandle; const ResourceName : string); var Stream : TStream; begin Stream := TResourceStream.Create( Instance, ResourceName, RT_RCDATA ); try LoadSurfaceFrameImage(anImage, Stream); finally Stream.Free; end; end; procedure LoadSurfaceFrameImageFromResId( out anImage : TSurfaceFrameImage; Instance : THandle; ResourceId : Integer); var Stream : TStream; begin Stream := TResourceStream.CreateFromID( Instance, ResourceId, RT_RCDATA ); try LoadSurfaceFrameImage(anImage, Stream); finally Stream.Free; end; end; end.
unit K512248597; {* [Requestlink:512248597] } // Модуль: "w:\common\components\rtl\Garant\Daily\K512248597.pas" // Стереотип: "TestCase" // Элемент модели: "K512248597" MUID: (52DF9692021D) // Имя типа: "TK512248597" {$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas} interface {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3IntfUses , EVDtoRTFWriterTest ; type TK512248597 = class(TEVDtoRTFWriterTest) {* [Requestlink:512248597] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK512248597 {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3ImplUses , TestFrameWork //#UC START# *52DF9692021Dimpl_uses* //#UC END# *52DF9692021Dimpl_uses* ; function TK512248597.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := '7.10'; end;//TK512248597.GetFolder function TK512248597.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '52DF9692021D'; end;//TK512248597.GetModelElementGUID initialization TestFramework.RegisterTest(TK512248597.Suite); {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) end.
{$MODE OBJFPC} {$INLINE ON} program Lighting; const InputFile = 'LIGHT.INP'; OutputFile = 'LIGHT.OUT'; maxN = 2000; maxS = Round(1E9); infty = maxN * maxS + 1; type TCandidate = record a, b, p: Integer; end; TTree = array[1..4 * maxN + 4] of Int64; var e: array[0..maxN] of TCandidate; tree: TTree; leaf: array[0..maxN] of Integer; f: array[0..maxN, 0..maxN] of Int64; t: Integer; n: Integer; res: Int64; procedure Enter; var f: TextFile; i: Integer; begin AssignFile(f, InputFile); Reset(f); try ReadLn(f, n, t); for i := 1 to n do with e[i] do begin ReadLn(f, a, b, p); Dec(a, b); b := a + 2 * b; if a < 0 then a := 0; if b > t then b := t; end; finally CloseFile(f); end; end; procedure ShellSort; var i, j, step: Integer; temp: TCandidate; begin step := n div 2; while step <> 0 do begin for i := step + 1 to n do begin temp := e[i]; j := i - step; while (j > 0) and (e[j].b > temp.b) do begin e[j + step] := e[j]; j := j - step; end; e[j + step] := temp; end; if step = 2 then step := 1 else step := step * 10 div 22; end; with e[0] do begin a := 0; b := 0; p := 0; end; end; function BinarySearch(aj: Integer): Integer; var L, M, H: Integer; begin //tim k nho nhat, b[k] >= a[j] L := 0; H := n; repeat //b[L - 1] < aj <= b[H + 1] M := (L + H) div 2; if e[M].b < aj then L := M + 1 else H := M - 1; until L > H; Result := L; end; procedure Build(x, L, H: Integer); var m: Integer; begin if L = H then leaf[L] := x else begin m := (L + H) shr 1; Build(x shl 1, L, m); Build(x shl 1 + 1, m + 1, H); end; end; procedure Preparation; var i, j: Integer; begin FillChar(f, SizeOf(f), Byte(-1)); f[0, 0] := 0; for i := 1 to n do begin if e[i].a = 0 then begin f[0, i] := e[i].p; f[i, 0] := f[0, i]; end; f[i, i] := infty; end; Build(1, 0, n); end; procedure ResetTree; var i: Integer; begin for i := 1 to 4 * (n + 1) do tree[i] := infty; end; function Min(x, y: Int64): Int64; inline; begin if x < y then Result := x else Result := y; end; procedure Update(i: Integer; f: Int64); begin i := leaf[i]; tree[i] := f; while i > 1 do begin i := i shr 1; tree[i] := Min(tree[i shl 1], tree[i shl 1 + 1]); end; end; function Query(i, j: Integer): Int64; function Request(x, L, H: Integer): Int64; var m: Integer; begin if (H < i) or (j < L) then Exit(Infty); if (i <= L) and (H <= j) then Exit(tree[x]); m := (L + H) div 2; Result := Min(Request(x shl 1, L, m), Request(x shl 1 + 1, m + 1, H)); end; begin if i > j then Exit(infty); Result := Request(1, 0, n); end; procedure SolveRecurrence; var i, j, k: Integer; begin for i := 0 to n do begin ResetTree; for j := 0 to i do Update(j, f[i, j]); for j := i + 1 to n do begin if f[i, j] = -1 then begin k := BinarySearch(e[j].a); f[i, j] := Query(k, j - 1); if f[i, j] < infty then Inc(f[i, j], e[j].p); f[j, i] := f[i, j]; end; Update(j, f[i, j]); end; end; res := infty; for i := 1 to n do for j := 1 + i to n do if (e[i].b = t) and (e[j].b = t) and (res > f[i, j]) then res := f[i, j]; if res = infty then res := -1; for i := 0 to n do begin for j := 0 to n do Write(stderr, f[i, j], ' '); WriteLn(stderr); end; end; procedure PrintResult; var f: TextFile; begin AssignFile(f, OutputFile); Rewrite(f); try Write(f, res); finally CloseFile(f); end; end; begin Enter; ShellSort; Preparation; SolveRecurrence; PrintResult; end. { LIGHT.INP 7 12 2 2 11 6 2 11 10 2 11 4 4 33 8 4 33 6 6 99 10 1 1 LIGHT.OUT 88 }
unit utils_findwnd; interface uses Windows, Sysutils; type PZsExWindowEnumFind = ^TZsExWindowEnumFind; TZsExWindowEnumFind = record FindCount : integer; FindWindow : array[0..255] of HWND; NeedWinCount : integer; ProcessId : DWORD; ExcludeWnd : HWND; ParentWnd : HWND; WndClassKey : string; WndCaptionKey : string; WndCaptionExcludeKey: string; CheckWndFunc : function(AWnd: HWND; AFind: PZsExWindowEnumFind): Boolean; end; function ZsEnumFindDesktopWindowProc(AWnd: HWND; lParam: LPARAM): BOOL; stdcall; implementation uses UtilsWindows; function ZsEnumFindDesktopWindowProc(AWnd: HWND; lParam: LPARAM): BOOL; stdcall; var tmpStr: string; tmpIsFind: Boolean; tmpFind: PZsExWindowEnumFind; tmpProcessId: DWORD; begin Result := true; tmpFind := PZsExWindowEnumFind(lparam); if nil = tmpFind then begin Result := false; exit; end; if not IsWindowVisible(AWnd) then exit; tmpIsFind := true; if '' <> tmpFind.WndClassKey then begin tmpStr := GetWndClassName(AWnd); if (not SameText(tmpStr, tmpFind.WndClassKey)) then begin if Pos(tmpFind.WndClassKey, tmpStr) < 1 then begin tmpIsFind := false; end; end; end; if tmpIsFind then begin if 0 <> tmpFind.ProcessId then begin GetWindowThreadProcessId(AWnd, tmpProcessId); if tmpProcessId <> tmpFind.ProcessId then begin tmpIsFind := false; end; end; end; if tmpIsFind then begin if ('' <> Trim(tmpFind.WndCaptionKey)) or ('' <> Trim(tmpFind.WndCaptionExcludeKey))then begin tmpStr := GetWndTextName(AWnd); if ('' <> Trim(tmpFind.WndCaptionKey)) then begin if Pos(tmpFind.WndCaptionKey, tmpStr) < 1 then begin tmpIsFind := false; end; end; if ('' <> Trim(tmpFind.WndCaptionExcludeKey)) then begin if Pos(tmpFind.WndCaptionExcludeKey, tmpStr) > 0 then begin tmpIsFind := false; end; end; end; end; if tmpIsFind then begin if Assigned(tmpFind.CheckWndFunc) then begin if (not tmpFind.CheckWndFunc(AWnd, tmpFind)) then begin tmpIsFind := false; end; end; end; if tmpIsFind then begin if 255 > tmpFind.FindCount then begin tmpFind.FindWindow[tmpFind.FindCount] := AWnd; tmpFind.FindCount := tmpFind.FindCount + 1; end; if 255 <> tmpFind.NeedWinCount then tmpFind.NeedWinCount := tmpFind.NeedWinCount - 1; if tmpFind.NeedWinCount < 1 then // 找到不用再找了 Result := false; end; end; end.
program TM1638_demo2; {$mode objfpc}{$H+} { Raspberry Pi Application } { Add your program code below, add additional units to the "uses" section if } { required and create new units by selecting File, New Unit from the menu. } { } { To compile your program select Run, Compile (or Run, Build) from the menu. } uses RaspberryPi, GlobalConfig, GlobalConst, GlobalTypes, Platform, Threads, SysUtils, Classes, Ultibo, Console, TM1638; var TM1630Ac: TTM1630; Handle: TWindowHandle; (* // definition for the displayable ASCII chars const FONT_DEFAULT: array [] of Byte = ( 0b00000000, // (32) <space> 0b10000110, // (33) ! 0b00100010, // (34) " 0b01111110, // (35) # 0b01101101, // (36) $ 0b00000000, // (37) % 0b00000000, // (38) & 0b00000010, // (39) ' 0b00110000, // (40) ( 0b00000110, // (41) ) 0b01100011, // (42) * 0b00000000, // (43) + 0b00000100, // (44) , 0b01000000, // (45) - 0b10000000, // (46) . 0b01010010, // (47) / 0b00111111, // (48) 0 0b00000110, // (49) 1 0b01011011, // (50) 2 0b01001111, // (51) 3 0b01100110, // (52) 4 0b01101101, // (53) 5 0b01111101, // (54) 6 0b00100111, // (55) 7 0b01111111, // (56) 8 0b01101111, // (57) 9 0b00000000, // (58) : 0b00000000, // (59) ; 0b00000000, // (60) < 0b01001000, // (61) = 0b00000000, // (62) > 0b01010011, // (63) ? 0b01011111, // (64) @ 0b01110111, // (65) A 0b01111111, // (66) B 0b00111001, // (67) C 0b00111111, // (68) D 0b01111001, // (69) E 0b01110001, // (70) F 0b00111101, // (71) G 0b01110110, // (72) H 0b00000110, // (73) I 0b00011111, // (74) J 0b01101001, // (75) K 0b00111000, // (76) L 0b00010101, // (77) M 0b00110111, // (78) N 0b00111111, // (79) O 0b01110011, // (80) P 0b01100111, // (81) Q 0b00110001, // (82) R 0b01101101, // (83) S 0b01111000, // (84) T 0b00111110, // (85) U 0b00101010, // (86) V 0b00011101, // (87) W 0b01110110, // (88) X 0b01101110, // (89) Y 0b01011011, // (90) Z 0b00111001, // (91) [ 0b01100100, // (92) \ (this can't be the last char on a line, even in comment or it'll concat) 0b00001111, // (93) ] 0b00000000, // (94) ^ 0b00001000, // (95) _ 0b00100000, // (96) ` 0b01011111, // (97) a 0b01111100, // (98) b 0b01011000, // (99) c 0b01011110, // (100) d 0b01111011, // (101) e 0b00110001, // (102) f 0b01101111, // (103) g 0b01110100, // (104) h 0b00000100, // (105) i 0b00001110, // (106) j 0b01110101, // (107) k 0b00110000, // (108) l 0b01010101, // (109) m 0b01010100, // (110) n 0b01011100, // (111) o 0b01110011, // (112) p 0b01100111, // (113) q 0b01010000, // (114) r 0b01101101, // (115) s 0b01111000, // (116) t 0b00011100, // (117) u 0b00101010, // (118) v 0b00011101, // (119) w 0b01110110, // (120) x 0b01101110, // (121) y 0b01000111, // (122) z 0b01000110, // (123) { 0b00000110, // (124) | 0b01110000, // (125) } 0b00000001, // (126) ~ ); *) function Counting(): Byte; var position: Byte; const {0} {1} {2} {3} {4} {5} {6} {7} {8} {9} digits: array[0..9] of Byte = ($3f, $06, $5b, $4f, $66, $6d, $7d, $07, $7f, $6f); digit: Byte = 0; begin TM1630Ac.SendCommand($40); TM1630Ac.Start(); TM1630Ac.ShiftOut(soLsbFirst, $C0); for position := 0 to 7 do begin TM1630Ac.ShiftOut(soLsbFirst, digits[digit]); TM1630Ac.ShiftOut(soLsbFirst, $00); end; { for position := 0 to 7 do begin TM1630Ac.ShiftOut(soLSBFIRST, FONT_DEFAULT[digit]); TM1630Ac.ShiftOut(LSBFIRST, 0x00); end; } TM1630Ac.Stop(); digit := (digit + 1) mod 10; if digit = 0 then Result := 1 else Result := 0; end; function Scroll(): Byte; var scrollLength, i, c: Byte; const scrollText: array [0..31] of Byte = (* *)(* *)(* *)(* *)(* *)(* *)(* *)(* *) ($00, $00, $00, $00, $00, $00, $00, $00, (*H*)(*E*)(*L*)(*L*)(*O*)(*.*)(*.*)(*.*) $76, $79, $38, $38, $3f, $80, $80, $80, (* *)(* *)(* *)(* *)(* *)(* *)(* *)(* *) $00, $00, $00, $00, $00, $00, $00, $00, (*H*)(*E*)(*L*)(*L*)(*O*)(*.*)(*.*)(*.*) $76, $79, $38, $38, $3f, $80, $80, $80); index: Byte = 0; begin scrollLength := Length(scrollText); TM1630Ac.SendCommand($40); TM1630Ac.Start(); TM1630Ac.ShiftOut(soLsbFirst, $C0); for i := 0 to 7 do begin c := scrollText[(index + i) mod scrollLength]; TM1630Ac.ShiftOut(soLsbFirst, c); if c <> 0 then TM1630Ac.ShiftOut(soLsbFirst, 1) else TM1630Ac.ShiftOut(soLsbFirst, 0); end; TM1630Ac.Stop(); index := (index + 1) mod (scrollLength shl 1); if index = 0 then Result := 1 else Result := 0; end; procedure Buttons(); var textStartPos, position, buttons, mask: Byte; const promptText: array [0..31] of Byte = (*P*) (*r*) (*E*) (*S*) (*S*) (* *) (* *) (* *) ($73, $50, $79, $6d, $6d, $00, $00, $00, (* *) (* *) (* *) (* *) (* *) (* *) (* *) (* *) $00, $00, $00, $00, $00, $00, $00, $00, (*b*) (*u*) (*t*) (*t*) (*o*) (*n*) (*S*) (* *) $7c, $1c, $78, $78, $5c, $54, $6d, $00, (* *) (* *) (* *) (* *) (* *) (* *) (* *) (* *) $00, $00, $00, $00, $00, $00, $00, $00); block: Byte = 0; begin textStartPos := (block div 4) shl 3; for position := 0 to 7 do begin TM1630Ac.SendCommand($44); TM1630Ac.Start(); TM1630Ac.ShiftOut(soLsbFirst, $C0 + (position << 1)); TM1630Ac.ShiftOut(soLsbFirst, promptText[textStartPos + position]); TM1630Ac.Stop(); end; block := (block + 1) mod 16; buttons := TM1630Ac.ReadButtons(); for position := 0 to 7 do begin mask := $1 shl position; if buttons and mask = 0 then TM1630Ac.SetLed(0, position) else TM1630Ac.SetLed(1, position); end; end; procedure Setup(); begin {Let's create a console window again but this time on the left side of the screen} Handle := ConsoleWindowCreate(ConsoleDeviceGetDefault, CONSOLE_POSITION_FULL, True); {To prove that worked let's output some text on the console window} ConsoleWindowWriteLn(Handle, 'TM1638 demo 2'); try TM1630Ac := TTM1630.Create; except on E: Exception do begin TM1630Ac := nil; ConsoleWindowWriteLn(Handle, 'Setup() error: ' + E.Message); end; end; end; const COUNTING_MODE = 0; SCROLL_MODE = 1; BUTTON_MODE = 2; procedure Loop(); const mode: Byte = COUNTING_MODE; begin try case mode of COUNTING_MODE: Inc(mode, Counting()); SCROLL_MODE: Inc(mode, Scroll()); BUTTON_MODE: Buttons(); end; Sleep(200); except on E: Exception do begin TM1630Ac.Free; TM1630Ac := nil; ConsoleWindowWriteLn(Handle, 'Loop() error: ' + E.Message); end; end; end; begin Setup(); while Assigned(TM1630Ac) do Loop(); ConsoleWindowWriteLn(Handle, ''); ConsoleWindowWriteLn(Handle, 'Bye'); {Halt the main thread if we ever get to here} ThreadHalt(0); end.
{ Mark Sattolo 428500 } { CSI1100A DGD-1 Chris Lankester } { Test program for Assignment#4 Question#2 } program GetSmallest (input, output); { This program takes an array X with N positive numbers, and a second array Y with M positive numbers, and gives the smallest number that appears in both arrays as the result "Smallest", or sets Smallest to -1 if there is no common element in the two arrays. } { Data Dictionary GIVENS: X, N - X is an array of N positive integers. Y, M - Y is an array of M positive integers. RESULTS: Smallest - the smallest value in both arrays, or -1 if there is no common element. INTERMEDIATES: Count - a counter to keep track of the # of passes through the top module. SmallX - the current smallest value of X. USES: FindSmallX, Compare } type Markarray = array[1..66] of integer; var N, M, Smallest, Count, SmallX : integer; X : Markarray; Y : Markarray; {*******************************************************************} procedure TestX(X : Markarray; N, Previous : integer; var SmallX, I : integer); begin while ((I < (N-1)) and (SmallX <= Previous)) do begin I := I + 1; SmallX := X[I+1] end { while } end; { procedure TestX } {*************************************************************************} procedure FindSmallX(N : integer; X : Markarray; var SmallX : integer); var I, Previous : integer; begin { FindSmallX } I := 0; Previous := SmallX; SmallX := X[1]; TestX(X, N, Previous, SmallX, I); while (I < (N-1)) do begin I := I + 1; if ((X[I+1] < SmallX) and (X[I+1] > Previous)) then SmallX := X[I+1] else { do nothing } end { while } end; { procedure FindSmallX } {***********************************************************************************} procedure Compare(Y: Markarray; M, SmallX : integer; var Smallest : integer); var J : integer; begin J := 0; while ((J < M) and (Smallest < 0)) do begin J := J + 1; if (Y[J] = SmallX) then Smallest := SmallX else { do nothing} end { while } end; { procedure Compare } {*************************************************************************************} procedure FillArray(var ArrayName : MarkArray; var ArraySize : integer); var K : integer; { K - an index in the prompt for values. } begin write('Please enter the size of the array? '); readln(ArraySize); for K := 1 to ArraySize do begin write('Please enter array value #', K, '? '); read(ArrayName[K]) end { for } end; { procedure FillArray } {*************************************************************************************} begin { program } { Get the input values } writeln('For the first array:'); FillArray(X, N); writeln; writeln('For the second array:'); FillArray(Y, M); { initialize the loop } Count := 0; Smallest := -1; SmallX := 0; { start the loop} while ((Count < N) and (Smallest < 0)) do begin FindSmallX(N, X, SmallX); Compare(Y, M, SmallX, Smallest); Count := Count + 1 end; { while } { Print out the results. } writeln; writeln('*************************************'); writeln('Mark Sattolo 428500'); writeln('CSI1100A DGD-1 Chris Lankester'); writeln('Assignment 4, Question 2'); writeln('*************************************'); writeln; writeln('The value of Smallest is ',Smallest,'.'); end. { program }
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clMailUtils; interface {$I clVer.inc} const DefaultPop3Port = 110; DefaultSmtpPort = 25; DefaultImapPort = 143; DefaultMailAgent = 'Clever Internet Suite'; function GenerateMessageID(const AHostName: string): string; function GenerateCramMD5Key(const AHostName: string): string; function GetIdnEmail(const AEmail: string): string; implementation uses {$IFNDEF DELPHIXE2} Windows, SysUtils, {$ELSE} Winapi.Windows, System.SysUtils, {$ENDIF} clSocket, clIdnTranslator; var MessageCounter: Integer = 0; function GenerateMessageID(const AHostName: string): string; var y, mm, d, h, m, s, ms: Word; begin DecodeTime(Now(), h, m, s, ms); DecodeDate(Date(), y, mm, d); Result := IntToHex(mm, 2) + IntToHex(d, 2) + IntToHex(h, 2) + IntToHex(m, 2) + IntToHex(s, 2) + IntToHex(ms, 2); InterlockedIncrement(MessageCounter); Result := '<' + IntToHex(Integer(GetTickCount()), 8) + system.Copy(Result, 1, 12) + IntToHex(MessageCounter, 3) + IntToHex(MessageCounter * 2, 3) + '@' + AHostName + '>'; end; function GenerateCramMD5Key(const AHostName: string): string; var y, mm, d, h, m, s, ms: Word; begin DecodeTime(Now(), h, m, s, ms); DecodeDate(Date(), y, mm, d); Result := Format('<INETSUITE-F%d%d%d%d%d.%s@%s>', [y, mm, d, h, m, IntToHex(m, 3) + IntToHex(s, 3) + IntToHex(ms, 3) + IntToHex(Random(100), 5), AHostName]); end; function GetIdnEmail(const AEmail: string): string; var ind: Integer; begin Result := AEmail; ind := system.Pos('@', Result); if (ind > 0) then begin Result := TclIdnTranslator.GetAsciiText(System.Copy(Result, 1, ind - 1)) + '@' + TclIdnTranslator.GetAscii(System.Copy(Result, ind + 1, Length(Result))); end; end; end.
PROGRAM Task1(INPUT, OUTPUT); CONST Max = 100; VAR IntSet: SET OF 2..Max; Counter, Position: INTEGER; BEGIN{Task1} Position := 2; IntSet : [2..Max]; WRITE('all prime numbers from 2 to ', Max,': '); WHILE (IntSet <> []) BEGIN WHILE (Counter <= Max) BEGIN IF ((Position MOD Counter) = 0) THEN IntSet := IntSet - [Counter]; END WRITE(Position, ', ') END END.{Task1}
unit atrCmdUtils; interface uses Classes, SysUtils, Windows, ActiveX, ShellApi; procedure WinExec(const ACmdLine: String; const ACmdShow: UINT = SW_SHOWNORMAL); function ShellExecute(const AWnd: HWND; const AOperation, AFileName: String; const AParameters: String = ''; const ADirectory: String = ''; const AShowCmd: Integer = SW_SHOWNORMAL): Boolean; function Ping(const host: string): string; procedure RunCmdWithOutInStrings(const CmdLine: AnsiString; ResLines: TStringList); function GetEnvVarValue(const VarName: string): string; { function ExecuteFile(FileName,StdInput: string; TimeOut: integer; var StdOutput:string) : boolean; } implementation function GetEnvVarValue(const VarName: string): string; var BufSize: Integer; // buffer size required for value begin // Get required buffer size (inc. terminal #0) BufSize := GetEnvironmentVariable( PChar(VarName), nil, 0); if BufSize > 0 then begin // Read env var value into result string SetLength(Result, BufSize - 1); GetEnvironmentVariable(PChar(VarName), PChar(Result), BufSize); end else // No such environment variable Result := ''; end; // RunDosInMemo('ping -t 192.168.28.200',Memo1); procedure RunCmdWithOutInStrings(const CmdLine: AnsiString; ResLines: TStringList); const BUFSIZE = 24000; var SecAttr: TSecurityAttributes; hReadPipe, hWritePipe: THandle; StartupInfo: TStartUpInfo; ProcessInfo: TProcessInformation; Buffer: PAnsiChar; WaitReason, BytesRead: DWord; begin with SecAttr do begin nlength := SizeOf(TSecurityAttributes); binherithandle := true; lpsecuritydescriptor := nil; end; // Creazione della pipe if Createpipe(hReadPipe, hWritePipe, @SecAttr, 0) then begin Buffer := AllocMem(BUFSIZE + 1); // Allochiamo un buffer di dimensioni BUFSIZE+1 FillChar(StartupInfo, SizeOf(StartupInfo), #0); StartupInfo.cb := SizeOf(StartupInfo); StartupInfo.hStdOutput := hWritePipe; StartupInfo.hStdInput := hReadPipe; StartupInfo.dwFlags := STARTF_USESTDHANDLES + STARTF_USESHOWWINDOW; StartupInfo.wShowWindow := SW_HIDE; if CreateProcess(nil, Pchar(CmdLine), @SecAttr, @SecAttr, true, NORMAL_PRIORITY_CLASS, nil, nil, StartupInfo, ProcessInfo) then begin // Attendiamo la fine dell'esecuzione del processo repeat WaitReason := WaitForSingleObject(ProcessInfo.hProcess, 100); until (WaitReason <> WAIT_TIMEOUT); // Leggiamo la pipe Repeat BytesRead := 0; // Leggiamo "BUFSIZE" bytes dalla pipe ReadFile(hReadPipe, Buffer[0], BUFSIZE, BytesRead, nil); // Convertiamo in una stringa "\0 terminated" Buffer[BytesRead] := #0; // Convertiamo i caratteri da DOS ad ANSI OemToAnsi(Buffer, Buffer); // Scriviamo nell' "OutMemo" l'output ricevuto tramite pipe ResLines.Text := ResLines.Text + String(Buffer); until (BytesRead < BUFSIZE); end; FreeMem(Buffer); CloseHandle(ProcessInfo.hProcess); CloseHandle(ProcessInfo.hThread); CloseHandle(hReadPipe); CloseHandle(hWritePipe); end; end; function Ping(const host: string): string; var CommandLine: string; t: TStringList; begin CommandLine := 'ping -n 3 -a ' + host; t := TStringList.Create; try RunCmdWithOutInStrings(CommandLine, t); Result := t.Text; finally t.Free; end; end; function ShellExecute(const AWnd: HWND; const AOperation, AFileName: String; const AParameters: String = ''; const ADirectory: String = ''; const AShowCmd: Integer = SW_SHOWNORMAL): Boolean; var ExecInfo: TShellExecuteInfo; NeedUninitialize: Boolean; begin Assert(AFileName <> ''); NeedUninitialize := SUCCEEDED(CoInitializeEx(nil, COINIT_APARTMENTTHREADED or COINIT_DISABLE_OLE1DDE)); try FillChar(ExecInfo, SizeOf(ExecInfo), 0); ExecInfo.cbSize := SizeOf(ExecInfo); ExecInfo.Wnd := AWnd; ExecInfo.lpVerb := Pointer(AOperation); ExecInfo.lpFile := Pchar(AFileName); ExecInfo.lpParameters := Pointer(AParameters); ExecInfo.lpDirectory := Pointer(ADirectory); ExecInfo.nShow := AShowCmd; ExecInfo.fMask := SEE_MASK_NOASYNC { = SEE_MASK_FLAG_DDEWAIT для старых версий Delphi } or SEE_MASK_FLAG_NO_UI; {$IFDEF UNICODE} // Необязательно, см. http://www.transl-gunsmoker.ru/2015/01/what-does-SEEMASKUNICODE-flag-in-ShellExecuteEx-actually-do.html ExecInfo.fMask := ExecInfo.fMask or SEE_MASK_UNICODE; {$ENDIF} {$WARN SYMBOL_PLATFORM OFF} Result := ShellExecuteEx(@ExecInfo); {$WARN SYMBOL_PLATFORM ON} finally if NeedUninitialize then CoUninitialize; end; end; procedure WinExec(const ACmdLine: String; const ACmdShow: UINT = SW_SHOWNORMAL); var SI: TStartUpInfo; PI: TProcessInformation; CmdLine: String; begin Assert(ACmdLine <> ''); CmdLine := ACmdLine; UniqueString(CmdLine); FillChar(SI, SizeOf(SI), 0); FillChar(PI, SizeOf(PI), 0); SI.cb := SizeOf(SI); SI.dwFlags := STARTF_USESHOWWINDOW; SI.wShowWindow := ACmdShow; SetLastError(ERROR_INVALID_PARAMETER); {$WARN SYMBOL_PLATFORM OFF} Win32Check(CreateProcess(nil, Pchar(CmdLine), nil, nil, False, CREATE_DEFAULT_ERROR_MODE {$IFDEF UNICODE} or CREATE_UNICODE_ENVIRONMENT{$ENDIF}, nil, nil, SI, PI)); {$WARN SYMBOL_PLATFORM ON} CloseHandle(PI.hThread); CloseHandle(PI.hProcess); end; { Это пример запуска консольных программ с передачей ей консольного ввода (как если бы он был введен с клавиатуры после запуска программы) и чтением консольного вывода. Таким способом можно запускать например стандартный виндовый ftp.exe (в невидимом окне) и тем самым отказаться от использования специализированных, зачастую глючных компонент. function ExecuteFile(FileName,StdInput: string; TimeOut: integer; var StdOutput:string) : boolean; label Error; type TPipeHandles = (IN_WRITE, IN_READ, OUT_WRITE, OUT_READ, ERR_WRITE, ERR_READ); type TPipeArray = array [TPipeHandles] of THandle; var i : integer; ph : TPipeHandles; sa : TSecurityAttributes; Pipes : TPipeArray; StartInf : TStartupInfo; ProcInf : TProcessInformation; Buf : array[0..1024] of byte; TimeStart : TDateTime; function ReadOutput : string; var i : integer; s : string; BytesRead : longint; begin Result := ''; repeat Buf[0]:=26; WriteFile(Pipes[OUT_WRITE],Buf,1,BytesRead,nil); if ReadFile(Pipes[OUT_READ],Buf,1024,BytesRead,nil) then begin if BytesRead>0 then begin buf[BytesRead]:=0; s := StrPas(@Buf[0]); i := Pos(#26,s); if i>0 then s := copy(s,1,i-1); Result := Result + s; end; end; if BytesRead1024 then break; until false; end; begin Result := false; for ph := Low(TPipeHandles) to High(TPipeHandles) do Pipes[ph] := INVALID_HANDLE_VALUE; // Создаем пайпы sa.nLength := sizeof(sa); sa.bInheritHandle := TRUE; sa.lpSecurityDescriptor := nil; if not CreatePipe(Pipes[IN_READ],Pipes[IN_WRITE], @sa, 0 ) then goto Error; if not CreatePipe(Pipes[OUT_READ],Pipes[OUT_WRITE], @sa, 0 ) then goto Error; if not CreatePipe(Pipes[ERR_READ],Pipes[ERR_WRITE], @sa, 0 ) then goto Error; // Пишем StdIn StrPCopy(@Buf[0],stdInput+^Z); WriteFile(Pipes[IN_WRITE],Buf,Length(stdInput),i,nil); // Хендл записи в StdIn надо закрыть - иначе выполняемая программа // может не прочитать или прочитать не весь StdIn. CloseHandle(Pipes[IN_WRITE]); Pipes[IN_WRITE] := INVALID_HANDLE_VALUE; FillChar(StartInf,sizeof(TStartupInfo),0); StartInf.cb := sizeof(TStartupInfo); StartInf.dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES; StartInf.wShowWindow := SW_SHOW; // SW_HIDE если надо запустить невидимо StartInf.hStdInput := Pipes[IN_READ]; StartInf.hStdOutput := Pipes[OUT_WRITE]; StartInf.hStdError := Pipes[ERR_WRITE]; if not CreateProcess(nil, PChar(FileName), nil, nil, True, NORMAL_PRIORITY_CLASS, nil, nil, StartInf, ProcInf) then goto Error; TimeStart := Now; repeat Application.ProcessMessages; i := WaitForSingleObject(ProcInf.hProcess,100); if i = WAIT_OBJECT_0 then break; if (Now-TimeStart)*SecsPerDay>TimeOut then break; until false; if iWAIT_OBJECT_0 then goto Error; StdOutput := ReadOutput; for ph := Low(TPipeHandles) to High(TPipeHandles) do if Pipes[ph]INVALID_HANDLE_VALUE then CloseHandle(Pipes[ph]); CloseHandle(ProcInf.hProcess); CloseHandle(ProcInf.hThread); Result := true; Exit; Error: if ProcInf.hProcessINVALID_HANDLE_VALUE then begin CloseHandle(ProcInf.hThread); i := WaitForSingleObject(ProcInf.hProcess, 1000); CloseHandle(ProcInf.hProcess); if iWAIT_OBJECT_0 then begin ProcInf.hProcess := OpenProcess(PROCESS_TERMINATE, FALSE, ProcInf.dwProcessId); if ProcInf.hProcess 0 then begin TerminateProcess(ProcInf.hProcess, 0); CloseHandle(ProcInf.hProcess); end; end; end; for ph := Low(TPipeHandles) to High(TPipeHandles) do if Pipes[ph]INVALID_HANDLE_VALUE then CloseHandle(Pipes[ph]); end; } end.
unit fb2rb_dispatch; {$WARN SYMBOL_PLATFORM OFF} interface uses ComObj, ActiveX, FB2_to_RB_TLB, StdVcl,fb2rb_engine,fb2_hyph_TLB,MSXML2_TLB; type TFB2RBExport = class(TAutoObject, IFB2RBExport) protected function Get_PageBreaksForLevels: Integer; safecall; function Get_ShortTOCLines: WordBool; safecall; function Get_SkipCover: WordBool; safecall; function Get_SkipDescr: WordBool; safecall; function Get_SkipImages: WordBool; safecall; function Get_TOCLevels: Integer; safecall; function Get_TransLitTitle: WordBool; safecall; procedure Set_PageBreaksForLevels(Value: Integer); safecall; procedure Set_ShortTOCLines(Value: WordBool); safecall; procedure Set_SkipCover(Value: WordBool); safecall; procedure Set_SkipDescr(Value: WordBool); safecall; procedure Set_SkipImages(Value: WordBool); safecall; procedure Set_TOCLevels(Value: Integer); safecall; procedure Set_TransLitTitle(Value: WordBool); safecall; function Get_HOwner: Integer; safecall; function Get_Hyphenator: IDispatch; safecall; function Get_RBMakePath: OleVariant; safecall; function Get_SaveTo: OleVariant; safecall; function Get_XSL: IDispatch; safecall; procedure Set_HOwner(Value: Integer); safecall; procedure Set_Hyphenator(const Value: IDispatch); safecall; procedure Set_RBMakePath(Value: OleVariant); safecall; procedure Set_SaveTo(Value: OleVariant); safecall; procedure Set_XSL(const Value: IDispatch); safecall; procedure Convert(const Document: IDispatch); safecall; procedure ConvertInteractive(hWnd: Integer; filename: OleVariant; const document: IDispatch); safecall; function Get_FileName: OleVariant; safecall; procedure Set_FileName(Value: OleVariant); safecall; procedure LoadLastSettingsFromReg; safecall; procedure LoadLastSettingsFromReg_(key: OleVariant); safecall; procedure LoadSettingsFromRegEngine(key: String); safecall; { Protected declarations } public Params:TFB2RBConverterSettings; ModulePath:String; procedure AfterConstruction;override; end; {DEFINE DEBUG} implementation uses ComServ,Windows,SysUtils,fb_2_rb_dialog,Registry,Classes,Dialogs; procedure TFB2RBExport.AfterConstruction; Begin FillChar(Params,SizeOf(Params),#0); Params.TOCLevel:=2; Params.PageBreakLeve:=2; Params.Target:=SaveToFile; SetLength(ModulePath,2000); GetModuleFileName(HInstance,@ModulePath[1],1999); SetLength(ModulePath,Pos(#0,ModulePath)-1); ModulePath:=IncludeTrailingPathDelimiter(ExtractFileDir(ModulePath)); Params.RBMakePath:=ModulePath+'rbmake.exe'; end; function TFB2RBExport.Get_PageBreaksForLevels: Integer; begin Result:=Params.PageBreakLeve; end; function TFB2RBExport.Get_ShortTOCLines: WordBool; begin Result:=Params.SHortenTOCLines; end; function TFB2RBExport.Get_SkipCover: WordBool; begin Result:=Params.SkipCOver; end; function TFB2RBExport.Get_SkipDescr: WordBool; begin Result:=Params.SKipDescr; end; function TFB2RBExport.Get_SkipImages: WordBool; begin Result:=Params.SkipImages; end; function TFB2RBExport.Get_TOCLevels: Integer; begin Result:=Params.TOCLevel; end; function TFB2RBExport.Get_TransLitTitle: WordBool; begin Result:=Params.TransLitTitle; end; procedure TFB2RBExport.Set_PageBreaksForLevels(Value: Integer); begin Params.PageBreakLeve:=Value; end; procedure TFB2RBExport.Set_ShortTOCLines(Value: WordBool); begin Params.SHortenTOCLines:=Value; end; procedure TFB2RBExport.Set_SkipCover(Value: WordBool); begin Params.SkipCOver:=Value; end; procedure TFB2RBExport.Set_SkipDescr(Value: WordBool); begin Params.SKipDescr:=Value; end; procedure TFB2RBExport.Set_SkipImages(Value: WordBool); begin Params.SkipImages:=Value; end; procedure TFB2RBExport.Set_TOCLevels(Value: Integer); begin Params.TOCLevel:=Value; end; procedure TFB2RBExport.Set_TransLitTitle(Value: WordBool); begin Params.TransLitTitle:=Value; end; function TFB2RBExport.Get_HOwner: Integer; begin Result:=Params.HParent; end; function TFB2RBExport.Get_Hyphenator: IDispatch; begin Result:=Params.HyphControler; end; function TFB2RBExport.Get_RBMakePath: OleVariant; begin Result:=Params.RBMakePath; end; function TFB2RBExport.Get_SaveTo: OleVariant; begin Result:=Params.Target; end; function TFB2RBExport.Get_XSL: IDispatch; begin Result:=Params.XSL; end; procedure TFB2RBExport.Set_HOwner(Value: Integer); begin Params.HParent:=Value; end; procedure TFB2RBExport.Set_Hyphenator(const Value: IDispatch); Var HC:IFB2Hyphenator; begin if Value.QueryInterface(IID_IFB2Hyphenator,HC) <> S_OK then Exception.Create('Invalid hyphenator interface on enter, should be called with IFB2Hyphenator'); Params.HyphControler:=HC; end; procedure TFB2RBExport.Set_RBMakePath(Value: OleVariant); begin Params.RBMakePath:=Value; end; procedure TFB2RBExport.Set_SaveTo(Value: OleVariant); begin Params.Target:=Value; end; procedure TFB2RBExport.Set_XSL(const Value: IDispatch); Var OutVar:IXMLDOMDocument2; begin if Value.QueryInterface(IID_IXMLDOMDocument2,OutVar) <> S_OK then MessageBox(0,'Invalid IDispatch interface on enter, should be called with IXMLDOMDocument2','Error',MB_OK or MB_ICONERROR) else Params.XSL:=OutVar; end; procedure TFB2RBExport.Convert(const Document: IDispatch); Var OutVar:IXMLDOMDocument2; begin if Document=Nil then MessageBox(0,'NILL document value, please provide valid IXMLDOMDocument2 on input.','Error',mb_ok or MB_ICONERROR) else try if Params.XSL=Nil then Begin Params.XSL:=CoFreeThreadedDOMDocument40.Create; Params.XSL.load(ModulePath+'FB2_2_rb.xsl'); end; if document.QueryInterface(IID_IXMLDOMDocument2,OutVar) <> S_OK then MessageBox(0,'Invalid IDispatch interface on enter, should be called with IXMLDOMDocument2','Error',MB_OK or MB_ICONERROR) else Begin Params.DOM:=IXMLDOMDocument2(OutVar); fb2rb_engine.TransFormToReb(Params); end; except on E: Exception do MessageBox(0,PChar(E.Message),'Error',mb_ok or MB_ICONERROR); end end; procedure TFB2RBExport.ConvertInteractive(hWnd: Integer; filename: OleVariant; const document: IDispatch); Var OutVar:IXMLDOMDocument2; B:Integer; begin Try if (document<>Nil) and (document.QueryInterface(IID_IXMLDOMDocument2,OutVar) <> S_OK) then MessageBox(hWnd,'Invalid IDispatch interface on enter, should be called with IXMLDOMDocument2','Error',MB_OK or MB_ICONERROR) else ExportDOM(hWnd,OutVar,filename); except on E: Exception do MessageBox(0,PChar(E.Message),'Error',mb_ok or MB_ICONERROR); end end; function TFB2RBExport.Get_FileName: OleVariant; begin Result:=Params.FileName; end; procedure TFB2RBExport.Set_FileName(Value: OleVariant); begin Params.FileName:=Value; end; procedure TFB2RBExport.LoadLastSettingsFromReg; Begin LoadSettingsFromRegEngine(RegistryKey); end; procedure TFB2RBExport.LoadLastSettingsFromReg_(key: OleVariant); Begin LoadSettingsFromRegEngine(Key); end; procedure TFB2RBExport.LoadSettingsFromRegEngine; Var Reg:TRegistry; SL:TStringList; DOM:IXMLDOMDocument2; Begin Try Reg:=TRegistry.Create; Try if Reg.OpenKeyReadOnly(Key) then Begin Params.SkipImages:=Reg.ReadBool('remove images'); Params.SKipDescr:=Reg.ReadBool('no description'); Params.SkipCOver:=Reg.ReadBool('skip coverpage'); Params.TransLitTitle:=Reg.ReadBool('translit author'); Params.SHortenTOCLines:=Reg.ReadBool('short section titles'); Params.TOCLevel:=Reg.ReadInteger('TOC deepness'); Params.PageBreakLeve:=Reg.ReadInteger('Page breaks level'); if Reg.ReadBool('save to disk') then Params.Target:=SaveToFile else if Reg.ReadInteger('REB media')=0 then Params.Target:=storeOnRebInt else Params.Target:=StoreOnRebSM; If Reg.ReadInteger('font name')<>0 then Begin SL:=TStringList.Create; Try Params.HyphControler:=CoFB2Hyphenator.Create; DOM:=CoFreeThreadedDOMDocument40.Create; DOM.preserveWhiteSpace:=True; DOM.load(ModulePath+'reb.xml'); Params.HyphControler.deviceDescr:=DOM; SL.Text:=Params.HyphControler.deviceSizeList; Params.HyphControler.currentDeviceSize:=SL[Reg.ReadInteger('device orientation')]; SL.Text:=Params.HyphControler.fontList; Params.HyphControler.currentFont:=SL[Reg.ReadInteger('font name')-1]; SL.Text:=Params.HyphControler.fontSizeList; Params.HyphControler.currentFontSize:=SL[Reg.ReadInteger('font size')]; finally SL.Free; end; end; end; FInally Reg.Free; end; except end; end; initialization TAutoObjectFactory.Create(ComServer, TFB2RBExport, Class_FB2RBExport, ciMultiInstance, tmApartment); end.
unit frmInIOCPClient; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, iocp_base, iocp_msgPacks, iocp_clients; type TFormInIOCPClient = class(TForm) InConnection1: TInConnection; InMessageClient1: TInMessageClient; btnInOut: TButton; InCertifyClient1: TInCertifyClient; Memo1: TMemo; btnLogin2: TButton; lbEditIP: TLabeledEdit; lbEditPort: TLabeledEdit; InFileClient1: TInFileClient; procedure FormCreate(Sender: TObject); procedure btnInOutClick(Sender: TObject); procedure InConnection1ReturnResult(Sender: TObject; Result: TResultParams); procedure InCertifyClient1ReturnResult(Sender: TObject; Result: TResultParams); procedure InMessageClient1ReturnResult(Sender: TObject; Result: TResultParams); procedure InCertifyClient1Certify(Sender: TObject; Action: TActionType; ActResult: Boolean); procedure InConnection1ReceiveMsg(Sender: TObject; Message: TResultParams); procedure btnLogin2Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure InConnection1Error(Sender: TObject; const Msg: string); procedure InFileClient1ReturnResult(Sender: TObject; Result: TResultParams); private { Private declarations } FLastMsgId: UInt64; procedure ListOfflineMsgs(Result: TResultParams); procedure SetInConnectionHost; public { Public declarations } end; var FormInIOCPClient: TFormInIOCPClient; implementation uses iocp_varis, iocp_utils; {$R *.dfm} procedure TFormInIOCPClient.btnInOutClick(Sender: TObject); begin // 方法 1: // TMessagePack 的宿主为 InConnection1, // 在 InConnection1.OnReturnResult 反馈结果 SetInConnectionHost; { if InConnection1.Logined then TMessagePack.Create(InConnection1).Post(atUserLogout) else with TMessagePack.Create(InConnection1) do begin UserName := 'aaa'; Password := 'aaa'; Post(atUserLogin); end; } // 方法 2:在 InCertifyClient1.OnReturnResult 反馈结果 if InConnection1.Logined then InCertifyClient1.Logout else with InCertifyClient1 do begin Group := 'Group_a'; // 分组 UserName := 'aaa'; Password := 'aaa'; Login; end; end; procedure TFormInIOCPClient.btnLogin2Click(Sender: TObject); begin SetInConnectionHost; if InConnection1.Logined then InCertifyClient1.Logout else with InCertifyClient1 do begin Group := 'Group_a'; // 分组 UserName := 'bbb'; Password := 'bbb'; Login; end; end; procedure TFormInIOCPClient.FormClose(Sender: TObject; var Action: TCloseAction); begin if InConnection1.Logined then InCertifyClient1.Logout; end; procedure TFormInIOCPClient.FormCreate(Sender: TObject); begin InConnection1.LocalPath := gAppPath + 'data\data_client'; // 数据目录 CreateDir(InConnection1.LocalPath); end; procedure TFormInIOCPClient.InCertifyClient1Certify(Sender: TObject; Action: TActionType; ActResult: Boolean); begin // 登录、登出结果,在 OnReturnResult 之前执行, // 可以在 OnReturnResult 中判断客户端状态 case Action of atUserLogin: if ActResult then begin btnInOut.Caption := '登出'; btnLogin2.Caption := '登出2'; end; atUserLogout: begin btnInOut.Caption := '登录'; btnLogin2.Caption := '登录2'; end; else { 无其他操作 } ; end; end; procedure TFormInIOCPClient.InCertifyClient1ReturnResult(Sender: TObject; Result: TResultParams); begin case Result.Action of atUserLogin: begin Memo1.Lines.Add(Result.Msg); if (Result.ActResult = arOK) then InMessageClient1.GetOfflineMsgs; // 取离线消息 end; atUserLogout: begin Memo1.Lines.Add(Result.Msg); InConnection1.Active := False; end; end; end; procedure TFormInIOCPClient.InConnection1Error(Sender: TObject; const Msg: string); begin Memo1.lines.Add(Msg); end; procedure TFormInIOCPClient.InConnection1ReceiveMsg(Sender: TObject; Message: TResultParams); begin // 收到其他客户端的推送消息 // 在服务端使用 InMessageManager1.Broadcast()、PushMsg() 发出 // Msg.Action、Mag.ActResult 与服务端发出处的一致 Memo1.lines.Add('收到推送消息:' + Message.PeerIPPort + ', 用户:' + Message.UserName + ', 消息:' + Message.Msg); if Message.Action = atFileUpShare then // 要下载共享文件 with TMessagePack.Create(InFileClient1) do begin FileName := Message.FileName; // 服务端文件名 LocalPath := 'temp'; // 下载存放到 temp 目录 Post(atFileDownShare); end; end; procedure TFormInIOCPClient.InConnection1ReturnResult(Sender: TObject; Result: TResultParams); begin case Result.Action of atUserLogin: begin Memo1.Lines.Add(Result.Msg); if (Result.ActResult = arOK) then begin btnInOut.Caption := '登出'; btnLogin2.Caption := '登出2'; InMessageClient1.GetOfflineMsgs; // 取离线消息 end; end; atUserLogout: begin Memo1.Lines.Add(Result.Msg); InConnection1.Active := False; btnInOut.Caption := '登录'; btnLogin2.Caption := '登录2'; end; else { 其他操作结果 } ; end; end; procedure TFormInIOCPClient.InFileClient1ReturnResult(Sender: TObject; Result: TResultParams); begin if Result.Action = atFileUpShare then if Result.ActResult = arOK then Memo1.Lines.Add('文件下载完毕'); end; procedure TFormInIOCPClient.InMessageClient1ReturnResult(Sender: TObject; Result: TResultParams); begin case Result.Action of atTextGetMsg: // 离线消息 ListOfflineMsgs(Result); end; end; procedure TFormInIOCPClient.ListOfflineMsgs(Result: TResultParams); var i, k: Integer; PackMsg: TReceivePack; // 接收消息包 Reader: TMessageReader; // 离线消息阅读器 begin // === 读出离线消息 === if not Assigned(Result.Attachment) then Exit; // 有附件,可能是离线消息,读出! Memo1.Lines.Add('离线消息: ' + Result.Msg); PackMsg := TReceivePack.Create; Reader := TMessageReader.Create; try // 此时 Attachment 已经关闭,但未释放 // 打开文件,如果不是消息文件 -> Count = 0 Reader.Open(Result.Attachment.FileName); // 请把以前读过的最大 MsgId 保存到磁盘, // 登录前读入并设置 LastMsgId = ???,从离线 // 消息文件中读出比 LastMsgId 大的消息。 for i := 0 to Reader.Count - 1 do begin if Reader.Extract(PackMsg, FLastMsgId) then // 读出比 LastMsgId 大的消息 begin for k := 0 to PackMsg.Count - 1 do // 遍历字段 with PackMsg.Fields[k] do Memo1.Lines.Add(Name + '=' + AsString); if PackMsg.Action = atFileUpShare then // 这个是共享文件,下载它 begin Memo1.Lines.Add('下载文件:' + PackMsg.FileName); with TMessagePack.Create(InFileClient1) do begin FileName := PackMsg.FileName; LocalPath := 'temp'; // 存放到 temp 目录 Post(atFileDownShare); // 下载共享文件 end; end; end; end; // 保存最大的消息号 if PackMsg.MsgId > FLastMsgId then begin FLastMsgId := PackMsg.MsgId; with TStringList.Create do try Add(IntToStr(FLastMsgId)); SaveToFile('data\MaxMsgId.ini'); finally Free; end; end; finally PackMsg.Free; Reader.Free; end; end; procedure TFormInIOCPClient.SetInConnectionHost; begin if not InConnection1.Active then begin InConnection1.ServerAddr := lbEditIP.Text; InConnection1.ServerPort := StrToInt(lbEditPort.Text); end; end; end.
unit nsConfiguration; (*----------------------------------------------------------------------------- Название: nsConfiguration Автор: М. Морозов Назначение: Модуль содержит инструменты для работы с конфигураций. История: $Id: nsConfiguration.pas,v 1.4 2013/09/25 17:13:02 lulin Exp $ $Log: nsConfiguration.pas,v $ Revision 1.4 2013/09/25 17:13:02 lulin - рефакторим подписку к настройкам. Revision 1.3 2013/05/23 06:55:41 morozov {RequestLink:372641792} Revision 1.2 2012/05/28 12:29:35 lulin {RequestLink:356848399} Revision 1.1 2012/04/16 13:20:36 lulin {RequestLink:237994598} Revision 1.64 2011/07/29 16:38:32 lulin {RequestLink:209585097}. - аккуратнее обрабатываем словарные теги. Revision 1.63 2011/07/29 14:18:53 lulin {RequestLink:209585097}. Revision 1.62 2011/02/01 17:43:31 lulin {RequestLink:228688602}. - делаем, чтобы разделитель "висел в воздухе". Revision 1.61 2011/01/27 12:16:51 lulin {RequestLink:248195582}. - избавляемся от развесистых макарон. Revision 1.60 2010/03/15 18:09:59 lulin {RequestLink:196969151}. Revision 1.59 2009/10/15 12:34:10 oman - new: Переносим на модель {RequestLink:122652464} Revision 1.58 2009/07/31 17:30:14 lulin - убираем мусор. Revision 1.57 2009/06/03 12:28:05 oman - new: компилируемся - [$148014435] Revision 1.56 2009/02/10 19:03:57 lulin - <K>: 133891247. Вычищаем морально устаревший модуль. Revision 1.55 2009/02/10 12:53:47 lulin - <K>: 133891247. Выделяем интерфейсы настройки. Revision 1.54 2009/01/26 13:55:45 oman - fix: Пакетно узнаем об измененности (К-133892891) Revision 1.53 2009/01/26 12:30:58 oman - fix: Пакетно узнаем об измененности (К-133892891) Revision 1.52 2008/08/06 08:54:40 oman Поменялись интерфейсы Revision 1.51 2008/03/26 17:59:12 lulin - <K>: 88080901. Revision 1.50 2008/03/26 11:37:12 lulin - зачистка в рамках <K>: 88080898. Revision 1.49 2008/03/26 11:12:48 lulin - зачистка в рамках <K>: 88080898. Revision 1.48 2008/01/10 07:23:32 oman Переход на новый адаптер Revision 1.47 2007/12/28 17:59:34 lulin - удалена ненужная глобальная переменная - ссылка на метод получения настроек. Revision 1.46 2007/12/12 12:23:01 mmorozov - rename function; Revision 1.45 2007/12/11 07:00:26 mmorozov - new: слушаем замену настроек (в рамках CQ: OIT5-27823); Revision 1.44 2007/06/05 06:57:29 oman - fix: Пропала реакция на измененность конфигурации - неправильно приводили строку (cq25548) Revision 1.43 2006/11/03 09:46:03 oman Merge with B_NEMESIS_6_4_0 Revision 1.42.4.1 2006/10/25 07:29:56 oman Продолжаем избавлятся от StdStr Revision 1.42 2006/05/04 11:42:48 lulin - cleanup. Revision 1.41 2006/05/03 14:25:42 oman - change: сведение редактирования настроек к одним воротам - new beh: операция "восстановить все" для списка конфигураций (cq20377) Revision 1.40 2006/04/17 14:42:33 oman - new beh: перекладываем StdStr в _StdRes Revision 1.39 2006/04/07 07:48:59 oman - new: В спсиске конфигураций не было нотификации об изменении настроек (сq20365) Revision 1.38 2006/03/28 11:56:43 oman - change: Изводим %s в константах + избавляемся от сборки сообщений из констант в коде. Revision 1.37 2006/03/16 15:05:42 oman - new beh: Перекладываем все текстовые константы в три места (StdStr, DebugStr и SystemStr) Revision 1.36 2006/01/19 16:03:14 oman - fix: неверно вычислялась доступность операция "восстановить" Revision 1.35 2006/01/18 09:38:34 oman - мелкий рефакторинг Revision 1.34 2005/12/13 16:12:20 oman - new behavior: базовый класс, реализующий InsEditSettingsInfo Revision 1.33 2005/12/12 11:55:36 oman -fix: pi_Print_Metrics_UseDocSettings не считалась принтерной настройкой Revision 1.32 2005/12/08 13:35:26 oman - fix: при смене конфигукций в реализации IvcmSettings оставалась неверная ссылка на адаптерные ISettings Revision 1.31 2005/09/21 08:34:52 dolgop - change: изменения, связанные с появлением IString в Settings Revision 1.30 2005/06/30 07:48:19 cyberz READY FOR TIE-TEMPLATE GENERATION Revision 1.29 2005/06/03 10:04:30 mmorozov remove: var ConfigurationListForMenu - за ненадобностью; Revision 1.28 2005/03/04 15:33:04 dinishev Директива Monitorings для уменшения количества подключаемых модулей Revision 1.27 2005/02/14 12:06:10 mmorozov new: class TnsConfigurationData; Revision 1.26 2005/01/18 10:36:42 am bugfix: сообщение о смене конфигурации рассылалось до перевставления форм, перечитывания тулбаров, etc Revision 1.25 2005/01/13 16:46:11 am change: поменялась идеология прошивания стилей Revision 1.24 2004/11/16 15:00:15 mmorozov new: _ReinsertForms перенесен на vcmDispatcher; Revision 1.23 2004/10/27 16:21:53 mmorozov - изменения в связи с возможностью восстанавливать, записывать по умолчанию "Настройки страницы"; Revision 1.22 2004/10/26 17:15:37 mmorozov new: возможность восстанавливать "Настройки страницы"; Revision 1.21 2004/10/18 07:54:06 mmorozov new behaviour: при смене таблицы стилей перечитывается таблица стилей; Revision 1.20 2004/09/23 09:17:15 mmorozov - add log; -----------------------------------------------------------------------------*) interface uses Classes, l3Tree_TLB, afwInterfaces, vcmInterfaces, vcmBase, vcmExternalInterfaces, SettingsUnit, nsConfigurationNodes, ConfigInterfaces ; type _afwSettingsReplace_Parent_ = TvcmBase; {$Include afwSettingsReplace.imp.pas} TnsEditSettingsInfo = class(_afwSettingsReplace_, InsEditSettingsInfo) {* - для передачи в диалоги редактирования конфигурации параметров с которой работают. } private // private members f_Settings: IvcmSettings; f_EditingSettings: IvcmStrings; f_IsActive: Boolean; f_IsPredefined: Boolean; f_Modified: Boolean; f_IsDifferFromDefault: Boolean; f_Config: IConfiguration; f_NotUserSettingList: IvcmStrings; protected // IafwSettingsReplaceListener procedure SettingsReplaceFinish; override; {* - после замены настроек. } protected // private methods function pm_GetEditingSettings: IvcmStrings; function pm_GetIsActive: Boolean; function pm_GetIsPredefined: Boolean; function pm_GetIsDifferFromDefault: Boolean; function pm_GetModified: Boolean; protected property Configuration: IConfiguration read f_Config; private // private methods function pm_GetSettings: IvcmSettings; procedure SetActive(const aValue: Boolean); protected // protected methods function MakeEditingSettings: IvcmStrings; virtual; abstract; procedure DoLoad(aRestoreDefault: Boolean = False); virtual; abstract; { Реальная загрузка } procedure DoSave(aSaveAsDefault: Boolean = False); virtual; abstract; { Реальное сохранение } procedure DoAfterLoad(aRestoreDefault: Boolean = False); virtual; procedure DoAfterSave(aSaveAsDefault: Boolean = False); virtual; procedure UpdateActivity; { Обновить активность/настройки } procedure DoneEditing; virtual; { Закончить редактирование } function DoGetModified: Boolean; virtual; {-} procedure CheckDifferFromDefault; {-} procedure Cleanup; override; {-} function MakeNotUserSettingList: IvcmStrings; virtual; function IsUserSetting(const aSettingName: String): Boolean; virtual; protected // protected properties property Settings: IvcmSettings read pm_GetSettings; public // public methods class function Make(const aConfig : IConfiguration = nil) : InsEditSettingsInfo; {-} constructor Create(const aConfig : IConfiguration = nil); reintroduce; virtual; {-} procedure InitialLoadStyleTableFromSettings; {-} procedure Load(aRestoreDefault: Boolean = False); {-} procedure Save(aSaveAsDefault: Boolean = False); {-} procedure MarkModified; {-} public // public properties property IsActive: Boolean read pm_GetIsActive; {-} property IsPredefined: Boolean read pm_GetIsPredefined; {-} property IsDifferFromDefault: Boolean read pm_GetIsDifferFromDefault; {-} property EditingSettings: IvcmStrings read pm_GetEditingSettings; {-} property Modified: Boolean read pm_GetModified; {-} end; implementation uses Forms, SysUtils, l3Interfaces, afwFacade, vcmStringList, vcmBaseMenuManager, vcmEntityForm, vcmSettings, {$If not (defined(Monitorings) or defined(Admin))} ddAppConfigTypes, {$IfEnd not (defined(Monitorings) or defined(Admin))} StdRes, DebugStr, DataAdapter, {$If not (defined(Monitorings) or defined(Admin))} nsAppConfig, {$IfEnd not (defined(Monitorings) or defined(Admin))} nsSettings, nsTypes, evDefaultStylesFontSizes, nsStyleEditor, nsConst, l3String, l3Base, afwSettingsChangePublisher ; function nsActiveConfiguration: IConfiguration; var lConfs : IConfigurationManager; begin lConfs := DefDataAdapter.NativeAdapter.MakeConfigurationManager; try lConfs.GetActive(Result); finally lConfs := nil; end; end; {$Include afwSettingsReplace.imp.pas} { TnsEditSettingsInfo } procedure TnsEditSettingsInfo.Cleanup; begin f_Settings := nil; f_EditingSettings := nil; f_Config := nil; f_NotUserSettingList := nil; inherited; end; function TnsEditSettingsInfo.MakeNotUserSettingList: IvcmStrings; var l_Strings: IvcmStrings; begin l_Strings := TvcmStringList.Make; Result := l_Strings; end; function TnsEditSettingsInfo.IsUserSetting(const aSettingName: String): Boolean; begin Result := (f_NotUserSettingList.IndexOf(aSettingName) < 0); end; constructor TnsEditSettingsInfo.Create(const aConfig: IConfiguration); begin inherited Create; f_Config := aConfig; if f_Config = nil then f_Config := nsActiveConfiguration; Assert(Assigned(f_Config),caNoActiveConfig); UpdateActivity; f_EditingSettings := MakeEditingSettings; f_IsPredefined := f_Config.GetIsReadonly; f_NotUserSettingList := MakeNotUserSettingList; CheckDifferFromDefault; Assert(Assigned(f_Settings),caNoSettings); end; function TnsEditSettingsInfo.pm_GetIsActive: Boolean; begin Result := f_IsActive; end; function TnsEditSettingsInfo.pm_GetIsDifferFromDefault: Boolean; begin Result := f_IsDifferFromDefault; end; function TnsEditSettingsInfo.pm_GetIsPredefined: Boolean; begin Result := f_IsPredefined; end; procedure TnsEditSettingsInfo.InitialLoadStyleTableFromSettings; var l_S : Il3CString; l_S1 : Il3CString; begin Load; l_S := Settings.LoadString(pi_StyleTable, nsStyleEditor.ResourceStyle, false); if l3IsNil(l_S) then l_S := l3CStr(nsStyleEditor.ResourceStyle); try Load(true); l_S1 := Settings.LoadString(pi_StyleTable, nsStyleEditor.ResourceStyle, false); if l3IsNil(l_S1) then l_S1 := l3CStr(nsStyleEditor.ResourceStyle); // !!! - БЕРЁМ настройки от УМ TevDefaultStylesFontSizes.Instance.SaveStylesFontSizes; finally Settings.SaveString(pi_StyleTable, l_S, l3Str(l_S1){nsStyleEditor.ResourceStyle}, false); end;//try..finally Load; end; procedure TnsEditSettingsInfo.Load(aRestoreDefault: Boolean); begin DoLoad(aRestoreDefault); DoAfterLoad(aRestoreDefault); end; class function TnsEditSettingsInfo.Make( const aConfig: IConfiguration): InsEditSettingsInfo; var l_Class: TnsEditSettingsInfo; begin l_Class := Create(aConfig); try Result := l_Class; finally vcmFree(l_Class); end; end; function TnsEditSettingsInfo.pm_GetEditingSettings: IvcmStrings; begin Result := f_EditingSettings; end; procedure TnsEditSettingsInfo.Save(aSaveAsDefault: Boolean); begin DoSave(ASaveAsDefault); DoAfterSave(ASaveAsDefault); end; function TnsEditSettingsInfo.pm_GetModified: Boolean; begin Result := DoGetModified; end; procedure TnsEditSettingsInfo.MarkModified; begin f_Modified := True; f_IsDifferFromDefault := True; end; procedure TnsEditSettingsInfo.CheckDifferFromDefault; var lIndex : Integer; lSettings: ISettingsManager; l_Name: PAnsiChar; l_List: IPropertyStringIDList; begin f_IsDifferFromDefault := False; lSettings := Settings as ISettingsManager; l_List := defDataAdapter.NativeAdapter.MakePropertyStringIDList; for lIndex := 0 to Pred(EditingSettings.Count) do begin l_Name := nsAStr(EditingSettings[lIndex]).S; // Если настройка включена в список не влияющих на признак изменений - пропустим // http://mdp.garant.ru/pages/viewpage.action?pageId=372641792 if not IsUserSetting(l_Name) then Continue; // настройка есть if lSettings.IsExist(l_Name) then l_List.Add(nsIStr(l_Name)); end;//for lIndex if lSettings.IsChangedSet(l_List) then f_IsDifferFromDefault := True; end; procedure TnsEditSettingsInfo.SetActive(const aValue: Boolean); begin if f_IsActive <> aValue then begin f_IsActive := aValue; f_Settings := nil; end; end; procedure TnsEditSettingsInfo.UpdateActivity; begin SetActive(nsActiveConfiguration.GetId = f_Config.GetId); end; procedure TnsEditSettingsInfo.DoAfterLoad(aRestoreDefault: Boolean); begin CheckDifferFromDefault; f_Modified := False; end; procedure TnsEditSettingsInfo.DoAfterSave(aSaveAsDefault: Boolean); begin CheckDifferFromDefault; f_Modified := False; end; function TnsEditSettingsInfo.pm_GetSettings: IvcmSettings; var l_Settings: ISettingsManager; begin if f_Settings = nil then begin if IsActive then f_Settings := afw.Settings else begin f_Config.GetSettings(l_Settings); f_Settings := TnsSettings.Make(l_Settings, defDataAdapter.NativeAdapter.MakeConfigurationManager); end; end; Result := f_Settings; end; procedure TnsEditSettingsInfo.DoneEditing; begin f_Settings := nil; end; function TnsEditSettingsInfo.DoGetModified: Boolean; begin Result := f_Modified; end; procedure TnsEditSettingsInfo.SettingsReplaceFinish; begin inherited; UpdateActivity; end; end.
{ DBAExplorer - Oracle Admin Management Tool Copyright (C) 2008 Alpaslan KILICKAYA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit frmTablespaceDetail; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, cxLookAndFeelPainters, cxGraphics, cxMemo, cxRichEdit, cxCheckBox, cxDropDownEdit, cxImageComboBox, cxSpinEdit, cxMaskEdit, cxButtonEdit, cxTextEdit, cxContainer, cxEdit, cxLabel, cxPC, cxControls, StdCtrls, cxButtons, ExtCtrls, OraTablespace, cxGroupBox, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, DB, cxDBData, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, MemDS, VirtualTable; type TTablespaceDetailFrm = class(TForm) pc: TcxPageControl; tsTablespace: TcxTabSheet; tsDataFile: TcxTabSheet; tsDDL: TcxTabSheet; redtDDL: TcxRichEdit; cxGroupBox2: TcxGroupBox; Label11: TcxLabel; Label12: TcxLabel; Label13: TcxLabel; Label14: TcxLabel; Label1: TcxLabel; Label2: TcxLabel; Label3: TcxLabel; Label4: TcxLabel; Label5: TcxLabel; Label6: TcxLabel; Label7: TcxLabel; Label8: TcxLabel; cxLabel1: TcxLabel; cxLabel2: TcxLabel; edtInitialExtend: TcxButtonEdit; edtNextExtend: TcxButtonEdit; edtMinExtents: TcxSpinEdit; edtMaxExtents: TcxSpinEdit; edtPctIncrease: TcxButtonEdit; icbStatus: TcxImageComboBox; icbContents: TcxImageComboBox; icbLogging: TcxImageComboBox; cbForceLogging: TcxCheckBox; icbExtentManagement: TcxImageComboBox; icbRetention: TcxImageComboBox; cbBigFile: TcxCheckBox; edtMinExtlen: TcxSpinEdit; edtBlockSize: TcxButtonEdit; icbSgmentSpaceManagement: TcxImageComboBox; cxLabel3: TcxLabel; cbCompress: TcxCheckBox; cxGroupBox3: TcxGroupBox; btnExecute: TcxButton; btnCancel: TcxButton; Bevel1: TBevel; icbAllocationType: TcxImageComboBox; edtName: TcxMaskEdit; gridDataFileDB: TcxGridDBTableView; gridDataFileLevel1: TcxGridLevel; gridDataFile: TcxGrid; btnAddDataFile: TcxButton; btnEditDataFile: TcxButton; btnDeleteDataFile: TcxButton; vtDataFile: TVirtualTable; dsDataFile: TDataSource; vtDataFileNAME: TStringField; vtDataFileSIZE: TFloatField; vtDataFileUNITS: TStringField; vtDataFileREUSE: TStringField; vtDataFileAUTOEXTEND: TStringField; vtDataFileNEXT: TFloatField; vtDataFileNEXT_UNIT: TStringField; vtDataFileMAX_UNLIMITED: TStringField; vtDataFileMAX_SIZE: TFloatField; vtDataFileMAX_UNIT: TStringField; gridDataFileDBNAME: TcxGridDBColumn; gridDataFileDBSIZE: TcxGridDBColumn; gridDataFileDBUNITS: TcxGridDBColumn; gridDataFileDBREUSE: TcxGridDBColumn; gridDataFileDBAUTOEXTEND: TcxGridDBColumn; gridDataFileDBNEXT: TcxGridDBColumn; gridDataFileDBNEXT_UNIT: TcxGridDBColumn; gridDataFileDBMAX_UNLIMITED: TcxGridDBColumn; gridDataFileDBMAX_SIZE: TcxGridDBColumn; gridDataFileDBMAX_UNIT: TcxGridDBColumn; vtDataFileRECORD_STATUS: TStringField; procedure btnCancelClick(Sender: TObject); procedure pcPageChanging(Sender: TObject; NewPage: TcxTabSheet; var AllowChange: Boolean); procedure btnExecuteClick(Sender: TObject); procedure btnAddDataFileClick(Sender: TObject); procedure btnEditDataFileClick(Sender: TObject); procedure btnDeleteDataFileClick(Sender: TObject); procedure vtDataFileAfterScroll(DataSet: TDataSet); private { Private declarations } FTablespace: TTablespace; FNewTablespace: TTablespace; procedure GetTablespaceDetail; function SetTablespaceDetail: boolean; procedure GetDataFiles; public { Public declarations } function Init(ATablespace: TTablespace): boolean; end; var TablespaceDetailFrm: TTablespaceDetailFrm; implementation {$R *.dfm} uses Util, frmSchemaBrowser, GenelDM, OraStorage, VisualOptions, frmDataFile; function TTablespaceDetailFrm.Init(ATablespace: TTablespace): boolean; begin TablespaceDetailFrm := TTablespaceDetailFrm.Create(Application); Self := TablespaceDetailFrm; DMGenel.ChangeLanguage(self); ChangeVisualGUI(self); FTablespace := TTablespace.Create; FTablespace := ATablespace; FNewTablespace := TTablespace.Create; FNewTablespace.OraSession := ATablespace.OraSession; FNewTablespace.Mode := ATablespace.Mode; GetTablespaceDetail; pc.ActivePage := tsTablespace; ShowModal; result := ModalResult = mrOk; Free; end; procedure TTablespaceDetailFrm.btnCancelClick(Sender: TObject); begin close; end; procedure TTablespaceDetailFrm.GetTablespaceDetail; begin if FTablespace.Mode = InsertMode then Caption := 'Create Tablespace ' else Caption := 'Alter Tablespace '+FTablespace.TABLESPACE_NAME; with FTablespace do begin edtName.Text := TABLESPACE_NAME; edtBlockSize.Text := FloatToStr(BLOCK_SIZE); edtInitialExtend.Text := FloatToStr(INITIAL_EXTENT); edtNextExtend.Text := FloatToStr(NEXT_EXTENT); edtMinExtents.Text := FloatToStr(MIN_EXTENTS); edtMaxExtents.Text := FloatToStr(MAX_EXTENTS); edtPctIncrease.Text := FloatToStr(PCT_INCREASE); edtMinExtlen.Text := FloatToStr(MIN_EXTLEN); icbStatus.ItemIndex := Integer(STATUS); icbContents.ItemIndex := Integer(CONTENTS); icbLogging.ItemIndex := Integer(LOGGING); cbForceLogging.Checked := FORCE_LOGGING; icbExtentManagement.ItemIndex := Integer(EXTENT_MANAGEMENT); icbAllocationType.ItemIndex := Integer(ALLOCATION_TYPE); icbSgmentSpaceManagement.ItemIndex := integer(SEGMENT_SPACE_MANAGEMENT); cbCompress.Checked := DEF_TAB_COMPRESSION; icbRetention.ItemIndex := Integer(RETENTION); cbBigFile.Checked := BIGFILE; end; edtName.enabled := FTablespace.Mode = InsertMode; edtBlockSize.enabled := FTablespace.Mode = InsertMode; edtInitialExtend.enabled := FTablespace.Mode = InsertMode; edtNextExtend.enabled := FTablespace.Mode = InsertMode; edtMinExtents.enabled := FTablespace.Mode = InsertMode; edtMaxExtents.enabled := FTablespace.Mode = InsertMode; edtPctIncrease.enabled := FTablespace.Mode = InsertMode; edtMinExtlen.enabled := FTablespace.Mode = InsertMode; icbContents.enabled := FTablespace.Mode = InsertMode; icbExtentManagement.enabled := FTablespace.Mode = InsertMode; icbAllocationType.enabled := FTablespace.Mode = InsertMode; icbSgmentSpaceManagement.enabled := FTablespace.Mode = InsertMode; icbRetention.enabled := FTablespace.Mode = InsertMode; cbBigFile.enabled := FTablespace.Mode = InsertMode; vtDataFile.Open; GetDataFiles; btnEditDataFile.Enabled := FTablespace.Mode = InsertMode; end; //GetTablespaceDetail; function TTablespaceDetailFrm.SetTablespaceDetail: boolean; begin result := true; if edtName.Text = '' then begin MessageDlg('Tablespace Name must be specified', mtWarning, [mbOk], 0); result := false; exit; end; if (FNewTablespace.Mode = InsertMode) and (FNewTablespace.DataFileCount <= 0) then begin MessageDlg('Required Data File', mtWarning, [mbOk], 0); result := false; exit; end; with FNewTablespace do begin TABLESPACE_NAME := edtName.Text; BLOCK_SIZE := StrToFloat(isNull(edtBlockSize.Text)); INITIAL_EXTENT := StrToFloat(isNull(edtInitialExtend.Text)); NEXT_EXTENT := StrToFloat(isNull(edtNextExtend.Text)); MIN_EXTENTS := StrToFloat(isNull(edtMinExtents.Text)); MAX_EXTENTS := StrToFloat(isNull(edtMaxExtents.Text)); PCT_INCREASE := StrToFloat(isNull(edtPctIncrease.Text)); MIN_EXTLEN := StrToFloat(isNull(edtMinExtlen.Text)); STATUS := TTablespaceStatus(icbStatus.ItemIndex); CONTENTS := TTablespaceContents(icbContents.ItemIndex); LOGGING := TLoggingType(icbLogging.ItemIndex); FORCE_LOGGING := cbForceLogging.Checked; EXTENT_MANAGEMENT := TTablespaceExtentManagement(icbExtentManagement.ItemIndex); ALLOCATION_TYPE := TTablespaceAllocation(icbAllocationType.ItemIndex); SEGMENT_SPACE_MANAGEMENT := TSegmentSpaceManagement(icbSgmentSpaceManagement.ItemIndex); DEF_TAB_COMPRESSION := cbCompress.Checked; RETENTION := TTablespaceRetention(icbRetention.ItemIndex); BIGFILE := cbBigFile.Checked; end; //FTablespace end; //SetTablespaceDetail procedure TTablespaceDetailFrm.pcPageChanging(Sender: TObject; NewPage: TcxTabSheet; var AllowChange: Boolean); begin if NewPage = tsDDL then begin if not SetTablespaceDetail then AllowChange := false else begin if FNewTablespace.Mode = InsertMode then redtDDL.Text := FNewTablespace.GetDDL else redtDDL.Text := FNewTablespace.GetAlterDDL(FTablespace); end; CodeColors(self, 'Default', redtDDL, false); end; end; procedure TTablespaceDetailFrm.btnExecuteClick(Sender: TObject); begin if not SetTablespaceDetail then exit; if FNewTablespace.Mode = InsertMode then begin redtDDL.Text := FNewTablespace.GetDDL; if FNewTablespace.CreateTablespace(redtDDL.Text) then ModalResult := mrOK; end else begin redtDDL.Text := FNewTablespace.GetAlterDDL(FTablespace); if FNewTablespace.AlterTablespace(redtDDL.Text) then ModalResult := mrOK; end; end; procedure TTablespaceDetailFrm.GetDataFiles; var DataFile: TDataFile; i: integer; begin for i:= 0 to FTablespace.DataFileCount -1 do begin DataFile := FTablespace.DatafileItems[i]; with vtDataFile do begin Append; FieldByName('NAME').AsString := dataFile^.NAME; FieldByName('SIZE').AsFloat := dataFile^.SIZE; FieldByName('UNITS').AsString := dataFile^.UNITS; FieldByName('REUSE').asString := BoolToStr(dataFile^.REUSE, 'YN'); FieldByName('AUTOEXTEND').asString := BoolToStr(dataFile^.AUTOEXTEND, 'YN'); FieldByName('NEXT').AsFloat := dataFile^.NEXT; FieldByName('NEXT_UNIT').AsString := dataFile^.NEXT_UNITS; FieldByName('MAX_UNLIMITED').AsString := BoolToStr(dataFile^.MAX_UNLIMITED, 'YN'); FieldByName('MAX_SIZE').AsFloat := dataFile^.MAX_SIZE; FieldByName('MAX_UNIT').AsString := dataFile^.MAX_UNITS; FieldByName('RECORD_STATUS').AsString := 'OLD'; post; end; end; end; procedure TTablespaceDetailFrm.btnAddDataFileClick(Sender: TObject); var DataFile: TDataFile; begin new(DataFile); DataFile^.TABLESPACE_NAME := edtName.Text; DataFile^.NAME := ''; DataFile^.SIZE := 0; DataFile^.UNITS:= ''; DataFile^.REUSE := FALSE; DataFile^.AUTOEXTEND:= FALSE; DataFile^.NEXT := 0; DataFile^.NEXT_UNITS:=''; DataFile^.MAX_UNLIMITED:=FALSE; DataFile^.MAX_SIZE:= 0; DataFile^.MAX_UNITS:=''; if DataFileFrm.Init(DataFile) then begin with vtDataFile do begin Append; FieldByName('NAME').AsString := dataFile^.NAME; FieldByName('SIZE').AsFloat := dataFile^.SIZE; FieldByName('UNITS').AsString := dataFile^.UNITS; FieldByName('REUSE').asString := BoolToStr(dataFile^.REUSE, 'YN'); FieldByName('AUTOEXTEND').asString := BoolToStr(dataFile^.AUTOEXTEND, 'YN'); FieldByName('NEXT').AsFloat := dataFile^.NEXT; FieldByName('NEXT_UNIT').AsString := dataFile^.NEXT_UNITS; FieldByName('MAX_UNLIMITED').AsString := BoolToStr(dataFile^.MAX_UNLIMITED, 'YN'); FieldByName('MAX_SIZE').AsFloat := dataFile^.MAX_SIZE; FieldByName('MAX_UNIT').AsString := dataFile^.MAX_UNITS; FieldByName('RECORD_STATUS').AsString := 'NEW'; post; FNewTablespace.DataFileAdd(DataFile); end; end; end; procedure TTablespaceDetailFrm.btnEditDataFileClick(Sender: TObject); var DataFile: TDataFile; index: integer; begin if not vtDataFile.Active then exit; if vtDataFile.RecordCount <= 0 then exit; index := FNewTablespace.FindByDataFileId(vtDataFile.FieldByName('NAME').AsString); DataFile := FNewTablespace.DatafileItems[index]; if DataFileFrm.Init(DataFile) then begin with vtDataFile do begin //locate('NAME',dataFile^.NAME, []); Edit; FieldByName('NAME').AsString := dataFile^.NAME; FieldByName('SIZE').AsFloat := dataFile^.SIZE; FieldByName('UNITS').AsString := dataFile^.UNITS; FieldByName('REUSE').asString := BoolToStr(dataFile^.REUSE, 'YN'); FieldByName('AUTOEXTEND').asString := BoolToStr(dataFile^.AUTOEXTEND, 'YN'); FieldByName('NEXT').AsFloat := dataFile^.NEXT; FieldByName('NEXT_UNIT').AsString := dataFile^.NEXT_UNITS; FieldByName('MAX_UNLIMITED').AsString := BoolToStr(dataFile^.MAX_UNLIMITED, 'YN'); FieldByName('MAX_SIZE').AsFloat := dataFile^.MAX_SIZE; FieldByName('MAX_UNIT').AsString := dataFile^.MAX_UNITS; post; end; end; end; procedure TTablespaceDetailFrm.btnDeleteDataFileClick(Sender: TObject); var index: integer; begin if not vtDataFile.Active then exit; if vtDataFile.RecordCount <= 0 then exit; index := FNewTablespace.FindByDataFileId(vtDataFile.FieldByName('NAME').AsString); FNewTablespace.DataFileDelete(index); vtDataFile.Delete; end; procedure TTablespaceDetailFrm.vtDataFileAfterScroll(DataSet: TDataSet); begin btnEditDataFile.Enabled := vtDataFile.FieldByName('RECORD_STATUS').AsString = 'NEW'; btnDeleteDataFile.Enabled := vtDataFile.FieldByName('RECORD_STATUS').AsString = 'NEW'; end; end.
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: Arno Garrels <arno.garrels@gmx.de> Creation: Oct 25, 2005 Description: Fast streams for ICS tested on D5 and D7. Version: 6.00 Legal issues: Copyright (C) 2005 by Arno Garrels, Berlin, Germany, contact: <arno.garrels@gmx.de> This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. History: Jan 05, 2006 V1.01 F. Piette added missing resourcestring for Delphi 6 Mar 26, 2006 V6.00 F. Piette started new version 6 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} unit OverbyteIcsStreams; interface {$Q-} { Disable overflow checking } {$B-} { Enable partial boolean evaluation } {$T-} { Untyped pointers } {$X+} { Enable extended syntax } {$I OverbyteIcsDefs.inc} {$IFDEF DELPHI6_UP} {$WARN SYMBOL_PLATFORM OFF} {$WARN SYMBOL_LIBRARY OFF} {$WARN SYMBOL_DEPRECATED OFF} {$ENDIF} {$IFNDEF VER80} { Not for Delphi 1 } {$H+} { Use long strings } {$J+} { Allow typed constant to be modified } {$ENDIF} {$IFDEF BCB3_UP} {$ObjExportAll On} {$ENDIF} uses Windows, SysUtils, Classes, {$IFDEF COMPILER6_UP} RTLConsts {$ELSE} Consts {$ENDIF}; {$IFDEF DELPHI6} resourcestring SFCreateErrorEx = 'Cannot create file "%s". %s'; SFOpenErrorEx = 'Cannot open file "%s". %s'; {$ENDIF} const DEFAULT_BUFSIZE = 4096; MIN_BUFSIZE = 512; MAX_BUFSIZE = 1024 * 64; type BigInt = {$IFDEF DELPHI6_UP} Int64 {$ELSE} Longint {$ENDIF}; TBufferedFileStream = class(TStream) private FHandle : Longint; FFileSize : BigInt; FFileOffset : BigInt; FBuf : PChar; FBufSize : Longint; FBufCount : Longint; FBufPos : Longint; FDirty : Boolean; protected procedure SetSize(NewSize: Longint); override; {$IFDEF DELPHI6_UP} procedure SetSize(const NewSize: Int64); override; {$ENDIF} function GetFileSize: BigInt; procedure Init(BufSize: Longint); procedure ReadFromFile; procedure WriteToFile; public constructor Create(const FileName: string; Mode: Word; BufferSize: LongInt);{$IFDEF DELPHI6_UP} overload; {$ENDIF} {$IFDEF DELPHI6_UP} constructor Create(const FileName: string; Mode: Word; Rights: Cardinal; BufferSize: LongInt); overload; {$ENDIF} destructor Destroy; override; procedure Flush; function Read(var Buffer; Count: Longint): Longint; override; function Seek(Offset: Longint; Origin: Word): Longint; override; {$IFDEF DELPHI6_UP} function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override; {$ENDIF} function Write(const Buffer; Count: Longint): Longint; override; property FastSize : BigInt read FFileSize; end; implementation {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function Min(IntOne, IntTwo: BigInt): BigInt; begin if IntOne > IntTwo then Result := IntTwo else Result := IntOne; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TBufferedFileStream.Init(BufSize: Longint); begin FBufSize := BufSize; if FBufSize < MIN_BUFSIZE then FBufsize := MIN_BUFSIZE else if FBufSize > MAX_BUFSIZE then FBufSize := MAX_BUFSIZE else if (FBufSize mod MIN_BUFSIZE) <> 0 then FBufSize := DEFAULT_BUFSIZE; GetMem(FBuf, FBufSize); FFileSize := GetFileSize; FBufCount := 0; FFileOffset := 0; FBufPos := 0; FDirty := False; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TBufferedFileStream.Create(const FileName: string; Mode: Word; BufferSize: LongInt); begin {$IFDEF DELPHI6_UP} Create(Filename, Mode, 0, BufferSize); {$ELSE} inherited Create; FHandle := -1; FBuf := nil; if Mode = fmCreate then begin FHandle := FileCreate(FileName); if FHandle < 0 then raise EFCreateError.CreateFmt(SFCreateError, [FileName]); end else begin FHandle := FileOpen(FileName, Mode); if FHandle < 0 then raise EFOpenError.CreateFmt(SFOpenError, [FileName]); end; Init(BufferSize); {$ENDIF} end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$IFDEF DELPHI6_UP} constructor TBufferedFileStream.Create(const FileName : string; Mode: Word; Rights: Cardinal; BufferSize: LongInt); begin inherited Create; FHandle := -1; FBuf := nil; if Mode = fmCreate then begin FHandle := FileCreate(FileName, Rights); if FHandle < 0 then raise EFCreateError.CreateResFmt(@SFCreateErrorEx, [ExpandFileName(FileName), SysErrorMessage(GetLastError)]); end else begin FHandle := FileOpen(FileName, Mode); if FHandle < 0 then raise EFOpenError.CreateResFmt(@SFOpenErrorEx, [ExpandFileName(FileName), SysErrorMessage(GetLastError)]); end; Init(BufferSize); end; {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} destructor TBufferedFileStream.Destroy; begin if (FHandle >= 0) then begin if FDirty then WriteToFile; FileClose(FHandle); end; if FBuf <> nil then FreeMem(FBuf, FBufSize); inherited Destroy; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TBufferedFileStream.GetFileSize: BigInt; var OldPos : BigInt; begin OldPos := FileSeek(FHandle, {$IFDEF DELPHI6_UP}Int64(0){$ELSE} 0 {$ENDIF}, soFromCurrent); Result := FileSeek(FHandle, {$IFDEF DELPHI6_UP}Int64(0){$ELSE}0{$ENDIF}, soFromEnd); FileSeek(FHandle, OldPos, soFromBeginning); if Result < 0 then raise Exception.Create('Cannot determine correct file size'); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TBufferedFileStream.ReadFromFile; var NewPos : BigInt; begin NewPos := FileSeek(FHandle, FFileOffset, soFromBeginning); if (NewPos <> FFileOffset) then raise Exception.Create('Seek before read from file failed'); FBufCount := FileRead(FHandle, FBuf^, FBufSize); if FBufCount = -1 then FBufCount := 0; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TBufferedFileStream.WriteToFile; var NewPos : BigInt; BytesWritten : Longint; begin NewPos := FileSeek(FHandle, FFileOffset, soFromBeginning); if (NewPos <> FFileOffset) then raise Exception.Create('Seek before write to file failed'); BytesWritten := FileWrite(FHandle, FBuf^, FBufCount); if (BytesWritten <> FBufCount) then raise Exception.Create('Could not write to file'); FDirty := False; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TBufferedFileStream.Flush; begin if FDirty and (FHandle >= 0) and (FBuf <> nil) then WriteToFile; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TBufferedFileStream.Read(var Buffer; Count: Longint): Longint; var Remaining : Longint; Copied : Longint; DestPos : Longint; begin Result := 0; if FHandle < 0 then Exit; Remaining := Min(Count, FFileSize - (FFileOffset + FBufPos)); Result := Remaining; if (Remaining > 0) then begin if (FBufCount = 0) then ReadFromFile; Copied := Min(Remaining, FBufCount - FBufPos); Move(FBuf[FBufPos], TByteArray(Buffer)[0], Copied); Inc(FBufPos, Copied); Dec(Remaining, Copied); DestPos := 0; while Remaining > 0 do begin if FDirty then WriteToFile; FBufPos := 0; Inc(FFileOffset, FBufSize); ReadFromFile; Inc(DestPos, Copied); Copied := Min(Remaining, FBufCount - FBufPos); Move(FBuf[FBufPos], TByteArray(Buffer)[DestPos], Copied); Inc(FBufPos, Copied); Dec(Remaining, Copied); end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TBufferedFileStream.Write(const Buffer; Count: Longint): Longint; var Remaining : Longint; Copied : Longint; DestPos : Longint; begin Result := 0; if FHandle < 0 then Exit; Remaining := Count; Result := Remaining; if (Remaining > 0) then begin if (FBufCount = 0) and ((FFileOffset + FBufPos) <= FFileSize) then ReadFromFile; Copied := Min(Remaining, FBufSize - FBufPos); Move(PChar(Buffer), FBuf[FBufPos], Copied); FDirty := True; Inc(FBufPos, Copied); if (FBufCount < FBufPos) then begin FBufCount := FBufPos; FFileSize := FFileOffset + FBufPos; end; Dec(Remaining, Copied); DestPos := 0; while Remaining > 0 do begin WriteToFile; FBufPos := 0; Inc(FFileOffset, FBufSize); if (FFileOffset < FFileSize) then ReadFromFile else FBufCount := 0; Inc(DestPos, Copied); Copied := Min(Remaining, FBufSize - FBufPos); Move(TByteArray(Buffer)[DestPos], FBuf[0], Copied); FDirty := True; Inc(FBufPos, Copied); if (FBufCount < FBufPos) then begin FBufCount := FBufPos; FFileSize := FFileOffset + FBufPos; end; Dec(Remaining, Copied); end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TBufferedFileStream.Seek(Offset: Longint; Origin: Word): Longint; {$IFNDEF DELPHI6_UP} var NewPos : Longint; NewOffset : Longint; {$ENDIF} begin {$IFDEF DELPHI6_UP} Result := Seek(Int64(Offset), TSeekOrigin(Origin)); {$ELSE} Result := 0; if FHandle < 0 then Exit; if (Offset = 0) and (Origin = soFromCurrent) then begin Result := FFileOffset + FBufPos; Exit; end; case Origin of soFromBeginning : NewPos := Offset; soFromCurrent : NewPos := (FFileOffset + FBufPos) + Offset; soFromEnd : NewPos := FFileSize + Offset; else raise Exception.Create('Invalid seek origin'); end; if (NewPos < 0) then NewPos := 0 else if (NewPos > FFileSize) then FFileSize := FileSeek(FHandle, NewPos - FFileSize, soFromEnd); NewOffset := (NewPos div FBufSize) * FBufSize; if (NewOffset <> FFileOffset) then begin if FDirty then WriteToFile; FFileOffset := NewOffset; FBufCount := 0; end; FBufPos := NewPos - FFileOffset; Result := NewPos; {$ENDIF} end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$IFDEF DELPHI6_UP} function TBufferedFileStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; var NewPos : BigInt; NewFileOffset : BigInt; begin Result := 0; if FHandle < 0 then Exit; if (Offset = 0) and (Origin = soCurrent) then begin Result := FFileOffset + FBufPos; Exit; end; case Origin of soBeginning : NewPos := Offset; soCurrent : NewPos := (FFileOffset + FBufPos) + Offset; soEnd : NewPos := FFileSize + Offset; else raise Exception.Create('Invalid seek origin'); end; if (NewPos < 0) then NewPos := 0 else if (NewPos > FFileSize) then FFileSize := FileSeek(FHandle, NewPos - FFileSize, soFromEnd); NewFileOffset := (NewPos div FBufSize) * FBufSize; if (NewFileOffset <> FFileOffset) then begin if FDirty then WriteToFile; FFileOffset := NewFileOffset; FBufCount := 0; end; FBufPos := NewPos - FFileOffset; Result := NewPos; end; {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TBufferedFileStream.SetSize(NewSize: Integer); begin {$IFDEF DELPHI6_UP} SetSize(Int64(NewSize)); {$ELSE} if FHandle < 0 then Exit; Seek(NewSize, soFromBeginning); if NewSize < FFileSize then FFileSize := FileSeek(FHandle, NewSize, soFromBeginning); if not SetEndOfFile(FHandle) then RaiseLastWin32Error; {$ENDIF} end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$IFDEF DELPHI6_UP} procedure TBufferedFileStream.SetSize(const NewSize: Int64); begin if FHandle < 0 then Exit; Seek(NewSize, soFromBeginning); if NewSize < FFileSize then FFileSize := FileSeek(FHandle, NewSize, soFromBeginning); {$IFDEF MSWINDOWS} if not SetEndOfFile(FHandle) then RaiseLastOSError; {$ELSE} if ftruncate(FHandle, Position) = -1 then raise EStreamError(sStreamSetSize); {$ENDIF} end; {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} end.
unit Acme.Robot.GUI.VCL.Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, System.Actions, Vcl.ActnList, Vcl.Imaging.pngimage, Acme.Robot.Core.Bot, Acme.Robot.Core.CleanBot, Acme.Robot.Core.Communications, Vcl.ComCtrls, Vcl.StdCtrls; type TMainForm = class(TForm, IEnhancedCommunicator) CommandPanel: TPanel; BotActionList: TActionList; ArenaBox: TScrollBox; BotImage: TImage; BotStatusBar: TStatusBar; BotTurnOnButton: TButton; BotTurnOnAction: TAction; BotTurnOffAction: TAction; BotOrientationNorthAction: TAction; BotOrientationSouthAction: TAction; BotOrientationEastAction: TAction; BotOrientationWestAction: TAction; BotHelloAction: TAction; BotMoveSlowAction: TAction; BotMoveFastAction: TAction; MessagePanel: TPanel; BotGoHomeAction: TAction; MoodGrumpyImage: TImage; MoodHappyImage: TImage; procedure BotActionListUpdate(Action: TBasicAction; var Handled: Boolean); procedure BotTurnOnActionExecute(Sender: TObject); procedure BotTurnOffActionExecute(Sender: TObject); procedure BotOrientationNorthActionExecute(Sender: TObject); procedure BotOrientationSouthActionExecute(Sender: TObject); procedure BotOrientationEastActionExecute(Sender: TObject); procedure BotOrientationWestActionExecute(Sender: TObject); procedure BotHelloActionExecute(Sender: TObject); procedure BotMoveSlowActionExecute(Sender: TObject); procedure BotMoveFastActionExecute(Sender: TObject); procedure BotGoHomeActionExecute(Sender: TObject); private FBot: ITalkingBot; public constructor Create(AOwner: TComponent); override; procedure ShowMood(AMood: TBotMood); procedure SayMessage(const AText: string); end; var MainForm: TMainForm; implementation {$R *.dfm} { TMainForm } procedure TMainForm.BotActionListUpdate(Action: TBasicAction; var Handled: Boolean); begin BotImage.Visible := FBot.Active; BotImage.Left := FBot.Location.X; BotImage.Top := FBot.Location.Y; BotStatusBar.SimpleText := FBot.ToString; Handled := True; end; procedure TMainForm.BotGoHomeActionExecute(Sender: TObject); begin FBot.GoHome; end; procedure TMainForm.BotHelloActionExecute(Sender: TObject); begin FBot.Say('Hello everybody!'); end; procedure TMainForm.BotMoveFastActionExecute(Sender: TObject); begin FBot.Move(20); end; procedure TMainForm.BotMoveSlowActionExecute(Sender: TObject); begin FBot.Move(5); end; procedure TMainForm.BotOrientationEastActionExecute(Sender: TObject); begin FBot.Rotate(TBotOrientation.East); end; procedure TMainForm.BotOrientationNorthActionExecute(Sender: TObject); begin FBot.Rotate(TBotOrientation.North); end; procedure TMainForm.BotOrientationSouthActionExecute(Sender: TObject); begin FBot.Rotate(TBotOrientation.South); end; procedure TMainForm.BotOrientationWestActionExecute(Sender: TObject); begin FBot.Rotate(TBotOrientation.West); end; procedure TMainForm.BotTurnOffActionExecute(Sender: TObject); begin FBot.TurnOff; end; procedure TMainForm.BotTurnOnActionExecute(Sender: TObject); begin FBot.TurnOn; end; constructor TMainForm.Create(AOwner: TComponent); var LCommunicator: IEnhancedCommunicator; begin inherited Create(AOwner); if not Supports(Self, IEnhancedCommunicator, LCommunicator) then LCommunicator := nil; FBot := NewCleanBot('SveltoBot', LCommunicator); end; procedure TMainForm.SayMessage(const AText: string); begin MessagePanel.Caption := AText; MessagePanel.Visible := Length(AText) > 0; end; procedure TMainForm.ShowMood(AMood: TBotMood); begin MoodHappyImage.Visible := AMood = TBotMood.Happy; MoodGrumpyImage.Visible := AMood = TBotMood.Grumpy; end; end.
{$REGION 'Copyright (C) CMC Development Team'} { ************************************************************************** Copyright (C) 2015 CMC Development Team CMC is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. CMC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CMC. If not, see <http://www.gnu.org/licenses/>. ************************************************************************** } { ************************************************************************** Additional Copyright (C) for this modul: Chromaprint: Audio fingerprinting toolkit Copyright (C) 2010-2012 Lukas Lalinsky <lalinsky@gmail.com> Lomont FFT: Fast Fourier Transformation Original code by Chris Lomont, 2010-2012, http://www.lomont.org/Software/ ************************************************************************** } {$ENDREGION} {$REGION 'Notes'} { ************************************************************************** See CP.Chromaprint.pas for more information ************************************************************************** } unit CP.FingerprinterConfiguration; {$IFDEF FPC} {$MODE delphi} {$ENDIF} interface uses Classes, SysUtils, CP.Def, CP.Classifier; type { TFingerprinterConfiguration } TFingerprinterConfiguration = class(TObject) protected FNumClassifiers: integer; FClassifiers: TClassifierArray; FNumFilterCoefficients: integer; FFilterCoefficients: TDoubleArray; FInterpolate: boolean; FRemoveSilence: boolean; FSilenceThreshold: integer; kChromaFilterCoefficients: TDoubleArray; public property FilterCoefficients: TDoubleArray read FFilterCoefficients; property NumClassifiers: integer read FNumClassifiers; property NumFilterCoefficients: integer read FNumFilterCoefficients; property Interpolate: boolean read FInterpolate write FInterpolate; property RemoveSilence: boolean read FRemoveSilence write FRemoveSilence; property SilenceThreshold: integer read FSilenceThreshold write FSilenceThreshold; property Classifiers: TClassifierArray read FClassifiers; public constructor Create; destructor Destroy; override; procedure SetClassifiers(Classifiers: TClassifierArray); procedure SetFilterCoefficients(FilterCoefficients: TDoubleArray); end; // Used for http://oxygene.sk/lukas/2010/07/introducing-chromaprint/ // Trained on a randomly selected test data { TFingerprinterConfigurationTest1 } TFingerprinterConfigurationTest1 = class(TFingerprinterConfiguration) public constructor Create; destructor Destroy; override; end; // Trained on 60k pairs based on eMusic samples (mp3) { TFingerprinterConfigurationTest2 } TFingerprinterConfigurationTest2 = class(TFingerprinterConfiguration) public constructor Create; destructor Destroy; override; end; // Trained on 60k pairs based on eMusic samples with interpolation enabled (mp3) { TFingerprinterConfigurationTest3 } TFingerprinterConfigurationTest3 = class(TFingerprinterConfiguration) public constructor Create; destructor Destroy; override; end; // Same as v2, but trims leading silence { TFingerprinterConfigurationTest4 } TFingerprinterConfigurationTest4 = class(TFingerprinterConfigurationTest2) public constructor Create; destructor Destroy; override; end; function CreateFingerprinterConfiguration(algorithm: integer): TFingerprinterConfiguration; inline; implementation uses CP.Quantizer, CP.Filter; const kChromaFilterSize = 5; function CreateFingerprinterConfiguration(algorithm: integer): TFingerprinterConfiguration; inline; begin case (algorithm) of ord(CHROMAPRINT_ALGORITHM_TEST1): Result := TFingerprinterConfigurationTest1.Create; ord(CHROMAPRINT_ALGORITHM_TEST2): Result := TFingerprinterConfigurationTest2.Create; ord(CHROMAPRINT_ALGORITHM_TEST3): Result := TFingerprinterConfigurationTest3.Create; ord(CHROMAPRINT_ALGORITHM_TEST4): Result := TFingerprinterConfigurationTest4.Create; else Result := nil; end; end; { TFingerprinterConfigurationTest4 } constructor TFingerprinterConfigurationTest4.Create; var kClassifiersTest: TClassifierArray; begin inherited Create; RemoveSilence := True; SilenceThreshold := 50; end; destructor TFingerprinterConfigurationTest4.Destroy; begin inherited; end; { TFingerprinterConfigurationTest3 } constructor TFingerprinterConfigurationTest3.Create; var kClassifiersTest: TClassifierArray; begin inherited Create; SetLength(kClassifiersTest, 16); kClassifiersTest[0] := TClassifier.Create(TFilter.Create(0, 4, 3, 15), TQuantizer.Create(1.98215, 2.35817, 2.63523)); kClassifiersTest[1] := TClassifier.Create(TFilter.Create(4, 4, 6, 15), TQuantizer.Create(-1.03809, -0.651211, -0.282167)); kClassifiersTest[2] := TClassifier.Create(TFilter.Create(1, 0, 4, 16), TQuantizer.Create(-0.298702, 0.119262, 0.558497)); kClassifiersTest[3] := TClassifier.Create(TFilter.Create(3, 8, 2, 12), TQuantizer.Create(-0.105439, 0.0153946, 0.135898)); kClassifiersTest[4] := TClassifier.Create(TFilter.Create(3, 4, 4, 8), TQuantizer.Create(-0.142891, 0.0258736, 0.200632)); kClassifiersTest[5] := TClassifier.Create(TFilter.Create(4, 0, 3, 5), TQuantizer.Create(-0.826319, -0.590612, -0.368214)); kClassifiersTest[6] := TClassifier.Create(TFilter.Create(1, 2, 2, 9), TQuantizer.Create(-0.557409, -0.233035, 0.0534525)); kClassifiersTest[7] := TClassifier.Create(TFilter.Create(2, 7, 3, 4), TQuantizer.Create(-0.0646826, 0.00620476, 0.0784847)); kClassifiersTest[8] := TClassifier.Create(TFilter.Create(2, 6, 2, 16), TQuantizer.Create(-0.192387, -0.029699, 0.215855)); kClassifiersTest[9] := TClassifier.Create(TFilter.Create(2, 1, 3, 2), TQuantizer.Create(-0.0397818, -0.00568076, 0.0292026)); kClassifiersTest[10] := TClassifier.Create(TFilter.Create(5, 10, 1, 15), TQuantizer.Create(-0.53823, -0.369934, -0.190235)); kClassifiersTest[11] := TClassifier.Create(TFilter.Create(3, 6, 2, 10), TQuantizer.Create(-0.124877, 0.0296483, 0.139239)); kClassifiersTest[12] := TClassifier.Create(TFilter.Create(2, 1, 1, 14), TQuantizer.Create(-0.101475, 0.0225617, 0.231971)); kClassifiersTest[13] := TClassifier.Create(TFilter.Create(3, 5, 6, 4), TQuantizer.Create(-0.0799915, -0.00729616, 0.063262)); kClassifiersTest[14] := TClassifier.Create(TFilter.Create(1, 9, 2, 12), TQuantizer.Create(-0.272556, 0.019424, 0.302559)); kClassifiersTest[15] := TClassifier.Create(TFilter.Create(3, 4, 2, 14), TQuantizer.Create(-0.164292, -0.0321188, 0.0846339)); SetClassifiers(kClassifiersTest); SetFilterCoefficients(kChromaFilterCoefficients); Interpolate := True; end; destructor TFingerprinterConfigurationTest3.Destroy; begin inherited; end; { TFingerprinterConfigurationTest2 } constructor TFingerprinterConfigurationTest2.Create; var kClassifiersTest: TClassifierArray; begin inherited Create; SetLength(kClassifiersTest, 16); kClassifiersTest[0] := TClassifier.Create(TFilter.Create(0, 4, 3, 15), TQuantizer.Create(1.98215, 2.35817, 2.63523)); kClassifiersTest[1] := TClassifier.Create(TFilter.Create(4, 4, 6, 15), TQuantizer.Create(-1.03809, -0.651211, -0.282167)); kClassifiersTest[2] := TClassifier.Create(TFilter.Create(1, 0, 4, 16), TQuantizer.Create(-0.298702, 0.119262, 0.558497)); kClassifiersTest[3] := TClassifier.Create(TFilter.Create(3, 8, 2, 12), TQuantizer.Create(-0.105439, 0.0153946, 0.135898)); kClassifiersTest[4] := TClassifier.Create(TFilter.Create(3, 4, 4, 8), TQuantizer.Create(-0.142891, 0.0258736, 0.200632)); kClassifiersTest[5] := TClassifier.Create(TFilter.Create(4, 0, 3, 5), TQuantizer.Create(-0.826319, -0.590612, -0.368214)); kClassifiersTest[6] := TClassifier.Create(TFilter.Create(1, 2, 2, 9), TQuantizer.Create(-0.557409, -0.233035, 0.0534525)); kClassifiersTest[7] := TClassifier.Create(TFilter.Create(2, 7, 3, 4), TQuantizer.Create(-0.0646826, 0.00620476, 0.0784847)); kClassifiersTest[8] := TClassifier.Create(TFilter.Create(2, 6, 2, 16), TQuantizer.Create(-0.192387, -0.029699, 0.215855)); kClassifiersTest[9] := TClassifier.Create(TFilter.Create(2, 1, 3, 2), TQuantizer.Create(-0.0397818, -0.00568076, 0.0292026)); kClassifiersTest[10] := TClassifier.Create(TFilter.Create(5, 10, 1, 15), TQuantizer.Create(-0.53823, -0.369934, -0.190235)); kClassifiersTest[11] := TClassifier.Create(TFilter.Create(3, 6, 2, 10), TQuantizer.Create(-0.124877, 0.0296483, 0.139239)); kClassifiersTest[12] := TClassifier.Create(TFilter.Create(2, 1, 1, 14), TQuantizer.Create(-0.101475, 0.0225617, 0.231971)); kClassifiersTest[13] := TClassifier.Create(TFilter.Create(3, 5, 6, 4), TQuantizer.Create(-0.0799915, -0.00729616, 0.063262)); kClassifiersTest[14] := TClassifier.Create(TFilter.Create(1, 9, 2, 12), TQuantizer.Create(-0.272556, 0.019424, 0.302559)); kClassifiersTest[15] := TClassifier.Create(TFilter.Create(3, 4, 2, 14), TQuantizer.Create(-0.164292, -0.0321188, 0.0846339)); SetClassifiers(kClassifiersTest); SetFilterCoefficients(kChromaFilterCoefficients); Interpolate := False; end; destructor TFingerprinterConfigurationTest2.Destroy; begin inherited; end; { TFingerprinterConfigurationTest1 } constructor TFingerprinterConfigurationTest1.Create; var kClassifiersTest: TClassifierArray; begin inherited Create; SetLength(kClassifiersTest, 16); kClassifiersTest[0] := TClassifier.Create(TFilter.Create(0, 0, 3, 15), TQuantizer.Create(2.10543, 2.45354, 2.69414)); kClassifiersTest[1] := TClassifier.Create(TFilter.Create(1, 0, 4, 14), TQuantizer.Create(-0.345922, 0.0463746, 0.446251)); kClassifiersTest[2] := TClassifier.Create(TFilter.Create(1, 4, 4, 11), TQuantizer.Create(-0.392132, 0.0291077, 0.443391)); kClassifiersTest[3] := TClassifier.Create(TFilter.Create(3, 0, 4, 14), TQuantizer.Create(-0.192851, 0.00583535, 0.204053)); kClassifiersTest[4] := TClassifier.Create(TFilter.Create(2, 8, 2, 4), TQuantizer.Create(-0.0771619, -0.00991999, 0.0575406)); kClassifiersTest[5] := TClassifier.Create(TFilter.Create(5, 6, 2, 15), TQuantizer.Create(-0.710437, -0.518954, -0.330402)); kClassifiersTest[6] := TClassifier.Create(TFilter.Create(1, 9, 2, 16), TQuantizer.Create(-0.353724, -0.0189719, 0.289768)); kClassifiersTest[7] := TClassifier.Create(TFilter.Create(3, 4, 2, 10), TQuantizer.Create(-0.128418, -0.0285697, 0.0591791)); kClassifiersTest[8] := TClassifier.Create(TFilter.Create(3, 9, 2, 16), TQuantizer.Create(-0.139052, -0.0228468, 0.0879723)); kClassifiersTest[9] := TClassifier.Create(TFilter.Create(2, 1, 3, 6), TQuantizer.Create(-0.133562, 0.00669205, 0.155012)); kClassifiersTest[10] := TClassifier.Create(TFilter.Create(3, 3, 6, 2), TQuantizer.Create(-0.0267, 0.00804829, 0.0459773)); kClassifiersTest[11] := TClassifier.Create(TFilter.Create(2, 8, 1, 10), TQuantizer.Create(-0.0972417, 0.0152227, 0.129003)); kClassifiersTest[12] := TClassifier.Create(TFilter.Create(3, 4, 4, 14), TQuantizer.Create(-0.141434, 0.00374515, 0.149935)); kClassifiersTest[13] := TClassifier.Create(TFilter.Create(5, 4, 2, 15), TQuantizer.Create(-0.64035, -0.466999, -0.285493)); kClassifiersTest[14] := TClassifier.Create(TFilter.Create(5, 9, 2, 3), TQuantizer.Create(-0.322792, -0.254258, -0.174278)); kClassifiersTest[15] := TClassifier.Create(TFilter.Create(2, 1, 8, 4), TQuantizer.Create(-0.0741375, -0.00590933, 0.0600357)); SetClassifiers(kClassifiersTest); SetFilterCoefficients(kChromaFilterCoefficients); Interpolate := False; end; destructor TFingerprinterConfigurationTest1.Destroy; begin inherited; end; { TFingerprinterConfiguration } constructor TFingerprinterConfiguration.Create; begin FNumClassifiers := 0; FClassifiers := nil; FRemoveSilence := False; FSilenceThreshold := 0; SetLength(kChromaFilterCoefficients, kChromaFilterSize); kChromaFilterCoefficients[0] := 0.25; kChromaFilterCoefficients[1] := 0.75; kChromaFilterCoefficients[2] := 1.0; kChromaFilterCoefficients[3] := 0.75; kChromaFilterCoefficients[4] := 0.25; end; destructor TFingerprinterConfiguration.Destroy; var i: integer; begin for i := 0 to Length(FClassifiers) - 1 do begin FClassifiers[i].Free; end; inherited; end; procedure TFingerprinterConfiguration.SetClassifiers(Classifiers: TClassifierArray); begin FClassifiers := Classifiers; FNumClassifiers := Length(Classifiers); end; procedure TFingerprinterConfiguration.SetFilterCoefficients(FilterCoefficients: TDoubleArray); begin FFilterCoefficients := FilterCoefficients; FNumFilterCoefficients := Length(FilterCoefficients); end; end.
unit cCadDizimo; interface uses System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Dialogs, FireDAC.Comp.Client, System.SysUtils; // LISTA DE UNITS type TDizimo = class private // VARIAVEIS PRIVADA SOMENTE DENTRO DA CLASSE ConexaoDB: TFDConnection; F_cod_dizimo: Integer; F_cod_talao: Integer; F_cod_cheque: Integer; F_nome: string; F_valor: Double; F_data: TDateTime; F_cargo: string; F_cod_congregacao: Integer; F_cod_pessoa :Integer; public constructor Create(aConexao: TFDConnection); // CONSTRUTOR DA CLASSE destructor Destroy; override; // DESTROI A CLASSE USAR OVERRIDE POR CAUSA function Inserir: Boolean; function Atualizar: Boolean; function Apagar: Boolean; function Selecionar(id: Integer): Boolean; published // VARIAVEIS PUBLICAS UTILAIZADAS PARA PROPRIEDADES DA CLASSE // PARA FORNECER INFORMAÇÕESD EM RUMTIME property cod_congregacao: Integer read F_cod_congregacao write F_cod_congregacao; property cod_dizimo: Integer read F_cod_dizimo write F_cod_dizimo; property cod_talao: Integer read F_cod_talao write F_cod_talao; property cod_cheque: Integer read F_cod_cheque write F_cod_cheque; property nome: string read F_nome write F_nome; property valor: Double read F_valor write F_valor; property cargo: string read F_cargo write F_cargo; property data: TDateTime read F_data write F_data; property cod_pessoa: Integer read F_cod_pessoa write F_cod_pessoa; end; implementation {$REGION 'Constructor and Destructor'} constructor TDizimo.Create; begin ConexaoDB := aConexao; end; destructor TDizimo.Destroy; begin inherited; end; {$ENDREGION} {$REGION 'CRUD'} function TDizimo.Apagar: Boolean; var Qry: TFDQuery; begin if MessageDlg('Apagar o Registro: ' + #13 + #13 + 'Código: ' + IntToStr(F_cod_dizimo) + #13 + 'Descrição: ' + F_nome, mtConfirmation, [mbYes, mbNo], 0) = mrNO then begin Result := false; Abort; end; Try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add ('DELETE FROM igreja.tb_dizimista WHERE cod_dizimo=:cod_dizimo '); Qry.ParamByName('cod_dizimo').AsInteger := F_cod_dizimo; try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; except ConexaoDB.Rollback; Result:=false; end; Finally if Assigned(Qry) then FreeAndNil(Qry) End; end; function TDizimo.Atualizar: Boolean; var Qry: TFDQuery; begin try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('UPDATE igreja.tb_dizimista '+ ' SET cod_talao=:cod_talao, cod_cheque=:cod_cheque, '+ ' nome=:nome, valor=:valor, `data`=:data, cargo=:cargo, cod_congregacao=:cod_congregacao, cod_pessoa=:cod_pessoa '+ ' WHERE cod_dizimo=:cod_dizimo '); Qry.ParamByName('cod_congregacao').AsInteger := F_cod_congregacao; Qry.ParamByName('cod_dizimo').AsInteger := F_cod_dizimo; Qry.ParamByName('cod_talao').AsInteger := F_cod_talao; Qry.ParamByName('cod_cheque').AsInteger := F_cod_cheque; Qry.ParamByName('nome').AsString := F_nome; Qry.ParamByName('valor').AsFloat := F_valor; Qry.ParamByName('data').AsDate := F_data; Qry.ParamByName('cargo').AsString := F_cargo; Qry.ParamByName('cod_pessoa').AsInteger := F_cod_pessoa; try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; except ConexaoDB.Rollback; Result:=false; end; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; function TDizimo.Inserir: Boolean; var Qry: TFDQuery; begin try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('INSERT INTO igreja.tb_dizimista '+ '(cod_talao, cod_cheque, nome, valor, `data`, cargo, cod_congregacao,cod_pessoa) '+ ' VALUES(:cod_talao,:cod_cheque,:nome,:valor,:data,:cargo,:cod_congregacao,:cod_pessoa)'); Qry.ParamByName('cod_congregacao').AsInteger := Self.F_cod_congregacao; Qry.ParamByName('cod_talao').AsInteger := Self.F_cod_talao; Qry.ParamByName('cod_cheque').AsInteger := Self.F_cod_cheque; Qry.ParamByName('nome').Asstring := Self.F_nome; Qry.ParamByName('valor').AsFloat := Self.F_valor; Qry.ParamByName('data').AsDate := Self.F_data; Qry.ParamByName('cargo').Asstring := Self.F_cargo; Qry.ParamByName('cod_pessoa').AsInteger := Self.F_cod_pessoa; try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; except ConexaoDB.Rollback; Result:=false; end; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; function TDizimo.Selecionar(id: Integer): Boolean; var Qry: TFDQuery; begin try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add ('SELECT cod_dizimo, cod_talao, cod_cheque, nome, valor, `data`, cargo, cod_congregacao,cod_pessoa '+ ' FROM igreja.tb_dizimista WHERE cod_dizimo=:cod_dizimo '); Qry.ParamByName('cod_dizimo').AsInteger := id; try Qry.Open; Self.F_cod_congregacao := Qry.FieldByName('cod_congregacao') .AsInteger; Self.F_cod_dizimo := Qry.FieldByName('cod_dizimo').AsInteger; Self.F_cod_talao := Qry.FieldByName('cod_talao').AsInteger; Self.F_cod_cheque := Qry.FieldByName('cod_cheque').AsInteger; Self.F_nome := Qry.FieldByName('nome').AsString; Self.F_valor := Qry.FieldByName('valor').AsFloat; Self.F_data := Qry.FieldByName('data').AsDateTime; Self.F_cargo := Qry.FieldByName('cargo').AsString; Qry.Open; Self.F_cod_pessoa := Qry.FieldByName('cod_pessoa').AsInteger ; Except Result := false; end; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; {$ENDREGION} end.
{$include lem_directives.inc} unit LemMetaObject; interface uses Classes, UTools; const // Object Animation Types oat_None = 0; // the object is not animated oat_Triggered = 1; // the object is triggered by a lemming oat_Continuous = 2; // the object is always moving oat_Once = 3; // the object is animated once at the beginning (entrance only) // Object Trigger Effects ote_None = 0; // no effect (harmless) ote_Exit = 1; // lemming reaches the exit ote_BlockerLeft = 2; // not used in DOS metadata, but reserved for 2D-objectmap ote_BlockerRight = 3; // not used in DOS metadata, but reserved for 2D-objectmap ote_TriggeredTrap = 4; // trap that animates once and kills a lemming ote_Drown = 5; // used for watertype objects ote_Vaporize = 6; // desintegration ote_OneWayWallLeft = 7; // bash en mine restriction (arrows) ote_OneWayWallRight = 8; // bash en mine restriction (arrows) ote_Steel = 9; // not used by DOS metadata, but reserved for 2D-objectmap // Object Sound Effects ose_None = 0; // no sound effect ose_SkillSelect = 1; // the sound you get when you click on one of the skill icons at the bottom of the screen ose_Entrance = 2; // entrance opening (sounds like "boing") ose_LevelIntro = 3; // level intro (the "let's go" sound) ose_SkillAssign = 4; // the sound you get when you assign a skill to lemming ose_OhNo = 5; // the "oh no" sound when a lemming is about to explode ose_ElectroTrap = 6; // sound effect of the electrode trap and zap trap, ose_SquishingTrap = 7; // sound effect of the rock squishing trap, pillar squishing trap, and spikes trap ose_Splattering = 8; // the "aargh" sound when the lemming fall down too far and splatters ose_RopeTrap = 9; // sound effect of the rope trap and slicer trap ose_HitsSteel = 10; // sound effect when a basher/miner/digger hits steel ose_Unknown = 11; // ? (not sure where used in game) ose_Explosion = 12; // sound effect of a lemming explosion ose_SpinningTrap = 13; // sound effect of the spinning-trap-of-death, coal pits, and fire shooters (when a lemming touches the object and dies) ose_TenTonTrap = 14; // sound effect of the 10-ton trap ose_BearTrap = 15; // sound effect of the bear trap ose_Exit = 16; // sound effect of a lemming exiting ose_Drowning = 17; // sound effect of a lemming dropping into water and drowning ose_BuilderWarning = 18; // sound effect for the last 3 bricks a builder is laying down type {------------------------------------------------------------------------------- This class describes interactive objects -------------------------------------------------------------------------------} TMetaObject = class(TCollectionItem) private protected fAnimationType : Integer; // oat_xxxx fStartAnimationFrameIndex : Integer; // frame with which the animation starts? fAnimationFrameCount : Integer; // number of animations fWidth : Integer; // the width of the bitmap fHeight : Integer; // the height of the bitmap fAnimationFrameDataSize : Integer; // DOS only: the datasize in bytes of one frame fMaskOffsetFromImage : Integer; // DOS only: the datalocation of the mask-bitmap relative to the animation fTriggerLeft : Integer; // x-offset of triggerarea (if triggered) fTriggerTop : Integer; // y-offset of triggerarea (if triggered) fTriggerWidth : Integer; // width of triggerarea (if triggered) fTriggerHeight : Integer; // height of triggerarea (if triggered) fTriggerEffect : Integer; // ote_xxxx see dos doc fAnimationFramesBaseLoc : Integer; // DOS only: data location of first frame in file (vgagr??.dat) fPreviewFrameIndex : Integer; // index of preview (previewscreen) fSoundEffect : Integer; // ose_xxxx what sound to play public procedure Assign(Source: TPersistent); override; published property AnimationType : Integer read fAnimationType write fAnimationType; property StartAnimationFrameIndex : Integer read fStartAnimationFrameIndex write fStartAnimationFrameIndex; property AnimationFrameCount : Integer read fAnimationFrameCount write fAnimationFrameCount; property Width : Integer read fWidth write fWidth; property Height : Integer read fHeight write fHeight; property AnimationFrameDataSize : Integer read fAnimationFrameDataSize write fAnimationFrameDataSize; property MaskOffsetFromImage : Integer read fMaskOffsetFromImage write fMaskOffsetFromImage; property TriggerLeft : Integer read fTriggerLeft write fTriggerLeft; property TriggerTop : Integer read fTriggerTop write fTriggerTop; property TriggerWidth : Integer read fTriggerWidth write fTriggerWidth; property TriggerHeight : Integer read fTriggerHeight write fTriggerHeight; property TriggerEffect : Integer read fTriggerEffect write fTriggerEffect; property AnimationFramesBaseLoc : Integer read fAnimationFramesBaseLoc write fAnimationFramesBaseLoc; property PreviewFrameIndex : Integer read fPreviewFrameIndex write fPreviewFrameIndex; property SoundEffect : Integer read fSoundEffect write fSoundEffect; end; TMetaObjects = class(TCollectionEx) private function GetItem(Index: Integer): TMetaObject; procedure SetItem(Index: Integer; const Value: TMetaObject); protected public constructor Create; function Add: TMetaObject; function Insert(Index: Integer): TMetaObject; property Items[Index: Integer]: TMetaObject read GetItem write SetItem; default; end; implementation procedure TMetaObject.Assign(Source: TPersistent); var M: TMetaObject absolute Source; begin if Source is TMetaObject then begin fAnimationType := M.fAnimationType; fStartAnimationFrameIndex := M.fStartAnimationFrameIndex; fAnimationFrameCount := M.fAnimationFrameCount; fWidth := M.fWidth; fHeight := M.fHeight; fAnimationFrameDataSize := M.fAnimationFrameDataSize; fMaskOffsetFromImage := M.fMaskOffsetFromImage; fTriggerLeft := M.fTriggerLeft; fTriggerTop := M.fTriggerTop; fTriggerWidth := M.fTriggerWidth; fTriggerHeight := M.fTriggerHeight; fTriggerEffect := M.fTriggerEffect; fAnimationFramesBaseLoc := M.fAnimationFramesBaseLoc; fPreviewFrameIndex := M.fPreviewFrameIndex; fSoundEffect := M.fSoundEffect; end else inherited Assign(Source); end; { TMetaObjects } function TMetaObjects.Add: TMetaObject; begin Result := TMetaObject(inherited Add); end; constructor TMetaObjects.Create; begin inherited Create(TMetaObject); end; function TMetaObjects.GetItem(Index: Integer): TMetaObject; begin Result := TMetaObject(inherited GetItem(Index)) end; function TMetaObjects.Insert(Index: Integer): TMetaObject; begin Result := TMetaObject(inherited Insert(Index)) end; procedure TMetaObjects.SetItem(Index: Integer; const Value: TMetaObject); begin inherited SetItem(Index, Value); end; end.
unit NtUtils.Objects.Namespace; interface uses Winapi.WinNt, Ntapi.ntobapi, NtUtils.Exceptions; type TDirectoryEnumEntry = record Name: String; TypeName: String; end; { Directories } // Create directory object function NtxCreateDirectory(out hDirectory: THandle; Name: String; DesiredAccess: TAccessMask = DIRECTORY_ALL_ACCESS; Root: THandle = 0; Attributes: Cardinal = 0): TNtxStatus; // Open directory object function NtxOpenDirectory(out hDirectory: THandle; Name: String; DesiredAccess: TAccessMask; Root: THandle = 0; Attributes: Cardinal = 0): TNtxStatus; // Enumerate named objects in a directory function NtxEnumerateDirectory(hDirectory: THandle; out Entries: TArray<TDirectoryEnumEntry>): TNtxStatus; { Symbolic links } // Create symbolic link function NtxCreateSymlink(out hSymlink: THandle; Name, Target: String; DesiredAccess: TAccessMask = SYMBOLIC_LINK_ALL_ACCESS; Root: THandle = 0; Attributes: Cardinal = 0): TNtxStatus; // Open symbolic link function NtxOpenSymlink(out hSymlink: THandle; Name: String; DesiredAccess: TAccessMask; Root: THandle = 0; Attributes: Cardinal = 0): TNtxStatus; // Get symbolic link target function NtxQueryTargetSymlink(hSymlink: THandle; out Target: String) : TNtxStatus; implementation uses Ntapi.ntdef, Ntapi.ntstatus; function NtxCreateDirectory(out hDirectory: THandle; Name: String; DesiredAccess: TAccessMask; Root: THandle; Attributes: Cardinal): TNtxStatus; var ObjAttr: TObjectAttributes; NameStr: UNICODE_STRING; begin NameStr.FromString(Name); InitializeObjectAttributes(ObjAttr, @NameStr, Attributes, Root); Result.Location := 'NtCreateDirectoryObject'; Result.Status := NtCreateDirectoryObject(hDirectory, DesiredAccess, ObjAttr); end; function NtxOpenDirectory(out hDirectory: THandle; Name: String; DesiredAccess: TAccessMask; Root: THandle; Attributes: Cardinal): TNtxStatus; var ObjAttr: TObjectAttributes; NameStr: UNICODE_STRING; begin NameStr.FromString(Name); InitializeObjectAttributes(ObjAttr, @NameStr, Attributes, Root); Result.Location := 'NtOpenDirectoryObject'; Result.LastCall.CallType := lcOpenCall; Result.LastCall.AccessMask := DesiredAccess; Result.LastCall.AccessMaskType := @DirectoryAccessType; Result.Status := NtOpenDirectoryObject(hDirectory, DesiredAccess, ObjAttr) end; function NtxEnumerateDirectory(hDirectory: THandle; out Entries: TArray<TDirectoryEnumEntry>): TNtxStatus; var Buffer: PObjectDirectoryInformation; BufferSize, Required, Context: Cardinal; begin Result.Location := 'NtQueryDirectoryObject'; Result.LastCall.Expects(DIRECTORY_QUERY, @DirectoryAccessType); // TODO: check, if there is a more efficient way to get directory content Context := 0; SetLength(Entries, 0); repeat // Retrive entries one by one BufferSize := 256; repeat Buffer := AllocMem(BufferSize); Result.Status := NtQueryDirectoryObject(hDirectory, Buffer, BufferSize, True, False, Context, @Required); if not Result.IsSuccess then FreeMem(Buffer); until not NtxExpandBuffer(Result, BufferSize, Required); if Result.IsSuccess then begin SetLength(Entries, Length(Entries) + 1); Entries[High(Entries)].Name := Buffer.Name.ToString; Entries[High(Entries)].TypeName := Buffer.TypeName.ToString; FreeMem(Buffer); Result.Status := STATUS_MORE_ENTRIES; end; until Result.Status <> STATUS_MORE_ENTRIES; if Result.Status = STATUS_NO_MORE_ENTRIES then Result.Status := STATUS_SUCCESS; end; function NtxCreateSymlink(out hSymlink: THandle; Name, Target: String; DesiredAccess: TAccessMask; Root: THandle; Attributes: Cardinal): TNtxStatus; var ObjAttr: TObjectAttributes; NameStr, TargetStr: UNICODE_STRING; begin NameStr.FromString(Name); TargetStr.FromString(Target); InitializeObjectAttributes(ObjAttr, @NameStr, Attributes, Root); Result.Location := 'NtCreateSymbolicLinkObject'; Result.Status := NtCreateSymbolicLinkObject(hSymlink, DesiredAccess, ObjAttr, TargetStr); end; function NtxOpenSymlink(out hSymlink: THandle; Name: String; DesiredAccess: TAccessMask; Root: THandle = 0; Attributes: Cardinal = 0): TNtxStatus; var ObjAttr: TObjectAttributes; NameStr: UNICODE_STRING; begin NameStr.FromString(Name); InitializeObjectAttributes(ObjAttr, @NameStr, Attributes, Root); Result.Location := 'NtOpenSymbolicLinkObject'; Result.LastCall.CallType := lcOpenCall; Result.LastCall.AccessMask := DesiredAccess; Result.LastCall.AccessMaskType := @SymlinkAccessType; Result.Status := NtOpenSymbolicLinkObject(hSymlink, DesiredAccess, ObjAttr) end; function NtxQueryTargetSymlink(hSymlink: THandle; out Target: String) : TNtxStatus; var Buffer: UNICODE_STRING; Required: Cardinal; begin Result.Location := 'NtQuerySymbolicLinkObject'; Result.LastCall.Expects(SYMBOLIC_LINK_QUERY, @SymlinkAccessType); Buffer.MaximumLength := 0; repeat Required := 0; Buffer.Length := 0; Buffer.Buffer := AllocMem(Buffer.MaximumLength); Result.Status := NtQuerySymbolicLinkObject(hSymlink, Buffer, @Required); if not Result.IsSuccess then FreeMem(Buffer.Buffer); until not NtxExpandStringBuffer(Result, Buffer, Required); if Result.IsSuccess then begin Target := Buffer.ToString; FreeMem(Buffer.Buffer); end; end; end.
// *************************************************************************** // // Delphi MVC Framework // // Copyright (c) 2010-2020 Daniele Teti and the DMVCFramework Team // // https://github.com/danieleteti/delphimvcframework // // Collaborators on this file: // João Antônio Duarte (https://github.com/joaoduarte19) // // *************************************************************************** // // 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 MVCFramework.Middleware.ETag; {$I dmvcframework.inc} interface uses MVCFramework, System.Classes; type /// <summary> /// The <b>ETag</b> HTTP response header is an identifier for a specific version of a resource. It lets caches be /// more efficient and save bandwidth, as a web server does not need to resend a full response if the content has /// not changed. See more about the specification: <see href="https://tools.ietf.org/html/rfc7232#section-2.3">RFC /// 7232</see> /// </summary> TMVCETagMiddleware = class(TInterfacedObject, IMVCMiddleware) private function GetHashMD5FromStream(AStream: TStream): string; public procedure OnBeforeRouting(AContext: TWebContext; var AHandled: Boolean); procedure OnBeforeControllerAction(AContext: TWebContext; const AControllerQualifiedClassName: string; const AActionName: string; var AHandled: Boolean); procedure OnAfterControllerAction(AContext: TWebContext; const AActionName: string; const AHandled: Boolean); procedure OnAfterRouting(AContext: TWebContext; const AHandled: Boolean); end; implementation uses {$IF defined(SEATTLEORBETTER)} System.Hash, {$ELSE} IdHashMessageDigest, {$ENDIF} System.SysUtils, MVCFramework.Commons; { TMVCETagMiddleware } function TMVCETagMiddleware.GetHashMD5FromStream(AStream: TStream): string; {$IF not defined(SEATTLEORBETTER)} var lMD5Hash: TIdHashMessageDigest5; {$ENDIF} begin {$IF defined(SEATTLEORBETTER)} Result := THashMD5.GetHashString(AStream); {$ELSE} lMD5Hash := TIdHashMessageDigest5.Create; try Result := lMD5Hash.HashStreamAsHex(AStream); finally lMD5Hash.Free; end; {$ENDIF} end; procedure TMVCETagMiddleware.OnAfterControllerAction(AContext: TWebContext; const AActionName: string; const AHandled: Boolean); begin // do nothing end; procedure TMVCETagMiddleware.OnAfterRouting(AContext: TWebContext; const AHandled: Boolean); var lContentStream: TStream; lRequestETag: string; lETag: string; begin lContentStream := AContext.Response.RawWebResponse.ContentStream; if not Assigned(lContentStream) then Exit; lRequestETag := AContext.Request.Headers['If-None-Match']; lETag := GetHashMD5FromStream(lContentStream); AContext.Response.SetCustomHeader('ETag', lETag); if (lETag <> '') and (lRequestETag = lETag) then begin AContext.Response.Content := ''; if lContentStream is TFileStream then begin AContext.Response.RawWebResponse.ContentStream := nil; end else begin lContentStream.Size := 0; end; AContext.Response.StatusCode := HTTP_STATUS.NotModified; AContext.Response.ReasonString := 'Not Modified' end; end; procedure TMVCETagMiddleware.OnBeforeControllerAction(AContext: TWebContext; const AControllerQualifiedClassName, AActionName: string; var AHandled: Boolean); begin // do nothing end; procedure TMVCETagMiddleware.OnBeforeRouting(AContext: TWebContext; var AHandled: Boolean); begin // do nothing end; end.
unit udmDireitosAcesso; interface uses Windows, System.UITypes,Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, udmPadrao, DBAccess, IBC, DB, MemDS; type TdmDireitosAcesso = class(TdmPadrao) qryManutencaoMODULO: TStringField; qryManutencaoGRUPO: TStringField; qryManutencaoMENU: TIntegerField; qryManutencaoDIREITOS: TStringField; qryManutencaoCONTROLE: TStringField; qryManutencaoDT_ALTERACAO: TDateTimeField; qryManutencaoOPERADOR: TStringField; qryLocalizacaoMODULO: TStringField; qryLocalizacaoGRUPO: TStringField; qryLocalizacaoMENU: TIntegerField; qryLocalizacaoDIREITOS: TStringField; qryLocalizacaoCONTROLE: TStringField; qryLocalizacaoDT_ALTERACAO: TDateTimeField; qryLocalizacaoOPERADOR: TStringField; protected procedure MontaSQLBusca(DataSet :TDataSet = Nil); override; procedure MontaSQLRefresh; override; private FMenu: Integer; FModulo: String; FGrupo: String; public property Modulo: String read FModulo write FModulo; property Grupo: String read FGrupo write FGrupo; property Menu: Integer read FMenu write FMenu; end; const SQL_DEFAULT = ' SELECT ' + ' MODULO, ' + ' GRUPO, ' + ' MENU, ' + ' DIREITOS, ' + ' CONTROLE, ' + ' DT_ALTERACAO, ' + ' OPERADOR ' + ' FROM STWOPETDIR '; var dmDireitosAcesso: TdmDireitosAcesso; implementation {$R *.dfm} { TdmDireitosAcesso } procedure TdmDireitosAcesso.MontaSQLBusca(DataSet: TDataSet); begin inherited; with (DataSet as TIBCQuery) do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE MODULO = :MODULO'); SQL.Add(' AND GRUPO = :GRUPO'); SQL.Add(' AND MENU = :MENU'); SQL.Add('ORDER BY MODULO, GRUPO, MENU'); Params[ 0].AsString := FModulo; Params[ 1].AsString := FGrupo; Params[ 2].AsInteger := FMenu; end; end; procedure TdmDireitosAcesso.MontaSQLRefresh; begin inherited; with qryManutencao do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('ORDER BY MODULO, GRUPO, MENU') end; end; end.
object Form1: TForm1 Left = 802 Top = 234 Width = 318 Height = 249 AutoSize = True BorderIcons = [biSystemMenu, biMinimize] BorderStyle = bsSizeToolWin Caption = 'User Activity Counter' Color = clRed Constraints.MaxHeight = 250 Constraints.MaxWidth = 320 Constraints.MinHeight = 249 Constraints.MinWidth = 318 Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] Icon.Data = { 0000010001004040040000000000680A00001600000028000000400000008000 0000010004000000000000080000000000000000000000000000000000000000 000000008000008000000080800080000000800080008080000080808000C0C0 C0000000FF0000FF000000FFFF00FF000000FF00FF00FFFF0000FFFFFF000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000333333333333310000000000000000000000000000 0000000000000000333333333333333333333330000000000000000000000000 0000000000000023333333333333333333333333300000000000000000000000 0000000000000333333333333333333333333333333100000000000000000000 0000000000033333333333333333333333333333333330000000000000000000 0000000002333333333333033333333333333333333333000000000000000000 0000000033333333333333033333333333333333333333300000000000000000 0000000333333333333322033333333333333333333333111000000000000000 0000003333333333332222213110011333333333333331199100000000000000 0000033333333333222220000000000000033333333331991911000000000000 0000233333333322222000000000000000000133333301119191000000000000 0002333333333222200000000000000000000001333011111999100000000000 0023333233322220000000000077700000000000030111111199900000000000 0333333323222200000000777777777710000000001111111119910000000000 0233333332222000000077778777777777000000000111111111111000000000 2333333322220000000778888888888777770000000011111111111000000000 3333333222200000077888888888888888777000000001111111119100000000 2333333222000000778888888888888888877700000000111111111100000002 2223332220000007888888888888888887887770000000011111111910000022 2222232220000007888888778888888888888877000000011111111110000022 2222222200000078888888888888888888888877700000001111111191000022 2222222000000788888778888888888888888887700000001111111111000222 2222222000000788888888888888888888888888730000000111111111000222 2222222000007888888888888888888888888888770000000111111111000222 2222220000000887888888888888888888888888770000000011111111100222 2222220000007887888888888876788888888888870000000011111111100222 22222200000078878FFF8888F706078888888888877000000011111111112222 2222220000008888FFFFF88F807F768888888888877000000011111111102222 2222220000008888F88FFFFF807F768888888888877000000011111111102222 2222200000008887FFFFF8FFF704068888888888877000000011111111102222 2222200000007F87FFFFFFFFFF87707888888888870000000001111111102222 2222200000007F87FF8FFFFFFFFF870788888888870000000078888877802222 22222000000078F88FFFFFFFFFFFF87078888888870000000078888888872222 22222000000007F87FFFFFFFFFFFFF8648888888870000000078888888802222 220000000000078F88FF8FFFFFFFFFF867888888700000000078888888800222 222222000000007FF78F8FFFFFFFFFFF86788888700000000088888888770266 2222220000000078F878FFF8FF888F88F8888887700000000088888888700262 2222220000000007FF878FF8FF8788888F888877000000000788888888700222 22222220000000007FF8788FFFF8FF8888888777700000000788788888700222 2222222000000000078FF888888F888888887777770000000887446788000222 22222220000000000078FFF88888888888877877777000007886444444000022 2222222200000000000078FFF888888888778F877700000088744444C4000022 2622222220000000000007788888888777007FF7770000078874444440000002 2222222220000000000000077787778700000788700000788744444440000002 22222222220000000000000007F8777000000077000000888644444440000000 2222222222200000000000007787777000000000000007887444444440000000 2222222222220000000000078887777700000000000078874444444000000000 022222222222200000000007FF88887700000000000788744444444000000000 022222222222220000000007FF88777700000000007887444444440000000000 0022222222222220000000078888777770000000788874444444400000000000 0002222222222222000000077777777730000007888744444446400000000000 0000222222222222060000000000000000000788887644444464000000000000 0000022222222220666660000000000000778888776664444644000000000000 0000002222222226666666688777777778888877666666446400000000000000 0000000222222206666666688888888888887766666666444000000000000000 0000000022222266666666688888888877766666666666600000000000000000 0000000002222666666666466777776666666666666666400000000000000000 0000000000020666666666466666666666666666666640000000000000000000 0000000000000666666666666666666666666666666400000000000000000000 0000000000000066666666666666666666666666640000000000000000000000 0000000000000000666664666666666666666660000000000000000000000000 0000000000000000000664666666666666664000000000000000000000000000 000000000000000000000000464444440000000000000000000000000000FFFF FE00007FFFFFFFFFF000000FFFFFFFFFC0000003FFFFFFFF00000000FFFFFFFC 000000003FFFFFF8000000001FFFFFF00000000007FFFFC00000000003FFFF80 0000000001FFFF000000000000FFFE00001FF000007FFE0000FFFF00003FFC00 03FFFFC0003FF8000FC007F0001FF8001F0001F8000FF0003C00007C000FE000 F800003E0007E000F000001F0007C001E000000F8003C003C0000007C003C007 C0000007E001800780000003E001800F80000003F001800F00000001F000001F 00000001F800001F00000001F800001E00000001F800003E00000000F800003E 00000000FC00003E00000000FC00003E00000000FC00003E00000001FC00003F 00000001FC00003F00000001FC00003F00000001FC00003F80000003FC00003F 80000003F800001FC0000003F800001FC0000007F800001FE0000003F800800F F0000001F000800FF8000001F0018007FC000001E001C007FF000001E001C003 FF800303C003C001FFF81F878003E001FFE007FF0007E000FFE007FE0007F000 7FE007FC000FF8001FE007F8000FF8000FE007F0001FFC0003E007C0003FFE00 00FFFF00007FFF00001FF800007FFF800000000000FFFFC00000000001FFFFE0 0000000007FFFFF0000000000FFFFFF8000000001FFFFFFE000000007FFFFFFF 00000000FFFFFFFFC0000003FFFFFFFFF800001FFFFFFFFFFF0000FFFFFF} OldCreateOrder = False Position = poScreenCenter Scaled = False OnClick = FormClick OnClose = FormClose OnCreate = FormCreate OnDblClick = HideToTrayExecute OnDestroy = FormDestroy OnKeyDown = FormKeyDown PixelsPerInch = 96 TextHeight = 13 object LBusy: TLabel Left = 65 Top = 120 Width = 51 Height = 24 Caption = 'LBusy' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -19 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False end object LIdle: TLabel Left = 65 Top = 152 Width = 40 Height = 24 Caption = 'LIdle' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -19 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False end object Label1: TLabel Left = 8 Top = 128 Width = 29 Height = 13 Caption = 'Busy: ' end object Label2: TLabel Left = 8 Top = 160 Width = 23 Height = 13 Caption = 'Idle: ' end object LPresent: TLabel Left = 65 Top = 56 Width = 74 Height = 24 Caption = 'LPresent' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -19 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False end object LAbsent: TLabel Left = 65 Top = 88 Width = 69 Height = 24 Caption = 'LAbsent' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -19 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False end object Label5: TLabel Left = 8 Top = 64 Width = 42 Height = 13 Caption = 'Present: ' end object Label6: TLabel Left = 8 Top = 96 Width = 39 Height = 13 Caption = 'Absent: ' end object Label3: TLabel Left = 179 Top = 34 Width = 20 Height = 13 Caption = 'Last' end object Label4: TLabel Left = 65 Top = 34 Width = 24 Height = 13 Caption = 'Total' end object LBusyL: TLabel Left = 179 Top = 120 Width = 61 Height = 24 Caption = 'LBusyL' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -19 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False end object LIdleL: TLabel Left = 179 Top = 152 Width = 50 Height = 24 Caption = 'LIdleL' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -19 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False end object lPresentL: TLabel Left = 179 Top = 56 Width = 84 Height = 24 Caption = 'LPresentL' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -19 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False end object LAbsentL: TLabel Left = 179 Top = 88 Width = 79 Height = 24 Caption = 'LAbsentL' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -19 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False end object LDateTime: TLabel Left = 65 Top = 0 Width = 91 Height = 24 Caption = 'LDateTime' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -19 Font.Name = 'MS Sans Serif' Font.Style = [] ParentFont = False end object Label7: TLabel Left = 8 Top = 6 Width = 55 Height = 13 Caption = 'Date Time: ' end object EITO: TEdit Left = 8 Top = 34 Width = 49 Height = 21 TabOrder = 0 Text = '300' Visible = False OnChange = EITOChange end object StatusBar1: TStatusBar Left = 0 Top = 191 Width = 302 Height = 19 Panels = < item Width = 50 end item Text = 'Present time' Width = 59 end item Text = 'Absent time' Width = 59 end item Text = 'github.com/duzun/UserActivityCounter' Width = 50 end> ParentShowHint = False ShowHint = True OnMouseDown = StatusBar1MouseDown OnMouseMove = StatusBar1MouseMove end object PauseBtn: TButton Left = 251 Top = 167 Width = 45 Height = 19 Caption = 'Pause' TabOrder = 2 TabStop = False OnClick = PauseBtnClick OnKeyDown = FormKeyDown end object Timer1: TTimer Interval = 1 OnTimer = Timer1Timer Left = 168 Top = 2 end object ActionList1: TActionList Left = 200 Top = 2 object ShowInfo: TAction Caption = 'ShowInfo' OnExecute = ShowInfoExecute end object OnPresenceChange: TAction Caption = 'OnPresenceChange' OnExecute = OnPresenceChangeExecute end object OnPresentChange: TAction Caption = 'OnPresentChange' OnExecute = OnPresentChangeExecute end object OnAbsentChange: TAction Caption = 'OnAbsentChange' OnExecute = OnAbsentChangeExecute end object OnBusyChange: TAction Caption = 'OnBusyChange' OnExecute = OnBusyChangeExecute end object OnIdleChange: TAction Caption = 'OnIdleChange' OnExecute = OnIdleChangeExecute end object SetIdle: TAction Caption = 'Set Idle' OnExecute = SetIdleExecute end object HideToTray: TAction Caption = 'HideToTray' OnExecute = HideToTrayExecute end object ShowFromTray: TAction Caption = 'ShowFromTray' OnExecute = ShowFromTrayExecute end end end
unit AddressBookContactFindResponseUnit; interface uses REST.Json.Types, GenericParametersUnit, AddressNoteUnit, CommonTypesUnit; type TAddressBookContactFindResponse = class(TGenericParameters) private [JSONName('results')] FResults: T2DimensionalStringArray; [JSONName('total')] FTotal: integer; [JSONName('fields')] FFields: TStringArray; public constructor Create; override; destructor Destroy; override; property Results: T2DimensionalStringArray read FResults; property Total: integer read FTotal; property Fields: TStringArray read FFields; end; implementation constructor TAddressBookContactFindResponse.Create; begin inherited; SetLength(FResults, 0); SetLength(FFields, 0); end; destructor TAddressBookContactFindResponse.Destroy; begin Finalize(FResults); Finalize(FFields); inherited; end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clAsyncClient; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} {$IFDEF DEMO}Forms, {$ENDIF}Messages, Windows, Classes, WinSock, SysUtils, {$ELSE} {$IFDEF DEMO}Vcl.Forms, {$ENDIF}Winapi.Messages, Winapi.Windows, System.Classes, Winapi.WinSock, System.SysUtils, {$ENDIF} clSocket, clUtils, clSspiTls, clTlsSocket, clSocketUtils, clIpAddress, clCertificateStore, clCertificate, clWUtils; type TclAsyncAction = (aaConnect, aaDisconnect, aaRead, aaWrite); TclAsyncConnection = class(TclConnection) public function ReadData(AData: TStream): Boolean; override; function WriteData(AData: TStream): Boolean; override; end; TclAsyncErrorEvent = procedure (Sender: TObject; AsyncAction: TclAsyncAction; AErrorCode: Integer; const AMessage: string) of object; TclAsyncClient = class(TComponent) private FServer: string; FPort: Integer; FLocalBinding: string; FConnection: TclAsyncConnection; FTimeOut: Integer; FWindowHandle: HWND; FSocketType: Integer; FSocketProtocol: Integer; FUseTLS: Boolean; FCertificateFlags: TclCertificateVerifyFlags; FTLSFlags: TclTlsFlags; FIsClosed: Boolean; FOnRead: TNotifyEvent; FOnWrite: TNotifyEvent; FOnConnect: TNotifyEvent; FOnConnecting: TNotifyEvent; FOnDisconnect: TNotifyEvent; FOnChanged: TNotifyEvent; FOnVerifyServer: TclVerifyPeerEvent; FOnGetCertificate: TclGetCertificateEvent; FOnAsyncError: TclAsyncErrorEvent; function GetBatchSize: Integer; function GetBitsPerSec: Integer; procedure SetBatchSize(const Value: Integer); procedure SetBitsPerSec(const Value: Integer); function GetActive: Boolean; procedure WaitForCompletion; procedure WndProc(var Message: TMessage); procedure HandleConnect(AErrorCode: Integer); procedure HandleRead(AErrorCode: Integer); procedure HandleWrite(AErrorCode: Integer); procedure HandleClose(AErrorCode: Integer); procedure HandleAsyncError(AsyncAction: TclAsyncAction; AErrorCode: Integer); procedure SetServer(const Value: string); procedure SetPort_(const Value: Integer); procedure SetLocalBinding(const Value: string); procedure SetTimeOut(const Value: Integer); procedure SetSocketType(const Value: Integer); procedure SetSocketProtocol(const Value: Integer); procedure SetUseTLS(const Value: Boolean); procedure SetCertificateFlags(const Value: TclCertificateVerifyFlags); procedure SetTLSFlags(const Value: TclTlsFlags); procedure GetCertificate(Sender: TObject; var ACertificate: TclCertificate; AExtraCerts: TclCertificateList; var Handled: Boolean); procedure VerifyServer(Sender: TObject; ACertificate: TclCertificate; const AStatusText: string; AStatusCode: Integer; var AVerified: Boolean); procedure SelectEvent(ASocket: TclSocket; lEvent: Integer); protected procedure DoDestroy; virtual; procedure Changed; virtual; procedure DoConnect; virtual; procedure DoConnecting; virtual; procedure DoDisconnect; virtual; procedure DoRead; virtual; procedure DoWrite; virtual; procedure DoAsyncError(AsyncAction: TclAsyncAction; AErrorCode: Integer; const AMessage: string); virtual; procedure DoGetCertificate(var ACertificate: TclCertificate; AExtraCerts: TclCertificateList; var Handled: Boolean); virtual; procedure DoVerifyServer(ACertificate: TclCertificate; const AStatusText: string; AStatusCode: Integer; var AVerified: Boolean); virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Open; procedure Close; function ReadData(AData: TStream): TclNetworkStreamAction; function WriteData(AData: TStream): TclNetworkStreamAction; procedure AssignTlsStream(); property Connection: TclAsyncConnection read FConnection; property Active: Boolean read GetActive; published property Server: string read FServer write SetServer; property Port: Integer read FPort write SetPort_; property LocalBinding: string read FLocalBinding write SetLocalBinding; property BatchSize: Integer read GetBatchSize write SetBatchSize default 8192; property BitsPerSec: Integer read GetBitsPerSec write SetBitsPerSec default 0; property TimeOut: Integer read FTimeOut write SetTimeOut default 60000; property SocketType: Integer read FSocketType write SetSocketType default SOCK_STREAM; property SocketProtocol: Integer read FSocketProtocol write SetSocketProtocol default IPPROTO_TCP; property UseTLS: Boolean read FUseTLS write SetUseTLS default False; property CertificateFlags: TclCertificateVerifyFlags read FCertificateFlags write SetCertificateFlags default []; property TLSFlags: TclTlsFlags read FTLSFlags write SetTLSFlags default [tfUseTLS]; property OnChanged: TNotifyEvent read FOnChanged write FOnChanged; property OnConnect: TNotifyEvent read FOnConnect write FOnConnect; property OnConnecting: TNotifyEvent read FOnConnecting write FOnConnecting; property OnDisconnect: TNotifyEvent read FOnDisconnect write FOnDisconnect; property OnRead: TNotifyEvent read FOnRead write FOnRead; property OnWrite: TNotifyEvent read FOnWrite write FOnWrite; property OnAsyncError: TclAsyncErrorEvent read FOnAsyncError write FOnAsyncError; property OnGetCertificate: TclGetCertificateEvent read FOnGetCertificate write FOnGetCertificate; property OnVerifyServer: TclVerifyPeerEvent read FOnVerifyServer write FOnVerifyServer; end; implementation {$IFDEF DEMO} {$IFNDEF IDEDEMO} var IsDemoDisplayed: Boolean = False; {$ENDIF} {$ENDIF} const CL_SOCKETEVENT = WM_USER + 2111; { TclAsyncClient } constructor TclAsyncClient.Create(AOwner: TComponent); begin inherited Create(AOwner); FWindowHandle := 0; StartupSocket(); FConnection := TclAsyncConnection.Create(); BatchSize := 8192; BitsPerSec := 0; TimeOut := 60000; FSocketType := SOCK_STREAM; FSocketProtocol := IPPROTO_TCP; FIsClosed := True; end; destructor TclAsyncClient.Destroy; begin Close(); WaitForCompletion(); DoDestroy(); FConnection.Free(); CleanupSocket(); if (FWindowHandle <> 0) then begin DeallocateWindow(FWindowHandle); end; inherited Destroy(); end; procedure TclAsyncClient.WaitForCompletion; var Msg: TMsg; begin while PeekMessage(Msg, 0, 0, 0, PM_REMOVE) do begin DispatchMessage(Msg); end; end; procedure TclAsyncClient.WndProc(var Message: TMessage); var errorCode: Integer; begin if (Message.Msg <> CL_SOCKETEVENT) or (TSocket(Message.wParam) <> Connection.Socket.Socket) then Exit; errorCode := HIWORD(Message.lParam); case LOWORD(Message.lParam) of FD_CONNECT: HandleConnect(errorCode); FD_READ: HandleRead(errorCode); FD_WRITE: HandleWrite(errorCode); FD_CLOSE: HandleClose(errorCode); end; end; function TclAsyncClient.WriteData(AData: TStream): TclNetworkStreamAction; begin Connection.WriteData(AData); Result := Connection.NetworkStream.NextAction; end; procedure TclAsyncClient.DoConnect; begin if Assigned(OnConnect) then begin OnConnect(Self); end; end; procedure TclAsyncClient.DoConnecting; begin if Assigned(OnConnecting) then begin OnConnecting(Self); end; end; procedure TclAsyncClient.DoDestroy; begin end; procedure TclAsyncClient.DoDisconnect; begin if Assigned(OnDisconnect) then begin OnDisconnect(Self); end; end; procedure TclAsyncClient.DoAsyncError(AsyncAction: TclAsyncAction; AErrorCode: Integer; const AMessage: string); begin if Assigned(OnAsyncError) then begin OnAsyncError(Self, AsyncAction, AErrorCode, AMessage); end; end; procedure TclAsyncClient.DoGetCertificate(var ACertificate: TclCertificate; AExtraCerts: TclCertificateList; var Handled: Boolean); begin if Assigned(OnGetCertificate) then begin OnGetCertificate(Self, ACertificate, AExtraCerts, Handled); end; end; procedure TclAsyncClient.DoRead; begin if Assigned(OnRead) then begin OnRead(Self); end; end; procedure TclAsyncClient.DoVerifyServer(ACertificate: TclCertificate; const AStatusText: string; AStatusCode: Integer; var AVerified: Boolean); begin if Assigned(OnVerifyServer) then begin OnVerifyServer(Self, ACertificate, AStatusText, AStatusCode, AVerified); end; end; procedure TclAsyncClient.DoWrite; begin if Assigned(OnWrite) then begin OnWrite(Self); end; end; function TclAsyncClient.GetActive: Boolean; begin Result := Connection.Active; end; function TclAsyncClient.GetBatchSize: Integer; begin Result := Connection.BatchSize; end; function TclAsyncClient.GetBitsPerSec: Integer; begin Result := Connection.BitsPerSec; end; procedure TclAsyncClient.GetCertificate(Sender: TObject; var ACertificate: TclCertificate; AExtraCerts: TclCertificateList; var Handled: Boolean); begin DoGetCertificate(ACertificate, AExtraCerts, Handled); end; procedure TclAsyncClient.HandleClose(AErrorCode: Integer); begin if not FIsClosed then begin FIsClosed := True; Connection.Close(False); if (AErrorCode = 0) then begin DoDisconnect(); end else begin HandleAsyncError(aaDisconnect, AErrorCode); end; end; end; procedure TclAsyncClient.HandleConnect(AErrorCode: Integer); begin if (AErrorCode = 0) then begin Connection.SetActive(True); repeat case Connection.NetworkStream.NextAction of saWrite: WriteData(nil) else Break; end; until False; DoConnect(); end else begin try Connection.Close(False); except on EclSocketError do; end; HandleAsyncError(aaConnect, AErrorCode); end; end; procedure TclAsyncClient.HandleAsyncError(AsyncAction: TclAsyncAction; AErrorCode: Integer); begin DoAsyncError(AsyncAction, AErrorCode, GetWSAErrorText(AErrorCode)); end; procedure TclAsyncClient.HandleRead(AErrorCode: Integer); begin if (AErrorCode = 0) then begin DoRead(); end else begin HandleAsyncError(aaRead, AErrorCode); end; end; procedure TclAsyncClient.HandleWrite(AErrorCode: Integer); begin if (AErrorCode = 0) then begin DoWrite(); end else begin HandleAsyncError(aaWrite, AErrorCode); end; end; procedure TclAsyncClient.SelectEvent(ASocket: TclSocket; lEvent: Integer); var res: Integer; begin res := WSAAsyncSelect(ASocket.Socket, FWindowHandle, CL_SOCKETEVENT, lEvent); if (res = SOCKET_ERROR) then begin RaiseSocketError(WSAGetLastError()); end; end; procedure TclAsyncClient.SetBatchSize(const Value: Integer); begin if (Connection.BatchSize <> Value) then begin Connection.BatchSize := Value; Changed(); end; end; procedure TclAsyncClient.SetBitsPerSec(const Value: Integer); begin if (Connection.BitsPerSec <> Value) then begin Connection.BitsPerSec := Value; Changed(); end; end; procedure TclAsyncClient.SetCertificateFlags(const Value: TclCertificateVerifyFlags); begin if (FCertificateFlags <> Value) then begin FCertificateFlags := Value; Changed(); end; end; procedure TclAsyncClient.SetLocalBinding(const Value: string); begin if (FLocalBinding <> Value) then begin FLocalBinding := Value; Changed(); end; end; procedure TclAsyncClient.SetPort_(const Value: Integer); begin if (FPort <> Value) then begin FPort := Value; Changed(); end; end; procedure TclAsyncClient.SetServer(const Value: string); begin if (FServer <> Value) then begin FServer := Value; Changed(); end; end; procedure TclAsyncClient.SetSocketProtocol(const Value: Integer); begin if (FSocketProtocol <> Value) then begin FSocketProtocol := Value; Changed(); end; end; procedure TclAsyncClient.SetSocketType(const Value: Integer); begin if (FSocketType <> Value) then begin FSocketType := Value; Changed(); end; end; procedure TclAsyncClient.SetTimeOut(const Value: Integer); begin if (FTimeOut <> Value) then begin FTimeOut := Value; Changed(); end; end; procedure TclAsyncClient.SetTLSFlags(const Value: TclTlsFlags); begin if (FTLSFlags <> Value) then begin FTLSFlags := Value; Changed(); end; end; procedure TclAsyncClient.SetUseTLS(const Value: Boolean); begin if (FUseTLS <> Value) then begin FUseTLS := Value; Changed(); end; end; procedure TclAsyncClient.VerifyServer(Sender: TObject; ACertificate: TclCertificate; const AStatusText: string; AStatusCode: Integer; var AVerified: Boolean); begin DoVerifyServer(ACertificate, AStatusText, AStatusCode, AVerified); end; procedure TclAsyncClient.Open; var addr, bindAddr: TclIPAddress; begin {$IFDEF DEMO} {$IFNDEF STANDALONEDEMO} if FindWindow('TAppBuilder', nil) = 0 then begin MessageBox(0, 'This demo version can be run under Delphi/C++Builder IDE only. ' + 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); ExitProcess(1); end else {$ENDIF} begin {$IFNDEF IDEDEMO} if (not IsDemoDisplayed) then begin MessageBox(0, 'Please visit www.clevercomponents.com to purchase your ' + 'copy of the library.', 'Information', MB_ICONEXCLAMATION or MB_TASKMODAL or MB_TOPMOST); end; IsDemoDisplayed := True; {$ENDIF} end; {$ENDIF} FIsClosed := False; if (FWindowHandle = 0) then begin FWindowHandle := AllocateWindow(WndProc); end; if (FWindowHandle = 0) then begin RaiseSocketError(clGetLastError()); end; if UseTLS then begin AssignTlsStream(); end else begin Connection.NetworkStream := TclNetworkStream.Create(); end; addr := nil; bindAddr := nil; try addr := TclIPAddress.CreateIpAddress(TclHostResolver.GetIPAddress(Server)); Connection.CreateSocket(addr.AddressFamily, SocketType, SocketProtocol); SelectEvent(Connection.Socket, FD_CONNECT or FD_CLOSE or FD_READ or FD_WRITE); if (Trim(LocalBinding) <> '') then begin bindAddr := TclIPAddress.CreateBindingIpAddress(LocalBinding, addr.AddressFamily); Connection.NetworkStream.Bind(bindAddr, 0); end; DoConnecting(); Connection.NetworkStream.Connect(addr, Port); finally bindAddr.Free(); addr.Free(); end; end; function TclAsyncClient.ReadData(AData: TStream): TclNetworkStreamAction; begin SelectEvent(Connection.Socket, FD_CONNECT or FD_CLOSE or FD_WRITE); try Connection.ReadData(AData); Result := Connection.NetworkStream.NextAction; finally SelectEvent(Connection.Socket, FD_CONNECT or FD_CLOSE or FD_READ or FD_WRITE); end; end; procedure TclAsyncClient.AssignTlsStream(); var tlsStream: TclTlsNetworkStream; begin tlsStream := TclTlsNetworkStream.Create(); Connection.NetworkStream := tlsStream; tlsStream.CertificateFlags := CertificateFlags; tlsStream.TLSFlags := TLSFlags; tlsStream.TargetName := Server; tlsStream.OnGetCertificate := GetCertificate; tlsStream.OnVerifyPeer := VerifyServer; end; procedure TclAsyncClient.Changed; begin if Assigned(OnChanged) then begin OnChanged(Self); end; end; procedure TclAsyncClient.Close; var wasActive: Boolean; action: TclNetworkStreamAction; begin action := saNone; wasActive := Active; Connection.Close(True); if wasActive then begin action := Connection.NetworkStream.NextAction; end; if (action = saWrite) then begin action := WriteData(nil); end; if (action = saNone) then begin HandleClose(0); end; end; { TclAsyncConnection } function TclAsyncConnection.ReadData(AData: TStream): Boolean; begin Result := NetworkStream.Read(AData); end; function TclAsyncConnection.WriteData(AData: TStream): Boolean; begin Result := NetworkStream.Write(AData); end; end.
unit Provider.Utils; interface uses Winapi.Windows; procedure WriteLNColor(Text: String; Color: Word); implementation procedure WriteLNColor(Text: String; Color: Word); var ConsoleHandle : THandle; BufInfo : TConsoleScreenBufferInfo; begin ConsoleHandle := TTextRec(Output).Handle; GetConsoleScreenBufferInfo( ConsoleHandle, BufInfo ); SetConsoleTextAttribute(ConsoleHandle, FOREGROUND_INTENSITY or Color); WriteLN(Text); SetConsoleTextAttribute(ConsoleHandle, BufInfo.wAttributes); end; end.
unit interpolation_; interface uses Unit4,Unit4_vars,Classes,SysUtils, Matrix_,vars_2d,math; function InterpNewton(IPointsAr: TPointsArray2d):string; function InterpSpline(IPointsAr: TPointsArray2d; c0: extended; cn: extended):TStrings; function InterpLagrange(IPointsAr: TPointsArray2d):string; type TCoffsAr= array of extended; var InterpOpbrackets: boolean; Interpfloatnums: integer; implementation function MultPolinoms(CoffsA: TCoffsAr; CoffsB: TCoffsAr):TCOffsAr; var lena, lenb, i,j,k,len: integer; sum: extended; begin lena:=length(CoffsA); lenb:=length(CoffsB); len:=lena+lenb-1; setlength(result,len); setlength(CoffsA,len); setlength(CoffsB,len); for i := lena to len - 1 do coffsa[i]:=0; for i := lenb to len - 1 do coffsb[i]:=0; for i := 0 to len - 1 do begin sum:=0; for j := 0 to i do sum:=sum+coffsa[j]*coffsb[i-j]; result[i]:=sum; end; end; function factorial(aNumber:integer):longint; begin if (aNumber < 0) then result:=-1; if (aNumber = 0) then result:=1 else result:=aNumber * factorial(aNumber - 1); // Otherwise, recurse until done. end; function sgn(cof: extended; possign: boolean): string; begin if IsZero(cof,IntPower(10,-InterpFloatNums)) then if possign then sgn:='+0' else sgn:='0' else if cof<0 then result:=FloatToStrF(cof, ffGeneral, Interpfloatnums, Interpfloatnums+2) else if possign then result:='+'+FloatToStrF(cof,ffGeneral,Interpfloatnums,Interpfloatnums+2) else sgn:=FloatToStrF(cof,ffGeneral,Interpfloatnums,Interpfloatnums+2); end; function InterpNewton(IPointsAr: TPointsArray2d):string; var diffs: array of array of extended; i,j,k: integer; N: integer; TTempCof, TTempCofA: TCoffsAR; sum: extended; begin N:=length(IPointsAr); setlength(diffs,N+1,N); for I := 0 to N - 1 do diffs[i,0]:=IPointsAr[i].y; for j := 1 to N - 1 do //расчет таблицы конечных разнстей. begin //первая строка - коэффициенты в многочлене со скобками. for i := 0 to N-J-1 do diffs[i,j]:=(diffs[i+1,j-1]-diffs[i,j-1])/(IPointsAr[i+j].x-IPointsAr[i].x); end; if Interpopbrackets then//строим строку с раскрытыми скобками begin diffs[1,0]:=1; diffs[1,1]:=-IPointsAr[0].x; diffs[2,1]:=1; setlength(TtempCofA,2); TTempCofA[0]:=-IPointsAr[0].x; TTempCofA[1]:=1; setlength(TTempCof,2); TTempCof[1]:=1; for j := 2 to N - 1 do begin TTempCof[0]:=-IPointsAr[j-1].x; TTempCofA:=MultPolinoms(TTempCofA,TTempCof); for i := 1 to j+1 do diffs[i,j]:=TTempCofA[i-1]; end; sum:=0;//собираем финальную строку for j := 0 to N - 1 do sum:=sum+diffs[0,j]*diffs[1,j]; result:=sgn(sum,false); for i := 2 to N do begin sum:=0; for j := i-1 to N - 1 do sum:=sum+diffs[0,j]*diffs[i,j]; result:=result+sgn(sum,true)+'*x^'+inttostr(i-1); end; end else //если скобки не раскрывать begin result:=sgn(diffs[0,0],false); for j := 1 to N - 1 do begin result:=result+sgn(diffs[0,j],true); for i := 0 to j - 1 do result:=result+'*(x'+sgn(-IPointsAr[i].x,true)+')'; end; end; setlength(Funcs2dArray, length(Funcs2dArray)+1); with Funcs2dArray[length(Funcs2dArray)-1] do begin Color:=$0000c000; Wdth:=1; objType:=YoX; NumOfPoints:=100; LeftX:=IPointsAr[0].x; RightX:=IPointsAr[n-1].x; Checked:=true; LeftXLine:=FloatToStrF(LeftX,ffGeneral,InterpFloatNums,InterpFloatNums+2); RightXLine:=FloatToStrF(RightX,ffGeneral,InterpFloatNums,InterpFloatNums+2); IsMathEx:=true; Name:='Interp Newton: '+result; FUnct:=AnalyseFunc2d(result,'x'); end; Funcs2dArray[length(Funcs2dArray)-1].FillPointsArray; FuncArCngd:=true; end; function InterpSpline(IPointsAr: TPointsArray2d; c0: extended; cn: extended):TStrings; var H,A,B,C,C1,D,F: TVect;//вектора: H - шагов (x(i) - x(i-1)) //A,B,C,D - вектора коэффициентов полиномов //F - матрица правых частей для расчета С Am: TMatrix; //основная матрица СЛАУ по С i,j,k,len,f2dlen: integer; slag: extended; resstr:string; begin len:=length(IPointsAr); setlength(A, len); setlength(B, len); setlength(C, len); setlength(C1,len-2); setlength(D, len); setlength(F, len-2); setlength(H, len-1); setlength(Am, len-2, len-2); for I := 0 to len - 1 do a[i]:=IPointsAr[i].y; for i := 0 to len - 2 do H[i]:=IPointsAr[i+1].x-IPointsAr[i].x; for i := 0 to len - 3 do Am[i,i]:=2*(H[i+1]+H[i]); for i := 0 to len - 4 do Am[i,i+1]:=H[i+1]; for i := 1 to len - 3 do Am[i,i-1]:=H[i]; for i := 0 to len - 3 do F[i]:=6*((a[i+2]-a[i+1])/H[i+1]-(a[i+1]-a[i])/H[i]); F[0]:=F[0]-c0; F[len-3]:=F[len-3]-cn; C1:=M_ProgSLAU(Am,F); for i := 0 to len - 3 do C[i+1]:=C1[i]; C[0]:=cn; C[len-1]:=cn; for i := 1 to len - 1 do d[i]:=(c[i]-c[i-1])/H[i-1]; for i := 1 to len - 1 do B[i]:=H[i-1]*C[i]/2-sqr(H[i-1])*D[i]/6+(a[i]-a[i-1])/H[i-1]; result:=TStringList.Create; f2dlen:=length(Funcs2dArray); SetLength(Funcs2dArray,f2dlen+len-1); for i := 0 to len-2 do begin if Interpopbrackets then begin slag:=a[i+1]-b[i+1]*IPointsAr[i+1].x+c[i+1]*sqr(IPointsAr[i+1].x)/2-d[i+1]*sqr(IPointsAr[i+1].x)*IPointsAr[i+1].x/6; resstr:=sgn(slag,false); slag:=b[i+1]-c[i+1]*IPointsAr[i+1].x+d[i+1]*sqr(IPointsAr[i+1].x)/2; resstr:=resstr+sgn(slag,true)+'*x'; slag:=c[i+1]/2-d[i+1]*IPointsAr[i+1].x/2; resstr:=resstr+sgn(slag,true)+'*x^2'; slag:=d[i+1]/6; resstr:=resstr+sgn(slag,true)+'*x^3'; end else begin slag:=a[i+1]; resstr:=sgn(slag,false); slag:=b[i+1]; resstr:=resstr+sgn(slag,true)+'*(x'+sgn(-IPointsAr[i+1].x,true)+')'; slag:=c[i+1]/2; resstr:=resstr+sgn(slag,true)+'*(x'+sgn(-IPointsAr[i+1].x,true)+')^2'; slag:=d[i+1]/6; resstr:=resstr+sgn(slag,true)+'*(x'+sgn(-IPointsAr[i+1].x,true)+')^3'; end; result.Add(resstr); with Funcs2dArray[f2dlen+i] do begin Color:=$0000c000; Wdth:=1; objType:=YoX; NumOfPoints:=100; LeftX:=IPointsAr[i].x; RightX:=IPointsAr[i+1].x; Checked:=true; LeftXLine:=FloatToStrF(LeftX,ffGeneral,InterpFloatNums,InterpFloatNums+2); RightXLine:=FloatToStrF(RightX,ffGeneral,InterpFloatNums,InterpFloatNums+2); IsMathEx:=true; Name:='Spline'+IntTOStr(i+1)+': '+resstr; FUnct:=AnalyseFunc2d(resstr,'x'); end; Funcs2dArray[f2dlen+i].FillPointsArray; end; FuncArCngd:=true; end; function InterpLagrange(IPointsAr: TPointsArray2d):string; var i,j,k: integer; koff,sum: extended; n: integer; xi: extended; begin result:=''; n:=length(IPointsAr); // if not opbrackets then begin for i := 0 to n - 1 do begin sum:=1; xi:=IPointsAr[i].x; for j := 0 to i - 1 do sum:=sum*(xi-IPointsAr[j].x); for j := i+1 to n - 1 do sum:=sum*(xi-IPointsAr[j].x); koff:=IPointsAr[i].y/sum; result:=result+sgn(koff,true); for j := 0 to n - 1 do if j<>i then begin result:=result+'*(x'+sgn(-IPointsAr[j].x,true)+')'; end; end; end; setlength(Funcs2dArray, length(Funcs2dArray)+1); with Funcs2dArray[length(Funcs2dArray)-1] do begin Color:=$0000c000; Wdth:=1; objType:=YoX; NumOfPoints:=100; LeftX:=IPointsAr[0].x; RightX:=IPointsAr[n-1].x; Checked:=true; LeftXLine:=FloatToStrF(LeftX,ffGeneral,InterpFloatNums,InterpFloatNums+2); RightXLine:=FloatToStrF(RightX,ffGeneral,InterpFloatNums,InterpFloatNums+2); IsMathEx:=true; Name:='Interp Lagrange: '+result; FUnct:=AnalyseFunc2d(result,'x'); end; Funcs2dArray[length(Funcs2dArray)-1].FillPointsArray; FuncArCngd:=true; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.66 3/24/2005 3:03:28 AM DSiders Modified TIdIMAP4.ParseStatusResult to correct an endless loop parsing an odd number of status messages/values in the server response. Rev 1.65 3/23/2005 3:03:40 PM DSiders Modified TIdIMAP4.Destroy to free resources for Capabilities and MUtf7 properties. Rev 1.64 3/4/2005 3:08:42 PM JPMugaas Removed compiler warning with stream. You sometimes need to use IdStreamVCL. Rev 1.63 3/3/2005 12:54:04 PM JPMugaas Replaced TStringList with TIdStringList. Rev 1.62 3/3/2005 12:09:04 PM JPMugaas TStrings were replaced with TIdStrings. Rev 1.60 20/02/2005 20:41:06 CCostelloe Cleanup and reorganisations Rev 1.59 11/29/2004 2:46:10 AM JPMugaas I hope that this fixes a compile error. Rev 1.58 11/27/04 3:11:56 AM RLebeau Fixed bug in ownership of SASLMechanisms property. Updated to use TextIsSame() instead of Uppercase() comparisons. Rev 1.57 11/8/2004 8:39:00 AM DSiders Removed comment in TIdIMAP4.SearchMailBox implementation that caused DOM problem when locating the symbol id. Rev 1.56 10/26/2004 10:19:58 PM JPMugaas Updated refs. Rev 1.55 2004.10.26 2:19:56 PM czhower Resolved alias conflict. Rev 1.54 6/11/2004 9:36:34 AM DSiders Added "Do not Localize" comments. Rev 1.53 6/4/04 12:48:12 PM RLebeau ContentTransferEncoding bug fix Rev 1.52 01/06/2004 19:03:46 CCostelloe .NET bug fix Rev 1.51 01/06/2004 01:16:18 CCostelloe Various improvements Rev 1.50 20/05/2004 22:04:14 CCostelloe IdStreamVCL changes Rev 1.49 20/05/2004 08:43:12 CCostelloe IdStream change Rev 1.48 16/05/2004 20:40:46 CCostelloe New TIdText/TIdAttachment processing Rev 1.47 24/04/2004 23:54:42 CCostelloe IMAP-style UTF-7 encoding/decoding of mailbox names added Rev 1.46 13/04/2004 22:24:28 CCostelloe Bug fix (FCapabilities not created if not DOTNET) Rev 1.45 3/18/2004 2:32:40 AM JPMugaas Should compile under D8 properly. Rev 1.44 3/8/2004 10:10:32 AM JPMugaas IMAP4 should now have SASLMechanisms again. Those work in DotNET now. SSL abstraction is now supported even in DotNET so that should not be IFDEF'ed out. Rev 1.43 07/03/2004 17:55:16 CCostelloe Updates to cover changes in other units Rev 1.42 2/4/2004 2:36:58 AM JPMugaas Moved more units down to the implementation clause in the units to make them easier to compile. Rev 1.41 2/3/2004 4:12:50 PM JPMugaas Fixed up units so they should compile. Rev 1.40 2004.02.03 5:43:48 PM czhower Name changes Rev 1.39 2004.02.03 2:12:10 PM czhower $I path change Rev 1.38 1/27/2004 4:01:12 PM SPerry StringStream ->IdStringStream Rev 1.37 1/25/2004 3:11:12 PM JPMugaas SASL Interface reworked to make it easier for developers to use. SSL and SASL reenabled components. Rev 1.36 23/01/2004 01:48:28 CCostelloe Added BinHex4.0 encoding support for parts Rev 1.35 1/21/2004 3:10:40 PM JPMugaas InitComponent Rev 1.34 31/12/2003 09:40:32 CCostelloe ChangeReplyClass removed, replaced AnsiSameText with TextIsSame, stream code not tested. Rev 1.33 28/12/2003 23:48:18 CCostelloe More TEMPORARY fixes to get it to compile under D7 and D8 .NET Rev 1.32 22/12/2003 01:20:20 CCostelloe .NET fixes. This is a TEMPORARY combined Indy9/10/.NET master file. Rev 1.31 14/12/2003 21:03:16 CCostelloe First version for .NET Rev 1.30 10/17/2003 12:11:06 AM DSiders Added localization comments. Added resource strings for exception messages. Rev 1.29 2003.10.12 3:53:10 PM czhower compile todos Rev 1.28 10/12/2003 1:49:50 PM BGooijen Changed comment of last checkin Rev 1.27 10/12/2003 1:43:34 PM BGooijen Changed IdCompilerDefines.inc to Core\IdCompilerDefines.inc Rev 1.26 20/09/2003 15:38:38 CCostelloe More patches added for different IMAP servers Rev 1.25 12/08/2003 01:17:38 CCostelloe Retrieve and AppendMsg updated to suit changes made to attachment encoding changes in other units Rev 1.24 21/07/2003 01:22:24 CCostelloe Added CopyMsg and UIDCopyMsgs. (UID)Receive(Peek) rewritten. AppendMsg still buggy with attachments. Public variable FGreetingBanner added. Added "if Connected then " to Destroy. Attachment filenames now decoded if necessary. Added support for multisection parts. Resolved issue of some servers leaving out the trailing "NIL NIL NIL" at the end of some body structures. UIDRetrieveAllHeaders removed Rev 1.23 18/06/2003 21:53:36 CCostelloe Rewrote GetResponse from scratch. Restored Capabilities for login. Compiles and runs properly (may be a couple of minor bugs not yet discovered). Rev 1.22 6/16/2003 11:48:18 PM JPMugaas Capabilities has to be restored for SASL and SSL support. Rev 1.21 17/06/2003 01:33:46 CCostelloe Updated to support new LoginSASL. Compiles OK, may not yet run OK. Rev 1.20 12/06/2003 10:17:54 CCostelloe Partial update for Indy 10's new Reply structure. Compiles but does not run correctly. Checked in to show problem with Get/SetNumericCode in IdReplyIMAP. Rev 1.19 04/06/2003 02:33:44 CCostelloe Compiles under Indy 10 with the revised Indy 10 structure, but does not yet work properly due to some of the changes. Will be fixed by me in a later check-in. Rev 1.18 14/05/2003 01:55:50 CCostelloe This version (with the extra IMAP functionality recently added) now compiles on Indy 10 and works in a real application. Rev 1.17 5/12/2003 02:19:56 AM JPMugaas Now should work properly again. I also removed all warnings and errors in Indy 10. Rev 1.16 5/11/2003 07:35:44 PM JPMugaas Rev 1.15 5/11/2003 07:11:06 PM JPMugaas Fixed to eliminate some warnings and compile errors in Indy 10. Rev 1.14 11/05/2003 23:53:52 CCostelloe Bug fix due to Windows 98 / 2000 discrepancies Rev 1.13 11/05/2003 23:08:36 CCostelloe Lots more bug fixes, plus IMAP code moved up from IdRFCReply Rev 1.12 5/10/2003 07:31:22 PM JPMugaas Updated with some bug fixes and some cleanups. Rev 1.11 5/9/2003 10:51:26 AM JPMugaas Bug fixes. Now works as it should. Verified. Rev 1.9 5/9/2003 03:49:44 AM JPMugaas IMAP4 now supports SASL. Merged some code from Ciaran which handles the + SASL continue reply in IMAP4 and makes a few improvements. Verified to work on two servers. Rev 1.8 5/8/2003 05:41:48 PM JPMugaas Added constant for SASL continuation. Rev 1.7 5/8/2003 03:17:50 PM JPMugaas Flattened ou the SASL authentication API, made a custom descendant of SASL enabled TIdMessageClient classes. Rev 1.6 5/8/2003 11:27:52 AM JPMugaas Moved feature negoation properties down to the ExplicitTLSClient level as feature negotiation goes hand in hand with explicit TLS support. Rev 1.5 5/8/2003 02:17:44 AM JPMugaas Fixed an AV in IdPOP3 with SASL list on forms. Made exceptions for SASL mechanisms missing more consistant, made IdPOP3 support feature feature negotiation, and consolidated some duplicate code. Rev 1.4 5/7/2003 10:20:32 PM JPMugaas Rev 1.3 5/7/2003 04:35:30 AM JPMugaas IMAP4 should now compile. Started on prelimary SSL support (not finished yet). Rev 1.2 15/04/2003 00:57:08 CCostelloe Rev 1.1 2/24/2003 09:03:06 PM JPMugaas Rev 1.0 11/13/2002 07:54:50 AM JPMugaas 2001-FEB-27 IC: First version most of the IMAP features are implemented and the core IdPOP3 features are implemented to allow a seamless switch. The unit is currently oriented to a session connection and not to constant connection, because of that server events that are raised from another user actions are not supported. 2001-APR-18 IC: Added support for the session's connection state with a special exception for commands preformed in wrong connection states. Exceptions were also added for response errors. 2001-MAY-05 IC: 2001-Mar-13 DS: Fixed Bug # 494813 in CheckMsgSeen where LastCmdResult.Text was not using the Ln index variable to access server responses. 2002-Apr-12 DS: fixed bug # 506026 in TIdIMAP4.ListSubscribedMailBoxes. Call ParseLSubResut instead of ParseListResult. 2003-Mar-31 CC: Added GetUID and UIDSearchMailBox, sorted out some bugs (details shown in comments in those functions which start with "CC:"). 2003-Apr-15 CC2:Sorted out some more bugs (details shown in comments in those functions which start with "CC2:"). Set FMailBoxSeparator in ParseListResult and ParseLSubResult. Some IMAP servers generally return "OK completed" even if they returned no data, such as passing a non-existent message number to them: they possibly should return NO or BAD; the functions here have been changed to return FALSE unless they get good data back, even if the server answers OK. Similar change made for other functions. There are a few exceptions, e.g. ListMailBoxes may only return "OK completed" if the user has no mailboxes, these are noted. Also, RetrieveStructure(), UIDRetrieveStructure, RetrievePart, UIDRetrievePart, RetrievePartPeek and UIDRetrievePartPeek added to allow user to find the structure of a message and just retrieve the part or parts he needs. 2003-Apr-30 CC3:Added functionality to retrieve the text of a message (only) via RetrieveText / UIDRetrieveText / RetrieveTextPeek / UIDRetrieveTextPeek. Return codes now generally reflect if the function succeeded instead of returning True even though function fails. 2003-May-15 CC4:Added functionality to retrieve individual parts of a message to a file, including the decoding of those parts. 2003-May-29 CC5:Response of some servers to UID version of commands varies, code changed to deal with those (UID position varies). Some servers return NO such as when you request an envelope for a message number that does not exist: functions return False instead of throwing an exception, as was done for other servers. The general logic is that if a valid result is returned from the IMAP server, return True; if there is no result (but the command is validly structured), return FALSE; if the command is badly structured or if it gives a response that this code does not expect, throw an exception (typically when we get a BAD response instead of OK or NO). Added IsNumberValid, IsUIDValid to prevent rubbishy parameters being passed through to IMAP functions. Sender field now filled in correctly in ParseEnvelope functions. All fields in ParseEnvelopeAddress are cleared out first, avoids an unwitting error where some entries, such as CC list, will append entries to existing entries. Full test script now used that tests every TIdIMAP command, more bugs eradicated. First version to pass testing against both CommuniGate and Cyrus IMAP servers. Not tested against Microsoft Exchange, don't have an Exchange account to test it against. 2003-Jun-10 CC6:Added (UID)RetrieveEnvelopeRaw, in case the user wants to do their own envelope parsing. Code in RetrievePart altered to make it more consistent. Altered to incorporate Indy 10's use of IdReplyIMAP4 (not complete at this stage). ReceiveBody added to IdIMAP4, due to the response of some servers, which gets (UID)Receive(Peek) functions to work on more servers. 2003-Jun-20 CC7:ReceiveBody altered to work with Indy 10. Made changes due to LoginSASL moving from TIdMessageSASLClient to TIdSASLList. Public variable FGreetingBanner added to help user identify the IMAP server he is connected to (may help him decide the best strategy). Made AppendMsg work a bit better (now uses platform-independent EOL and supports ExtraHeaders field). Added 2nd version of AppendMsg. Added "if Connected then " to Destroy. Attachment filenames now decoded if necessary. Added support for multisection parts. 2003-Jul-16 CC8:Added RemoveAnyAdditionalResponses. Resolved issue of some servers leaving out the trailing "NIL NIL NIL" at the end of some body structures. (UID)Retrieve(Peek) functions integrated via InternalRetrieve, new method of implementing these functions (all variations of Retrieve) added for Indy 10 based on getting message by the byte-count and then feeding it into the standard message parser. UIDRetrieveAllHeaders removed: it was never implemented anyway but it makes no sense to retrieve a non-contiguous list which would have gaps due to missing UIDs. In the Indy 10 version, AppendMsg functions were altered to support the sending of attachments (attachments had never been supported in AppendMsg prior to this). Added CopyMsg and UIDCopyMsgs to complete the command set. 2003-Jul-30 CC9:Removed wDoublePoint so that the code is compliant with the guidelines. Allowed for servers that don't implement search commands in Indy 9 (OK in 10). InternalRetrieve altered to (hopefully) deal with optional "FLAGS (\Seen)" in response. 2003-Aug-22 CCA:Yet another IMAP oddity - a server returns NIL for the mailbox separator, ParseListResult modified. Added "Length (LLine) > 0)" test to stop GPF on empty line in ReceiveBody. 2003-Sep-26 CCB:Changed SendCmd altered to try to remove anything that may be unprocessed from a previous (probably failed) command. This uses the property FMilliSecsToWaitToClearBuffer, which defaults to 10ms. Added EIdDisconnectedProbablyIdledOut, trapped in GetInternalResponse. Unsolicited responses now filtered out (they are now transferred from FLastCmdResult.Text to a new field, FLastCmdResult.Extra, leaving just the responses we want to our command in FLastCmdResult.Text). 2003-Oct-21 CCC:Original GetLineResponse merged with GetResponse to reduce complexity and to add filtering unsolicited responses when we are looking for single-line responses (which GetLineResponse did), removed/coded-out much of these functions to make the code much simpler. Removed RemoveAnyAdditionalResponses, no longer needed. Parsing of body structure reworked to support ParentPart concept allowing parsing of indefinitely-nested MIME parts. Note that a`MIME "alternative" message with a plain-text and a html part will have part[0] marked "alternative" with size 0 and ImapPartNumber of 1, a part[1] of type text/plain with a ParentPart of 0 and an ImapPartNumber of 1.1, and finally a part[2] of type text/html again with a ParentPart of 0 and an ImapPartNumber of 1.2. Imap part number changed from an integer to string, allowing retrieval of IMAP sub-parts, e.g. part '3.2' is the 2nd subpart of part 3. 2003-Nov-20 CCD:Added UIDRetrievePartHeader & RetrievePartHeader. Started to use an abstracted parsing method for the command response in UIDRetrieveFlags. Added function FindHowServerCreatesFolders. 2003-Dec-04 CCE:Copied DotNet connection changes from IdSMTP to tempoarily bypass the SASL authentications until they are ported. 2004-Jan-23 CCF:Finished .NET port, added BinHex4.0 encoding. 2004-Apr-16 CCG:Added UTF-7 decoding/encoding code kindly written and submitted by Roman Puls for encoding/decoding mailbox names. IMAP does not use standard UTF-7 code (what's new?!) so these routines are localised to this unit. } unit IdIMAP4; { IMAP 4 (Internet Message Access Protocol - Version 4 Rev 1) By Idan Cohen i_cohen@yahoo.com } interface { Todo -oIC : Change the mailbox list commands so that they receive TMailBoxTree structures and so they can store in them the mailbox name and it's attributes. } { Todo -oIC : Add support for \* special flag in messages, and check for \Recent flag in STORE command because it cant be stored (will get no reply!!!) } { Todo -oIC : 5.1.2. Mailbox Namespace Naming Convention By convention, the first hierarchical element of any mailbox name which begins with "#" identifies the "namespace" of the remainder of the name. This makes it possible to disambiguate between different types of mailbox stores, each of which have their own namespaces. For example, implementations which offer access to USENET newsgroups MAY use the "#news" namespace to partition the USENET newsgroup namespace from that of other mailboxes. Thus, the comp.mail.misc newsgroup would have an mailbox name of "#news.comp.mail.misc", and the name "comp.mail.misc" could refer to a different object (e.g. a user's private mailbox). } { TO BE CONSIDERED -CC : Double-quotes in mailbox names can cause major but subtle failures. Maybe add the automatic stripping of double-quotes if passed in mailbox names, to avoid ending up with ""INBOX"" } {CC3: WARNING - if the following gives a "File not found" error on compilation, you need to add the path "C:\Program Files\Borland\Delphi7\Source\Indy" in Project -> Options -> Directories/Conditionals -> Search Path} {$I IdCompilerDefines.inc} uses Classes, {$IFNDEF VCL_6_OR_ABOVE}IdCTypes,{$ENDIF} IdMessage, IdAssignedNumbers, IdMailBox, IdException, IdGlobal, IdMessageParts, IdMessageClient, IdReply, IdComponent, IdMessageCoder, IdHeaderList, IdCoderHeader, IdCoderMIME, IdCoderQuotedPrintable, IdCoderBinHex4, IdSASLCollection, IdMessageCollection, IdBaseComponent; { MUTF7 } type EmUTF7Error = class(EIdSilentException); EmUTF7Encode = class(EmUTF7Error); EmUTF7Decode = class(EmUTF7Error); type // TODO: make a TIdTextEncoding implementation for Modified UTF-7 TIdMUTF7 = class(TObject) public function Encode(const aString : TIdUnicodeString): AnsiString; function Decode(const aString : AnsiString): TIdUnicodeString; function Valid(const aMUTF7String : AnsiString): Boolean; function Append(const aMUTF7String: AnsiString; const aStr: TIdUnicodeString): AnsiString; end; { TIdIMAP4 } const wsOk = 1; wsNo = 2; wsBad = 3; wsPreAuth = 4; wsBye = 5; wsContinue = 6; type TIdIMAP4FolderTreatment = ( //Result codes from FindHowServerCreatesFolders ftAllowsTopLevelCreation, //Folders can be created at the same level as Inbox (the top level) ftFoldersMustBeUnderInbox, //Folders must be created under INBOX, such as INBOX.Sent ftDoesNotAllowFolderCreation, //Wont allow you create folders at top level or under Inbox (may be read-only connection) ftCannotTestBecauseHasNoInbox, //Wont allow top-level creation but cannot test creation under Inbox because it does not exist ftCannotRetrieveAnyFolders //No folders present for that user, cannot be determined ); type TIdIMAP4AuthenticationType = ( iatUserPass, iatSASL ); const DEF_IMAP4_AUTH = iatUserPass; IDF_DEFAULT_MS_TO_WAIT_TO_CLEAR_BUFFER = 10; {CC3: TIdImapMessagePart and TIdImapMessageParts added for retrieving individual parts of a message via IMAP, because IMAP uses some additional terms. Note that (rarely) an IMAP can have two sub-"parts" in the one part - they are sent in the one part by the server, typically a plain-text and html version with a boundary at the start, in between, and at the end. TIdIMAP fills in the boundary in that case, and the FSubpart holds the info on the second part. I call these multisection parts.} type TIdImapMessagePart = class(TCollectionItem) protected FBodyType: string; FBodySubType: string; FFileName: string; FDescription: string; FEncoding: TIdMessageEncoding; FCharSet: string; FContentTransferEncoding: string; FSize: integer; FUnparsedEntry: string; {Text returned from server: useful for debugging or workarounds} FBoundary: string; {Only used for multisection parts} FParentPart: Integer; FImapPartNumber: string; public constructor Create(Collection: TCollection); override; property BodyType : String read FBodyType write FBodyType; property BodySubType : String read FBodySubType write FBodySubType; property FileName : String read FFileName write FFileName; property Description : String read FDescription write FDescription; property Encoding: TIdMessageEncoding read FEncoding write FEncoding; property CharSet: string read FCharSet write FCharSet; property ContentTransferEncoding : String read FContentTransferEncoding write FContentTransferEncoding; property Size : integer read FSize write FSize; property UnparsedEntry : string read FUnparsedEntry write FUnparsedEntry; property Boundary : string read FBoundary write FBoundary; property ParentPart: integer read FParentPart write FParentPart; property ImapPartNumber: string read FImapPartNumber write FImapPartNumber; end; {CC3: Added for validating message number} EIdNumberInvalid = class(EIdException); {CCB: Added for server disconnecting you if idle too long...} EIdDisconnectedProbablyIdledOut = class(EIdException); TIdImapMessageParts = class(TOwnedCollection) protected function GetItem(Index: Integer): TIdImapMessagePart; procedure SetItem(Index: Integer; const Value: TIdImapMessagePart); public constructor Create(AOwner: TPersistent); reintroduce; function Add: TIdImapMessagePart; reintroduce; property Items[Index: Integer]: TIdImapMessagePart read GetItem write SetItem; default; end; {CCD: Added to parse out responses, because the order in which the responses appear varies between servers. A typical line that gets parsed into this is: * 9 FETCH (UID 1234 FLAGS (\Seen \Deleted)) } TIdIMAPLineStruct = class(TObject) protected HasStar: Boolean; //Line starts with a '*' MessageNumber: string; //Line has a message number (after the *) Command: string; //IMAP servers send back the command they are responding to, e.g. FETCH UID: string; //Sometimes the UID is echoed back Flags: TIdMessageFlagsSet; //Sometimes the FLAGS are echoed back Complete: Boolean; //If false, line has no closing bracket (response continues on following line(s)) ByteCount: integer; //The value in a trailing byte count like {123}, -1 means not present IMAPFunction: string; //E.g. FLAGS IMAPValue: string; //E.g. '(\Seen \Deleted)' end; TIdIMAP4Commands = ( cmdCAPABILITY, cmdNOOP, cmdLOGOUT, cmdAUTHENTICATE, cmdLOGIN, cmdSELECT, cmdEXAMINE, cmdCREATE, cmdDELETE, cmdRENAME, cmdSUBSCRIBE, cmdUNSUBSCRIBE, cmdLIST, cmdLSUB, cmdSTATUS, cmdAPPEND, cmdCHECK, cmdCLOSE, cmdEXPUNGE, cmdSEARCH, cmdFETCH, cmdSTORE, cmdCOPY, cmdUID, cmdXCmd ); {CC3: Add csUnexpectedlyDisconnected for when we receive "Connection reset by peer"} TIdIMAP4ConnectionState = ( csAny, csNonAuthenticated, csAuthenticated, csSelected, csUnexpectedlyDisconnected ); {**************************************************************************** Universal commands CAPABILITY, NOOP, and LOGOUT Authenticated state commands SELECT, EXAMINE, CREATE, DELETE, RENAME, SUBSCRIBE, UNSUBSCRIBE, LIST, LSUB, STATUS, and APPEND Selected state commands CHECK, CLOSE, EXPUNGE, SEARCH, FETCH, STORE, COPY, and UID *****************************************************************************} TIdIMAP4SearchKey = ( skAll, //All messages in the mailbox; the default initial key for ANDing. skAnswered, //Messages with the \Answered flag set. skBcc, //Messages that contain the specified string in the envelope structure's BCC field. skBefore, //Messages whose internal date is earlier than the specified date. skBody, //Messages that contain the specified string in the body of the message. skCc, //Messages that contain the specified string in the envelope structure's CC field. skDeleted, //Messages with the \Deleted flag set. skDraft, //Messages with the \Draft flag set. skFlagged, //Messages with the \Flagged flag set. skFrom, //Messages that contain the specified string in the envelope structure's FROM field. skHeader, //Messages that have a header with the specified field-name (as defined in [RFC-822]) //and that contains the specified string in the [RFC-822] field-body. skKeyword, //Messages with the specified keyword set. skLarger, //Messages with an [RFC-822] size larger than the specified number of octets. skNew, //Messages that have the \Recent flag set but not the \Seen flag. //This is functionally equivalent to "(RECENT UNSEEN)". skNot, //Messages that do not match the specified search key. skOld, //Messages that do not have the \Recent flag set. This is functionally //equivalent to "NOT RECENT" (as opposed to "NOT NEW"). skOn, //Messages whose internal date is within the specified date. skOr, //Messages that match either search key. skRecent, //Messages that have the \Recent flag set. skSeen, //Messages that have the \Seen flag set. skSentBefore,//Messages whose [RFC-822] Date: header is earlier than the specified date. skSentOn, //Messages whose [RFC-822] Date: header is within the specified date. skSentSince, //Messages whose [RFC-822] Date: header is within or later than the specified date. skSince, //Messages whose internal date is within or later than the specified date. skSmaller, //Messages with an [RFC-822] size smaller than the specified number of octets. skSubject, //Messages that contain the specified string in the envelope structure's SUBJECT field. skText, //Messages that contain the specified string in the header or body of the message. skTo, //Messages that contain the specified string in the envelope structure's TO field. skUID, //Messages with unique identifiers corresponding to the specified unique identifier set. skUnanswered,//Messages that do not have the \Answered flag set. skUndeleted, //Messages that do not have the \Deleted flag set. skUndraft, //Messages that do not have the \Draft flag set. skUnflagged, //Messages that do not have the \Flagged flag set. skUnKeyWord, //Messages that do not have the specified keyword set. skUnseen, skGmailRaw, //Gmail-specific extension toaccess full Gmail search syntax skGmailMsgID, //Gmail-specific unique message identifier skGmailThreadID, //Gmail-specific thread identifier skGmailLabels //Gmail-specific labels ); TIdIMAP4SearchKeyArray = array of TIdIMAP4SearchKey; TIdIMAP4SearchRec = record Date: TDateTime; Size: Integer; Text: String; SearchKey : TIdIMAP4SearchKey; end; TIdIMAP4SearchRecArray = array of TIdIMAP4SearchRec; TIdIMAP4StatusDataItem = ( mdMessages, mdRecent, mdUIDNext, mdUIDValidity, mdUnseen ); TIdIMAP4StoreDataItem = ( sdReplace, sdReplaceSilent, sdAdd, sdAddSilent, sdRemove, sdRemoveSilent ); TIdRetrieveOnSelect = ( rsDisabled, rsHeaders, rsMessages ); TIdAlertEvent = procedure(ASender: TObject; const AAlertMsg: String) of object; TIdIMAP4 = class(TIdMessageClient) protected FCmdCounter : Integer; FConnectionState : TIdIMAP4ConnectionState; FMailBox : TIdMailBox; FMailBoxSeparator: Char; FOnAlert: TIdAlertEvent; FRetrieveOnSelect: TIdRetrieveOnSelect; FMilliSecsToWaitToClearBuffer: integer; FMUTF7: TIdMUTF7; FOnWorkForPart: TWorkEvent; FOnWorkBeginForPart: TWorkBeginEvent; FOnWorkEndForPart: TWorkEndEvent; FGreetingBanner : String; {CC7: Added because it may help identify the server} FHasCapa : Boolean; FSASLMechanisms : TIdSASLEntries; FAuthType : TIdIMAP4AuthenticationType; FCapabilities: TStrings; FLineStruct: TIdIMAPLineStruct; function GetReplyClass:TIdReplyClass; override; function GetSupportsTLS: Boolean; override; function CheckConnectionState(AAllowedState: TIdIMAP4ConnectionState): TIdIMAP4ConnectionState; overload; function CheckConnectionState(const AAllowedStates: array of TIdIMAP4ConnectionState): TIdIMAP4ConnectionState; overload; function CheckReplyForCapabilities: Boolean; procedure BeginWorkForPart(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64); procedure DoWorkForPart(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64); procedure EndWorkForPart(ASender: TObject; AWorkMode: TWorkMode); //The following call FMUTF7 but do exception-handling on invalid strings... function DoMUTFEncode(const aString : String): String; function DoMUTFDecode(const aString : String): String; function GetCmdCounter: String; function GetConnectionStateName: String; function GetNewCmdCounter: String; property LastCmdCounter: String read GetCmdCounter; property NewCmdCounter: String read GetNewCmdCounter; { General Functions } function ArrayToNumberStr (const AMsgNumList: array of Integer): String; function MessageFlagSetToStr (const AFlags: TIdMessageFlagsSet): String; procedure StripCRLFs(var AText: string); overload; virtual; //Allow users to optimise procedure StripCRLFs(ASourceStream, ADestStream: TStream); overload; { Parser Functions } procedure ParseImapPart(ABodyStructure: string; AImapParts: TIdImapMessageParts; AThisImapPart: TIdImapMessagePart; AParentImapPart: TIdImapMessagePart; APartNumber: integer); procedure ParseMessagePart(ABodyStructure: string; AMessageParts: TIdMessageParts; AThisMessagePart: TIdMessagePart; AParentMessagePart: TIdMessagePart; APartNumber: integer); procedure ParseBodyStructureResult(ABodyStructure: string; ATheParts: TIdMessageParts; AImapParts: TIdImapMessageParts); procedure ParseBodyStructurePart(APartString: string; AThePart: TIdMessagePart; AImapPart: TIdImapMessagePart); procedure ParseTheLine(ALine: string; APartsList: TStrings); procedure ParseIntoParts(APartString: string; AParams: TStrings); procedure ParseIntoBrackettedQuotedAndUnquotedParts(APartString: string; AParams: TStrings; AKeepBrackets: Boolean); procedure BreakApartParamsInQuotes(const AParam: string; AParsedList: TStrings); function GetNextWord(AParam: string): string; function GetNextQuotedParam(AParam: string; ARemoveQuotes: Boolean): string; procedure ParseExpungeResult (AMB: TIdMailBox; ACmdResultDetails: TStrings); procedure ParseListResult (AMBList: TStrings; ACmdResultDetails: TStrings); procedure ParseLSubResult(AMBList: TStrings; ACmdResultDetails: TStrings); procedure InternalParseListResult(ACmd: string; AMBList: TStrings; ACmdResultDetails: TStrings); procedure ParseMailBoxAttributeString(AAttributesList: String; var AAttributes: TIdMailBoxAttributesSet); procedure ParseMessageFlagString (AFlagsList: String; var AFlags: TIdMessageFlagsSet); procedure ParseSelectResult (AMB: TIdMailBox; ACmdResultDetails: TStrings); procedure ParseStatusResult (AMB: TIdMailBox; ACmdResultDetails: TStrings); procedure ParseSearchResult (AMB: TIdMailBox; ACmdResultDetails: TStrings); procedure ParseEnvelopeResult (AMsg: TIdMessage; ACmdResultStr: String); function ParseLastCmdResult(ALine: string; AExpectedCommand: string; AExpectedIMAPFunction: array of string): Boolean; procedure ParseLastCmdResultButAppendInfo(ALine: string); function InternalRetrieve(const AMsgNum: Integer; AUseUID: Boolean; AUsePeek: Boolean; AMsg: TIdMessage): Boolean; function InternalRetrievePart(const AMsgNum: Integer; const APartNum: string; AUseUID: Boolean; AUsePeek: Boolean; ADestStream: TStream; var ABuffer: {$IFDEF DOTNET}TIdBytes{$ELSE}PByte{$ENDIF}; var ABufferLength: Integer; {NOTE: var args cannot have default params} ADestFileNameAndPath: string = ''; {Do not Localize} AContentTransferEncoding: string = 'text'): Boolean; {Do not Localize} //Retrieves the specified number of headers of the selected mailbox to the specified TIdMessageCollection. function InternalRetrieveHeaders(AMsgList: TIdMessageCollection; ACount: LongInt): Boolean; //Retrieves the specified number of messages of the selected mailbox to the specified TIdMessageCollection. function InternalRetrieveMsgs(AMsgList: TIdMessageCollection; ACount: LongInt): Boolean; function InternalSearchMailBox(const ASearchInfo: array of TIdIMAP4SearchRec; AUseUID: Boolean; const ACharSet: string): Boolean; function ParseBodyStructureSectionAsEquates(AParam: string): string; function ParseBodyStructureSectionAsEquates2(AParam: string): string; function InternalRetrieveText(const AMsgNum: Integer; var AText: string; AUseUID: Boolean; AUsePeek: Boolean; AUseFirstPartInsteadOfText: Boolean): Boolean; function IsCapabilityListed(ACapability: string): Boolean; function InternalRetrieveEnvelope(const AMsgNum: Integer; AMsg: TIdMessage; ADestList: TStrings): Boolean; function UIDInternalRetrieveEnvelope(const AMsgUID: String; AMsg: TIdMessage; ADestList: TStrings): Boolean; function InternalRetrievePartHeader(const AMsgNum: Integer; const APartNum: string; const AUseUID: Boolean; AHeaders: TIdHeaderList): Boolean; function ReceiveHeader(AMsg: TIdMessage; const AAltTerm: string = ''): string; override; {CC3: Need to validate message numbers (relative and UIDs) and part numbers, because otherwise the routines wait for a response that never arrives and so functions never return. Also used for validating part numbers.} function IsNumberValid(const ANumber: Integer): Boolean; function IsUIDValid(const AUID: string): Boolean; function IsImapPartNumberValid(const AUID: string): Boolean; function IsItDigitsAndOptionallyPeriod(const AStr: string; AAllowPeriod: Boolean): Boolean; {CC6: Override IdMessageClient's ReceiveBody due to the responses from some servers...} procedure ReceiveBody(AMsg: TIdMessage; const ADelim: string = '.'); override; {Do not Localize} procedure InitComponent; override; procedure SetMailBox(const Value: TIdMailBox); procedure SetSASLMechanisms(AValue: TIdSASLEntries); public { TIdIMAP4 Commands } destructor Destroy; override; //Requests a listing of capabilities that the server supports... function Capability: Boolean; overload; function Capability(ASlCapability: TStrings): Boolean; overload; function FindHowServerCreatesFolders: TIdIMAP4FolderTreatment; procedure DoAlert(const AMsg: String); property ConnectionState: TIdIMAP4ConnectionState read FConnectionState; property MailBox: TIdMailBox read FMailBox write SetMailBox; {CC7: Two versions of AppendMsg are provided. The first is the normal one you would use. The second allows you to specify an alternative header list which will be used in place of AMsg.Headers. An email client may need the second type if it sends an email via IdSMTP and wants to copy it to a "Sent" IMAP folder. In Indy 10, IdSMTP puts the generated headers in the LastGeneratedHeaders field, so you can use the second version of AppendMsg, passing it AMsg.LastGeneratedHeaders as the AAlternativeHeaders field. Note that IdSMTP puts both the Headers and the ExtraHeaders fields in LastGeneratedHeaders.} function AppendMsg(const AMBName: String; AMsg: TIdMessage; const AFlags: TIdMessageFlagsSet = []): Boolean; overload; function AppendMsg(const AMBName: String; AMsg: TIdMessage; AAlternativeHeaders: TIdHeaderList; const AFlags: TIdMessageFlagsSet = []): Boolean; overload; //The following are used for raw (unparsed) messages in a file or stream... function AppendMsgNoEncodeFromFile(const AMBName: String; ASourceFile: string; const AFlags: TIdMessageFlagsSet = []): Boolean; function AppendMsgNoEncodeFromStream(const AMBName: String; AStream: TStream; const AFlags: TIdMessageFlagsSet = []): Boolean; //Requests a checkpoint of the currently selected mailbox. Does NOTHING on most servers. function CheckMailBox: Boolean; //Checks if the message was read or not. function CheckMsgSeen(const AMsgNum: Integer): Boolean; //Method for logging in manually if you didn't login at connect procedure Login; virtual; //Connects and logins to the IMAP4 account. function Connect(const AAutoLogin: boolean = true): Boolean; reintroduce; virtual; //Closes the current selected mailbox in the account. function CloseMailBox: Boolean; //Creates a new mailbox with the specified name in the account. function CreateMailBox(const AMBName: String): Boolean; //Deletes the specified mailbox from the account. function DeleteMailBox(const AMBName: String): Boolean; //Marks messages for deletion, it will be deleted when the mailbox is purged. function DeleteMsgs(const AMsgNumList: array of Integer): Boolean; //Logouts and disconnects from the IMAP account. procedure Disconnect(ANotifyPeer: Boolean); override; procedure DisconnectNotifyPeer; override; //Examines the specified mailbox and inserts the results to the TIdMailBox provided. function ExamineMailBox(const AMBName: String; AMB: TIdMailBox): Boolean; //Expunges (deletes the marked files) the current selected mailbox in the account. function ExpungeMailBox: Boolean; //Sends a NOOP (No Operation) to keep the account connection with the server alive. procedure KeepAlive; //Returns a list of all the child mailboxes (one level down) to the mailbox supplied. //This should be used when you fear that there are too many mailboxes and the listing of //all of them could be time consuming, so this should be used to retrieve specific mailboxes. function ListInferiorMailBoxes(AMailBoxList, AInferiorMailBoxList: TStrings): Boolean; //Returns a list of all the mailboxes in the user account. function ListMailBoxes(AMailBoxList: TStrings): Boolean; //Returns a list of all the subscribed mailboxes in the user account. function ListSubscribedMailBoxes (AMailBoxList: TStrings): Boolean; //Renames the specified mailbox in the account. function RenameMailBox(const AOldMBName, ANewMBName: String): Boolean; //Searches the current selected mailbox for messages matching the SearchRec and //returns the results to the mailbox SearchResults array. function SearchMailBox(const ASearchInfo: array of TIdIMAP4SearchRec; const ACharSet: string = ''): Boolean; //Selects the current a mailbox in the account. function SelectMailBox(const AMBName: String): Boolean; //Retrieves the status of the indicated mailbox. {CC2: It is pointless calling StatusMailBox with AStatusDataItems set to [] because you are asking the IMAP server to update none of the status flags. Instead, if called with no AStatusDataItems specified, we use the standard flags returned by SelectMailBox, which allows the user to easily check if the mailbox has changed.} function StatusMailBox(const AMBName: String; AMB: TIdMailBox): Boolean; overload; function StatusMailBox(const AMBName: String; AMB: TIdMailBox; const AStatusDataItems: array of TIdIMAP4StatusDataItem): Boolean; overload; //Changes (adds or removes) message flags. function StoreFlags(const AMsgNumList: array of Integer; const AStoreMethod: TIdIMAP4StoreDataItem; const AFlags: TIdMessageFlagsSet): Boolean; //Adds the specified mailbox name to the server's set of "active" or "subscribed" //mailboxes as returned by the LSUB command. function SubscribeMailBox(const AMBName: String): Boolean; {CC8: Added CopyMsg, should have always been there...} function CopyMsg(const AMsgNum: Integer; const AMBName: String): Boolean; //Copies a message from the current selected mailbox to the specified mailbox. {Do not Localize} function CopyMsgs(const AMsgNumList: array of Integer; const AMBName: String): Boolean; //Retrieves a whole message while marking it read. function Retrieve(const AMsgNum: Integer; AMsg: TIdMessage): Boolean; //Retrieves a whole message "raw" and saves it to file, while marking it read. function RetrieveNoDecodeToFile(const AMsgNum: Integer; ADestFile: string): Boolean; function RetrieveNoDecodeToStream(const AMsgNum: Integer; AStream: TStream): Boolean; //Retrieves all envelope of the selected mailbox to the specified TIdMessageCollection. function RetrieveAllEnvelopes(AMsgList: TIdMessageCollection): Boolean; //Retrieves all headers of the selected mailbox to the specified TIdMessageCollection. function RetrieveAllHeaders(AMsgList: TIdMessageCollection): Boolean; //Retrieves the first NN headers of the selected mailbox to the specified TIdMessageCollection. function RetrieveFirstHeaders(AMsgList: TIdMessageCollection; ACount: LongInt): Boolean; //Retrieves all messages of the selected mailbox to the specified TIdMessageCollection. function RetrieveAllMsgs(AMsgList: TIdMessageCollection): Boolean; //Retrieves the first NN messages of the selected mailbox to the specified TIdMessageCollection. function RetrieveFirstMsgs(AMsgList: TIdMessageCollection; ACount: LongInt): Boolean; //Retrieves the message envelope, parses it, and discards the envelope. function RetrieveEnvelope(const AMsgNum: Integer; AMsg: TIdMessage): Boolean; //Retrieves the message envelope into a TStringList but does NOT parse it. function RetrieveEnvelopeRaw(const AMsgNum: Integer; ADestList: TStrings): Boolean; //Returnes the message flag values. function RetrieveFlags(const AMsgNum: Integer; var AFlags: TIdMessageFlagsSet): Boolean; {CC2: Following added for retrieving individual parts of a message...} function InternalRetrieveStructure(const AMsgNum: Integer; AMsg: TIdMessage; AParts: TIdImapMessageParts): Boolean; //Retrieve only the message structure (this tells you what parts are in the message). function RetrieveStructure(const AMsgNum: Integer; AMsg: TIdMessage): Boolean; overload; function RetrieveStructure(const AMsgNum: Integer; AParts: TIdImapMessageParts): Boolean; overload; {CC2: Following added for retrieving individual parts of a message...} {Retrieve a specific individual part of a message to a stream (part/sub-part like '2' or '2.3')...} function RetrievePart(const AMsgNum: Integer; const APartNum: string; ADestStream: TStream; AContentTransferEncoding: string = 'text'): Boolean; overload; {Do not Localize} {Retrieve a specific individual part of a message where part is an integer or sub-part like '2.3'...} function RetrievePart(const AMsgNum: Integer; const APartNum: string; var ABuffer: {$IFDEF DOTNET}TIdBytes{$ELSE}PByte{$ENDIF}; var ABufferLength: Integer; AContentTransferEncoding: string = 'text'): Boolean; overload; {Do not Localize} {Retrieve a specific individual part of a message where part is an integer (for backward compatibility)...} function RetrievePart(const AMsgNum: Integer; const APartNum: Integer; var ABuffer: {$IFDEF DOTNET}TIdBytes{$ELSE}PByte{$ENDIF}; var ABufferLength: Integer; AContentTransferEncoding: string = 'text'): Boolean; overload; {Do not Localize} {Retrieve a specific individual part of a message to a stream (part/sub-part like '2' or '2.3') without marking the message as "read"...} function RetrievePartPeek(const AMsgNum: Integer; const APartNum: string; ADestStream: TStream; AContentTransferEncoding: string = 'text'): Boolean; overload; {Do not Localize} {Retrieve a specific individual part of a message where part is an integer or sub-part like '2.3' without marking the message as "read"...} function RetrievePartPeek(const AMsgNum: Integer; const APartNum: string; var ABuffer: {$IFDEF DOTNET}TIdBytes{$ELSE}PByte{$ENDIF}; var ABufferLength: Integer; AContentTransferEncoding: string = 'text'): Boolean; overload; {Do not Localize} {Retrieve a specific individual part of a message where part is an integer (for backward compatibility) without marking the message as "read"...} function RetrievePartPeek(const AMsgNum: Integer; const APartNum: Integer; var ABuffer: {$IFDEF DOTNET}TIdBytes{$ELSE}PByte{$ENDIF}; var ABufferLength: Integer; AContentTransferEncoding: string = 'text'): Boolean; overload; {Do not Localize} {CC2: Following added for retrieving individual parts of a message...} {Retrieve a specific individual part of a message where part is an integer (for backward compatibility)...} function RetrievePartToFile(const AMsgNum: Integer; const APartNum: Integer; ALength: Integer; ADestFileNameAndPath: string; AContentTransferEncoding: string): Boolean; overload; {Retrieve a specific individual part of a message where part is an integer or sub-part like '2.3'...} function RetrievePartToFile(const AMsgNum: Integer; const APartNum: string; ALength: Integer; ADestFileNameAndPath: string; AContentTransferEncoding: string): Boolean; overload; {CC2: Following added for retrieving individual parts of a message...} {Retrieve a specific individual part of a message where part is an integer (for backward compatibility) without marking the message as "read"...} function RetrievePartToFilePeek(const AMsgNum: Integer; const APartNum: Integer; ALength: Integer; ADestFileNameAndPath: string; AContentTransferEncoding: string): Boolean; overload; {Retrieve a specific individual part of a message where part is an integer or sub-part like '2.3' without marking the message as "read"...} function RetrievePartToFilePeek(const AMsgNum: Integer; const APartNum: string; ALength: Integer; ADestFileNameAndPath: string; AContentTransferEncoding: string): Boolean; overload; {CC3: Following added for retrieving the text-only part of a message...} function RetrieveText(const AMsgNum: Integer; var AText: string): Boolean; {CC4: An alternative for retrieving the text-only part of a message which may give a better response from some IMAP implementations...} function RetrieveText2(const AMsgNum: Integer; var AText: string): Boolean; {CC3: Following added for retrieving the text-only part of a message without marking the message as "read"...} function RetrieveTextPeek(const AMsgNum: Integer; var AText: string): Boolean; function RetrieveTextPeek2(const AMsgNum: Integer; var AText: string): Boolean; //Retrieves only the message header. function RetrieveHeader (const AMsgNum: Integer; AMsg: TIdMessage): Boolean; //CCD: Retrieve the header for a particular part... function RetrievePartHeader(const AMsgNum: Integer; const APartNum: string; AHeaders: TIdHeaderList): Boolean; //Retrives the current selected mailbox size. function RetrieveMailBoxSize: Integer; //Returnes the message size. function RetrieveMsgSize(const AMsgNum: Integer): Integer; //Retrieves a whole message while keeping its Seen flag unchanged //(preserving the previous value). function RetrievePeek(const AMsgNum: Integer; AMsg: TIdMessage): Boolean; //Get the UID corresponding to a relative message number. function GetUID(const AMsgNum: Integer; var AUID: string): Boolean; //Copies a message from the current selected mailbox to the specified mailbox. function UIDCopyMsg(const AMsgUID: String; const AMBName: String): Boolean; {CC8: Added UID version of CopyMsgs...} function UIDCopyMsgs(const AMsgUIDList: TStrings; const AMBName: String): Boolean; //Checks if the message was read or not. function UIDCheckMsgSeen(const AMsgUID: String): Boolean; //Marks a message for deletion, it will be deleted when the mailbox will be purged. function UIDDeleteMsg(const AMsgUID: String): Boolean; function UIDDeleteMsgs(const AMsgUIDList: array of String): Boolean; //Retrieves all envelope and UID of the selected mailbox to the specified TIdMessageCollection. function UIDRetrieveAllEnvelopes(AMsgList: TIdMessageCollection): Boolean; //Retrieves a whole message while marking it read. function UIDRetrieve(const AMsgUID: String; AMsg: TIdMessage): Boolean; //Retrieves a whole message "raw" and saves it to file, while marking it read. function UIDRetrieveNoDecodeToFile(const AMsgUID: String; ADestFile: string): Boolean; function UIDRetrieveNoDecodeToStream(const AMsgUID: String; AStream: TStream): Boolean; //Retrieves the message envelope, parses it, and discards the envelope. function UIDRetrieveEnvelope(const AMsgUID: String; AMsg: TIdMessage): Boolean; //Retrieves the message envelope into a TStringList but does NOT parse it. function UIDRetrieveEnvelopeRaw(const AMsgUID: String; ADestList: TStrings): Boolean; //Returnes the message flag values. function UIDRetrieveFlags(const AMsgUID: String; var AFlags: TIdMessageFlagsSet): Boolean; {CC2: Following added for retrieving individual parts of a message...} function UIDInternalRetrieveStructure(const AMsgUID: String; AMsg: TIdMessage; AParts: TIdImapMessageParts): Boolean; //Retrieve only the message structure (this tells you what parts are in the message). function UIDRetrieveStructure(const AMsgUID: String; AMsg: TIdMessage): Boolean; overload; function UIDRetrieveStructure(const AMsgUID: String; AParts: TIdImapMessageParts): Boolean; overload; {Retrieve a specific individual part of a message to a stream (part/sub-part like '2' or '2.3')...} function UIDRetrievePart(const AMsgUID: String; const APartNum: string; var ADestStream: TStream; AContentTransferEncoding: string = 'text'): Boolean; overload; {Do not Localize} {Retrieve a specific individual part of a message where part is an integer or sub-part like '2.3'...} function UIDRetrievePart(const AMsgUID: String; const APartNum: string; var ABuffer: {$IFDEF DOTNET}TIdBytes{$ELSE}PByte{$ENDIF}; var ABufferLength: Integer; AContentTransferEncoding: string = 'text'): Boolean; overload; {Do not Localize} {Retrieve a specific individual part of a message where part is an integer (for backward compatibility)...} function UIDRetrievePart(const AMsgUID: String; const APartNum: Integer; var ABuffer: {$IFDEF DOTNET}TIdBytes{$ELSE}PByte{$ENDIF}; var ABufferLength: Integer; AContentTransferEncoding: string = 'text'): Boolean; overload; {Do not Localize} {Retrieve a specific individual part of a message to a stream (part/sub-part like '2' or '2.3') without marking the message as "read"...} function UIDRetrievePartPeek(const AMsgUID: String; const APartNum: string; var ADestStream: TStream; AContentTransferEncoding: string = 'text'): Boolean; overload; {Do not Localize} {Retrieve a specific individual part of a message where part is an integer or sub-part like '2.3'...} function UIDRetrievePartPeek(const AMsgUID: String; const APartNum: string; var ABuffer: {$IFDEF DOTNET}TIdBytes{$ELSE}PByte{$ENDIF}; var ABufferLength: Integer; AContentTransferEncoding: string = 'text'): Boolean; overload; {Do not Localize} {Retrieve a specific individual part of a message where part is an integer (for backward compatibility)...} function UIDRetrievePartPeek(const AMsgUID: String; const APartNum: Integer; var ABuffer: {$IFDEF DOTNET}TIdBytes{$ELSE}PByte{$ENDIF}; var ABufferLength: Integer; AContentTransferEncoding: string = 'text'): Boolean; overload; {Do not Localize} {Retrieve a specific individual part of a message where part is an integer (for backward compatibility)...} function UIDRetrievePartToFile(const AMsgUID: String; const APartNum: Integer; ALength: Integer; ADestFileNameAndPath: string; AContentTransferEncoding: string): Boolean; overload; {Retrieve a specific individual part of a message where part is an integer or sub-part like '2.3'...} function UIDRetrievePartToFile(const AMsgUID: String; const APartNum: string; ALength: Integer; ADestFileNameAndPath: string; AContentTransferEncoding: string): Boolean; overload; {Retrieve a specific individual part of a message where part is an integer (for backward compatibility)...} function UIDRetrievePartToFilePeek(const AMsgUID: String; const APartNum: Integer; ALength: Integer; ADestFileNameAndPath: string; AContentTransferEncoding: string): Boolean; overload; {Retrieve a specific individual part of a message where part is an integer or sub-part like '2.3'...} function UIDRetrievePartToFilePeek(const AMsgUID: String; const APartNum: string; ALength: Integer; ADestFileNameAndPath: string; AContentTransferEncoding: string): Boolean; overload; {Following added for retrieving the text-only part of a message...} function UIDRetrieveText(const AMsgUID: String; var AText: string): Boolean; function UIDRetrieveText2(const AMsgUID: String; var AText: string): Boolean; {Following added for retrieving the text-only part of a message without marking the message as read...} function UIDRetrieveTextPeek(const AMsgUID: String; var AText: string): Boolean; function UIDRetrieveTextPeek2(const AMsgUID: String; var AText: string): Boolean; //Retrieves only the message header. function UIDRetrieveHeader(const AMsgUID: String; AMsg: TIdMessage): Boolean; //Retrieve the header for a particular part... function UIDRetrievePartHeader(const AMsgUID: String; const APartNum: string; AHeaders: TIdHeaderList): Boolean; //Retrives the current selected mailbox size. function UIDRetrieveMailBoxSize: Integer; //Returnes the message size. function UIDRetrieveMsgSize(const AMsgUID: String): Integer; //Retrieves a whole message while keeping its Seen flag untucked //(preserving the previous value). function UIDRetrievePeek(const AMsgUID: String; AMsg: TIdMessage): Boolean; //Searches the current selected mailbox for messages matching the SearchRec and //returnes the results as UIDs to the mailbox SearchResults array. function UIDSearchMailBox(const ASearchInfo: array of TIdIMAP4SearchRec; const ACharSet: String = ''): Boolean; //Changes (adds or removes) message flags. function UIDStoreFlags(const AMsgUID: String; const AStoreMethod: TIdIMAP4StoreDataItem; const AFlags: TIdMessageFlagsSet): Boolean; overload; function UIDStoreFlags(const AMsgUIDList: array of String; const AStoreMethod: TIdIMAP4StoreDataItem; const AFlags: TIdMessageFlagsSet): Boolean; overload; //Removes the specified mailbox name from the server's set of "active" or "subscribed" //mailboxes as returned by the LSUB command. function UnsubscribeMailBox(const AMBName: String): Boolean; { IdTCPConnection Commands } function GetInternalResponse(const ATag: String; AExpectedResponses: array of String; ASingleLineMode: Boolean; ASingleLineMayBeSplit: Boolean = False): string; reintroduce; overload; function GetResponse: string; reintroduce; overload; function SendCmd(const AOut: string; AExpectedResponses: array of String; ASingleLineMode: Boolean = False; ASingleLineMayBeSplit: Boolean = False): string; reintroduce; overload; function SendCmd(const ATag, AOut: string; AExpectedResponses: array of String; ASingleLineMode: Boolean = False; ASingleLineMayBeSplit: Boolean = False): string; overload; function ReadLnWait: string; {$IFDEF HAS_DEPRECATED}deprecated{$IFDEF HAS_DEPRECATED_MSG} 'Use IOHandler.ReadLnWait()'{$ENDIF};{$ENDIF} procedure WriteLn(const AOut: string = ''); {$IFDEF HAS_DEPRECATED}deprecated{$IFDEF HAS_DEPRECATED_MSG} 'Use IOHandler.WriteLn()'{$ENDIF};{$ENDIF} { IdTCPConnection Commands } published property OnAlert: TIdAlertEvent read FOnAlert write FOnAlert; property Password; property RetrieveOnSelect: TIdRetrieveOnSelect read FRetrieveOnSelect write FRetrieveOnSelect default rsDisabled; property Port default IdPORT_IMAP4; property Username; property MailBoxSeparator: Char read FMailBoxSeparator write FMailBoxSeparator default '/'; {Do not Localize} {GreetingBanner added because it may help identify the server...} property GreetingBanner : string read FGreetingBanner; property Host; property UseTLS; property SASLMechanisms : TIdSASLEntries read FSASLMechanisms write SetSASLMechanisms; property AuthType : TIdIMAP4AuthenticationType read FAuthType write FAuthType default DEF_IMAP4_AUTH; property MilliSecsToWaitToClearBuffer: integer read FMilliSecsToWaitToClearBuffer write FMilliSecsToWaitToClearBuffer; {The following is the OnWork property for use when retrieving PARTS of a message. It is also used for AppendMsg and Retrieve. This is in addition to the normal OnWork property, which is exposed by TIdIMAP4, but which is only activated during IMAP sending & receiving of commands (subject to the general OnWork caveats, i.e. it is only called during certain methods, note OnWork[Begin][End] are all only called in the methods AllData(), PerformCapture() and Read/WriteStream() ). When a PART of a message is processed, use this for progress notification of retrieval of IMAP parts, such as retrieving attachments. OnWorkBegin and OnWorkEnd are not exposed, because they won't be activated during the processing of a part.} property OnWorkForPart: TWorkEvent read FOnWorkForPart write FOnWorkForPart; property OnWorkBeginForPart: TWorkBeginEvent read FOnWorkBeginForPart write FOnWorkBeginForPart; property OnWorkEndForPart: TWorkEndEvent read FOnWorkEndForPart write FOnWorkEndForPart; end; implementation uses //facilitate inlining on {$IFDEF KYLIXCOMPAT} Libc, {$IFDEF MACOSX} Posix.Unistd, {$ENDIF} {$ENDIF} //facilitate inlining only. {$IFDEF WINDOWS} {$IFDEF USE_INLINE} Windows, {$ELSE} //facilitate inlining only. {$IFDEF VCL_2009_OR_ABOVE} Windows, {$ENDIF} {$ENDIF} {$ENDIF} {$IFDEF DOTNET} {$IFDEF USE_INLINE} System.IO, {$ENDIF} {$ENDIF} {$IFDEF DOTNET} IdStreamNET, {$ELSE} IdStreamVCL, {$ENDIF} IdCoder, IdEMailAddress, IdResourceStrings, IdExplicitTLSClientServerBase, IdGlobalProtocols, IdExceptionCore, IdStack, IdStackConsts, IdStream, IdTCPStream, IdText, IdAttachment, IdResourceStringsProtocols, IdBuffer, IdAttachmentMemory, IdReplyIMAP4, IdTCPConnection, IdSSL, IdSASL, SysUtils; type TIdIMAP4FetchDataItem = ( fdAll, //Macro equivalent to: (FLAGS INTERNALDATE RFC822.SIZE ENVELOPE) fdBody, //Non-extensible form of BODYSTRUCTURE. fdBodyExtensible, fdBodyPeek, fdBodyStructure, //The [MIME-IMB] body structure of the message. This //is computed by the server by parsing the [MIME-IMB] //header fields in the [RFC-822] header and [MIME-IMB] headers. fdEnvelope, //The envelope structure of the message. This is //computed by the server by parsing the [RFC-822] //header into the component parts, defaulting various //fields as necessary. fdFast, //Macro equivalent to: (FLAGS INTERNALDATE RFC822.SIZE) fdFlags, //The flags that are set for this message. fdFull, //Macro equivalent to: (FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODY) fdInternalDate, //The internal date of the message. fdRFC822, //Functionally equivalent to BODY[], differing in the //syntax of the resulting untagged FETCH data (RFC822 //is returned). fdRFC822Header, //Functionally equivalent to BODY.PEEK[HEADER], //differing in the syntax of the resulting untagged //FETCH data (RFC822.HEADER is returned). fdRFC822Size, //The [RFC-822] size of the message. fdRFC822Text, //Functionally equivalent to BODY[TEXT], differing in //the syntax of the resulting untagged FETCH data //(RFC822.TEXT is returned). fdHeader, //CC: Added to get the header of a part fdUID, //The unique identifier for the message. fdGmailMsgID, //Gmail-specific unique identifier for the message. fdGmailThreadID, //Gmail-specific thread identifier for the message. fdGmailLabels //Gmail-specific labels for the message. ); const IMAP4Commands : array [TIdIMAP4Commands] of String = ( { Client Commands - Any State} 'CAPABILITY', {Do not Localize} 'NOOP', {Do not Localize} 'LOGOUT', {Do not Localize} { Client Commands - Non Authenticated State} 'AUTHENTICATE', {Do not Localize} 'LOGIN', {Do not Localize} { Client Commands - Authenticated State} 'SELECT', {Do not Localize} 'EXAMINE', {Do not Localize} 'CREATE', {Do not Localize} 'DELETE', {Do not Localize} 'RENAME', {Do not Localize} 'SUBSCRIBE', {Do not Localize} 'UNSUBSCRIBE', {Do not Localize} 'LIST', {Do not Localize} 'LSUB', {Do not Localize} 'STATUS', {Do not Localize} 'APPEND', {Do not Localize} { Client Commands - Selected State} 'CHECK', {Do not Localize} 'CLOSE', {Do not Localize} 'EXPUNGE', {Do not Localize} 'SEARCH', {Do not Localize} 'FETCH', {Do not Localize} 'STORE', {Do not Localize} 'COPY', {Do not Localize} 'UID', {Do not Localize} { Client Commands - Experimental/ Expansion} 'X' {Do not Localize} ); IMAP4FetchDataItem : array [TIdIMAP4FetchDataItem] of String = ( 'ALL', {Do not Localize} //Macro equivalent to: (FLAGS INTERNALDATE RFC822.SIZE ENVELOPE) 'BODY', {Do not Localize} //Non-extensible form of BODYSTRUCTURE. 'BODY[%s]<%s>', {Do not Localize} 'BODY.PEEK[]', {Do not Localize} 'BODYSTRUCTURE', {Do not Localize} //The [MIME-IMB] body structure of the message. This //is computed by the server by parsing the [MIME-IMB] //header fields in the [RFC-822] header and [MIME-IMB] headers. 'ENVELOPE', {Do not Localize} //The envelope structure of the message. This is //computed by the server by parsing the [RFC-822] //header into the component parts, defaulting various //fields as necessary. 'FAST', {Do not Localize} //Macro equivalent to: (FLAGS INTERNALDATE RFC822.SIZE) 'FLAGS', {Do not Localize} //The flags that are set for this message. 'FULL', {Do not Localize} //Macro equivalent to: (FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODY) 'INTERNALDATE', {Do not Localize} //The internal date of the message. 'RFC822', {Do not Localize} //Functionally equivalent to BODY[], differing in the //syntax of the resulting untagged FETCH data (RFC822 //is returned). 'RFC822.HEADER', {Do not Localize} //Functionally equivalent to BODY.PEEK[HEADER], //differing in the syntax of the resulting untagged //FETCH data (RFC822.HEADER is returned). 'RFC822.SIZE', {Do not Localize} //The [RFC-822] size of the message. 'RFC822.TEXT', {Do not Localize} //Functionally equivalent to BODY[TEXT], differing in //the syntax of the resulting untagged FETCH data //(RFC822.TEXT is returned). 'HEADER', {Do not Localize} //CC: Added to get the header of a part 'UID', {Do not Localize} //The unique identifier for the message. 'X-GM-MSGID', {Do not Localize} //Gmail-specific unique identifier for the message. 'X-GM-THRID', {Do not Localize} //Gmail-specific thread identifier for the message. 'X-GM-LABELS' {Do not Localize} //Gmail-specific labels for the message. ); IMAP4SearchKeys : array [TIdIMAP4SearchKey] of String = ( 'ALL', {Do not Localize} //All messages in the mailbox; the default initial key for ANDing. 'ANSWERED', {Do not Localize} //Messages with the \Answered flag set. 'BCC', {Do not Localize} //Messages that contain the specified string in the envelope structure's BCC field. 'BEFORE', {Do not Localize} //Messages whose internal date is earlier than the specified date. 'BODY', {Do not Localize} //Messages that contain the specified string in the body of the message. 'CC', {Do not Localize} //Messages that contain the specified string in the envelope structure's CC field. 'DELETED', {Do not Localize} //Messages with the \Deleted flag set. 'DRAFT', {Do not Localize} //Messages with the \Draft flag set. 'FLAGGED', {Do not Localize} //Messages with the \Flagged flag set. 'FROM', {Do not Localize} //Messages that contain the specified string in the envelope structure's FROM field. 'HEADER', {Do not Localize} //Messages that have a header with the specified field-name (as defined in [RFC-822]) //and that contains the specified string in the [RFC-822] field-body. 'KEYWORD', {Do not Localize} //Messages with the specified keyword set. 'LARGER', {Do not Localize} //Messages with an [RFC-822] size larger than the specified number of octets. 'NEW', {Do not Localize} //Messages that have the \Recent flag set but not the \Seen flag. //This is functionally equivalent to "(RECENT UNSEEN)". 'NOT', {Do not Localize} //Messages that do not match the specified search key. 'OLD', {Do not Localize} //Messages that do not have the \Recent flag set. This is functionally //equivalent to "NOT RECENT" (as opposed to "NOT NEW"). 'ON', {Do not Localize} //Messages whose internal date is within the specified date. 'OR', {Do not Localize} //Messages that match either search key. 'RECENT', {Do not Localize} //Messages that have the \Recent flag set. 'SEEN', {Do not Localize} //Messages that have the \Seen flag set. 'SENTBEFORE',{Do not Localize} //Messages whose [RFC-822] Date: header is earlier than the specified date. 'SENTON', {Do not Localize} //Messages whose [RFC-822] Date: header is within the specified date. 'SENTSINCE', {Do not Localize} //Messages whose [RFC-822] Date: header is within or later than the specified date. 'SINCE', {Do not Localize} //Messages whose internal date is within or later than the specified date. 'SMALLER', {Do not Localize} //Messages with an [RFC-822] size smaller than the specified number of octets. 'SUBJECT', {Do not Localize} //Messages that contain the specified string in the envelope structure's SUBJECT field. 'TEXT', {Do not Localize} //Messages that contain the specified string in the header or body of the message. 'TO', {Do not Localize} //Messages that contain the specified string in the envelope structure's TO field. 'UID', {Do not Localize} //Messages with unique identifiers corresponding to the specified unique identifier set. 'UNANSWERED',{Do not Localize} //Messages that do not have the \Answered flag set. 'UNDELETED', {Do not Localize} //Messages that do not have the \Deleted flag set. 'UNDRAFT', {Do not Localize} //Messages that do not have the \Draft flag set. 'UNFLAGGED', {Do not Localize} //Messages that do not have the \Flagged flag set. 'UNKEYWORD', {Do not Localize} //Messages that do not have the specified keyword set. 'UNSEEN', {Do not Localize} 'X-GM-RAW', {Do not Localize} //Gmail extension to SEARCH command to allow full access to Gmail search syntax 'X-GM-MSGID',{Do not Localize} //Gmail extension to SEARCH command to allow access to Gmail message identifier 'X-GM-THRID',{Do not Localize} //Gmail extension to SEARCH command to allow access to Gmail thread identifier 'X-GM-LABELS'{Do not Localize} //Gmail extension to SEARCH command to allow access to Gmail labels ); IMAP4StoreDataItem : array [TIdIMAP4StoreDataItem] of String = ( 'FLAGS', {Do not Localize} 'FLAGS.SILENT', {Do not Localize} '+FLAGS', {Do not Localize} '+FLAGS.SILENT', {Do not Localize} '-FLAGS', {Do not Localize} '-FLAGS.SILENT' {Do not Localize} ); IMAP4StatusDataItem : array [TIdIMAP4StatusDataItem] of String = ( 'MESSAGES', {Do not Localize} 'RECENT', {Do not Localize} 'UIDNEXT', {Do not Localize} 'UIDVALIDITY', {Do not Localize} 'UNSEEN' {Do not Localize} ); function IMAPQuotedStr(const S: String): String; begin Result := '"' + StringsReplace(S, ['\', '"'], ['\\', '\"']) + '"'; {Do not Localize} end; { TIdSASLEntriesIMAP4 } // RLebeau 2/8/2013 - TIdSASLEntries.LoginSASL() uses TIdTCPConnection.SendCmd() // but TIdIMAP4 does not override the necessary virtuals to make that SendCmd() // work correctly with IMAP. TIdIMAP reintroduces its own SendCmd() implementation, // which TIdSASLEntries does not call. Until that can be changed, we will have // to send the IMAP 'AUTHENTICATE' command manually! Doing it this way so as // not to introduce an interface change that breaks backwards compatibility... function CheckStrFail(const AStr : String; const AOk, ACont: array of string) : Boolean; begin Result := (PosInStrArray(AStr, AOk) = -1) and (PosInStrArray(AStr, ACont) = -1); end; function PerformSASLLogin_IMAP(ASASL: TIdSASL; AEncoder: TIdEncoder; ADecoder: TIdDecoder; AClient : TIdIMAP4): Boolean; const AOkReplies: array[0..0] of string = (IMAP_OK); AContinueReplies: array[0..0] of string = (IMAP_CONT); var S: String; begin Result := False; // TODO: support 'SASL-IR' extension... AClient.SendCmd(AClient.NewCmdCounter, 'AUTHENTICATE ' + String(ASASL.ServiceName), [], True); {Do not Localize} if CheckStrFail(AClient.LastCmdResult.Code, AOkReplies, AContinueReplies) then begin Exit; // this mechanism is not supported end; if (PosInStrArray(AClient.LastCmdResult.Code, AOkReplies) > -1) then begin Result := True; Exit; // we've authenticated successfully :) end; S := ADecoder.DecodeString(TrimRight(TIdReplyIMAP4(AClient.LastCmdResult).Extra.Text)); S := ASASL.StartAuthenticate(S, AClient.Host, IdGSKSSN_imap); AClient.IOHandler.WriteLn(AEncoder.Encode(S)); AClient.GetInternalResponse('', [], True); if CheckStrFail(AClient.LastCmdResult.Code, AOkReplies, AContinueReplies) then begin ASASL.FinishAuthenticate; Exit; end; while PosInStrArray(AClient.LastCmdResult.Code, AContinueReplies) > -1 do begin S := ADecoder.DecodeString(TrimRight(TIdReplyIMAP4(AClient.LastCmdResult).Extra.Text)); S := ASASL.ContinueAuthenticate(S, AClient.Host, IdGSKSSN_imap); AClient.IOHandler.WriteLn(AEncoder.Encode(S)); AClient.GetInternalResponse('', [], True); if CheckStrFail(AClient.LastCmdResult.Code, AOkReplies, AContinueReplies) then begin ASASL.FinishAuthenticate; Exit; end; end; Result := (PosInStrArray(AClient.LastCmdResult.Code, AOkReplies) > -1); ASASL.FinishAuthenticate; end; type TIdSASLEntriesIMAP4 = class(TIdSASLEntries) public procedure LoginSASL_IMAP(AClient: TIdIMAP4); end; procedure TIdSASLEntriesIMAP4.LoginSASL_IMAP(AClient: TIdIMAP4); var i : Integer; LE : TIdEncoderMIME; LD : TIdDecoderMIME; LSupportedSASL : TStrings; LSASLList: TList; LSASL : TIdSASL; LError : TIdReply; function SetupErrorReply: TIdReply; begin Result := TIdReplyClass(AClient.LastCmdResult.ClassType).Create(nil); Result.Assign(AClient.LastCmdResult); end; begin // make sure the collection is not empty CheckIfEmpty; //create a list of mechanisms that both parties support LSASLList := TList.Create; try LSupportedSASL := TStringList.Create; try ParseCapaReplyToList(AClient.FCapabilities, LSupportedSASL, 'AUTH'); {Do not Localize} for i := Count-1 downto 0 do begin LSASL := Items[i].SASL; if LSASL <> nil then begin if not LSASL.IsAuthProtocolAvailable(LSupportedSASL) then begin Continue; end; if LSASLList.IndexOf(LSASL) = -1 then begin LSASLList.Add(LSASL); end; end; end; finally FreeAndNil(LSupportedSASL); end; if LSASLList.Count = 0 then begin EIdSASLNotSupported.Toss(RSSASLNotSupported); end; //now do it LE := nil; try LD := nil; try LError := nil; try for i := 0 to LSASLList.Count-1 do begin LSASL := TIdSASL(LSASLList.Items[i]); if not LSASL.IsReadyToStart then begin Continue; end; if not Assigned(LE) then begin LE := TIdEncoderMIME.Create(nil); end; if not Assigned(LD) then begin LD := TIdDecoderMIME.Create(nil); end; if PerformSASLLogin_IMAP(LSASL, LE, LD, AClient) then begin Exit; end; if not Assigned(LError) then begin LError := SetupErrorReply; end; end; if Assigned(LError) then begin LError.RaiseReplyError; end else begin EIdSASLNotReady.Toss(RSSASLNotReady); end; finally FreeAndNil(LError); end; finally FreeAndNil(LD); end; finally FreeAndNil(LE); end; finally FreeAndNil(LSASLList); end; end; { TIdIMAP4WorkHelper } type TIdIMAP4WorkHelper = class(TIdComponent) protected fIMAP4: TIdIMAP4; fOldTarget: TIdComponent; public constructor Create(AIMAP4: TIdIMAP4); reintroduce; destructor Destroy; override; end; constructor TIdIMAP4WorkHelper.Create(AIMAP4: TIdIMAP4); begin inherited Create(nil); fIMAP4 := AIMAP4; fOldTarget := fIMAP4.WorkTarget; fIMAP4.WorkTarget := Self; Self.OnWorkBegin := fIMAP4.BeginWorkForPart; Self.OnWork := fIMAP4.DoWorkForPart; Self.OnWorkEnd := fIMAP4.EndWorkForPart; end; destructor TIdIMAP4WorkHelper.Destroy; begin fIMAP4.WorkTarget := fOldTarget; inherited Destroy; end; { TIdEMUTF7 } const b64Chars : array[0..63] of AnsiChar = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,'; {Do not Localize} b64Index : array [0..127] of Integer = ( -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, // 16 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, // 32 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,63,-1,-1,-1, // 48 52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1, // 64 -1,00,01,02,03,04,05,06,07,08,09,10,11,12,13,14, // 80 15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1, // 96 -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40, // 112 41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1 // 128 ); b64Table : array[0..127] of Integer = ( $FF,$FF,$FF,$FF, $FF,$FF,$FF,$FF, $FF,$FF,$FF,$FF, $FF,$FF,$FF,$FF, // 16 $FF,$FF,$FF,$FF, $FF,$FF,$FF,$FF, $FF,$FF,$FF,$FF, $FF,$FF,$FF,$FF, // 32 $20,$21,$22,$23, $24,$25,$FF,$27, $28,$29,$2A,$2B, $2C,$2D,$2E,$2F, // 48 $30,$31,$32,$33, $34,$35,$36,$37, $38,$39,$3A,$3B, $3C,$3D,$3E,$3F, // 64 $40,$41,$42,$43, $44,$45,$46,$47, $48,$49,$4A,$4B, $4C,$4D,$4E,$4F, // 80 $50,$51,$52,$53, $54,$55,$56,$57, $58,$59,$5A,$5B, $5C,$5D,$5E,$5F, // 96 $60,$61,$62,$63, $64,$65,$66,$67, $68,$69,$6A,$6B, $6C,$6D,$6E,$6F, // 112 $70,$71,$72,$73, $74,$75,$76,$77, $78,$79,$7A,$7B, $7C,$7D,$7E,$FF);// 128 // TODO: re-write this to derive from IdCoder3To4.pas or IdCoderMIME.pas classes... function TIdMUTF7.Encode(const aString: TIdUnicodeString): AnsiString; { -- MUTF7Encode ------------------------------------------------------------- PRE: nothing POST: returns a string encoded as described in IETF RFC 3501, section 5.1.3 based upon RFC 2152 2004-03-02 roman puls: speed improvements of around 2000 percent due to replacement of pchar/while loops to delphi-style string/for loops. Minor changes for '&' handling. Delphi 8 compatible. 2004-02-29 roman puls: initial version ---} var c : Word; bitBuf : Cardinal; bitShift : Integer; x : Integer; escaped : Boolean; begin Result := ''; escaped := False; bitShift := 0; bitBuf := 0; for x := 1 to Length(aString) do begin c := Word(aString[x]); // c must be < 128 _and_ in table b64table if (c <= $7f) and (b64Table[c] <> $FF) or (aString[x] = '&') then begin // we can directly encode that char if escaped then begin if (bitShift > 0) then begin // flush bitbuffer if needed Result := Result + b64Chars[bitBuf shl (6 - bitShift) and $3F]; end; Result := Result + '-'; // leave escape sequence escaped := False; end; if (aString[x] = '&') then begin // escape special char "&" Result := Result + '&-'; end else begin Result := Result + AnsiChar(c); // store direct translated char end; end else begin if not escaped then begin Result := Result + '&'; bitShift := 0; bitBuf := 0; escaped := True; end; bitbuf := (bitBuf shl 16) or c; // shift and store new bye Inc(bitShift, 16); while (bitShift >= 6) do begin // flush buffer as far as we can Dec(bitShift, 6); Result := Result + b64Chars[(bitBuf shr bitShift) and $3F]; end; end; end; // we love duplicate work but must test for flush buffers for the price // of speed (loop) if escaped then begin if (bitShift > 0) then begin Result := Result + b64Chars[bitBuf shl (6 - bitShift) and $3F]; end; Result := Result + '-'; end; end; function TIdMUTF7.Decode(const aString: AnsiString): TIdUnicodeString; { -- mUTF7Decode ------------------------------------------------------------- PRE: aString encoding must conform to IETF RFC 3501, section 5.1.3 POST: SUCCESS: an 8bit string FAILURE: an exception of type EMUTF7Decode 2004-03-02 roman puls: speed improvements of around 400 percent due to replacement of pchar/while loops to delphi-style string/for loops. Delphi 8 compatible. 2004-02-29 roman puls: initial version ---} const bitMasks: array[0..4] of Cardinal = ($00000000, $00000001, $00000003, $00000007, $0000000F); var ch : Byte; last : Char; bitBuf : Cardinal; escaped : Boolean; x, bitShift: Integer; begin Result := ''; escaped := False; bitShift := 0; last := #0; bitBuf := 0; for x := 1 to Length(aString) do begin ch := Byte(aString[x]); if not escaped then begin if (aString[x] = '&') then begin // escape sequence found escaped := True; bitBuf := 0; bitShift := 0; last := '&'; end else if (ch < $80) and (b64Table[ch] <> $FF) then begin Result := Result + WideChar(ch); end else begin raise EMUTF7Decode.CreateFmt('Illegal char #%d in UTF7 sequence.', [ch]); {do not localize} end; end else begin // we're escaped { break out of escape mode } if (aString[x] = '-') then begin // extra check for pending bits if (last = '&') then begin // special sequence '&-' ? Result := Result + '&'; end else begin if (bitShift >= 16) then begin Dec(bitShift, 16); Result := Result + WideChar((bitBuf shr bitShift) and $FFFF); end; if (bitShift > 4) or ((bitBuf and bitMasks[bitShift]) <> 0) then begin // check for bitboundaries raise EMUTF7Decode.Create('Illegal bit sequence in MUTF7 string'); {do not localize} end; end; escaped := False; end else begin // still escaped // check range for ch: must be < 128 and in b64table if (ch >= $80) or (b64Index[ch] = -1) then begin raise EMUTF7Decode.CreateFmt('Illegal char #%d in UTF7 sequence.', [ch]); {do not localize} end; ch := b64Index[ch]; bitBuf := (bitBuf shl 6) or (ch and $3F); Inc(bitShift, 6); if (bitShift >= 16) then begin Dec(bitShift, 16); Result := Result + WideChar((bitBuf shr bitShift) and $FFFF); end; end; last := #0; end; end; if escaped then begin raise EmUTF7Decode.create('Missing unescape in UTF7 sequence.'); {do not localize} end; end; function TIdMUTF7.Valid(const aMUTF7String : AnsiString): Boolean; { -- mUTF7valid ------------------------------------------------------------- PRE: NIL POST: returns true if string is correctly encoded (as described in mUTF7Encode) returns false otherwise } begin try Result := (aMUTF7String = {mUTF7}Encode({mUTF7}Decode(aMUTF7String))); except on e: EmUTF7Error do begin Result := False; end; // do not handle others end; end; function TIdMUTF7.Append(const aMUTF7String: AnsiString; const aStr : TIdUnicodeString): AnsiString; { -- mUTF7Append ------------------------------------------------------------- PRE: aMUTF7String is complying to mUTF7Encode's description POST: SUCCESS: a concatenation of both input strings in mUTF FAILURE: an exception of EMUTF7Decode or EMUTF7Decode will be raised } begin Result := {mUTF7}Encode({mUTF7}Decode(aMUTF7String) + aStr); end; { TIdImapMessageParts } constructor TIdImapMessagePart.Create(Collection: TCollection); begin {Make sure these are initialised properly...} inherited Create(Collection); FParentPart := -1; FBoundary := ''; {Do not Localize} end; constructor TIdImapMessageParts.Create(AOwner: TPersistent); begin inherited Create(AOwner, TIdImapMessagePart); end; function TIdImapMessageParts.GetItem(Index: Integer): TIdImapMessagePart; begin Result := TIdImapMessagePart(inherited GetItem(Index)); end; function TIdImapMessageParts.Add: TIdImapMessagePart; begin Result := TIdImapMessagePart(inherited Add); end; procedure TIdImapMessageParts.SetItem(Index: Integer; const Value: TIdImapMessagePart); begin inherited SetItem(Index, Value); end; { TIdIMAP4 } procedure TIdIMAP4.BeginWorkForPart(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64); begin if Assigned(FOnWorkBeginForPart) then begin FOnWorkBeginForPart(Self, AWorkMode, AWorkCountMax); end; end; procedure TIdIMAP4.DoWorkForPart(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64); begin if Assigned(FOnWorkForPart) then begin FOnWorkForPart(Self, AWorkMode, AWorkCount); end; end; procedure TIdIMAP4.EndWorkForPart(ASender: TObject; AWorkMode: TWorkMode); begin if Assigned(FOnWorkEndForPart) then begin FOnWorkEndForPart(Self, AWorkMode); end; end; //The following call FMUTF7 but do exception-handling on invalid strings... function TIdIMAP4.DoMUTFEncode(const aString : String): String; begin // TODO: if the server advertises the "UTF8=ACCEPT" capability, use // a UTF-8 quoted string instead of IMAP's Modified UTF-7... try Result := String(FMUTF7.Encode(TIdUnicodeString(aString))); except Result := aString; end; end; function TIdIMAP4.DoMUTFDecode(const aString : String): String; begin try Result := String(FMUTF7.Decode(AnsiString(aString))); except Result := aString; end; end; function TIdIMAP4.GetReplyClass:TIdReplyClass; begin Result := TIdReplyIMAP4; end; function TIdIMAP4.GetSupportsTLS: Boolean; begin Result := IsCapabilityListed('STARTTLS'); //do not localize end; function TIdIMAP4.CheckConnectionState(AAllowedState: TIdIMAP4ConnectionState): TIdIMAP4ConnectionState; begin Result := CheckConnectionState([AAllowedState]); end; function TIdIMAP4.CheckConnectionState(const AAllowedStates: array of TIdIMAP4ConnectionState): TIdIMAP4ConnectionState; var i: integer; begin if High(AAllowedStates) > -1 then begin for i := Low(AAllowedStates) to High(AAllowedStates) do begin if FConnectionState = AAllowedStates[i] then begin Result := FConnectionState; Exit; end; end; end; raise EIdConnectionStateError.CreateFmt(RSIMAP4ConnectionStateError, [GetConnectionStateName]); end; function TIdIMAP4.CheckReplyForCapabilities: Boolean; var I: Integer; begin FCapabilities.Clear; FHasCapa := False; with TIdReplyIMAP4(FLastCmdResult).Extra do begin for I := 0 to Count-1 do begin if TextStartsWith(Strings[I], 'CAPABILITY ') then begin {Do not Localize} BreakApart(Strings[I], ' ', FCapabilities); {Do not Localize} // RLebeau: do not delete the first item anymore! It specifies the IMAP // version/revision, which is needed to support certain extensions, like // 'IMAP4rev1'... {FCapabilities.Delete(0);} FHasCapa := True; Break; end; end; end; Result := FHasCapa; end; function TIdIMAP4.FindHowServerCreatesFolders: TIdIMAP4FolderTreatment; var LUsersFolders: TStringList; LN: integer; LInbox: string; LTestFolder: string; begin LUsersFolders := TStringList.Create; try {$IFDEF HAS_TStringList_CaseSensitive} LUsersFolders.CaseSensitive := False; {$ENDIF} //Get folder names... if (not ListMailBoxes(LUsersFolders)) or (LUsersFolders.Count = 0) then begin Result := ftCannotRetrieveAnyFolders; Exit; end; //Do we have an Inbox? LN := IndyIndexOf(LUsersFolders, 'INBOX'); {Do not Localize} if LN = -1 then begin Result := ftCannotTestBecauseHasNoInbox; Exit; end; LInbox := LUsersFolders.Strings[LN]; //Make sure our test folder does not already exist at the top level... LTestFolder := 'CiaransTestFolder'; {Do not Localize} while IndyIndexOf(LUsersFolders, LTestFolder) <> -1 do begin LTestFolder := LTestFolder + '9'; {Do not Localize} end; //Try to create LTestFolder at the top level... if CreateMailbox(LTestFolder) then begin //We were able to create it at the top level - delete it and exit.. DeleteMailbox(LTestFolder); Result := ftAllowsTopLevelCreation; Exit; end; //See if our test folder does not exist under INBOX... LTestFolder := LInbox + FMailBoxSeparator + 'CiaransTestFolder'; {Do not Localize} while IndyIndexOf(LUsersFolders, LTestFolder) <> -1 do begin LTestFolder := LTestFolder + '9'; {Do not Localize} end; //Try to create LTestFolder under Inbox... if CreateMailbox(LTestFolder) then begin //We were able to create it under the top level - delete it and exit.. DeleteMailbox(LTestFolder); Result := ftFoldersMustBeUnderInbox; Exit; end; //It does not allow us create folders under any level (read-only?)... Result := ftDoesNotAllowFolderCreation; finally FreeAndNil(LUsersFolders); end; end; function TIdIMAP4.IsNumberValid(const ANumber: Integer): Boolean; {CC3: Need to validate message numbers (relative and UIDs), because otherwise the routines wait for a response that never arrives and so functions never return.} begin if ANumber < 1 then begin raise EIdNumberInvalid.Create(RSIMAP4NumberInvalid); end; Result := True; end; function TIdIMAP4.IsUIDValid(const AUID: string): Boolean; {CC3: Need to validate message numbers (relative and UIDs), because otherwise the routines wait for a response that never arrives and so functions never return.} begin //Must be digits only (no - or .) IsItDigitsAndOptionallyPeriod(AUID, False); Result := IsNumberValid(IndyStrToInt(AUID)); end; function TIdIMAP4.IsImapPartNumberValid(const AUID: string): Boolean; {CC3: IMAP part numbers are 3 or 4.5 etc, i.e. digits or period allowed} begin Result := IsItDigitsAndOptionallyPeriod(AUID, True); end; function TIdIMAP4.IsItDigitsAndOptionallyPeriod(const AStr: string; AAllowPeriod: Boolean): Boolean; var LN: integer; begin if Length(AStr) = 0 then begin raise EIdNumberInvalid.Create(RSIMAP4NumberInvalid); end; for LN := 1 to Length(AStr) do begin if not IsNumeric(AStr[LN]) then begin if (not AAllowPeriod) or (AStr[LN] <> '.') then begin {Do not Localize} raise EIdNumberInvalid.Create(RSIMAP4NumberInvalid); end; end; end; Result := True; end; function TIdIMAP4.GetUID(const AMsgNum: Integer; var AUID: string): Boolean; {This gets the message UID from the message relative number.} begin Result := False; AUID := ''; {Do not Localize} IsNumberValid(AMsgNum); CheckConnectionState(csSelected); {Some servers return NO if the requested message number is not present (e.g. Cyrus), others return OK but no data (CommuniGate).} SendCmd(NewCmdCounter, IMAP4Commands[cmdFetch] + ' ' + IntToStr(AMsgNum) + ' (' + IMAP4FetchDataItem[fdUID] + ')', {Do not Localize} [IMAP4Commands[cmdFetch]]); if LastCmdResult.Code = IMAP_OK then begin //Might as well leave 3rd param as [] because ParseLastCmdResult always grabs the UID... if LastCmdResult.Text.Count > 0 then begin if ParseLastCmdResult(LastCmdResult.Text[0], IMAP4Commands[cmdFetch], []) then begin AUID := FLineStruct.UID; Result := True; end; end; end; end; procedure TIdIMAP4.WriteLn(const AOut: string = ''); begin IOHandler.WriteLn(AOut); end; function TIdIMAP4.ReadLnWait: string; begin Result := IOHandler.ReadLnWait; {This can have hit an exception of Connection Reset By Peer (timeout)} end; { IdTCPConnection Commands... } function TIdIMAP4.GetInternalResponse(const ATag: String; AExpectedResponses: array of String; ASingleLineMode: Boolean; ASingleLineMayBeSplit: Boolean {= False}): string; {ASingleLineMode is True if the caller just wants the FIRST line of the response, e.g., he may be looking only for "* FETCH (blah blah)", because he needs to parse that line to figure out how the rest will follow. This arises with a number of the FETCH commands where the caller needs to get the byte-count from the first line before he can retrieve the rest of the response. Note "FETCH" would have to be in AExpectedResponses. When False, the caller wants everything up to and including the reply terminator (e.g. "C45 OK Completed"). In ASingleLineMode, we ignore any lines that dont have one of AExpectedResponses at the start, otherwise we add all lines to .Text and later strip out any lines that dont have one of AExpectedResponses at the start. ASingleLineMayBeSplit (which should only be used with ASingleLineMode = True) deals with the (unusual) case where the server cannot or does not fit a single-line response onto one line. This arises when FETCHing the BODYSTRUCTURE, which can be very long. The server (Courier, anyway) signals it by adding a byte-count to the end of the first line, that would not normally be present.} //For example, for normal short responses, the server would send: // * FETCH (BODYSTRUCTURE (Part1 Part2)) //but if it splits it, it sends: // * FETCH (BODYSTRUCTURE (Part1 {16} // Part2)) //The number in the chain brackets {16} seems to be random. {WARNING: If you use ASingleLineMayBeSplit on a line that is EXPECTED to end with a byte-count, the code will break, so don't use it unless absolutely necessary.} var LLine: String; LResponse: TStringList; LWord: string; LPos: integer; LStrippedLineLength: Integer; LGotALineWithAnExpectedResponse: Boolean; LStrippedLine: string; LSplitLine: string; begin LGotALineWithAnExpectedResponse := False; LResponse := TStringList.Create; try repeat LLine := IOHandler.ReadLnWait; LResponse.Add(LLine); {CCB: Trap case of server telling you that you have been disconnected, usually because you were inactive for too long (get "* BYE idle time too long"). } if TextStartsWith(LLine, '* BYE') then begin {Do not Localize} {If BYE is in AExpectedResponses, this means we are expecting to disconnect, i.e. it is a LOGOUT.} if PosInStrArray('BYE', AExpectedResponses) = -1 then begin {Do not Localize} {We were not expecting a BYE response. For the moment, throw an exception. Could modify this by adding a ReconnectOnDisconnect property to automatically reconnect?} FConnectionState := csUnexpectedlyDisconnected; raise EIdDisconnectedProbablyIdledOut.Create(RSIMAP4DisconnectedProbablyIdledOut); end; end; if ASingleLineMode then begin LStrippedLine := LLine; if TextStartsWith(LStrippedLine, '* ') then begin {Do not Localize} LStrippedLine := Copy(LStrippedLine, 3, MaxInt); end; LGotALineWithAnExpectedResponse := TIdReplyIMAP4(FLastCmdResult).DoesLineHaveExpectedResponse(LStrippedLine, AExpectedResponses); if LGotALineWithAnExpectedResponse then begin //See if it may continue on the next line... if ASingleLineMayBeSplit then begin //If the line is split, it will have a byte-count field at the end... while TextEndsWith(LStrippedLine, '}') do begin //It is split. //First, remove the byte count... LPos := Length(LStrippedLine)-1; while LPos >= 1 do begin if LStrippedLine[LPos] = '{' then begin Break; end; Dec(LPos); end; LStrippedLineLength := StrToInt(Copy(LStrippedLine, LPos+1, (Length(LStrippedLine)-LPos)-1)); LStrippedLine := Copy(LStrippedLine, 1, LPos-1); //The rest of the reply is on the following line... LSplitLine := IOHandler.ReadString(LStrippedLineLength); // At this point LSplitLine should be parsed and the following characters should be escaped... " CR LF. LResponse.Add(LSplitLine); LStrippedLine := LStrippedLine + LSplitLine; LSplitLine := IOHandler.ReadLnWait; //Cannot thrash LLine, need it later LResponse.Add(LSplitLine); LStrippedLine := LStrippedLine + LSplitLine; end; end; FLastCmdResult.Text.Clear; TIdReplyIMAP4(FLastCmdResult).Extra.Clear; FLastCmdResult.Text.Add(LStrippedLine); end; end; //Need to get the 1st word on the line in case it is +, PREAUTH, etc... LPos := Pos(' ', LLine); {Do not Localize} if LPos <> 0 then begin {There are at least two words on this line...} LWord := Trim(Copy(LLine, 1, LPos-1)); end; until TextStartsWith(LLine, ATag) or (PosInStrArray(LWord, VALID_TAGGEDREPLIES) <> -1) or LGotALineWithAnExpectedResponse; if LGotALineWithAnExpectedResponse then begin //This only arises if ASingleLineMode is True... FLastCmdResult.Code := IMAP_OK; end else begin FLastCmdResult.FormattedReply := LResponse; TIdReplyIMAP4(FLastCmdResult).RemoveUnsolicitedResponses(AExpectedResponses); end; Result := FLastCmdResult.Code; finally FreeAndNil(LResponse); end; end; function TIdIMAP4.SendCmd(const AOut: string; AExpectedResponses: array of String; ASingleLineMode: Boolean = False; ASingleLineMayBeSplit: Boolean = False): string; begin Result := SendCmd(NewCmdCounter, AOut, AExpectedResponses, ASingleLineMode, ASingleLineMayBeSplit); end; function TIdIMAP4.SendCmd(const ATag, AOut: string; AExpectedResponses: array of String; ASingleLineMode: Boolean = False; ASingleLineMayBeSplit: Boolean = False): string; var LCmd: String; begin {CC3: Catch "Connection reset by peer"...} try if (AOut <> #0) then begin //Remove anything that may be unprocessed from a previous (probably failed) command... repeat IOHandler.InputBuffer.Clear; until not IOHandler.CheckForDataOnSource(MilliSecsToWaitToClearBuffer); LCmd := ATag + ' ' + AOut; CheckConnected; PrepareCmd(LCmd); IOHandler.WriteLn(LCmd); end; Result := GetInternalResponse(ATag, AExpectedResponses, ASingleLineMode, ASingleLineMayBeSplit); except on E: EIdSocketError do begin if E.LastError = Id_WSAECONNRESET then begin //Connection reset by peer... FConnectionState := csUnexpectedlyDisconnected; end; raise; end; end; end; { ...IdTCPConnection Commands } procedure TIdIMAP4.DoAlert(const AMsg: String); begin if Assigned(OnAlert) then begin OnAlert(Self, AMsg); end; end; procedure TIdIMAP4.SetMailBox(const Value: TIdMailBox); begin FMailBox.Assign(Value); end; procedure TIdIMAP4.SetSASLMechanisms(AValue: TIdSASLEntries); begin FSASLMechanisms.Assign(AValue); end; procedure TIdIMAP4.Login; var LIO: TIdSSLIOHandlerSocketBase; begin try if (IOHandler is TIdSSLIOHandlerSocketBase) and (UseTLS in ExplicitTLSVals) then begin LIO := TIdSSLIOHandlerSocketBase(IOHandler); //we check passthrough because we can either be using TLS currently with //implicit TLS support or because STARTLS was issued previously. if LIO.PassThrough then begin if SupportsTLS then begin if SendCmd(NewCmdCounter, 'STARTTLS', []) = IMAP_OK then begin {Do not Localize} TLSHandshake; //obtain capabilities again - RFC2595 Capability; end else begin ProcessTLSNegCmdFailed; end; end else begin ProcessTLSNotAvail; end; end; end; FConnectionState := csNonAuthenticated; FCmdCounter := 0; if FAuthType = iatUserPass then begin if Length(Password) <> 0 then begin {Do not Localize} SendCmd(NewCmdCounter, IMAP4Commands[cmdLogin] + ' ' + Username + ' ' + IMAPQuotedStr(Password), [IMAP_OK]); {Do not Localize} end else begin SendCmd(NewCmdCounter, IMAP4Commands[cmdLogin] + ' ' + Username, [IMAP_OK]); {Do not Localize} end; if LastCmdResult.Code <> IMAP_OK then begin RaiseExceptionForLastCmdResult; end; end else begin if not FHasCapa then begin Capability; end; // FSASLMechanisms.LoginSASL('AUTHENTICATE', FHost, IdGSKSSN_imap, [IMAP_OK], [IMAP_CONT], Self, FCapabilities); {Do not Localize} TIdSASLEntriesIMAP4(FSASLMechanisms).LoginSASL_IMAP(Self); end; FConnectionState := csAuthenticated; // RLebeau: check if the response includes new Capabilities, if not then query for them... if not CheckReplyForCapabilities then begin Capability; end; except Disconnect; raise; end; end; function TIdIMAP4.Connect(const AAutoLogin: Boolean = True): Boolean; begin {CC2: Need to set FConnectionState to csNonAuthenticated here. If not, then an unsuccessful connect after a previous successful connect (such as when a client program changes users) can leave it as csAuthenticated.} FConnectionState := csNonAuthenticated; try {CC2: Don't call Connect if already connected, this could be just a change of user} if not Connected then begin inherited Connect; GetResponse; // if PosInStrArray(LastCmdResult.Code, [IMAP_OK, IMAP_PREAUTH]) = -1 then begin {Should have got OK or PREAUTH in the greeting. Happened with some server, may need further investigation and coding...} // end; {CC7: Save FGreetingBanner so the user can use it to determine what type of server he is connected to...} if LastCmdResult.Text.Count > 0 then begin FGreetingBanner := LastCmdResult.Text[0]; end else begin FGreetingBanner := ''; end; if LastCmdResult.Code = IMAP_PREAUTH then begin FConnectionState := csAuthenticated; FCmdCounter := 0; // RLebeau: check if the greeting includes initial Capabilities, if not then query for them... if not CheckReplyForCapabilities then begin Capability; end; end else begin // RLebeau: check if the greeting includes initial Capabilities... CheckReplyForCapabilities; end; end; if AAutoLogin then begin Login; end; except Disconnect(False); raise; end; Result := True; end; procedure TIdIMAP4.InitComponent; begin inherited InitComponent; FMailBox := TIdMailBox.Create(Self); //FSASLMechanisms := TIdSASLEntries.Create(Self); FSASLMechanisms := TIdSASLEntriesIMAP4.Create(Self); Port := IdPORT_IMAP4; FLineStruct := TIdIMAPLineStruct.Create; FCapabilities := TStringList.Create; {$IFDEF HAS_TStringList_CaseSensitive} TStringList(FCapabilities).CaseSensitive := False; {$ENDIF} FMUTF7 := TIdMUTF7.Create; //Todo: Not sure which number is appropriate. Should be tested further. FImplicitTLSProtPort := IdPORT_IMAP4S; FRegularProtPort := IdPORT_IMAP4; FMilliSecsToWaitToClearBuffer := IDF_DEFAULT_MS_TO_WAIT_TO_CLEAR_BUFFER; FCmdCounter := 0; FConnectionState := csNonAuthenticated; FRetrieveOnSelect := rsDisabled; {CC2: FMailBoxSeparator is now detected when a mailbox is selected, following line is probably redundant, but leave it here as a default just in case.} FMailBoxSeparator := '/'; {Do not Localize} end; procedure TIdIMAP4.Disconnect(ANotifyPeer: Boolean); begin try inherited Disconnect(ANotifyPeer); finally FConnectionState := csNonAuthenticated; FCapabilities.Clear; end; end; procedure TIdIMAP4.DisconnectNotifyPeer; begin inherited DisconnectNotifyPeer; //IMPORTANT: Logout must pass 'BYE' as the first //element of the AExpectedResponses array (the 3rd param in SendCmd //below), because this flags to GetInternalResponse that this is the //logout, and it must EXPECT the BYE response SendCmd(NewCmdCounter, IMAP4Commands[cmdLogout], ['BYE']); {Do not Localize} end; procedure TIdIMAP4.KeepAlive; begin //Avialable in any state. SendCmd(NewCmdCounter, IMAP4Commands[cmdNoop], []); end; function TIdIMAP4.IsCapabilityListed(ACapability: string):Boolean; begin if not FHasCapa then begin Capability; end; Result := IndyIndexOf(TStringList(FCapabilities), ACapability) <> -1; end; function TIdIMAP4.Capability: Boolean; begin FHasCapa := Capability(FCapabilities); Result := FHasCapa; end; function TIdIMAP4.Capability(ASlCapability: TStrings): Boolean; begin //Available in any state. Result := False; ASlCapability.Clear; SendCmd(NewCmdCounter, IMAP4Commands[CmdCapability], [IMAP4Commands[CmdCapability]]); if LastCmdResult.Code = IMAP_OK then begin if LastCmdResult.Text.Count > 0 then begin BreakApart(LastCmdResult.Text[0], ' ', ASlCapability); {Do not Localize} end; // RLebeau: do not delete the first item anymore! It specifies the IMAP // version/revision, which is needed to support certain extensions, like // 'IMAP4rev1'... { if ASlCapability.Count > 0 then begin ASlCapability.Delete(0); end; } Result := True; end; end; function TIdIMAP4.GetCmdCounter: String; begin Result := 'C' + IntToStr(FCmdCounter); {Do not Localize} end; function TIdIMAP4.GetNewCmdCounter: String; begin Inc(FCmdCounter); Result := 'C' + IntToStr(FCmdCounter); {Do not Localize} end; destructor TIdIMAP4.Destroy; begin {Disconnect before we die} { Note we have to pass false to an overloaded method or an exception is raised in the destructor. That can cause weirdness in the IDE. } if Connected then begin Disconnect(False); end; FreeAndNil(FMailBox); FreeAndNil(FSASLMechanisms); FreeAndNil(FLineStruct); FreeAndNil(FCapabilities); FreeAndNil(FMUTF7); inherited Destroy; end; function TIdIMAP4.SelectMailBox(const AMBName: String): Boolean; begin Result := False; CheckConnectionState([csAuthenticated, csSelected]); SendCmd(NewCmdCounter, IMAP4Commands[cmdSelect] + ' "' + DoMUTFEncode(AMBName) + '"', {Do not Localize} ['FLAGS', 'OK', 'EXISTS', 'RECENT', '[READ-WRITE]', '[ALERT]']); {Do not Localize} if LastCmdResult.Code = IMAP_OK then begin //Put the parse in the IMAP Class and send the MB; ParseSelectResult(FMailBox, LastCmdResult.Text); FMailBox.Name := AMBName; FConnectionState := csSelected; case RetrieveOnSelect of rsHeaders: RetrieveAllHeaders(FMailBox.MessageList); rsMessages: RetrieveAllMsgs(FMailBox.MessageList); end; Result := True; end; end; function TIdIMAP4.ExamineMailBox(const AMBName: String; AMB: TIdMailBox): Boolean; begin Result := False; CheckConnectionState([csAuthenticated, csSelected]); //TO DO: Check that Examine's expected responses really are STATUS, FLAGS and OK... SendCmd(NewCmdCounter, IMAP4Commands[cmdExamine] + ' "' + DoMUTFEncode(AMBName) + '"', {Do not Localize} ['STATUS', 'FLAGS', 'OK', 'EXISTS', 'RECENT', '[READ-WRITE]', '[ALERT]']); {Do not Localize} if LastCmdResult.Code = IMAP_OK then begin ParseSelectResult(AMB, LastCmdResult.Text); AMB.Name := AMBName; FConnectionState := csSelected; Result := True; end; end; function TIdIMAP4.CloseMailBox: Boolean; begin Result := False; CheckConnectionState(csSelected); SendCmd(NewCmdCounter, IMAP4Commands[cmdClose], []); if LastCmdResult.Code = IMAP_OK then begin MailBox.Clear; FConnectionState := csAuthenticated; Result := True; end; end; function TIdIMAP4.CreateMailBox(const AMBName: String): Boolean; begin {CC5: Recode to return False if NO returned rather than throwing an exception...} Result := False; CheckConnectionState([csAuthenticated, csSelected]); {CC5: The NO response is typically due to Permission Denied} SendCmd(NewCmdCounter, IMAP4Commands[cmdCreate] + ' "' + DoMUTFEncode(AMBName) + '"', []); {Do not Localize} if LastCmdResult.Code = IMAP_OK then begin Result := True; end; end; function TIdIMAP4.DeleteMailBox(const AMBName: String): Boolean; begin {CC5: Recode to return False if NO returned rather than throwing an exception...} Result := False; CheckConnectionState([csAuthenticated, csSelected]); {CC5: The NO response is typically due to Permission Denied} SendCmd(NewCmdCounter, IMAP4Commands[cmdDelete] + ' "' + DoMUTFEncode(AMBName) + '"', []); {Do not Localize} if LastCmdResult.Code = IMAP_OK then begin Result := True; end; end; function TIdIMAP4.RenameMailBox(const AOldMBName, ANewMBName: String): Boolean; begin {CC5: Recode to return False if NO returned rather than throwing an exception...} Result := False; CheckConnectionState([csAuthenticated, csSelected]); {CC5: The NO response is typically due to Permission Denied} SendCmd(NewCmdCounter, IMAP4Commands[cmdRename] + ' "' + DoMUTFEncode(AOldMBName) + '" "' + DoMUTFEncode(ANewMBName) + '"', {Do not Localize} []); if LastCmdResult.Code = IMAP_OK then begin Result := True; end; end; function TIdIMAP4.StatusMailBox(const AMBName: String; AMB: TIdMailBox): Boolean; {CC2: It is pointless calling StatusMailBox with AStatusDataItems set to [] because you are asking the IMAP server to update none of the status flags. Instead, if called with no AStatusDataItems specified, use the standard flags returned by SelectMailBox, which allows the user to easily check if the mailbox has changed. Overload the functions, since AStatusDataItems cannot be set to nil.} var AStatusDataItems: array[1..5] of TIdIMAP4StatusDataItem; begin AStatusDataItems[1] := mdMessages; AStatusDataItems[2] := mdRecent; AStatusDataItems[3] := mdUIDNext; AStatusDataItems[4] := mdUIDValidity; AStatusDataItems[5] := mdUnseen; Result := StatusMailBox(AMBName, AMB, AStatusDataItems); end; function TIdIMAP4.StatusMailBox(const AMBName: String; AMB: TIdMailBox; const AStatusDataItems: array of TIdIMAP4StatusDataItem): Boolean; var LDataItems : string; Ln : Integer; begin Result := False; CheckConnectionState([csAuthenticated, csSelected]); for Ln := Low(AStatusDataItems) to High(AStatusDataItems) do begin case AStatusDataItems[Ln] of mdMessages: LDataItems := LDataItems + IMAP4StatusDataItem[mdMessages] + ' '; {Do not Localize} mdRecent: LDataItems := LDataItems + IMAP4StatusDataItem[mdRecent] + ' '; {Do not Localize} mdUIDNext: LDataItems := LDataItems + IMAP4StatusDataItem[mdUIDNext] + ' '; {Do not Localize} mdUIDValidity: LDataItems := LDataItems + IMAP4StatusDataItem[mdUIDValidity] + ' '; {Do not Localize} mdUnseen: LDataItems := LDataItems + IMAP4StatusDataItem[mdUnseen] + ' '; {Do not Localize} end; end; SendCmd(NewCmdCounter, IMAP4Commands[cmdStatus] + ' "' + DoMUTFEncode(AMBName) + '" (' + Trim(LDataItems) + ')', {Do not Localize} [IMAP4Commands[cmdStatus]]); if LastCmdResult.Code = IMAP_OK then begin ParseStatusResult(AMB, LastCmdResult.Text); Result := True; end; end; function TIdIMAP4.CheckMailBox: Boolean; begin Result := False; CheckConnectionState(csSelected); SendCmd(NewCmdCounter, IMAP4Commands[cmdCheck], []); if LastCmdResult.Code = IMAP_OK then begin Result := True; end; end; function TIdIMAP4.ExpungeMailBox: Boolean; begin Result := False; CheckConnectionState(csSelected); SendCmd(NewCmdCounter, IMAP4Commands[cmdExpunge], []); if LastCmdResult.Code = IMAP_OK then begin ParseExpungeResult(FMailBox, LastCmdResult.Text); Result := True; end; end; //This function is needed because when using the regular DateToStr with dd/MMM/yyyy //(which is the IMAP needed convension) may give the month as the local language //three letter month instead of the English month needed. function DateToIMAPDateStr (const ADate: TDateTime): String; var LDay, LMonth, LYear : Word; begin {Do not use the global settings from the system unit here because: 1) It might not be thread safe 2) Changing the settings could create problems for a user who's local date conventions are diffrent than dd-mm-yyyy. Some people prefer mm-dd-yyy. Don't mess with a user's display settings. 3) Using the display settings for dates may not always work as expected if a user changes their settings at a time between whn you do it but before the date is formatted. } DecodeDate(ADate, LYear, LMonth, LDay); Result := IndyFormat('%.2d-%s-%.4d', [LDay, UpperCase(monthnames[LMonth]), LYear]); {Do not Localize} end; function TIdIMAP4.InternalSearchMailBox(const ASearchInfo: array of TIdIMAP4SearchRec; AUseUID: Boolean; const ACharSet: string): Boolean; var LCmd: String; Ln : Integer; LTextBuf: TIdBytes; LCharSet: string; LEncoding: TIdTextEncoding; LLiteral: string; LUseNonSyncLiteral: Boolean; LUseUTF8QuotedString: Boolean; function RequiresEncoding(const S: String): Boolean; var I: Integer; begin Result := False; for I := 1 to Length(S) do begin if Ord(S[I]) > $7F then begin Result := True; Exit; end; end; end; function IsCharsetNeeded: Boolean; var I : Integer; begin Result := False; for I := Low(ASearchInfo) to High(ASearchInfo) do begin case ASearchInfo[I].SearchKey of skBcc, skBody, skCc, skFrom, skSubject, skText, skTo, skUID, skGmailRaw, skGmailMsgID, skGmailThreadID, skGmailLabels: if RequiresEncoding(ASearchInfo[I].Text) then begin Result := True; Exit; end; end; end; end; begin Result := False; CheckConnectionState(csSelected); LCmd := NewCmdCounter + ' '; {Do not Localize} if AUseUID then begin LCmd := LCmd + IMAP4Commands[cmdUID] + ' '; {Do not Localize} end; LCmd := LCmd + IMAP4Commands[cmdSearch]; if IsCharsetNeeded then begin LUseNonSyncLiteral := IsCapabilityListed('LITERAL+'); {Do not localize} LUseUTF8QuotedString := IsCapabilityListed('UTF8=ACCEPT') or {Do not localize} IsCapabilityListed('UTF8=ONLY') or {Do not localize} IsCapabilityListed('UTF8=ALL'); {Do not localize} if LUseUTF8QuotedString then begin LCharSet := 'UTF-8'; {Do not Localize} end else begin LCharSet := Trim(ACharSet); if LCharSet = '' then begin LCharSet := 'UTF-8'; {Do not Localize} end; end; LCmd := LCmd + ' CHARSET ' + LCharSet; {Do not localize} LEncoding := CharsetToEncoding(LCharSet); end else begin LUseNonSyncLiteral := False; LUseUTF8QuotedString := False; LEncoding := nil; end; {$IFNDEF DOTNET} try {$ENDIF} {CC3: Catch "Connection reset by peer"...} try //Remove anything that may be unprocessed from a previous (probably failed) command... repeat IOHandler.InputBuffer.Clear; until not IOHandler.CheckForDataOnSource(MilliSecsToWaitToClearBuffer); CheckConnected; //IMAP.PrepareCmd(LCmd); // now encode the search values. Most values are ASCII and do not need // special encoding. For text values that do need to be encoded, IMAP // string literals have to be used in order to support 8-bit octets in // charset encoded payloads... for Ln := Low(ASearchInfo) to High(ASearchInfo) do begin case ASearchInfo[Ln].SearchKey of skAll, skAnswered, skDeleted, skDraft, skFlagged, skNew, skNot, skOld, skOr, skRecent, skSeen, skUnanswered, skUndeleted, skUndraft, skUnflagged, skUnKeyWord, skUnseen: LCmd := LCmd + ' ' + IMAP4SearchKeys[ASearchInfo[Ln].SearchKey]; {Do not Localize} skBcc, skBody, skCc, skFrom, skSubject, skText, skTo, skUID, skGmailRaw, skGmailMsgID, skGmailThreadID, skGmailLabels: begin // TODO: support RFC 5738 to allow for UTF-8 encoded quoted strings if not RequiresEncoding(ASearchInfo[Ln].Text) then begin LCmd := LCmd + ' ' + IMAP4SearchKeys[ASearchInfo[Ln].SearchKey] + ' ' + IMAPQuotedStr(ASearchInfo[Ln].Text); {Do not Localize} end else begin if LUseUTF8QuotedString then begin LCmd := LCmd + ' ' + IMAP4SearchKeys[ASearchInfo[Ln].SearchKey] + ' *'; {Do not Localize} IOHandler.Write(LCmd); IOHandler.Write(IMAPQuotedStr(ASearchInfo[Ln].Text), LEncoding{$IFDEF STRING_IS_ANSI}, IndyOSDefaultEncoding{$ENDIF}); end else begin LTextBuf := ToBytes(ASearchInfo[Ln].Text, LEncoding{$IFDEF STRING_IS_ANSI}, IndyOSDefaultEncoding{$ENDIF}); if LUseNonSyncLiteral then begin LLiteral := '{' + IntToStr(Length(LTextBuf)) + '+}'; {Do not Localize} end else begin LLiteral := '{' + IntToStr(Length(LTextBuf)) + '}'; {Do not Localize} end; LCmd := LCmd + ' ' + IMAP4SearchKeys[ASearchInfo[Ln].SearchKey] + ' ' + LLiteral; {Do not Localize} IOHandler.WriteLn(LCmd); if not LUseNonSyncLiteral then begin if GetInternalResponse(GetCmdCounter, [IMAP4Commands[cmdSearch], IMAP4Commands[cmdUID]], False) <> IMAP_CONT then begin RaiseExceptionForLastCmdResult; end; end; IOHandler.Write(LTextBuf); end; LTextBuf := nil; LCmd := ''; end; end; skBefore, skOn, skSentBefore, skSentOn, skSentSince, skSince: LCmd := LCmd + ' ' + IMAP4SearchKeys[ASearchInfo[Ln].SearchKey] + ' ' + DateToIMAPDateStr(ASearchInfo[Ln].Date); {Do not Localize} skLarger, skSmaller: LCmd := LCmd + ' ' + IMAP4SearchKeys[ASearchInfo[Ln].SearchKey] + ' ' + IntToStr(ASearchInfo[Ln].Size); {Do not Localize} end; end; if LCmd <> '' then begin IOHandler.Write(LCmd); end; // After we send the last of the data, we need to send an EXTRA CRLF to terminates the SEARCH command... IOHandler.WriteLn; if GetInternalResponse(GetCmdCounter, [IMAP4Commands[cmdSearch], IMAP4Commands[cmdUID]], False) = IMAP_OK then begin ParseSearchResult(FMailBox, LastCmdResult.Text); Result := True; end; except on E: EIdSocketError do begin if E.LastError = Id_WSAECONNRESET then begin //Connection reset by peer... FConnectionState := csUnexpectedlyDisconnected; end; raise; end; end; {$IFNDEF DOTNET} finally if LEncoding <> nil then begin LEncoding.Free; end; end; {$ENDIF} end; function TIdIMAP4.SearchMailBox(const ASearchInfo: array of TIdIMAP4SearchRec; const ACharSet: string = ''): Boolean; begin Result := InternalSearchMailBox(ASearchInfo, False, ACharSet); end; function TIdIMAP4.UIDSearchMailBox(const ASearchInfo: array of TIdIMAP4SearchRec; const ACharSet: string = '') : Boolean; begin Result := InternalSearchMailBox(ASearchInfo, True, ACharSet); end; function TIdIMAP4.SubscribeMailBox(const AMBName: String): Boolean; begin Result := False; CheckConnectionState([csAuthenticated, csSelected]); SendCmd(NewCmdCounter, IMAP4Commands[cmdSubscribe] + ' "' + DoMUTFEncode(AMBName) + '"', {Do not Localize} []); if LastCmdResult.Code = IMAP_OK then begin Result := True; end; end; function TIdIMAP4.UnsubscribeMailBox(const AMBName: String): Boolean; begin Result := False; CheckConnectionState([csAuthenticated, csSelected]); SendCmd(NewCmdCounter, IMAP4Commands[cmdUnsubscribe] + ' "' + DoMUTFEncode(AMBName) + '"', {Do not Localize} []); if LastCmdResult.Code = IMAP_OK then begin Result := True; end; end; function TIdIMAP4.ListMailBoxes(AMailBoxList: TStrings): Boolean; begin Result := False; {CC2: This is one of the few cases where the server can return only "OK completed" meaning that the user has no mailboxes.} CheckConnectionState([csAuthenticated, csSelected]); SendCmd(NewCmdCounter, IMAP4Commands[cmdList] + ' "" *', [IMAP4Commands[cmdList]]); {Do not Localize} if LastCmdResult.Code = IMAP_OK then begin ParseListResult(AMailBoxList, LastCmdResult.Text); Result := True; end; end; function TIdIMAP4.ListInferiorMailBoxes(AMailBoxList, AInferiorMailBoxList: TStrings): Boolean; var Ln : Integer; LAuxMailBoxList : TStringList; begin Result := False; {CC2: This is one of the few cases where the server can return only "OK completed" meaning that the user has no inferior mailboxes.} CheckConnectionState([csAuthenticated, csSelected]); if AMailBoxList = nil then begin SendCmd(NewCmdCounter, IMAP4Commands[cmdList] + ' "" %', [IMAP4Commands[cmdList]]); {Do not Localize} if LastCmdResult.Code = IMAP_OK then begin ParseListResult(AInferiorMailBoxList, LastCmdResult.Text); //The INBOX mailbox is added because I think it always has to exist //in an IMAP4 account (default) but it does not list it in this command. Result := True; end; end else begin LAuxMailBoxList := TStringList.Create; try AInferiorMailBoxList.Clear; for Ln := 0 to AMailBoxList.Count - 1 do begin SendCmd(NewCmdCounter, IMAP4Commands[cmdList] + ' "" "' + DoMUTFEncode(AMailBoxList[Ln]) + FMailBoxSeparator + '%"', {Do not Localize} [IMAP4Commands[cmdList]]); if LastCmdResult.Code = IMAP_OK then begin ParseListResult(LAuxMailBoxList, LastCmdResult.Text); AInferiorMailBoxList.AddStrings(LAuxMailBoxList); Result := True; end else begin Break; end; end; finally FreeAndNil(LAuxMailBoxList); end; end; end; function TIdIMAP4.ListSubscribedMailBoxes(AMailBoxList: TStrings): Boolean; begin {CC2: This is one of the few cases where the server can return only "OK completed" meaning that the user has no subscribed mailboxes.} Result := False; CheckConnectionState([csAuthenticated, csSelected]); SendCmd(NewCmdCounter, IMAP4Commands[cmdLSub] + ' "" *', [IMAP4Commands[cmdList], IMAP4Commands[cmdLSub]]); {Do not Localize} if LastCmdResult.Code = IMAP_OK then begin // ds - fixed bug # 506026 ParseLSubResult(AMailBoxList, LastCmdResult.Text); Result := True; end; end; function TIdIMAP4.StoreFlags(const AMsgNumList: array of Integer; const AStoreMethod: TIdIMAP4StoreDataItem; const AFlags: TIdMessageFlagsSet): Boolean; var LDataItem, LMsgSet, LFlags: String; begin Result := False; if Length(AMsgNumList) > 0 then begin LMsgSet := ArrayToNumberStr(AMsgNumList); case AStoreMethod of sdReplace: LDataItem := IMAP4StoreDataItem[sdReplaceSilent]; sdAdd: LDataItem := IMAP4StoreDataItem[sdAddSilent]; sdRemove: LDataItem := IMAP4StoreDataItem[sdRemoveSilent]; end; LFlags := MessageFlagSetToStr(AFlags); CheckConnectionState(csSelected); SendCmd(NewCmdCounter, IMAP4Commands[cmdStore] + ' ' + LMsgSet + ' ' + LDataItem + ' (' + LFlags + ')', {Do not Localize} []); if LastCmdResult.Code = IMAP_OK then begin Result := True; end; end; end; function TIdIMAP4.UIDStoreFlags(const AMsgUID: String; const AStoreMethod: TIdIMAP4StoreDataItem; const AFlags: TIdMessageFlagsSet): Boolean; var LDataItem, LFlags : String; begin Result := False; IsUIDValid(AMsgUID); case AStoreMethod of sdReplace: LDataItem := IMAP4StoreDataItem[sdReplaceSilent]; sdAdd: LDataItem := IMAP4StoreDataItem[sdAddSilent]; sdRemove: LDataItem := IMAP4StoreDataItem[sdRemoveSilent]; end; LFlags := MessageFlagSetToStr(AFlags); CheckConnectionState(csSelected); SendCmd(NewCmdCounter, IMAP4Commands[cmdUID] + ' ' + IMAP4Commands[cmdStore] + ' ' + AMsgUID + ' ' + LDataItem + ' (' + LFlags + ')', {Do not Localize} []); if LastCmdResult.Code = IMAP_OK then begin Result := True; end; end; function TIdIMAP4.UIDStoreFlags(const AMsgUIDList: array of String; const AStoreMethod: TIdIMAP4StoreDataItem; const AFlags: TIdMessageFlagsSet): Boolean; var LDataItem, LMsgSet, LFlags : String; LN: integer; begin Result := False; LMsgSet := ''; for LN := 0 to Length(AMsgUIDList) -1 do begin IsUIDValid(AMsgUIDList[LN]); if LN > 0 then begin LMsgSet := LMsgSet + ','; {Do not Localize} end; LMsgSet := LMsgSet+AMsgUIDList[LN]; end; case AStoreMethod of sdReplace: LDataItem := IMAP4StoreDataItem[sdReplaceSilent]; sdAdd: LDataItem := IMAP4StoreDataItem[sdAddSilent]; sdRemove: LDataItem := IMAP4StoreDataItem[sdRemoveSilent]; end; LFlags := MessageFlagSetToStr(AFlags); CheckConnectionState(csSelected); SendCmd(NewCmdCounter, IMAP4Commands[cmdUID] + ' ' + IMAP4Commands[cmdStore] + ' ' + LMsgSet + ' ' + LDataItem + ' (' + LFlags + ')', {Do not Localize} []); if LastCmdResult.Code = IMAP_OK then begin Result := True; end; end; function TIdIMAP4.CopyMsgs(const AMsgNumList: array of Integer; const AMBName: String): Boolean; var LMsgSet : String; begin Result := False; if Length(AMsgNumList) > 0 then begin LMsgSet := ArrayToNumberStr ( AMsgNumList ); CheckConnectionState(csSelected); SendCmd(NewCmdCounter, IMAP4Commands[cmdCopy] + ' ' + LMsgSet + ' "' + DoMUTFEncode(AMBName) + '"', []); {Do not Localize} if LastCmdResult.Code = IMAP_OK then begin Result := True; end; end; end; function TIdIMAP4.UIDCopyMsgs(const AMsgUIDList: TStrings; const AMBName: String): Boolean; var LCmd : String; LN: integer; begin Result := False; if AMsgUIDList.Count > 0 then begin LCmd := IMAP4Commands[cmdUID] + ' ' + IMAP4Commands[cmdCopy] + ' '; {Do not Localize} for LN := 0 to AMsgUIDList.Count-1 do begin IsUIDValid(AMsgUIDList.Strings[LN]); if LN = 0 then begin LCmd := LCmd + AMsgUIDList.Strings[LN]; end else begin LCmd := LCmd + ',' + AMsgUIDList.Strings[LN]; {Do not Localize} end; end; LCmd := LCmd + ' "' + DoMUTFEncode(AMBName) + '"'; {Do not Localize} CheckConnectionState(csSelected); SendCmd(NewCmdCounter, LCmd, []); if LastCmdResult.Code = IMAP_OK then begin Result := True; end; end; end; function TIdIMAP4.CopyMsg(const AMsgNum: Integer; const AMBName: String): Boolean; //Copies a message from the current selected mailbox to the specified mailbox. begin Result := False; IsNumberValid(AMsgNum); CheckConnectionState(csSelected); SendCmd(NewCmdCounter, IMAP4Commands[cmdCopy] + ' ' + IntToStr(AMsgNum) + ' "' + DoMUTFEncode(AMBName) + '"', []); {Do not Localize} if LastCmdResult.Code = IMAP_OK then begin Result := True; end; end; function TIdIMAP4.UIDCopyMsg(const AMsgUID: String; const AMBName: String): Boolean; //Copies a message from the current selected mailbox to the specified mailbox. begin Result := False; IsUIDValid(AMsgUID); CheckConnectionState(csSelected); SendCmd(NewCmdCounter, IMAP4Commands[cmdUID] + ' ' + IMAP4Commands[cmdCopy] + ' ' + AMsgUID + ' "' + DoMUTFEncode(AMBName) + '"', []); {Do not Localize} if LastCmdResult.Code = IMAP_OK then begin Result := True; end; end; function TIdIMAP4.AppendMsg(const AMBName: String; AMsg: TIdMessage; const AFlags: TIdMessageFlagsSet = []): Boolean; begin Result := AppendMsg(AMBName, AMsg, nil, AFlags); end; function TIdIMAP4.AppendMsg(const AMBName: String; AMsg: TIdMessage; AAlternativeHeaders: TIdHeaderList; const AFlags: TIdMessageFlagsSet = []): Boolean; var LFlags, LMsgLiteral: String; LUseNonSyncLiteral: Boolean; Ln: Integer; LCmd: string; LLength: TIdStreamSize; LHeadersToSend: TIdHeaderList; LHeadersAsString: string; LHeadersAsBytes: TIdBytes; LStream: TStream; LHelper: TIdIMAP4WorkHelper; LMsgClient: TIdMessageClient; LMsgIO: TIdIOHandlerStreamMsg; begin Result := False; CheckConnectionState([csAuthenticated, csSelected]); if Length(AMBName) <> 0 then begin LFlags := MessageFlagSetToStr(AFlags); if LFlags <> '' then begin {Do not Localize} LFlags := '(' + LFlags + ')'; {Do not Localize} end; {CC8: In Indy 10, we want to support attachments (previous versions did not). The problem is that we have to know the size of the message in advance of sending it for the IMAP APPEND command. The problem is that there is no way of calculating the size of a message without generating the encoded message. Therefore, write the message out to a temporary stream, and then get the size of the data, which with a bit of adjustment, will give us the size of the message we will send. The "adjustment" is necessary because SaveToStream generates it's own headers, which will be different to both the ones in AMsg and AAlternativeHeaders, in the Date header, if nothing else.} LStream := TMemoryStream.Create; try {RLebeau 12/09/2012: this is a workaround to a design limitation in TIdMessage.SaveToStream(). It always outputs the stream data in an escaped format using SMTP dot transparency, but that is not used in IMAP! Until this design is corrected, we have to use a workaround for now. This logic is copied from TIdMessage.SaveToSteam() and slightly tweaked...} //AMsg.SaveToStream(LStream); LMsgClient := TIdMessageClient.Create(nil); try LMsgIO := TIdIOHandlerStreamMsg.Create(nil, nil, LStream); try LMsgIO.FreeStreams := False; LMsgIO.UnescapeLines := True; // this is the key piece that makes it work! LMsgClient.IOHandler := LMsgIO; try LMsgClient.SendMsg(AMsg, False); finally LMsgClient.IOHandler := nil; end; finally LMsgIO.Free; end; finally LMsgClient.Free; end; // end workaround LStream.Position := 0; {We are better off making up the headers as a string first rather than predicting its length. Slightly wasteful of memory, but it will not take up much.} LHeadersAsString := ''; if AAlternativeHeaders <> nil then begin {Use the headers that the user has passed to us...} LHeadersToSend := AAlternativeHeaders; end else if AMsg.NoEncode then begin {Use the headers that are in the message AMsg...} LHeadersToSend := AMsg.Headers; end else begin {Use the headers that SaveToStream() generated...} LHeadersToSend := AMsg.LastGeneratedHeaders; end; // not using LHeadersToSend.Text because it uses platform-specific line breaks for Ln := 0 to Pred(LHeadersToSend.Count) do begin LHeadersAsString := LHeadersAsString + LHeadersToSend[Ln] + EOL; end; LHeadersAsBytes := ToBytes(LHeadersAsString + EOL); LHeadersAsString := ''; {Get the size of the headers we are sending...} repeat until Length(ReadLnFromStream(LStream)) = 0; {We have to subtract the size of the headers in the file and add back the size of the headers we are to use to get the size of the message we are going to send...} LLength := Length(LHeadersAsBytes) + (LStream.Size - LStream.Position); LUseNonSyncLiteral := IsCapabilityListed('LITERAL+'); {Do not Localize} if LUseNonSyncLiteral then begin LMsgLiteral := '{' + IntToStr ( LLength ) + '+}'; {Do not Localize} end else begin LMsgLiteral := '{' + IntToStr ( LLength ) + '}'; {Do not Localize} end; {CC: The original code sent the APPEND command first, then followed it with the message. Maybe this worked with some server, but most send a response like "+ Send the additional command..." between the two, which was not expected by the client and caused an exception.} //CC: Added double quotes around mailbox name, else mailbox names with spaces will cause server parsing error LCmd := IMAP4Commands[cmdAppend] + ' "' + DoMUTFEncode(AMBName) + '" '; {Do not Localize} if Length(LFlags) <> 0 then begin LCmd := LCmd + LFlags + ' '; {Do not Localize} end; LCmd := LCmd + LMsgLiteral; {Do not Localize} {CC3: Catch "Connection reset by peer"...} try if LUseNonSyncLiteral then begin {Send the APPEND command and the message immediately, no + response needed...} IOHandler.WriteLn(NewCmdCounter + ' ' + LCmd); end else begin {Try sending the APPEND command, get the + response, then send the message...} SendCmd(NewCmdCounter, LCmd, []); if LastCmdResult.Code <> IMAP_CONT then begin Exit; end; end; LHelper := TIdIMAP4WorkHelper.Create(Self); try IOHandler.Write(LHeadersAsBytes); {RLebeau: passing -1 to TIdIOHandler.Write(TStream) will send the rest of the stream starting at its current Position...} IOHandler.Write(LStream, -1, False); finally FreeAndNil(LHelper); end; {WARNING: After we send the message (which should be exactly LLength bytes long), we need to send an EXTRA CRLF which is in addition to the count in LLength, because this CRLF terminates the APPEND command...} IOHandler.WriteLn; if GetInternalResponse(LastCmdCounter, [IMAP4Commands[cmdAppend]], False) = IMAP_OK then begin Result := True; end; except on E: EIdSocketError do begin if E.LastError = Id_WSAECONNRESET then begin //Connection reset by peer... FConnectionState := csUnexpectedlyDisconnected; end; raise; end; end; finally LStream.Free; end; end; end; function TIdIMAP4.AppendMsgNoEncodeFromFile(const AMBName: String; ASourceFile: string; const AFlags: TIdMessageFlagsSet = []): Boolean; var LSourceStream: TIdReadFileExclusiveStream; begin LSourceStream := TIdReadFileExclusiveStream.Create(ASourceFile); try Result := AppendMsgNoEncodeFromStream(AMBName, LSourceStream, AFlags); finally FreeAndNil(LSourceStream); end; end; function TIdIMAP4.AppendMsgNoEncodeFromStream(const AMBName: String; AStream: TStream; const AFlags: TIdMessageFlagsSet = []): Boolean; const cTerminator: array[0..4] of Byte = (13, 10, Ord('.'), 13, 10); var LFlags, LMsgLiteral: String; LUseNonSyncLiteral: Boolean; I: Integer; LFound: Boolean; LCmd: string; LLength: TIdStreamSize; LTempStream: TMemoryStream; LHelper: TIdIMAP4WorkHelper; LBuf: TIdBytes; begin Result := False; CheckConnectionState([csAuthenticated, csSelected]); if Length(AMBName) <> 0 then begin {Do not Localize} LFlags := MessageFlagSetToStr(AFlags); if LFlags <> '' then begin {Do not Localize} LFlags := '(' + LFlags + ')'; {Do not Localize} end; LLength := AStream.Size; LTempStream := TMemoryStream.Create; try //Hunt for CRLF.CRLF, if present then we need to remove it... // RLebeau: why? The lines of the message data are not required to be // dot-prefixed like in SMTP, so why should TIdIMAP care about any // termination sequences in the file? We are telling the server exactly // how large the message actually is. What if the message data actually // contains a valid line with just a dot on it? This code would end up // truncating the message that is stored on the server... SetLength(LBuf, 5); LTempStream.CopyFrom(AStream, LLength); LTempStream.Position := 0; repeat if TIdStreamHelper.ReadBytes(LTempStream, LBuf, 5) < 5 then begin Break; end; LFound := True; for I := 0 to 4 do begin if LBuf[I] <> cTerminator[I] then begin LFound := False; Break; end; end; if LFound then begin LLength := LTempStream.Position-5; Break; end; TIdStreamHelper.Seek(LTempStream, -4, soCurrent); until False; LUseNonSyncLiteral := IsCapabilityListed('LITERAL+'); {Do not Localize} if LUseNonSyncLiteral then begin LMsgLiteral := '{' + IntToStr(LLength) + '+}'; {Do not Localize} end else begin LMsgLiteral := '{' + IntToStr(LLength) + '}'; {Do not Localize} end; {CC: The original code sent the APPEND command first, then followed it with the message. Maybe this worked with some server, but most send a response like "+ Send the additional command..." between the two, which was not expected by the client and caused an exception.} //CC: Added double quotes around mailbox name, else mailbox names with spaces will cause server parsing error LCmd := IMAP4Commands[cmdAppend] + ' "' + DoMUTFEncode(AMBName) + '" '; {Do not Localize} if Length(LFlags) <> 0 then begin {Do not Localize} LCmd := LCmd + LFlags + ' '; {Do not Localize} end; LCmd := LCmd + LMsgLiteral; {Do not Localize} {CC3: Catch "Connection reset by peer"...} try if LUseNonSyncLiteral then begin {Send the APPEND command and the message immediately, no + response needed...} IOHandler.WriteLn(NewCmdCounter + ' ' + LCmd); end else begin {Try sending the APPEND command, get the + response, then send the message...} SendCmd(NewCmdCounter, LCmd, []); if LastCmdResult.Code <> IMAP_CONT then begin Exit; end; end; LTempStream.Position := 0; LHelper := TIdIMAP4WorkHelper.Create(Self); try IOHandler.Write(LTempStream, LLength); finally FreeAndNil(LHelper); end; {WARNING: After we send the message (which should be exactly LLength bytes long), we need to send an EXTRA CRLF which is in addition to the count in LLength, because this CRLF terminates the APPEND command...} IOHandler.WriteLn; if GetInternalResponse(LastCmdCounter, [IMAP4Commands[cmdAppend]], False) = IMAP_OK then begin Result := True; end; except on E: EIdSocketError do begin if E.LastError = Id_WSAECONNRESET then begin //Connection reset by peer... FConnectionState := csUnexpectedlyDisconnected; end; raise; end; end; finally FreeAndNil(LTempStream); end; end; end; function TIdIMAP4.RetrieveEnvelope(const AMsgNum: Integer; AMsg: TIdMessage): Boolean; begin Result := InternalRetrieveEnvelope(AMsgNum, AMsg, nil); end; function TIdIMAP4.RetrieveEnvelopeRaw(const AMsgNum: Integer; ADestList: TStrings): Boolean; begin Result := InternalRetrieveEnvelope(AMsgNum, nil, ADestList); end; function TIdIMAP4.InternalRetrieveEnvelope(const AMsgNum: Integer; AMsg: TIdMessage; ADestList: TStrings): Boolean; begin {CC2: Return False if message number is invalid...} IsNumberValid(AMsgNum); Result := False; CheckConnectionState(csSelected); {Some servers return NO if the requested message number is not present (e.g. Cyrus), others return OK but no data (CommuniGate).} SendCmd(NewCmdCounter, IMAP4Commands[cmdFetch] + ' ' + IntToStr(AMsgNum) + ' (' + IMAP4FetchDataItem[fdEnvelope] + ')', {Do not Localize} [IMAP4Commands[cmdFetch]]); if LastCmdResult.Code = IMAP_OK then begin if LastCmdResult.Text.Count > 0 then begin if ParseLastCmdResult(LastCmdResult.Text[0], IMAP4Commands[cmdFetch], [IMAP4FetchDataItem[fdEnvelope]]) then begin if ADestList <> nil then begin ADestList.Clear; ADestList.Add(FLineStruct.IMAPValue); end; if AMsg <> nil then begin ParseEnvelopeResult(AMsg, FLineStruct.IMAPValue); end; Result := True; end; end; end; end; function TIdIMAP4.UIDRetrieveEnvelope(const AMsgUID: String; AMsg: TIdMessage): Boolean; begin Result := UIDInternalRetrieveEnvelope(AMsgUID, AMsg, nil); end; function TIdIMAP4.UIDRetrieveEnvelopeRaw(const AMsgUID: String; ADestList: TStrings): Boolean; begin Result := UIDInternalRetrieveEnvelope(AMsgUID, nil, ADestList); end; function TIdIMAP4.UIDInternalRetrieveEnvelope(const AMsgUID: String; AMsg: TIdMessage; ADestList: TStrings): Boolean; begin IsUIDValid(AMsgUID); {CC2: Return False if message number is invalid...} Result := False; CheckConnectionState(csSelected); {Some servers return NO if the requested message number is not present (e.g. Cyrus), others return OK but no data (CommuniGate).} SendCmd(NewCmdCounter, IMAP4Commands[cmdUID] + ' ' + IMAP4Commands[cmdFetch] + ' ' + AMsgUID + ' (' + IMAP4FetchDataItem[fdEnvelope] + ')', {Do not Localize} [IMAP4Commands[cmdFetch], IMAP4Commands[cmdUID]]); if LastCmdResult.Code = IMAP_OK then begin if LastCmdResult.Text.Count > 0 then begin if ParseLastCmdResult(LastCmdResult.Text[0], IMAP4Commands[cmdFetch], [IMAP4FetchDataItem[fdEnvelope]]) then begin if ADestList <> nil then begin ADestList.Clear; ADestList.Add(FLineStruct.IMAPValue); end; if AMsg <> nil then begin ParseEnvelopeResult(AMsg, FLineStruct.IMAPValue); end; Result := True; end; end; end; end; function TIdIMAP4.RetrieveAllEnvelopes(AMsgList: TIdMessageCollection): Boolean; {NOTE: If AMsgList is empty or does not have enough records, records will be added. If you pass a non-empty AMsgList, it is assumed the records are in relative record number sequence: if not, pass in an empty AMsgList and copy the results to your own AMsgList.} var Ln: Integer; LMsg: TIdMessage; begin Result := False; {CC2: This is one of the few cases where the server can return only "OK completed" meaning that the user has no envelopes.} CheckConnectionState(csSelected); SendCmd(NewCmdCounter, IMAP4Commands[cmdFetch] + ' 1:* (' + IMAP4FetchDataItem[fdEnvelope] + ')', {Do not Localize} [IMAP4Commands[cmdFetch]]); if LastCmdResult.Code = IMAP_OK then begin for Ln := 0 to LastCmdResult.Text.Count-1 do begin if ParseLastCmdResult(LastCmdResult.Text[Ln], IMAP4Commands[cmdFetch], [IMAP4FetchDataItem[fdEnvelope]]) then begin if LN >= AMsgList.Count then begin LMsg := AMsgList.Add.Msg; end else begin LMsg := AMsgList.Messages[LN]; end; ParseEnvelopeResult(LMsg, FLineStruct.IMAPValue); end; end; Result := True; end; end; function TIdIMAP4.UIDRetrieveAllEnvelopes(AMsgList: TIdMessageCollection): Boolean; {NOTE: If AMsgList is empty or does not have enough records, records will be added. If you pass a non-empty AMsgList, it is assumed the records are in relative record number sequence: if not, pass in an empty AMsgList and copy the results to your own AMsgList.} var Ln: Integer; LMsg: TIdMessage; begin Result := False; {CC2: This is one of the few cases where the server can return only "OK completed" meaning that the user has no envelopes.} CheckConnectionState(csSelected); SendCmd(NewCmdCounter, IMAP4Commands[cmdUID] + ' ' + IMAP4Commands[cmdFetch] + ' 1:* (' + IMAP4FetchDataItem[fdEnvelope] + ' ' + IMAP4FetchDataItem[fdFlags] + ')', {Do not Localize} [IMAP4Commands[cmdFetch]]); if LastCmdResult.Code = IMAP_OK then begin for Ln := 0 to LastCmdResult.Text.Count-1 do begin if ParseLastCmdResult(LastCmdResult.Text[Ln], IMAP4Commands[cmdFetch], [IMAP4FetchDataItem[fdEnvelope]]) then begin if LN >= AMsgList.Count then begin LMsg := AMsgList.Add.Msg; end else begin LMsg := AMsgList.Messages[LN]; end; ParseEnvelopeResult(LMsg, FLineStruct.IMAPValue); LMsg.UID := FLineStruct.UID; LMsg.Flags := FLineStruct.Flags; end; end; Result := True; end; end; function TIdIMAP4.RetrieveText(const AMsgNum: Integer; var AText: string): Boolean; //Retrieve a specific individual part of a message begin IsNumberValid(AMsgNum); Result := InternalRetrieveText(AMsgNum, AText, False, False, False); end; function TIdIMAP4.RetrieveText2(const AMsgNum: Integer; var AText: string): Boolean; //Retrieve a specific individual part of a message begin IsNumberValid(AMsgNum); Result := InternalRetrieveText(AMsgNum, AText, False, False, True); end; function TIdIMAP4.RetrieveTextPeek(const AMsgNum: Integer; var AText: string): Boolean; {CC3: Added: Retrieve the text part of the message...} begin IsNumberValid(AMsgNum); Result := InternalRetrieveText(AMsgNum, AText, False, True, False); end; function TIdIMAP4.RetrieveTextPeek2(const AMsgNum: Integer; var AText: string): Boolean; {CC3: Added: Retrieve the text part of the message...} begin IsNumberValid(AMsgNum); Result := InternalRetrieveText(AMsgNum, AText, False, True, True); end; function TIdIMAP4.UIDRetrieveText(const AMsgUID: String; var AText: string): Boolean; {CC3: Added: Retrieve the text part of the message...} begin IsUIDValid(AMsgUID); Result := InternalRetrieveText(IndyStrToInt(AMsgUID), AText, True, False, False); end; function TIdIMAP4.UIDRetrieveText2(const AMsgUID: String; var AText: string): Boolean; {CC3: Added: Retrieve the text part of the message...} begin IsUIDValid(AMsgUID); Result := InternalRetrieveText(IndyStrToInt(AMsgUID), AText, True, False, True); end; function TIdIMAP4.UIDRetrieveTextPeek(const AMsgUID: String; var AText: string): Boolean; {CC3: Added: Retrieve the text part of the message...} begin IsUIDValid(AMsgUID); Result := InternalRetrieveText(IndyStrToInt(AMsgUID), AText, True, True, False); end; function TIdIMAP4.UIDRetrieveTextPeek2(const AMsgUID: String; var AText: string): Boolean; {CC3: Added: Retrieve the text part of the message...} begin IsUIDValid(AMsgUID); Result := InternalRetrieveText(IndyStrToInt(AMsgUID), AText, True, True, True); end; function TIdIMAP4.InternalRetrieveText(const AMsgNum: Integer; var AText: string; AUseUID: Boolean; AUsePeek: Boolean; AUseFirstPartInsteadOfText: Boolean): Boolean; {CC3: Added: Retrieve the text part of the message...} var LCmd: string; LParts: TIdImapMessageParts; LThePart: TIdImapMessagePart; LCharSet: String; LContentTransferEncoding: string; LTextPart: integer; LHelper: TIdIMAP4WorkHelper; procedure DoDecode(ADecoderClass: TIdDecoderClass = nil; AStripCRLFs: Boolean = False); var LDecoder: TIdDecoder; LStream: TStream; LStrippedStream: TStringStream; LUnstrippedStream: TStringStream; LEncoding: TIdTextEncoding; begin LStream := TMemoryStream.Create; try if ADecoderClass <> nil then begin LDecoder := ADecoderClass.Create(Self); try LDecoder.DecodeBegin(LStream); try LUnstrippedStream := TStringStream.Create(''); try IOHandler.ReadStream(LUnstrippedStream, FLineStruct.ByteCount); //ReadStream uses OnWork, most other methods dont {This is more complicated than quoted-printable because we have to strip CRLFs that have been inserted by the MTA to avoid overly long lines...} if AStripCRLFs then begin LStrippedStream := TStringStream.Create(''); try StripCRLFs(LUnstrippedStream, LStrippedStream); LDecoder.Decode(LStrippedStream.DataString); finally FreeAndNil(LStrippedStream); end; end else begin LDecoder.Decode(LUnstrippedStream.DataString); end; finally FreeAndNil(LUnstrippedStream); end; finally LDecoder.DecodeEnd; end; finally FreeAndNil(LDecoder); end; end else begin IOHandler.ReadStream(LStream, FLineStruct.ByteCount); //ReadStream uses OnWork, most other methods dont end; LStream.Position := 0; if LCharSet <> '' then begin LEncoding := CharsetToEncoding(LCharSet); {$IFNDEF DOTNET} try {$ENDIF} AText := ReadStringFromStream(LStream, -1, LEncoding{$IFDEF STRING_IS_ANSI}, IndyOSDefaultEncoding{$ENDIF}); {$IFNDEF DOTNET} finally LEncoding.Free; end; {$ENDIF} end else begin AText := ReadStringFromStream(LStream, -1, Indy8BitEncoding{$IFDEF STRING_IS_ANSI}, Indy8BitEncoding{$ENDIF}); end; finally FreeAndNil(LStream); end; end; begin Result := False; AText := ''; {Do not Localize} CheckConnectionState(csSelected); LTextPart := 0; {The text part is usually part 1 but could be part 2} if AUseFirstPartInsteadOfText then begin {In this case, we need the body structure to find out what encoding has been applied to part 1...} LParts := TIdImapMessageParts.Create(nil); try if AUseUID then begin if not UIDRetrieveStructure(IntToStr(AMsgNum), LParts) then begin Exit; end; end else begin if not RetrieveStructure(AMsgNum, LParts) then begin Exit; end; end; {Get the info we want out of LParts...} repeat LThePart := LParts.Items[LTextPart]; {Part 1 is index 0} if LThePart.FSize = 0 then begin {Some emails have part 0 empty, they intend you to use part 1} if LTextPart = 0 then begin LTextPart := 1; Continue; end else begin Break; end; end; until False; LCharSet := LThePart.CharSet; LContentTransferEncoding := LThePart.ContentTransferEncoding; finally FreeAndNil(LParts); end; end else begin // TODO: detect LCharSet and LContentTransferEncoding... end; LCmd := ''; if AUseUID then begin LCmd := LCmd + IMAP4Commands[cmdUID] + ' '; {Do not Localize} end; LCmd := LCmd + IMAP4Commands[cmdFetch] + ' ' + IntToStr(AMsgNum) + ' ('; {Do not Localize} if AUsePeek then begin LCmd := LCmd + IMAP4FetchDataItem[fdBody]+'.PEEK'; {Do not Localize} end else begin LCmd := LCmd + IMAP4FetchDataItem[fdBody]; end; if not AUseFirstPartInsteadOfText then begin LCmd := LCmd + '[TEXT])'; {Do not Localize} end else begin LCmd := LCmd + '[' + IntToStr(LTextPart+1) + '])'; {Do not Localize} end; SendCmd(NewCmdCounter, LCmd, [IMAP4Commands[cmdFetch], IMAP4Commands[cmdUID]], True); if LastCmdResult.Code = IMAP_OK then begin try {For an invalid request (non-existent part or message), NIL is returned as the size...} if (LastCmdResult.Text.Count < 1) or (not ParseLastCmdResult(LastCmdResult.Text[0], IMAP4Commands[cmdFetch], [IMAP4FetchDataItem[fdBody]+'['+'TEXT'+']' , IMAP4FetchDataItem[fdBody]+'['+IntToStr(LTextPart+1)+']'])) {do not localize} or (PosInStrArray(FLineStruct.IMAPValue, ['NIL', '""'], False) <> -1) {do not localize} or (FLineStruct.ByteCount < 1) then begin GetInternalResponse(GetCmdCounter, [IMAP4Commands[cmdFetch], IMAP4Commands[cmdUID]], False); Result := False; Exit; end; LHelper := TIdIMAP4WorkHelper.Create(Self); try if TextIsSame(LContentTransferEncoding, 'base64') then begin {Do not Localize} DoDecode(TIdDecoderMIME, True); end else if TextIsSame(LContentTransferEncoding, 'quoted-printable') then begin {Do not Localize} DoDecode(TIdDecoderQuotedPrintable); end else if TextIsSame(LContentTransferEncoding, 'binhex40') then begin {Do not Localize} DoDecode(TIdDecoderBinHex4); end else begin {Assume no encoding (8bit) or something we cannot decode...} DoDecode(); end; finally FreeAndNil(LHelper); end; IOHandler.ReadLnWait; {Remove last line, ')' or 'UID 1)'} if GetInternalResponse(GetCmdCounter, [IMAP4Commands[cmdFetch], IMAP4Commands[cmdUID]], False) = IMAP_OK then begin Result := True; end; except on E: EIdSocketError do begin if E.LastError = Id_WSAECONNRESET then begin //Connection reset by peer... FConnectionState := csUnexpectedlyDisconnected; end; raise; end; end; end; end; function TIdIMAP4.RetrieveStructure(const AMsgNum: Integer; AMsg: TIdMessage): Boolean; begin IsNumberValid(AMsgNum); Result := InternalRetrieveStructure(AMsgNum, AMsg, nil); end; function TIdIMAP4.RetrieveStructure(const AMsgNum: Integer; AParts: TIdImapMessageParts): Boolean; begin IsNumberValid(AMsgNum); Result := InternalRetrieveStructure(AMsgNum, nil, AParts); end; function TIdIMAP4.InternalRetrieveStructure(const AMsgNum: Integer; AMsg: TIdMessage; AParts: TIdImapMessageParts): Boolean; var LTheParts: TIdMessageParts; begin Result := False; CheckConnectionState(csSelected); SendCmd(NewCmdCounter, IMAP4Commands[cmdFetch] + ' ' + IntToStr(AMsgNum) + ' (' + IMAP4FetchDataItem[fdBodyStructure] + ')', [IMAP4Commands[cmdFetch]], True); if LastCmdResult.Code = IMAP_OK then begin {CC3: Catch "Connection reset by peer"...} try if LastCmdResult.Text.Count > 0 then begin if ParseLastCmdResult(LastCmdResult.Text[0], IMAP4Commands[cmdFetch], [IMAP4FetchDataItem[fdBodyStructure]]) then begin if AMsg <> nil then begin LTheParts := AMsg.MessageParts; end else begin LTheParts := nil; end; ParseBodyStructureResult(FLineStruct.IMAPValue, LTheParts, AParts); if GetInternalResponse(GetCmdCounter, [IMAP4Commands[cmdFetch]], False) = IMAP_OK then begin Result := True; end; end; end; except on E: EIdSocketError do begin if E.LastError = Id_WSAECONNRESET then begin //Connection reset by peer... FConnectionState := csUnexpectedlyDisconnected; end; raise; end; end; end; end; // retrieve a specific individual part of a message function TIdIMAP4.RetrievePart(const AMsgNum: Integer; const APartNum: string; ADestStream: TStream; AContentTransferEncoding: string): Boolean; var LDummy1: {$IFDEF DOTNET}TIdBytes{$ELSE}PByte{$ENDIF}; LDummy2: Integer; begin IsNumberValid(AMsgNum); if ADestStream = nil then begin Result := False; Exit; end; Result := InternalRetrievePart(AMsgNum, APartNum, False, False, ADestStream, LDummy1, LDummy2, '', AContentTransferEncoding); {Do not Localize} end; function TIdIMAP4.RetrievePart(const AMsgNum: Integer; const APartNum: Integer; var ABuffer: {$IFDEF DOTNET}TIdBytes{$ELSE}PByte{$ENDIF}; var ABufferLength: Integer; AContentTransferEncoding: string): Boolean; begin IsNumberValid(APartNum); Result := RetrievePart(AMsgNum, IntToStr(APartNum), ABuffer, ABufferLength, AContentTransferEncoding); end; // Retrieve a specific individual part of a message function TIdIMAP4.RetrievePart(const AMsgNum: Integer; const APartNum: string; var ABuffer: {$IFDEF DOTNET}TIdBytes{$ELSE}PByte{$ENDIF}; var ABufferLength: Integer; AContentTransferEncoding: string): Boolean; begin IsNumberValid(AMsgNum); Result := InternalRetrievePart(AMsgNum, APartNum, False, False, nil, ABuffer, ABufferLength, '', AContentTransferEncoding); {Do not Localize} end; // retrieve a specific individual part of a message function TIdIMAP4.RetrievePartPeek(const AMsgNum: Integer; const APartNum: string; ADestStream: TStream; AContentTransferEncoding: string): Boolean; var LDummy1: {$IFDEF DOTNET}TIdBytes{$ELSE}PByte{$ENDIF}; LDummy2: Integer; begin IsNumberValid(AMsgNum); if ADestStream = nil then begin Result := False; Exit; end; Result := InternalRetrievePart(AMsgNum, APartNum, False, True, ADestStream, LDummy1, LDummy2, '', AContentTransferEncoding); {Do not Localize} end; function TIdIMAP4.RetrievePartPeek(const AMsgNum: Integer; const APartNum: Integer; var ABuffer: {$IFDEF DOTNET}TIdBytes{$ELSE}PByte{$ENDIF}; var ABufferLength: Integer; AContentTransferEncoding: string): Boolean; begin IsNumberValid(APartNum); Result := RetrievePartPeek(AMsgNum, IntToStr(APartNum), ABuffer, ABufferLength, AContentTransferEncoding); end; //Retrieve a specific individual part of a message function TIdIMAP4.RetrievePartPeek(const AMsgNum: Integer; const APartNum: string; var ABuffer: {$IFDEF DOTNET}TIdBytes{$ELSE}PByte{$ENDIF}; var ABufferLength: Integer; AContentTransferEncoding: string): Boolean; begin IsNumberValid(AMsgNum); Result := InternalRetrievePart(AMsgNum, APartNum, False, True, nil, ABuffer, ABufferLength, '', AContentTransferEncoding); {Do not Localize} end; // Retrieve a specific individual part of a message function TIdIMAP4.UIDRetrievePart(const AMsgUID: String; const APartNum: string; var ADestStream: TStream; AContentTransferEncoding: string): Boolean; var LDummy1: {$IFDEF DOTNET}TIdBytes{$ELSE}PByte{$ENDIF}; LDummy2: Integer; begin IsUIDValid(AMsgUID); if ADestStream = nil then begin Result := False; Exit; end; Result := InternalRetrievePart(IndyStrToInt(AMsgUID), APartNum, True, False, ADestStream, LDummy1, LDummy2, '', AContentTransferEncoding); {Do not Localize} end; function TIdIMAP4.UIDRetrievePart(const AMsgUID: String; const APartNum: Integer; var ABuffer: {$IFDEF DOTNET}TIdBytes{$ELSE}PByte{$ENDIF}; var ABufferLength: Integer; AContentTransferEncoding: string): Boolean; begin IsNumberValid(APartNum); Result := UIDRetrievePart(AMsgUID, IntToStr(APartNum), ABuffer, ABufferLength, AContentTransferEncoding); end; // Retrieve a specific individual part of a message function TIdIMAP4.UIDRetrievePart(const AMsgUID: String; const APartNum: string; var ABuffer: {$IFDEF DOTNET}TIdBytes{$ELSE}PByte{$ENDIF}; var ABufferLength: Integer; AContentTransferEncoding: string): Boolean; begin IsUIDValid(AMsgUID); Result := InternalRetrievePart(IndyStrToInt(AMsgUID), APartNum, True, False, nil, ABuffer, ABufferLength, '', AContentTransferEncoding); {Do not Localize} end; // retrieve a specific individual part of a message function TIdIMAP4.UIDRetrievePartPeek(const AMsgUID: String; const APartNum: string; var ADestStream: TStream; AContentTransferEncoding: string): Boolean; var LDummy1: {$IFDEF DOTNET}TIdBytes{$ELSE}PByte{$ENDIF}; LDummy2: Integer; begin IsUIDValid(AMsgUID); if ADestStream = nil then begin Result := False; Exit; end; Result := InternalRetrievePart(IndyStrToInt(AMsgUID), APartNum, True, True, ADestStream, LDummy1, LDummy2, '', AContentTransferEncoding); {Do not Localize} end; function TIdIMAP4.UIDRetrievePartPeek(const AMsgUID: String; const APartNum: Integer; var ABuffer: {$IFDEF DOTNET}TIdBytes{$ELSE}PByte{$ENDIF}; var ABufferLength: Integer; AContentTransferEncoding: string): Boolean; begin IsNumberValid(APartNum); Result := UIDRetrievePartPeek(AMsgUID, IntToStr(APartNum), ABuffer, ABufferLength, AContentTransferEncoding); end; function TIdIMAP4.UIDRetrievePartPeek(const AMsgUID: String; const APartNum: string; var ABuffer: {$IFDEF DOTNET}TIdBytes{$ELSE}PByte{$ENDIF}; var ABufferLength: Integer; AContentTransferEncoding: string): Boolean; //Retrieve a specific individual part of a message begin IsUIDValid(AMsgUID); Result := InternalRetrievePart(IndyStrToInt(AMsgUID), APartNum, True, True, nil, ABuffer, ABufferLength, '', AContentTransferEncoding); {Do not Localize} end; function TIdIMAP4.RetrievePartToFile(const AMsgNum: Integer; const APartNum: Integer; ALength: Integer; ADestFileNameAndPath: string; AContentTransferEncoding: string): Boolean; begin IsNumberValid(APartNum); Result := RetrievePartToFile(AMsgNum, IntToStr(APartNum), ALength, ADestFileNameAndPath, AContentTransferEncoding); end; // retrieve a specific individual part of a message function TIdIMAP4.RetrievePartToFile(const AMsgNum: Integer; const APartNum: string; ALength: Integer; ADestFileNameAndPath: string; AContentTransferEncoding: string): Boolean; var LDummy: {$IFDEF DOTNET}TIdBytes{$ELSE}PByte{$ENDIF}; begin IsNumberValid(AMsgNum); if Length(ADestFileNameAndPath) = 0 then begin Result := False; Exit; end; Result := InternalRetrievePart(AMsgNum, APartNum, False, False, nil, LDummy, ALength, ADestFileNameAndPath, AContentTransferEncoding); end; function TIdIMAP4.RetrievePartToFilePeek(const AMsgNum: Integer; const APartNum: Integer; ALength: Integer; ADestFileNameAndPath: string; AContentTransferEncoding: string): Boolean; begin IsNumberValid(APartNum); Result := RetrievePartToFilePeek(AMsgNum, IntToStr(APartNum), ALength, ADestFileNameAndPath, AContentTransferEncoding); end; // retrieve a specific individual part of a message function TIdIMAP4.RetrievePartToFilePeek(const AMsgNum: Integer; const APartNum: string; ALength: Integer; ADestFileNameAndPath: string; AContentTransferEncoding: string): Boolean; var LDummy: {$IFDEF DOTNET}TIdBytes{$ELSE}PByte{$ENDIF}; begin IsNumberValid(AMsgNum); if Length(ADestFileNameAndPath) = 0 then begin Result := False; Exit; end; Result := InternalRetrievePart(AMsgNum, APartNum, False, True, nil, LDummy, ALength, ADestFileNameAndPath, AContentTransferEncoding); end; function TIdIMAP4.UIDRetrievePartToFile(const AMsgUID: String; const APartNum: Integer; ALength: Integer; ADestFileNameAndPath: string; AContentTransferEncoding: string): Boolean; begin IsNumberValid(APartNum); Result := UIDRetrievePartToFile(AMsgUID, IntToStr(APartNum), ALength, ADestFileNameAndPath, AContentTransferEncoding); end; // retrieve a specific individual part of a message function TIdIMAP4.UIDRetrievePartToFile(const AMsgUID: String; const APartNum: string; ALength: Integer; ADestFileNameAndPath: string; AContentTransferEncoding: string): Boolean; var LDummy: {$IFDEF DOTNET}TIdBytes{$ELSE}PByte{$ENDIF}; begin IsUIDValid(AMsgUID); if Length(ADestFileNameAndPath) = 0 then begin Result := False; Exit; end; Result := InternalRetrievePart(IndyStrToInt(AMsgUID), APartNum, True, False, nil, LDummy, ALength, ADestFileNameAndPath, AContentTransferEncoding); end; function TIdIMAP4.UIDRetrievePartToFilePeek(const AMsgUID: String; const APartNum: Integer; ALength: Integer; ADestFileNameAndPath: string; AContentTransferEncoding: string): Boolean; begin IsNumberValid(APartNum); Result := UIDRetrievePartToFilePeek(AMsgUID, IntToStr(APartNum), ALength, ADestFileNameAndPath, AContentTransferEncoding); end; // retrieve a specific individual part of a message function TIdIMAP4.UIDRetrievePartToFilePeek(const AMsgUID: String; const APartNum: {Integer} string; ALength: Integer; ADestFileNameAndPath: string; AContentTransferEncoding: string): Boolean; var LDummy: {$IFDEF DOTNET}TIdBytes{$ELSE}PByte{$ENDIF}; begin IsUIDValid(AMsgUID); if Length(ADestFileNameAndPath) = 0 then begin Result := False; Exit; end; Result := InternalRetrievePart(IndyStrToInt(AMsgUID), APartNum, True, True, nil, LDummy, ALength, ADestFileNameAndPath, AContentTransferEncoding); end; // retrieve a specific individual part of a message // TODO: remove the ABufferLength output parameter under DOTNET, it is redundant... function TIdIMAP4.InternalRetrievePart(const AMsgNum: Integer; const APartNum: {Integer} string; AUseUID: Boolean; AUsePeek: Boolean; ADestStream: TStream; var ABuffer: {$IFDEF DOTNET}TIdBytes{$ELSE}PByte{$ENDIF}; var ABufferLength: Integer; {NOTE: var args cannot have default params} ADestFileNameAndPath: string; AContentTransferEncoding: string): Boolean; var LCmd: string; bCreatedStream: Boolean; LDestStream: TStream; // LPartSizeParam: string; LHelper: TIdIMAP4WorkHelper; procedure DoDecode(ADecoderClass: TIdDecoderClass = nil; AStripCRLFs: Boolean = False); var LDecoder: TIdDecoder; LStream: TStream; LStrippedStream: TStringStream; LUnstrippedStream: TStringStream; begin if LDestStream = nil then begin LStream := TMemoryStream.Create; end else begin LStream := LDestStream; end; try if ADecoderClass <> nil then begin LDecoder := ADecoderClass.Create(Self); try LDecoder.DecodeBegin(LStream); try LUnstrippedStream := TStringStream.Create(''); try IOHandler.ReadStream(LUnstrippedStream, ABufferLength); //ReadStream uses OnWork, most other methods dont {This is more complicated than quoted-printable because we have to strip CRLFs that have been inserted by the MTA to avoid overly long lines...} if AStripCRLFs then begin LStrippedStream := TStringStream.Create(''); try StripCRLFs(LUnstrippedStream, LStrippedStream); LDecoder.Decode(LStrippedStream.DataString); finally FreeAndNil(LStrippedStream); end; end else begin LDecoder.Decode(LUnstrippedStream.DataString); end; finally FreeAndNil(LUnstrippedStream); end; finally LDecoder.DecodeEnd; end; finally FreeAndNil(LDecoder); end; end else begin IOHandler.ReadStream(LStream, ABufferLength); //ReadStream uses OnWork, most other methods dont end; if LDestStream = nil then begin ABufferLength := LStream.Size; {$IFDEF DOTNET} //ABuffer is a TIdBytes. SetLength(ABuffer, ABufferLength); if ABufferLength > 0 then begin LStream.Position := 0; ReadTIdBytesFromStream(LStream, ABuffer, ABufferLength); end; {$ELSE} //ABuffer is a PByte. GetMem(ABuffer, ABufferLength); if ABufferLength > 0 then begin LStream.Position := 0; LStream.ReadBuffer(ABuffer^, ABufferLength); end; {$ENDIF} end; finally if LDestStream = nil then begin FreeAndNil(LStream); end; end; end; begin {CCC: Make sure part number is valid since it is now passed as a string...} IsImapPartNumberValid(APartNum); Result := False; ABuffer := nil; ABufferLength := 0; CheckConnectionState(csSelected); LCmd := ''; if AUseUID then begin LCmd := LCmd + IMAP4Commands[cmdUID] + ' '; {Do not Localize} end; LCmd := LCmd + IMAP4Commands[cmdFetch] + ' ' + IntToStr(AMsgNum) + ' ('; {Do not Localize} if AUsePeek then begin LCmd := LCmd + IMAP4FetchDataItem[fdBody]+'.PEEK'; {Do not Localize} end else begin LCmd := LCmd + IMAP4FetchDataItem[fdBody]; end; LCmd := LCmd + '[' + APartNum + '])'; {Do not Localize} SendCmd(NewCmdCounter, LCmd, [IMAP4Commands[cmdFetch], IMAP4Commands[cmdUID]], True); if LastCmdResult.Code = IMAP_OK then begin {CC3: Catch "Connection reset by peer"...} try //LPartSizeParam := ''; {Do not Localize} if ( (LastCmdResult.Text.Count < 1) or (not ParseLastCmdResult(LastCmdResult.Text[0], IMAP4Commands[cmdFetch], [])) or (PosInStrArray(FLineStruct.IMAPValue, ['NIL', '""'], False) <> -1) {do not localize} or (FLineStruct.ByteCount < 1) ) then begin GetInternalResponse(GetCmdCounter, [IMAP4Commands[cmdFetch], IMAP4Commands[cmdUID]], False); Result := False; Exit; end; {CC4: Some messages have an empty first part. These respond as: 17 FETCH (BODY[1] "" UID 20) instead of the more normal: 17 FETCH (BODY[1] {11} {This bracket is not part of the response! ... UID 20) } ABufferLength := FLineStruct.ByteCount; bCreatedStream := False; if ADestStream = nil then begin if Length(ADestFileNameAndPath) = 0 then begin {User wants to write it to a memory block...} LDestStream := nil; end else begin {User wants to write it to a file...} LDestStream := TIdFileCreateStream.Create(ADestFileNameAndPath); bCreatedStream := True; end; end else begin {User wants to write it to a stream ...} LDestStream := ADestStream; end; try LHelper := TIdIMAP4WorkHelper.Create(Self); try if TextIsSame(AContentTransferEncoding, 'base64') then begin {Do not Localize} DoDecode(TIdDecoderMIME, True); end else if TextIsSame(AContentTransferEncoding, 'quoted-printable') then begin {Do not Localize} DoDecode(TIdDecoderQuotedPrintable); end else if TextIsSame(AContentTransferEncoding, 'binhex40') then begin {Do not Localize} DoDecode(TIdDecoderBinHex4); end else begin {Assume no encoding (8bit) or something we cannot decode...} DoDecode; end; finally FreeAndNil(LHelper); end; finally if bCreatedStream then begin FreeAndNil(LDestStream); end; end; IOHandler.ReadLnWait; {Remove last line, ')' or 'UID 1)'} if GetInternalResponse(GetCmdCounter, [IMAP4Commands[cmdFetch], IMAP4Commands[cmdUID]], False) = IMAP_OK then begin Result := True; end; except on E: EIdSocketError do begin if E.LastError = Id_WSAECONNRESET then begin //Connection reset by peer... FConnectionState := csUnexpectedlyDisconnected; end; raise; end; end; end; end; function TIdIMAP4.UIDRetrieveStructure(const AMsgUID: String; AMsg: TIdMessage): Boolean; begin IsUIDValid(AMsgUID); Result := UIDInternalRetrieveStructure(AMsgUID, AMsg, nil); end; function TIdIMAP4.UIDRetrieveStructure(const AMsgUID: String; AParts: TIdImapMessageParts): Boolean; begin IsUIDValid(AMsgUID); Result := UIDInternalRetrieveStructure(AMsgUID, nil, AParts); end; function TIdIMAP4.UIDInternalRetrieveStructure(const AMsgUID: String; AMsg: TIdMessage; AParts: TIdImapMessageParts): Boolean; var //LSlRetrieve : TStringList; //LStr: string; LTheParts: TIdMessageParts; begin Result := False; CheckConnectionState(csSelected); //Note: The normal single-line response may be split for huge bodystructures, //allow for this by setting ASingleLineMayBeSplit to True... SendCmd(NewCmdCounter, IMAP4Commands[cmdUID] + ' ' + IMAP4Commands[cmdFetch] + ' ' + AMsgUID + ' (' + IMAP4FetchDataItem[fdBodyStructure] + ')', {Do not Localize} [IMAP4Commands[cmdFetch], IMAP4Commands[cmdUID]], True, True); if LastCmdResult.Code = IMAP_OK then begin {CC3: Catch "Connection reset by peer"...} try if LastCmdResult.Text.Count > 0 then begin if ParseLastCmdResult(LastCmdResult.Text[0], IMAP4Commands[cmdFetch], [IMAP4FetchDataItem[fdBodyStructure]]) then begin if AMsg <> nil then begin LTheParts := AMsg.MessageParts; end else begin LTheParts := nil; end; ParseBodyStructureResult(FLineStruct.IMAPValue, LTheParts, AParts); if GetInternalResponse(GetCmdCounter, [IMAP4Commands[cmdFetch], IMAP4Commands[cmdUID]], False) = IMAP_OK then begin Result := True; end; end; end; except on E: EIdSocketError do begin if E.LastError = Id_WSAECONNRESET then begin //Connection reset by peer... FConnectionState := csUnexpectedlyDisconnected; end; raise; end; end; end; end; function TIdIMAP4.RetrieveHeader(const AMsgNum: Integer; AMsg: TIdMessage): Boolean; var LStr: string; begin Result := False; IsNumberValid(AMsgNum); CheckConnectionState(csSelected); SendCmd(NewCmdCounter, IMAP4Commands[cmdFetch] + ' ' + IntToStr(AMsgNum) + ' (' + IMAP4FetchDataItem[fdRFC822Header] + ')', {Do not Localize} [IMAP4Commands[cmdFetch]], True); if LastCmdResult.Code = IMAP_OK then begin {CC3: Catch "Connection reset by peer"...} try if LastCmdResult.Text.Count > 0 then begin if ParseLastCmdResult(LastCmdResult.Text[0], IMAP4Commands[cmdFetch], [IMAP4FetchDataItem[fdRFC822Header]]) and (FLineStruct.ByteCount > 0) then begin BeginWork(wmRead, FLineStruct.ByteCount); //allow ReadString to use OnWork try LStr := IOHandler.ReadString(FLineStruct.ByteCount); finally EndWork(wmRead); end; {CC2: Clear out body so don't get multiple copies of bodies} AMsg.Clear; AMsg.Headers.Text := LStr; AMsg.ProcessHeaders; LStr := IOHandler.ReadLnWait; {Remove trailing line after the message, probably a ')' } ParseLastCmdResultButAppendInfo(LStr); //There may be a UID or FLAGS in this if GetInternalResponse(GetCmdCounter, [IMAP4Commands[cmdFetch]], False) = IMAP_OK then begin Result := True; end; end; end; except on E: EIdSocketError do begin if E.LastError = Id_WSAECONNRESET then begin //Connection reset by peer... FConnectionState := csUnexpectedlyDisconnected; end; raise; end; end; end; end; function TIdIMAP4.UIDRetrieveHeader(const AMsgUID: String; AMsg: TIdMessage): Boolean; var LStr: string; begin Result := False; IsUIDValid(AMsgUID); CheckConnectionState(csSelected); SendCmd(NewCmdCounter, IMAP4Commands[cmdUID] + ' ' + IMAP4Commands[cmdFetch] + ' ' + AMsgUID + ' (' + IMAP4FetchDataItem[fdRFC822Header] + ')', {Do not Localize} [IMAP4Commands[cmdFetch], IMAP4Commands[cmdUID]], True); if LastCmdResult.Code = IMAP_OK then begin {CC3: Catch "Connection reset by peer"...} try if LastCmdResult.Text.Count > 0 then begin if ParseLastCmdResult(LastCmdResult.Text[0], IMAP4Commands[cmdFetch], [IMAP4FetchDataItem[fdRFC822Header]]) and (FLineStruct.ByteCount > 0) then begin BeginWork(wmRead, FLineStruct.ByteCount); //allow ReadString to use OnWork try LStr := IOHandler.ReadString(FLineStruct.ByteCount); finally EndWork(wmRead); end; {CC2: Clear out body so don't get multiple copies of bodies} AMsg.Clear; AMsg.Headers.Text := LStr; AMsg.ProcessHeaders; LStr := IOHandler.ReadLnWait; {Remove trailing line after the message, probably a ')' } ParseLastCmdResultButAppendInfo(LStr); //There may be a UID or FLAGS in this if GetInternalResponse(GetCmdCounter, [IMAP4Commands[cmdFetch], IMAP4Commands[cmdUID]], False) = IMAP_OK then begin Result := True; end; end; end; except on E: EIdSocketError do begin if E.LastError = Id_WSAECONNRESET then begin //Connection reset by peer... FConnectionState := csUnexpectedlyDisconnected; end; raise; end; end; end; end; function TIdIMAP4.RetrievePartHeader(const AMsgNum: Integer; const APartNum: string; AHeaders: TIdHeaderList): Boolean; begin IsNumberValid(AMsgNum); Result := InternalRetrievePartHeader(AMsgNum, APartNum, False, AHeaders); end; function TIdIMAP4.UIDRetrievePartHeader(const AMsgUID: String; const APartNum: string; AHeaders: TIdHeaderList): Boolean; begin IsUIDValid(AMsgUID); Result := InternalRetrievePartHeader(IndyStrToInt(AMsgUID), APartNum, True, AHeaders); end; function TIdIMAP4.InternalRetrievePartHeader(const AMsgNum: Integer; const APartNum: string; const AUseUID: Boolean; AHeaders: TIdHeaderList): Boolean; var LCmd: string; begin Result := False; CheckConnectionState(csSelected); LCmd := ''; if AUseUID then begin LCmd := LCmd + IMAP4Commands[cmdUID] + ' '; {Do not Localize} end; LCmd := LCmd + IMAP4Commands[cmdFetch] + ' ' + IntToStr(AMsgNum) + ' (' + IMAP4FetchDataItem[fdBody] + '[' + APartNum + '.' + IMAP4FetchDataItem[fdHeader] + '])'; {Do not Localize} SendCmd(NewCmdCounter, LCmd, [IMAP4Commands[cmdFetch], IMAP4Commands[cmdUID]], True); if LastCmdResult.Code = IMAP_OK then begin {CC3: Catch "Connection reset by peer"...} try if LastCmdResult.Text.Count > 0 then begin if ParseLastCmdResult(LastCmdResult.Text[0], IMAP4Commands[cmdFetch], []) and (PosInStrArray(FLineStruct.IMAPValue, ['NIL', '""'], False) = -1) and (FLineStruct.ByteCount > 0) then begin {CC4: Some messages have an empty first part. These respond as: 17 FETCH (BODY[1] "" UID 20) instead of the more normal: 17 FETCH (BODY[1] {11} {This bracket is not part of the response! ... UID 20) } BeginWork(wmRead, FLineStruct.ByteCount); //allow ReadString to use OnWork try AHeaders.Text := IOHandler.ReadString(FLineStruct.ByteCount); finally EndWork(wmRead); end; end; end; IOHandler.ReadLnWait; if GetInternalResponse(GetCmdCounter, [IMAP4Commands[cmdFetch], IMAP4Commands[cmdUID]], False) = IMAP_OK then begin Result := True; end; except on E: EIdSocketError do begin if E.LastError = Id_WSAECONNRESET then begin //Connection reset by peer... FConnectionState := csUnexpectedlyDisconnected; end; raise; end; end; end; end; //This code was just pulled up from IdMessageClient so that logging could be added. function TIdIMAP4.ReceiveHeader(AMsg: TIdMessage; const AAltTerm: string = ''): string; begin repeat Result := IOHandler.ReadLn; // Exchange Bug: Exchange sometimes returns . when getting a message instead of // '' then a . - That is there is no seperation between the header and the message for an // empty message. if ((Length(AAltTerm) = 0) and (Result = '.')) or (Result = AAltTerm) then begin Break; end else if Length(Result) <> 0 then begin AMsg.Headers.Append(Result); end; until False; AMsg.ProcessHeaders; end; function TIdIMAP4.Retrieve(const AMsgNum: Integer; AMsg: TIdMessage): Boolean; begin IsNumberValid(AMsgNum); Result := InternalRetrieve(AMsgNum, False, False, AMsg); end; //Retrieves a whole message "raw" and saves it to file, while marking it read. function TIdIMAP4.RetrieveNoDecodeToFile(const AMsgNum: Integer; ADestFile: string): Boolean; var LMsg: TIdMessage; begin Result := False; IsNumberValid(AMsgNum); LMsg := TIdMessage.Create(nil); try LMsg.NoDecode := True; LMsg.NoEncode := True; if InternalRetrieve(AMsgNum, False, False, LMsg) then begin {RLebeau 12/09/2012: NOT currently using the same workaround here that is being used in AppendMsg() to avoid SMTP dot transparent output from TIdMessage.SaveToStream(). The reason for this is because I don't know how this method is being used and I don't want to break anything that may be depending on that transparent output being generated...} LMsg.SaveToFile(ADestFile); Result := True; end; finally FreeAndNil(LMsg); end; end; //Retrieves a whole message "raw" and saves it to file, while marking it read. function TIdIMAP4.RetrieveNoDecodeToStream(const AMsgNum: Integer; AStream: TStream): Boolean; var LMsg: TIdMessage; begin Result := False; IsNumberValid(AMsgNum); LMsg := TIdMessage.Create(nil); try LMsg.NoDecode := True; LMsg.NoEncode := True; if InternalRetrieve(AMsgNum, False, False, LMsg) then begin {RLebeau 12/09/2012: NOT currently using the same workaround here that is being used in AppendMsg() to avoid SMTP dot transparent output from TIdMessage.SaveToStream(). The reason for this is because I don't know how this method is being used and I don't want to break anything that may be depending on that transparent output being generated...} LMsg.SaveToStream(AStream); Result := True; end; finally FreeAndNil(LMsg); end; end; function TIdIMAP4.RetrievePeek(const AMsgNum: Integer; AMsg: TIdMessage): Boolean; begin IsNumberValid(AMsgNum); Result := InternalRetrieve(AMsgNum, False, True, AMsg); end; function TIdIMAP4.UIDRetrieve(const AMsgUID: String; AMsg: TIdMessage): Boolean; begin IsUIDValid(AMsgUID); Result := InternalRetrieve(IndyStrToInt(AMsgUID), True, False, AMsg); end; //Retrieves a whole message "raw" and saves it to file, while marking it read. function TIdIMAP4.UIDRetrieveNoDecodeToFile(const AMsgUID: String; ADestFile: string): Boolean; var LMsg: TIdMessage; begin Result := False; IsUIDValid(AMsgUID); LMsg := TIdMessage.Create(nil); try LMsg.NoDecode := True; LMsg.NoEncode := True; if InternalRetrieve(IndyStrToInt(AMsgUID), True, False, LMsg) then begin {RLebeau 12/09/2012: NOT currently using the same workaround here that is being used in AppendMsg() to avoid SMTP dot transparent output from TIdMessage.SaveToStream(). The reason for this is because I don't know how this method is being used and I don't want to break anything that may be depending on that transparent output being generated...} LMsg.SaveToFile(ADestFile); Result := True; end; finally FreeAndNil(LMsg); end; end; //Retrieves a whole message "raw" and saves it to file, while marking it read. function TIdIMAP4.UIDRetrieveNoDecodeToStream(const AMsgUID: String; AStream: TStream): Boolean; var LMsg: TIdMessage; begin Result := False; IsUIDValid(AMsgUID); LMsg := TIdMessage.Create(nil); try LMsg.NoDecode := True; LMsg.NoEncode := True; if InternalRetrieve(IndyStrToInt(AMsgUID), True, False, LMsg) then begin {RLebeau 12/09/2012: NOT currently using the same workaround here that is being used in AppendMsg() to avoid SMTP dot transparent output from TIdMessage.SaveToStream(). The reason for this is because I don't know how this method is being used and I don't want to break anything that may be depending on that transparent output being generated...} LMsg.SaveToStream(AStream); Result := True; end; finally FreeAndNil(LMsg); end; end; function TIdIMAP4.UIDRetrievePeek(const AMsgUID: String; AMsg: TIdMessage): Boolean; begin IsUIDValid(AMsgUID); Result := InternalRetrieve(IndyStrToInt(AMsgUID), True, True, AMsg); end; function TIdIMAP4.InternalRetrieve(const AMsgNum: Integer; AUseUID: Boolean; AUsePeek: Boolean; AMsg: TIdMessage): Boolean; var LStr: String; LCmd: string; LDestStream: TStream; LHelper: TIdIMAP4WorkHelper; LMsgClient: TIdMessageClient; LMsgIO: TIdIOHandlerStreamMsg; begin Result := False; CheckConnectionState(csSelected); LCmd := ''; if AUseUID then begin LCmd := LCmd + IMAP4Commands[cmdUID] + ' '; {Do not Localize} end; LCmd := LCmd + IMAP4Commands[cmdFetch] + ' ' + IntToStr ( AMsgNum ) + ' ('; {Do not Localize} if AUsePeek then begin LCmd := LCmd + IMAP4FetchDataItem[fdBodyPeek]; {Do not Localize} end else begin LCmd := LCmd + IMAP4FetchDataItem[fdRFC822]; {Do not Localize} end; LCmd := LCmd + ')'; {Do not Localize} SendCmd(NewCmdCounter, LCmd, [IMAP4Commands[cmdFetch], IMAP4Commands[cmdUID]], True); if LastCmdResult.Code = IMAP_OK then begin {CC3: Catch "Connection reset by peer"...} try //Leave 3rd param as [] because ParseLastCmdResult can get a number of odd //replies ( variants on Body[] )... if (LastCmdResult.Text.Count < 1) or (not ParseLastCmdResult(LastCmdResult.Text[0], IMAP4Commands[cmdFetch], [])) then begin Exit; end; {CC8: Retrieve via byte count instead of looking for terminator, which was impossible to get working with all the different IMAP servers because some left the terminator (LExpectedResponse) at the end of a message line, so you could not decide if it was part of the message or the terminator.} AMsg.Clear; if FLineStruct.ByteCount > 0 then begin {Use a temporary memory block to suck the message into...} LDestStream := TMemoryStream.Create; try LHelper := TIdIMAP4WorkHelper.Create(Self); try IOHandler.ReadStream(LDestStream, FLineStruct.ByteCount); //ReadStream uses OnWork, most other methods dont finally FreeAndNil(LHelper); end; {Feed stream into the standard message parser...} LDestStream.Position := 0; {RLebeau 12/09/2012: this is a workaround to a design limitation in TIdMessage.LoadFromStream(). It assumes the stream data is always in an escaped format using SMTP dot transparency, but that is not the case in IMAP! Until this design is corrected, we have to use a workaround for now. This logic is copied from TIdMessage.LoadFromStream() and slightly tweaked...} //AMsg.LoadFromStream(LDestStream); LMsgClient := TIdMessageClient.Create(nil); try LMsgIO := TIdIOHandlerStreamMsg.Create(nil, LDestStream); try LMsgIO.FreeStreams := False; LMsgIO.EscapeLines := True; // this is the key piece that makes it work! LMsgClient.IOHandler := LMsgIO; try LMsgIO.Open; LMsgClient.ProcessMessage(AMsg, False); finally LMsgClient.IOHandler := nil; end; finally LMsgIO.Free; end; finally LMsgClient.Free; end; // end workaround finally FreeAndNil(LDestStream); end; end; LStr := IOHandler.ReadLnWait; {Remove trailing line after the message, probably a ')' } ParseLastCmdResultButAppendInfo(LStr); //There may be a UID or FLAGS in this if GetInternalResponse(GetCmdCounter, [IMAP4Commands[cmdFetch], IMAP4Commands[cmdUID]], False) = IMAP_OK then begin AMsg.UID := FLineStruct.UID; AMsg.Flags := FLineStruct.Flags; Result := True; end; except on E: EIdSocketError do begin if E.LastError = Id_WSAECONNRESET then begin //Connection reset by peer... FConnectionState := csUnexpectedlyDisconnected; end; raise; end; end; end; end; function TIdIMAP4.RetrieveAllHeaders(AMsgList: TIdMessageCollection): Boolean; begin Result := InternalRetrieveHeaders(AMsgList, -1); end; function TIdIMAP4.RetrieveFirstHeaders(AMsgList: TIdMessageCollection; ACount: LongInt): Boolean; begin Result := InternalRetrieveHeaders(AMsgList, ACount); end; function TIdIMAP4.InternalRetrieveHeaders(AMsgList: TIdMessageCollection; ACount: Integer): Boolean; var LMsgItem : TIdMessageItem; Ln : Integer; begin {CC2: This may get a response of "OK completed" if there are no messages} CheckConnectionState(csSelected); Result := False; if AMsgList <> nil then begin if (ACount < 0) or (ACount > FMailBox.TotalMsgs) then begin ACount := FMailBox.TotalMsgs; end; for Ln := 1 to ACount do begin LMsgItem := AMsgList.Add; if not RetrieveHeader(Ln, LMsgItem.Msg) then begin Exit; end; end; Result := True; end; end; function TIdIMAP4.RetrieveAllMsgs(AMsgList: TIdMessageCollection): Boolean; begin Result := InternalRetrieveMsgs(AMsgList, -1); end; function TIdIMAP4.RetrieveFirstMsgs(AMsgList: TIdMessageCollection; ACount: LongInt): Boolean; begin Result := InternalRetrieveMsgs(AMsgList, ACount); end; function TIdIMAP4.InternalRetrieveMsgs(AMsgList: TIdMessageCollection; ACount: LongInt): Boolean; var LMsgItem : TIdMessageItem; Ln : Integer; begin {CC2: This may get a response of "OK completed" if there are no messages} CheckConnectionState(csSelected); Result := False; if AMsgList <> nil then begin if (ACount < 0) or (ACount > FMailBox.TotalMsgs) then begin ACount := FMailBox.TotalMsgs; end; for Ln := 1 to ACount do begin LMsgItem := AMsgList.Add; if not Retrieve(Ln, LMsgItem.Msg) then begin Exit; end; end; Result := True; end; end; function TIdIMAP4.DeleteMsgs(const AMsgNumList: array of Integer): Boolean; begin Result := StoreFlags(AMsgNumList, sdAdd, [mfDeleted]); end; function TIdIMAP4.UIDDeleteMsg(const AMsgUID: String): Boolean; begin IsUIDValid(AMsgUID); Result := UIDStoreFlags(AMsgUID, sdAdd, [mfDeleted]); end; function TIdIMAP4.UIDDeleteMsgs(const AMsgUIDList: array of String): Boolean; begin Result := UIDStoreFlags(AMsgUIDList, sdAdd, [mfDeleted]); end; function TIdIMAP4.RetrieveMailBoxSize: Integer; var Ln : Integer; begin CheckConnectionState(csSelected); Result := -1; {CC2: This should not be checking FMailBox.TotalMsgs because the server may have added messages to the mailbox unknown to us, and we are going to ask the server anyway (if it's empty, we will return 0 anyway} SendCmd(NewCmdCounter, IMAP4Commands[cmdFetch] + ' 1:*' + ' (' + IMAP4FetchDataItem[fdRFC822Size] + ')', {Do not Localize} [IMAP4Commands[cmdFetch]]); if LastCmdResult.Code = IMAP_OK then begin Result := 0; for Ln := 0 to FMailBox.TotalMsgs - 1 do begin if ParseLastCmdResult(LastCmdResult.Text[Ln], IMAP4Commands[cmdFetch], [IMAP4FetchDataItem[fdRFC822Size]]) then begin Result := Result + IndyStrToInt( FLineStruct.IMAPValue ); end else begin {CC2: Return -1, not 0, if we cannot parse the result...} Result := -1; Exit; end; end; end; end; function TIdIMAP4.UIDRetrieveMailBoxSize: Integer; var Ln : Integer; begin CheckConnectionState(csSelected); Result := -1; {CC2: This should not be checking FMailBox.TotalMsgs because the server may have added messages to the mailbox unknown to us, and we are going to ask the server anyway (if it's empty, we will return 0 anyway} SendCmd(NewCmdCounter, IMAP4Commands[cmdUID] + ' ' + IMAP4Commands[cmdFetch] + ' 1:*' + ' (' + IMAP4FetchDataItem[fdRFC822Size] + ')', {Do not Localize} [IMAP4Commands[cmdFetch], IMAP4Commands[cmdUID]]); if LastCmdResult.Code = IMAP_OK then begin Result := 0; for Ln := 0 to FMailBox.TotalMsgs - 1 do begin if ParseLastCmdResult(LastCmdResult.Text[Ln], IMAP4Commands[cmdFetch], [IMAP4FetchDataItem[fdRFC822Size]]) then begin Result := Result + IndyStrToInt(FLineStruct.IMAPValue); end else begin {CC2: Return -1, not 0, if we cannot parse the result...} Result := -1; Break; end; end; end; end; function TIdIMAP4.RetrieveMsgSize(const AMsgNum: Integer): Integer; begin Result := -1; IsNumberValid(AMsgNum); CheckConnectionState(csSelected); SendCmd(NewCmdCounter, IMAP4Commands[cmdFetch] + ' ' + IntToStr ( AMsgNum ) + ' (' + IMAP4FetchDataItem[fdRFC822Size] + ')', {Do not Localize} [IMAP4Commands[cmdFetch]]); if LastCmdResult.Code = IMAP_OK then begin if (LastCmdResult.Text.Count > 0) and ParseLastCmdResult(LastCmdResult.Text[0], IMAP4Commands[cmdFetch], [IMAP4FetchDataItem[fdRFC822Size]]) then begin Result := IndyStrToInt(FLineStruct.IMAPValue); end; end; end; function TIdIMAP4.UIDRetrieveMsgSize(const AMsgUID: String): Integer; begin IsUIDValid(AMsgUID); Result := -1; CheckConnectionState(csSelected); SendCmd(NewCmdCounter, IMAP4Commands[cmdUID] + ' ' + IMAP4Commands[cmdFetch] + ' ' + AMsgUID + ' (' + IMAP4FetchDataItem[fdRFC822Size] + ')', {Do not Localize} [IMAP4Commands[cmdFetch], IMAP4Commands[cmdUID]]); if LastCmdResult.Code = IMAP_OK then begin if (LastCmdResult.Text.Count > 0) and ParseLastCmdResult(LastCmdResult.Text[0], IMAP4Commands[cmdFetch], [IMAP4FetchDataItem[fdRFC822Size]]) then begin Result := IndyStrToInt(FLineStruct.IMAPValue); end; end; end; function TIdIMAP4.CheckMsgSeen(const AMsgNum: Integer): Boolean; var LFlags: TIdMessageFlagsSet; begin IsNumberValid(AMsgNum); Result := False; CheckConnectionState(csSelected); SendCmd(NewCmdCounter, IMAP4Commands[cmdFetch] + ' ' + IntToStr(AMsgNum) + ' (' + IMAP4FetchDataItem[fdFlags] + ')', {Do not Localize} [IMAP4Commands[cmdFetch]]); if LastCmdResult.Code = IMAP_OK then begin if (LastCmdResult.Text.Count > 0) and ParseLastCmdResult(LastCmdResult.Text[0], IMAP4Commands[cmdFetch], [IMAP4FetchDataItem[fdFlags]]) then begin LFlags := FLineStruct.Flags; if mfSeen in LFlags then begin Result := True; end; end; end; end; function TIdIMAP4.UIDCheckMsgSeen(const AMsgUID: String): Boolean; var LFlags: TIdMessageFlagsSet; begin IsUIDValid(AMsgUID); {Default to unseen, so if get no flags back (i.e. no \Seen flag) we return False (i.e. we return it is unseen) Some servers return nothing at all if no flags set (the better ones return an empty set).} Result := False; CheckConnectionState(csSelected); SendCmd(NewCmdCounter, IMAP4Commands[cmdUID] + ' ' + IMAP4Commands[cmdFetch] + ' ' + AMsgUID + ' (' + IMAP4FetchDataItem[fdFlags] + ')', {Do not Localize} [IMAP4Commands[cmdFetch], IMAP4Commands[cmdUID]]); if LastCmdResult.Code = IMAP_OK then begin if (LastCmdResult.Text.Count > 0) and ParseLastCmdResult(LastCmdResult.Text[0], IMAP4Commands[cmdFetch], [IMAP4FetchDataItem[fdFlags]]) then begin LFlags := FLineStruct.Flags; if mfSeen in LFlags then begin Result := True; end; end; end; end; function TIdIMAP4.RetrieveFlags(const AMsgNum: Integer; var AFlags: {Pointer}TIdMessageFlagsSet): Boolean; begin IsNumberValid(AMsgNum); Result := False; {CC: Empty set to avoid returning resuts from a previous call if call fails} AFlags := []; CheckConnectionState(csSelected); SendCmd(NewCmdCounter, IMAP4Commands[cmdFetch] + ' ' + IntToStr (AMsgNum) + ' (' + IMAP4FetchDataItem[fdFlags] + ')', {Do not Localize} [IMAP4Commands[cmdFetch]]); if LastCmdResult.Code = IMAP_OK then begin if (LastCmdResult.Text.Count > 0) and ParseLastCmdResult(LastCmdResult.Text[0], IMAP4Commands[cmdFetch], [IMAP4FetchDataItem[fdFlags]]) then begin AFlags := FLineStruct.Flags; Result := True; end; end; end; function TIdIMAP4.UIDRetrieveFlags(const AMsgUID: String; var AFlags: TIdMessageFlagsSet): Boolean; begin IsUIDValid(AMsgUID); Result := False; {BUG FIX: Empty set to avoid returning resuts from a previous call if call fails} AFlags := []; CheckConnectionState(csSelected); SendCmd(NewCmdCounter, IMAP4Commands[cmdUID] + ' ' + IMAP4Commands[cmdFetch] + ' ' + AMsgUID + ' (' + IMAP4FetchDataItem[fdFlags] + ')', {Do not Localize} [IMAP4Commands[cmdFetch], IMAP4Commands[cmdUID]]); if LastCmdResult.Code = IMAP_OK then begin if (LastCmdResult.Text.Count > 0) and ParseLastCmdResult(LastCmdResult.Text[0], IMAP4Commands[cmdFetch], [IMAP4FetchDataItem[fdFlags]]) then begin AFlags := FLineStruct.Flags; Result := True; end; end; end; function TIdIMAP4.GetConnectionStateName: String; begin case FConnectionState of csAny : Result := RSIMAP4ConnectionStateAny; csNonAuthenticated : Result := RSIMAP4ConnectionStateNonAuthenticated; csAuthenticated : Result := RSIMAP4ConnectionStateAuthenticated; csSelected : Result := RSIMAP4ConnectionStateSelected; csUnexpectedlyDisconnected : Result := RSIMAP4ConnectionStateUnexpectedlyDisconnected; end; end; { TIdIMAP4 Commands } { Parser Functions... } {This recursively parses down. It gets either a line like: "text" "plain" ("charset" "ISO-8859-1") NIL NIL "7bit" 40 1 NIL NIL NIL which it parses into AThisImapPart, and we are done (at the end of the recursive calls), or a line like: ("text" "plain"...NIL)("text" "html"...NIL) "alternative" ("boundary" "----bdry") NIL NIL when we need to add "alternative" and the boundary to this part, but recurse down for the 1st two parts. } procedure TIdIMAP4.ParseImapPart(ABodyStructure: string; AImapParts: TIdImapMessageParts; AThisImapPart: TIdImapMessagePart; AParentImapPart: TIdImapMessagePart; //ImapPart version APartNumber: integer); var LNextImapPart: TIdImapMessagePart; LSubParts: TStringList; LPartNumber: integer; begin ABodyStructure := Trim(ABodyStructure); AThisImapPart.FUnparsedEntry := ABodyStructure; if ABodyStructure[1] <> '(' then begin {Do not Localize} //We are at the bottom. Parse the low-level '"text" "plain"...' into this part. ParseBodyStructurePart(ABodyStructure, nil, AThisImapPart); if AParentImapPart = nil then begin //This is the top-level part, and it is "text" "plain" etc, so it is not MIME... AThisImapPart.Encoding := mePlainText; AThisImapPart.ImapPartNumber := '1'; {Do not Localize} AThisImapPart.ParentPart := -1; end else begin AThisImapPart.Encoding := meMIME; AThisImapPart.ImapPartNumber := AParentImapPart.ImapPartNumber+'.'+IntToStr(APartNumber); {Do not Localize} //If we are the first level down in MIME, the parent part was '', so trim... if AThisImapPart.ImapPartNumber[1] = '.' then begin {Do not Localize} AThisImapPart.ImapPartNumber := Copy(AThisImapPart.ImapPartNumber, 2, MaxInt); end; AThisImapPart.ParentPart := AParentImapPart.Index; end; end else begin AThisImapPart.Encoding := meMIME; if AParentImapPart = nil then begin AThisImapPart.ImapPartNumber := ''; AThisImapPart.ParentPart := -1; end else begin AThisImapPart.ImapPartNumber := AParentImapPart.ImapPartNumber+'.'+IntToStr(APartNumber); {Do not Localize} //If we are the first level down in MIME, the parent part was '', so trim... if AThisImapPart.ImapPartNumber[1] = '.' then begin {Do not Localize} AThisImapPart.ImapPartNumber := Copy(AThisImapPart.ImapPartNumber, 2, MaxInt); end; AThisImapPart.ParentPart := AParentImapPart.Index; end; LSubParts := TStringList.Create; try ParseIntoBrackettedQuotedAndUnquotedParts(ABodyStructure, LSubParts, True); LPartNumber := 1; while (LSubParts.Count > 0) and (LSubParts[0] <> '') and (LSubParts[0][1] = '(') do begin {Do not Localize} LNextImapPart := AImapParts.Add; ParseImapPart(Copy(LSubParts[0], 2, Length(LSubParts[0])-2), AImapParts, LNextImapPart, AThisImapPart, LPartNumber); LSubParts.Delete(0); Inc(LPartNumber); end; if LSubParts.Count > 0 then begin //LSubParts now (only) holds the params for this part... AThisImapPart.FBodyType := LowerCase(GetNextQuotedParam(LSubParts[0], True)); //mixed, alternative end else begin AThisImapPart.FBodyType := ''; end; finally FreeAndNil(LSubParts); end; end; end; { WARNING: Not used by writer, may have bugs. Version of ParseImapPart except using TIdMessageParts. Added for compatibility with TIdMessage.MessageParts, but does not have enough functionality for many IMAP functions. } procedure TIdIMAP4.ParseMessagePart(ABodyStructure: string; AMessageParts: TIdMessageParts; AThisMessagePart: TIdMessagePart; AParentMessagePart: TIdMessagePart; //MessageParts version APartNumber: integer); var LNextMessagePart: TIdMessagePart; LSubParts: TStringList; LPartNumber: integer; begin ABodyStructure := Trim(ABodyStructure); if ABodyStructure[1] <> '(' then begin {Do not Localize} //We are at the bottom. Parse this into this part. ParseBodyStructurePart(ABodyStructure, AThisMessagePart, nil); if AParentMessagePart = nil then begin //This is the top-level part, and it is "text" "plain" etc, so it is not MIME... AThisMessagePart.ParentPart := -1; end else begin AThisMessagePart.ParentPart := AParentMessagePart.Index; end; end else begin LSubParts := TStringList.Create; try ParseIntoBrackettedQuotedAndUnquotedParts(ABodyStructure, LSubParts, True); LPartNumber := 1; while (LSubParts.Count > 0) and (LSubParts[0] <> '') and (LSubParts[0][1] = '(') do begin {Do not Localize} LNextMessagePart := TIdAttachmentMemory.Create(AMessageParts); ParseMessagePart(Copy(LSubParts[0], 2, Length(LSubParts[0])-2), AMessageParts, LNextMessagePart, AThisMessagePart, LPartNumber); LSubParts.Delete(0); Inc(LPartNumber); end; //LSubParts now (only) holds the params for this part... if AParentMessagePart = nil then begin AThisMessagePart.ParentPart := -1; end else begin AThisMessagePart.ParentPart := AParentMessagePart.Index; end; finally FreeAndNil(LSubParts); end; end; end; {CC2: Function added to support individual part retreival} { If it's a single-part message, it won't be enclosed in brackets - it will be: "body type": "TEXT", "application", "image", "MESSAGE" (followed by subtype RFC822 for envelopes, ignore) "body subtype": "PLAIN", "octet-stream", "tiff", "html" "body parameter parenthesized list": bracketted list of pairs ("CHARSET" "US-ASCII" "NAME" "cc.tif" "format" "flowed"), ("charset" "ISO-8859-1") "body id": NIL, 986767766767887@fg.com "body description": NIL, "Compiler diff" "body encoding": "7bit" "8bit" "binary" (NO encoding used with these), "quoted-printable" "base64" "ietf-token" "x-token" "body size" 2279 "body lines" 48 (only present for some types, only those with "body type=text" and "body subtype=plain" that I found, if not present it WONT be a NIL, it just won't be there! However, it won't be needed) <don't know> NIL <don't know> ("inline" ("filename" "classbd.h")), ("attachment" ("filename" "DEGDAY.WB3")) <don't know> NIL Example: * 4 FETCH (BODYSTRUCTURE ("text" "plain" ("charset" "ISO-8859-1") NIL NIL "7bit" 40 1 NIL NIL NIL)) --------------------------------------------------------------------------- For most multi-part messages, each part will be bracketted: ( (part 1 stuff) (part 2 stuff) "mixed" (boundary) NIL NIL ) Example: * 1 FETCH (BODYSTRUCTURE (("text" "plain" ("charset" "us-ascii" "format" "flowed") NIL NIL "7bit" 52 3 NIL NIL NIL)("text" "plain" ("name" "tnkin.txt") NIL NIL "7bit" 28421 203 NIL ("inline" ("filename" "tnkin.txt")) NIL) "mixed" ("boundary" "------------070105030104060407030601") NIL NIL)) --------------------------------------------------------------------------- Some multiparts are bracketted again. This is the "alternative" encoding, part 1 has two parts, a plain-text part and a html part: ( ( (part 1a stuff) (part 1b stuff) "alternative" (boundary) NIL NIL ) (part 2 stuff) "mixed" (boundary) NIL NIL ) 1 2 2 1 Example: * 50 FETCH (BODYSTRUCTURE ((("text" "plain" ("charset" "ISO-8859-1") NIL NIL "quoted-printable" 415 12 NIL NIL NIL)("text" "html" ("charset" "ISO-8859-1") NIL NIL "quoted-printable" 1034 25 NIL NIL NIL) "alternative" ("boundary" "----=_NextPart_001_0027_01C33A37.33CFE220") NIL NIL)("application" "x-zip-compressed" ("name" "IdIMAP4.zip") NIL NIL "base64" 20572 NIL ("attachment" ("filename" "IdIMAP4.zip")) NIL) "mixed" ("boundary" "----=_NextPart_000_0026_01C33A37.33CFE220") NIL NIL) UID 62) } procedure TIdIMAP4.ParseBodyStructureResult(ABodyStructure: string; ATheParts: TIdMessageParts; AImapParts: TIdImapMessageParts); begin {CC7: New code uses a different parsing method that allows for multisection parts.} if AImapParts <> nil then begin //Just sort out the ImapParts version for now ParseImapPart(ABodyStructure, AImapParts, AImapParts.Add, nil, -1); end; if ATheParts <> nil then begin ParseMessagePart(ABodyStructure, ATheParts, TIdAttachmentMemory.Create(ATheParts), nil, -1); end; end; procedure TIdIMAP4.ParseTheLine(ALine: string; APartsList: TStrings); var LTempList: TStringList; LN: integer; LStr, LWord: string; begin {Parse it and see what we get...} LTempList := TStringList.Create; try ParseIntoParts(ALine, LTempList); {Copy any parts from LTempList into the list of parts LPartsList...} for LN := 0 to LTempList.Count-1 do begin LStr := LTempList.Strings[LN]; LWord := LowerCase(GetNextWord(LStr)); if CharEquals(LStr, 1, '(') or (PosInStrArray(LWord, ['"text"', '"image"', '"application"'], False) <> -1) then begin {Do not Localize} APartsList.Add(LStr); end; end; finally FreeAndNil(LTempList); end; end; procedure TIdIMAP4.ParseBodyStructurePart(APartString: string; AThePart: TIdMessagePart; AImapPart: TIdImapMessagePart); {CC3: Function added to support individual part retreival} var LParams: TStringList; // LContentDispositionStuff: string; LCharSet: String; LFilename: string; LDescription: string; LTemp: string; LSize: integer; LPos: Integer; begin {Individual parameters may be strings like "text", NIL, a number, or bracketted pairs like ("CHARSET" "US-ASCII" "NAME" "cc.tif" "format" "flowed")...} {There are three common line formats, with differing numbers of parameters: (a) "TEXT" "HTML" ("CHARSET" "iso-8859-1") NIL NIL "QUOTED-PRINTABLE" 2879 69 NIL NIL NIL (a) "TEXT" "HTML" ("CHARSET" "iso-8859-1") NIL NIL "QUOTED-PRINTABLE" 2879 69 NIL NIL (c) "TEXT" "HTML" ("CHARSET" "iso-8859-1") NIL NIL "QUOTED-PRINTABLE" 2879 69 Note the last one only has 7 parameters, need to watch we don't index past the 7th!} LParams := TStringList.Create; try ParseIntoParts(APartString, LParams); {Build up strings into same format as used by message decoders...} {Content Disposition: If present, may be at index 8 or 9...} {CC8: Altered to allow for case where it may not be present at all (get "List index out of bounds" error if try to access non-existent LParams[9])...} // LContentDispositionStuff := ''; {Do not Localize} // if LParams.Count > 9 then begin {Have an LParams[9]} // if TextIsSame(LParams[9], 'NIL') then begin {Do not Localize} {It's NIL at 9, must be at 8...} // if TextIsSame(LParams[8], 'NIL') then begin {Do not Localize} // LContentDispositionStuff := LParams[8]; // end; // end else begin {It's not NIL, must be valid...} // LContentDispositionStuff := LParams[9]; // end; // end else if LParams.Count > 8 then begin {Have an LParams[8]} // if TextIsSame(LParams[8], 'NIL') then begin {Do not Localize} // LContentDispositionStuff := LParams[8]; // end; // end; {Find and clean up the filename, if present...} LFilename := ''; {Do not Localize} LPos := IndyPos('"NAME"', UpperCase(APartString)); {Do not Localize} if LPos > 0 then begin LTemp := Copy(APartString, LPos+7, MaxInt); LFilename := GetNextQuotedParam(LTemp, False); end else begin LPos := IndyPos('"FILENAME"', UpperCase(APartString)); {Do not Localize} if LPos > 0 then begin LTemp := Copy(APartString, LPos+11, MaxInt); LFilename := GetNextQuotedParam(LTemp, False); end; end; {If the filename starts and ends with double-quotes, remove them...} if Length(LFilename) > 1 then begin if TextStartsWith(LFilename, '"') and TextEndsWith(LFilename, '"') then begin {Do not Localize} LFilename := Copy(LFilename, 2, Length(LFilename)-2); end; end; {CC7: The filename may be encoded, so decode it...} if Length(LFilename) > 1 then begin LFilename := DecodeHeader(LFilename); end; LCharSet := ''; if IndyPos('"CHARSET"', UpperCase(LParams[2])) > 0 then begin {Do not Localize} LTemp := Copy(LParams[2], IndyPos('"CHARSET" ', UpperCase(LParams[2]))+10, MaxInt); {Do not Localize} LCharSet := GetNextQuotedParam(LTemp, True); end; LSize := 0; if (not TextIsSame(LParams[6], 'NIL')) and (Length(LParams[6]) <> 0) then begin LSize := IndyStrToInt(LParams[6]); {Do not Localize} end; LDescription := ''; {Do not Localize} if (LParams.Count > 9) and (not TextIsSame(LParams[9], 'NIL')) then begin {Do not Localize} LDescription := GetNextQuotedParam(LParams[9], False); end else if (LParams.Count > 8) and (not TextIsSame(LParams[8], 'NIL')) then begin {Do not Localize} LDescription := GetNextQuotedParam(LParams[8], False); end; if AThePart <> nil then begin {Put into the same format as TIdMessage MessageParts...} AThePart.ContentType := LParams[0]+'/'+LParams[1]+ParseBodyStructureSectionAsEquates(LParams[2]); {Do not Localize} AThePart.ContentTransfer := LParams[5]; //Watch out for BinHex4.0, the encoding is inferred from the Content-Type... if IsHeaderMediaType(AThePart.ContentType, 'application/mac-binhex40') then begin {do not localize} AThePart.ContentTransfer := 'binhex40'; {do not localize} end; AThePart.DisplayName := LFilename; end; if AImapPart <> nil then begin AImapPart.FBodyType := LParams[0]; AImapPart.FBodySubType := LParams[1]; AImapPart.FFileName := LFilename; AImapPart.FDescription := LDescription; AImapPart.FCharSet := LCharSet; AImapPart.FContentTransferEncoding := LParams[5]; AImapPart.FSize := LSize; //Watch out for BinHex4.0, the encoding is inferred from the Content-Type... if ( (TextIsSame(AImapPart.FBodyType, 'application')) {do not localize} and (TextIsSame(AImapPart.FBodySubType, 'mac-binhex40')) ) then begin {do not localize} AImapPart.FContentTransferEncoding := 'binhex40'; {do not localize} end; end; finally FreeAndNil(LParams); end; end; procedure TIdIMAP4.ParseIntoParts(APartString: string; AParams: TStrings); var LInPart: Integer; LStartPos: Integer; //don't rename this LParam. That's the same asa windows identifier LParamater: string; LBracketLevel: Integer; Ln: Integer; LInQuotesInsideBrackets: Boolean; begin LStartPos := 0; {Stop compiler whining} LBracketLevel := 0; {Stop compiler whining} LInQuotesInsideBrackets := False; {Stop compiler whining} LInPart := 0; {0 is not in a part, 1 is in a quote-delimited part, 2 is in a bracketted parameter-pair list} for Ln := 1 to Length(APartString) do begin if LInPart = 1 then begin if APartString[Ln] = '"' then begin {Do not Localize} LParamater := Copy(APartString, LStartPos+1, Ln-LStartPos-1); AParams.Add(LParamater); LInPart := 0; end; end else if LInPart = 2 then begin //We have to watch out that we don't close this entry on a closing bracket within //quotes, like ("Blah" "Blah)Blah"), so monitor if we are in quotes within brackets. if APartString[Ln] = '"' then begin {Do not Localize} LInQuotesInsideBrackets := not LInQuotesInsideBrackets; end else begin //Brackets don't count if they are within quoted strings... if not LInQuotesInsideBrackets then begin if APartString[Ln] = '(' then begin {Do not Localize} Inc(LBracketLevel); end else if APartString[Ln] = ')' then begin {Do not Localize} Dec(LBracketLevel); if LBracketLevel = 0 then begin LParamater := Copy(APartString, LStartPos+1, Ln-LStartPos-1); AParams.Add(LParamater); LInPart := 0; end; end; end; end; end else if LInPart = 3 then begin if APartString[Ln] = 'L' then begin {Do not Localize} LParamater := Copy(APartString, LStartPos, Ln-LStartPos+1); AParams.Add(LParamater); LInPart := 0; end; end else if LInPart = 4 then begin if not IsNumeric(APartString[Ln]) then begin LParamater := Copy(APartString, LStartPos, Ln-LStartPos); AParams.Add(LParamater); LInPart := 0; end; end else if APartString[Ln] = '"' then begin {Do not Localize} {Start of a quoted param like "text"} LStartPos := Ln; LInPart := 1; end else if APartString[Ln] = '(' then begin {Do not Localize} {Start of a set of paired parameter/value strings within brackets, such as ("charset" "us-ascii"). Note these can be nested (bracket pairs within bracket pairs) } LStartPos := Ln; LInPart := 2; LBracketLevel := 1; LInQuotesInsideBrackets := False; end else if TextIsSame(APartString[Ln], 'N') then begin {Do not Localize} {Start of a NIL entry} LStartPos := Ln; LInPart := 3; end else if IsNumeric(APartString[Ln]) then begin {Start of a numeric entry like 12345} LStartPos := Ln; LInPart := 4; end; end; {We could be in a numeric entry when we hit the end of the line...} if LInPart = 4 then begin LParamater := Copy(APartString, LStartPos, MaxInt); AParams.Add(LParamater); end; end; procedure TIdIMAP4.ParseIntoBrackettedQuotedAndUnquotedParts(APartString: string; AParams: TStrings; AKeepBrackets: Boolean); var LInPart: Integer; LStartPos: Integer; //don't rename this back to LParam, that's a Windows identifier. LParamater: string; LBracketLevel: Integer; Ln: Integer; LInQuotesInsideBrackets: Boolean; begin {Break: * LIST (\UnMarked \AnotherFlag) "/" "Mailbox name" into: * LIST (\UnMarked \AnotherFlag) "/" "Mailbox name" If AKeepBrackets is false, return '\UnMarked \AnotherFlag' instead of '(\UnMarked \AnotherFlag)' } AParams.Clear; LStartPos := 0; {Stop compiler whining} LBracketLevel := 0; {Stop compiler whining} LInQuotesInsideBrackets := False; {Stop compiler whining} LInPart := 0; {0 is not in a part, 1 is in a quote-delimited part, 2 is in a bracketted part, 3 is a word} APartString := Trim(APartString); for Ln := 1 to Length(APartString) do begin if LInPart = 1 then begin if APartString[Ln] = '"' then begin {Do not Localize} LParamater := Copy(APartString, LStartPos+1, Ln-LStartPos-1); AParams.Add(LParamater); LInPart := 0; end; end else if LInPart = 2 then begin //We have to watch out that we don't close this entry on a closing bracket within //quotes, like ("Blah" "Blah)Blah"), so monitor if we are in quotes within brackets. if APartString[Ln] = '"' then begin {Do not Localize} LInQuotesInsideBrackets := not LInQuotesInsideBrackets; end else begin //Brackets don't count if they are within quoted strings... if not LInQuotesInsideBrackets then begin if APartString[Ln] = '(' then begin {Do not Localize} Inc(LBracketLevel); end else if APartString[Ln] = ')' then begin {Do not Localize} Dec(LBracketLevel); if LBracketLevel = 0 then begin if AKeepBrackets then begin LParamater := Copy(APartString, LStartPos, Ln-LStartPos+1); end else begin LParamater := Copy(APartString, LStartPos+1, Ln-LStartPos-1); end; AParams.Add(LParamater); LInPart := 0; end; end; end; end; end else if LInPart = 3 then begin if APartString[Ln] = ' ' then begin {Do not Localize} LParamater := Copy(APartString, LStartPos, Ln-LStartPos); AParams.Add(LParamater); LInPart := 0; end; end else if APartString[Ln] = '"' then begin {Do not Localize} {Start of a quoted param like "text"} LStartPos := Ln; LInPart := 1; end else if APartString[Ln] = '(' then begin {Do not Localize} {Start of a set of paired parameter/value strings within brackets, such as ("charset" "us-ascii"). Note these can be nested (bracket pairs within bracket pairs) } LStartPos := Ln; LInPart := 2; LBracketLevel := 1; LInQuotesInsideBrackets := False; end else if APartString[Ln] <> ' ' then begin {Do not Localize} {Start of an entry like 12345} LStartPos := Ln; LInPart := 3; end; end; {We could be in an entry when we hit the end of the line...} if LInPart = 3 then begin LParamater := Copy(APartString, LStartPos, MaxInt); AParams.Add(LParamater); end else if LInPart = 2 then begin if AKeepBrackets then begin LParamater := Copy(APartString, LStartPos, MaxInt); end else begin LParamater := Copy(APartString, LStartPos+1, MaxInt); end; if (not AKeepBrackets) and TextEndsWith(LParamater, ')') then begin {Do not Localize} LParamater := Copy(LParamater, 1, Length(LParamater)-1); end; AParams.Add(LParamater); end else if LInPart = 1 then begin LParamater := Copy(APartString, LStartPos+1, MaxInt); if TextEndsWith(LParamater, '"') then begin {Do not Localize} LParamater := Copy(LParamater, 1, Length(LParamater)-1); end; AParams.Add(LParamater); end; end; function TIdIMAP4.ParseBodyStructureSectionAsEquates(AParam: string): string; {Convert: "Name1" "Value1" "Name2" "Value2" to: ; Name1="Value1"; Name2="Value2" } var LParse: TStringList; LN: integer; begin Result := ''; {Do not Localize} if (Length(AParam) = 0) or TextIsSame(AParam, 'NIL') then begin {Do not Localize} Exit; end; LParse := TStringList.Create; try BreakApartParamsInQuotes(AParam, LParse); if LParse.Count < 2 then begin Exit; end; if ((LParse.Count mod 2) <> 0) then begin Exit; end; for LN := 0 to ((LParse.Count div 2)-1) do begin Result := Result + '; ' + Copy(LParse[LN*2], 2, Length(LParse[LN*2])-2) + '=' + LParse[(LN*2)+1]; {Do not Localize} end; finally FreeAndNil(LParse); end; end; function TIdIMAP4.ParseBodyStructureSectionAsEquates2(AParam: string): string; {Convert: "Name1" ("Name2" "Value2") to: Name1; Name2="Value2" } var LParse: TStringList; LParams: string; begin Result := ''; {Do not Localize} if (Length(AParam) = 0) or TextIsSame(AParam, 'NIL') then begin {Do not Localize} Exit; end; LParse := TStringList.Create; try BreakApart(AParam, ' ', LParse); {Do not Localize} if LParse.Count < 3 then begin Exit; end; LParams := Copy(AParam, Pos('(', AParam)+1, MaxInt); {Do not Localize} LParams := Copy(LParams, 1, Length(LParams)-1); LParams := ParseBodyStructureSectionAsEquates(LParams); if Length(LParams) = 0 then begin {Do not Localize} Result := Copy(LParse[0], 2, Length(LParse[0])-2) + LParams; end; finally FreeAndNil(LParse); end; end; function TIdIMAP4.GetNextWord(AParam: string): string; var LPos: integer; begin Result := ''; {Do not Localize} AParam := Trim(AParam); LPos := Pos(' ', AParam); {Do not Localize} if LPos = 0 then begin Exit; end; Result := Copy(AParam, 1, LPos-1); end; function TIdIMAP4.GetNextQuotedParam(AParam: string; ARemoveQuotes: Boolean): string; {If AParam is: "file name.ext" NIL NIL then this returns: "file name.ext" Note it returns the quotes, UNLESS ARemoveQuotes is True. Also note that if AParam does NOT start with a quote, it returns the next word. } var LN: integer; LPos: integer; begin {CCB: Modified code so it did not access past the end of the string if AParam was not actually in quotes (e.g. the MIME boundary parameter is only optionally in quotes).} LN := 1; {Skip any preceding spaces...} while AParam[LN] = ' ' do begin {Do not Localize} LN := LN + 1; end; if AParam[LN] <> '"' then begin {Do not Localize} {Not actually enclosed in quotes. Must be a single word.} AParam := Copy(AParam, LN, MaxInt); LPos := Pos(' ', AParam); {Do not Localize} if LPos > 0 then begin {Strip off this word...} Result := Copy(AParam, 1, LPos-1); end else begin {This is the last word on the line, return it all...} Result := AParam; end; end else begin {It starts with a quote...} AParam := Copy(AParam, LN, MaxInt); LN := 2; while AParam[LN] <> '"' do begin {Do not Localize} LN := LN + 1; end; Result := Copy(AParam, 1, LN); if ARemoveQuotes then begin Result := Copy(Result, 2, Length(Result)-2); end; end; end; procedure TIdIMAP4.BreakApartParamsInQuotes(const AParam: string; AParsedList: TStrings); var Ln : Integer; LStartPos: Integer; begin LStartPos := -1; AParsedList.Clear; for Ln := 1 to Length(AParam) do begin if AParam[LN] = '"' then begin {Do not Localize} if LStartPos > -1 then begin {The end of a quoted parameter...} AParsedList.Add(Copy(AParam, LStartPos, LN-LStartPos+1)); LStartPos := -1; end else begin {The start of a quoted parameter...} LStartPos := Ln; end; end; end; end; procedure TIdIMAP4.ParseExpungeResult(AMB: TIdMailBox; ACmdResultDetails: TStrings); var Ln : Integer; LSlExpunge : TStringList; begin SetLength ( AMB.DeletedMsgs, 0 ); LSlExpunge := TStringList.Create; try if ACmdResultDetails.Count > 1 then begin for Ln := 0 to ACmdResultDetails.Count - 1 do begin BreakApart(ACmdResultDetails[Ln], ' ', LSlExpunge); {Do not Localize} if TextIsSame(LSlExpunge[1], IMAP4Commands[cmdExpunge]) then begin SetLength(AMB.DeletedMsgs, (Length(AMB.DeletedMsgs) + 1)); AMB.DeletedMsgs[Length(AMB.DeletedMsgs) - 1] := IndyStrToInt(LSlExpunge[0]); end; LSlExpunge.Clear; end; end; finally FreeAndNil(LSlExpunge); end; end; procedure TIdIMAP4.ParseMessageFlagString(AFlagsList: String; var AFlags: TIdMessageFlagsSet); {CC5: Note this only supports the system flags defined in RFC 2060.} var LSlFlags : TStringList; Ln, I : Integer; begin AFlags := []; LSlFlags := TStringList.Create; try BreakApart(AFlagsList, ' ', LSlFlags); {Do not Localize} for Ln := 0 to LSlFlags.Count-1 do begin I := PosInStrArray( LSlFlags[Ln], [MessageFlags[mfAnswered], MessageFlags[mfFlagged], MessageFlags[mfDeleted], MessageFlags[mfDraft], MessageFlags[mfSeen], MessageFlags[mfRecent]], False); case I of 0..5: Include(AFlags, TIdMessageFlags(I)); end; end; finally FreeAndNil(LSlFlags); end; end; procedure TIdIMAP4.ParseMailBoxAttributeString(AAttributesList: String; var AAttributes: TIdMailBoxAttributesSet); var LSlAttributes : TStringList; Ln : Integer; I: Integer; begin AAttributes := []; LSlAttributes := TStringList.Create; try BreakApart(AAttributesList, ' ', LSlAttributes); {Do not Localize} for Ln := 0 to LSlAttributes.Count - 1 do begin I := PosInStrArray( LSlAttributes[Ln], [MailBoxAttributes[maNoinferiors], MailBoxAttributes[maNoselect], MailBoxAttributes[maMarked], MailBoxAttributes[maUnmarked]], False); case I of 0..3: Include(AAttributes, TIdMailBoxAttributes(I)); end; end; finally FreeAndNil(LSlAttributes); end; end; procedure TIdIMAP4.ParseSearchResult(AMB: TIdMailBox; ACmdResultDetails: TStrings); var Ln: Integer; LSlSearch: TStringList; begin LSlSearch := TStringList.Create; try SetLength(AMB.SearchResult, 0); if ACmdResultDetails.Count > 0 then begin if Pos(IMAP4Commands[cmdSearch], ACmdResultDetails[0]) > 0 then begin BreakApart(ACmdResultDetails[0], ' ', LSlSearch); {Do not Localize} for Ln := 1 to LSlSearch.Count - 1 do begin SetLength(AMB.SearchResult, (Length(AMB.SearchResult) + 1)); AMB.SearchResult[Length(AMB.SearchResult) - 1] := IndyStrToInt(LSlSearch[Ln]); end; end; end; finally FreeAndNil(LSlSearch); end; end; procedure TIdIMAP4.ParseStatusResult(AMB: TIdMailBox; ACmdResultDetails: TStrings); var Ln: Integer; LRespStr : String; LStatStr: String; LStatPos: Integer; LSlStatus : TStringList; begin LSlStatus := TStringList.Create; try if ACmdResultDetails.Count > 0 then begin // TODO: convert server response to uppercase? LRespStr := Trim(ACmdResultDetails[0]); LStatPos := Pos(IMAP4Commands[cmdStatus], LRespStr); if (LStatPos > 0) then begin LStatStr := Trim(Copy(LRespStr, LStatPos+Length(IMAP4Commands[cmdStatus]), Length(LRespStr))); AMB.Name := Trim(Fetch(LStatStr, '(', True)); {do not localize} if TextEndsWith(LStatStr, ')') then begin {do not localize} IdDelete(LStatStr, Length(LStatStr), 1); end; BreakApart(LStatStr, ' ', LSlStatus); {do not localize} // find status data items by name, values are on following line Ln := LSlStatus.IndexOf(IMAP4StatusDataItem[mdMessages]); if Ln <> -1 then begin AMB.TotalMsgs := IndyStrToInt(LSlStatus[Ln + 1]); end; Ln := LSlStatus.IndexOf(IMAP4StatusDataItem[mdRecent]); if Ln <> -1 then begin AMB.RecentMsgs := IndyStrToInt(LSlStatus[Ln + 1]); end; Ln := LSlStatus.IndexOf(IMAP4StatusDataItem[mdUnseen]); if Ln <> -1 then begin AMB.UnseenMsgs := IndyStrToInt(LSlStatus[Ln + 1]); end; Ln := LSlStatus.IndexOf(IMAP4StatusDataItem[mdUIDNext]); if Ln <> -1 then begin AMB.UIDNext := LSlStatus[Ln + 1]; end; Ln := LSlStatus.IndexOf(IMAP4StatusDataItem[mdUIDValidity]); if Ln <> -1 then begin AMB.UIDValidity := LSlStatus[Ln + 1]; end; end; end; finally FreeAndNil(LSlStatus); end; end; procedure TIdIMAP4.ParseSelectResult(AMB : TIdMailBox; ACmdResultDetails: TStrings); var Ln : Integer; LStr : String; LFlags: TIdMessageFlagsSet; LLine: String; LPos: Integer; begin AMB.Clear; for Ln := 0 to ACmdResultDetails.Count - 1 do begin LLine := ACmdResultDetails[Ln]; LPos := Pos(' EXISTS', LLine); {Do not Localize} if LPos > 0 then begin AMB.TotalMsgs := IndyStrToInt(Copy(LLine, 1, LPos - 1)); Continue; end; LPos := Pos(' RECENT', LLine); {Do not Localize} if LPos > 0 then begin AMB.RecentMsgs := IndyStrToInt(Copy(LLine, 1, LPos - 1)); {Do not Localize} Continue; end; LPos := Pos('[UIDVALIDITY ', LLine); {Do not Localize} if LPos > 0 then begin Inc(LPos, 13); AMB.UIDValidity := Trim(Copy(LLine, LPos, (Integer(PosIdx(']', LLine, LPos)) - LPos))); {Do not Localize} Continue; end; LPos := Pos('[UIDNEXT ', LLine); {Do not Localize} if LPos > 0 then begin Inc(LPos, 9); AMB.UIDNext := Trim(Copy(LLine, LPos, (Integer(PosIdx(']', LLine, LPos)) - LPos))); {Do not Localize} Continue; end; LPos := Pos('[PERMANENTFLAGS ', LLine); {Do not Localize} if LPos > 0 then begin {Do not Localize} LPos := PosIdx('(', LLine, LPos + 16) + 1; {Do not Localize} ParseMessageFlagString(Copy(LLine, LPos, Integer(PosIdx(')', LLine, LPos)) - LPos), LFlags); {Do not Localize} AMB.ChangeableFlags := LFlags; Continue; end; LPos := Pos('FLAGS ', LLine); {Do not Localize} if LPos > 0 then begin LPos := PosIdx('(', LLine, LPos + 6) + 1; {Do not Localize} ParseMessageFlagString(Copy(LLine, LPos, (Integer(PosIdx(')', LLine, LPos)) - LPos)), LFlags); {Do not Localize} AMB.Flags := LFlags; Continue; end; LPos := Pos('[UNSEEN ', LLine); {Do not Localize} if LPos> 0 then begin Inc(LPos, 8); AMB.FirstUnseenMsg := IndyStrToInt(Copy(LLine, LPos, (Integer(PosIdx(']', LLine, LPos)) - LPos))); {Do not Localize} Continue; end; LPos := Pos('[READ-', LLine); {Do not Localize} if LPos > 0 then begin Inc(LPos, 6); LStr := Trim(Copy(LLine, LPos, Integer(PosIdx(']', LLine, LPos)) - LPos)); {Do not Localize} {CCB: AMB.State ambiguous unless coded response received - default to msReadOnly...} if TextIsSame(LStr, 'WRITE') then begin {Do not Localize} AMB.State := msReadWrite; end else {if TextIsSame(LStr, 'ONLY') then} begin {Do not Localize} AMB.State := msReadOnly; end; Continue; end; LPos := Pos('[ALERT]', LLine); {Do not Localize} if LPos > 0 then begin LStr := Trim(Copy(LLine, LPos + 7, MaxInt)); if Length(LStr) <> 0 then begin DoAlert(LStr); end; Continue; end; end; end; procedure TIdIMAP4.ParseListResult(AMBList: TStrings; ACmdResultDetails: TStrings); begin InternalParseListResult(IMAP4Commands[cmdList], AMBList, ACmdResultDetails); end; procedure TIdIMAP4.InternalParseListResult(ACmd: string; AMBList: TStrings; ACmdResultDetails: TStrings); var Ln : Integer; LSlRetrieve : TStringList; LStr : String; LWord: string; begin AMBList.Clear; LSlRetrieve := TStringList.Create; try for Ln := 0 to ACmdResultDetails.Count - 1 do begin LStr := ACmdResultDetails[Ln]; //Todo: Get mail box attributes here {CC2: Could put mailbox attributes in AMBList's Objects property?} {The line is of the form: * LIST (\UnMarked \AnotherFlag) "/" "Mailbox name" } {CCA: code modified because some servers return NIL as the mailbox separator, i.e.: * LIST (\UnMarked \AnotherFlag) NIL "Mailbox name" } ParseIntoBrackettedQuotedAndUnquotedParts(LStr, LSlRetrieve, False); if LSlRetrieve.Count > 3 then begin //Make sure 1st word is LIST (may be an unsolicited response)... if TextIsSame(LSlRetrieve[0], {IMAP4Commands[cmdList]} ACmd) then begin {Get the mailbox separator...} LWord := Trim(LSlRetrieve[LSlRetrieve.Count-2]); if TextIsSame(LWord, 'NIL') or (LWord = '') then begin {Do not Localize} FMailBoxSeparator := #0; end else begin FMailBoxSeparator := LWord[1]; end; {Now get the mailbox name...} LWord := Trim(LSlRetrieve[LSlRetrieve.Count-1]); AMBList.Add(DoMUTFDecode(LWord)); end; end; end; finally FreeAndNil(LSlRetrieve); end; end; procedure TIdIMAP4.ParseLSubResult(AMBList: TStrings; ACmdResultDetails: TStrings); begin InternalParseListResult(IMAP4Commands[cmdLSub], AMBList, ACmdResultDetails); end; procedure TIdIMAP4.ParseEnvelopeResult(AMsg: TIdMessage; ACmdResultStr: String); procedure DecodeEnvelopeAddress(const AAddressStr: String; AEmailAddressItem: TIdEmailAddressItem); overload; var LStr, LTemp: String; I: Integer; {$IFNDEF DOTNET} LPChar: PChar; {$ENDIF} begin if TextStartsWith(AAddressStr, '(') and TextEndsWith(AAddressStr, ')') and {Do not Localize} Assigned(AEmailAddressItem) then begin LStr := Copy(AAddressStr, 2, Length (AAddressStr) - 2); //Gets the name part if TextStartsWith(LStr, 'NIL ') then begin {Do not Localize} LStr := Copy(LStr, 5, MaxInt); {Do not Localize} end else if TextStartsWith(LStr, '{') then begin {Do not Localize} LStr := Copy(LStr, Pos('}', LStr) + 1, MaxInt); {Do not Localize} I := Pos('" ', LStr); AEmailAddressItem.Name := Copy(LStr, 1, I-1); {Do not Localize} LStr := Copy(LStr, I+2, MaxInt); {Do not Localize} end else begin I := Pos('" ', LStr); LTemp := Copy(LStr, 1, I); {$IFDEF DOTNET} AEmailAddressItem.Name := Copy(LTemp, 2, Length(LTemp)-2); {ExtractQuotedStr ( LTemp, '"' ); {Do not Localize} {$ELSE} LPChar := PChar(LTemp); AEmailAddressItem.Name := AnsiExtractQuotedStr(LPChar, '"'); {Do not Localize} {$ENDIF} LStr := Copy(LStr, I+2, MaxInt); {Do not Localize} end; //Gets the source root part if TextStartsWith(LStr, 'NIL ') then begin {Do not Localize} LStr := Copy(LStr, 5, MaxInt); {Do not Localize} end else begin I := Pos('" ', LStr); LTemp := Copy(LStr, 1, I); {$IFDEF DOTNET} AEmailAddressItem.Name := Copy(LTemp, 2, Length(LTemp)-2); {AnsiExtractQuotedStr ( LTemp, '"' ); {Do not Localize} {$ELSE} LPChar := PChar(LTemp); AEmailAddressItem.Name := AnsiExtractQuotedStr(LPChar, '"'); {Do not Localize} {$ENDIF} LStr := Copy(LStr, I+2, MaxInt); {Do not Localize} end; //Gets the mailbox name part if TextStartsWith(LStr, 'NIL ') then begin {Do not Localize} LStr := Copy(LStr, 5, MaxInt); {Do not Localize} end else begin I := Pos('" ', LStr); LTemp := Copy(LStr, 1, I); {Do not Localize} {$IFDEF DOTNET} AEmailAddressItem.Address := Copy(LTemp, 2, Length(LTemp)-2); {AnsiExtractQuotedStr ( LTemp, '"' ); {Do not Localize} {$ELSE} LPChar := PChar(LTemp); AEmailAddressItem.Address := AnsiExtractQuotedStr(LPChar, '"'); {Do not Localize} {$ENDIF} LStr := Copy(LStr, I+2, MaxInt); {Do not Localize} end; //Gets the host name part if not TextIsSame(LStr, 'NIL') then begin {Do not Localize} LTemp := Copy(LStr, 1, MaxInt); {$IFDEF DOTNET} AEmailAddressItem.Address := AEmailAddressItem.Address + '@' + {Do not Localize} Copy(LTemp, 2, Length(LTemp)-2); {AnsiExtractQuotedStr ( LTemp, '"' ); {Do not Localize} {$ELSE} LPChar := PChar(LTemp); AEmailAddressItem.Address := AEmailAddressItem.Address + '@' + {Do not Localize} AnsiExtractQuotedStr(LPChar, '"'); {Do not Localize} {$ENDIF} end; end; end; procedure DecodeEnvelopeAddress(const AAddressStr: String; AEmailAddressList: TIdEmailAddressList); overload; var LStr: String; I: Integer; begin if TextStartsWith(AAddressStr, '(') and TextEndsWith(AAddressStr, ')') and {Do not Localize} Assigned(AEmailAddressList) then begin LStr := Copy(AAddressStr, 2, Length (AAddressStr) - 2); repeat I := Pos(')', LStr); if I = 0 then begin Break; end; DecodeEnvelopeAddress(Copy(LStr, 1, I), AEmailAddressList.Add); {Do not Localize} LStr := Trim(Copy(LStr, I+1, MaxInt)); {Do not Localize} until False; end; end; var LStr, LTemp: String; I: Integer; {$IFNDEF DOTNET} LPChar: PChar; {$ENDIF} begin //The fields of the envelope structure are in the //following order: date, subject, from, sender, //reply-to, to, cc, bcc, in-reply-to, and message-id. //The date, subject, in-reply-to, and message-id //fields are strings. The from, sender, reply-to, //to, cc, and bcc fields are parenthesized lists of //address structures. //An address structure is a parenthesized list that //describes an electronic mail address. The fields //of an address structure are in the following order: //personal name, [SMTP] at-domain-list (source //route), mailbox name, and host name. //* 4 FETCH (ENVELOPE ("Sun, 15 Jul 2001 02:56:45 -0700 (PDT)" "Your Borland Commu //nity Account Activation Code" (("Borland Community" NIL "mailbot" "borland.com") //) NIL NIL (("" NIL "name" "company.com")) NIL NIL NIL "<200107150956.CAA1 //8152@borland.com>")) {CC5: Cleared out any existing fields to avoid mangling new entries with old/stale ones.} //Extract envelope date field AMsg.Date := 0; if TextStartsWith(ACmdResultStr, 'NIL ') then begin {Do not Localize} ACmdResultStr := Copy(ACmdResultStr, 5, MaxInt); end else begin I := Pos('" ', ACmdResultStr); {Do not Localize} LTemp := Copy(ACmdResultStr, 1, I); {$IFDEF DOTNET} LStr := Copy(LTemp, 2, Length(LTemp)-2); {$ELSE} LPChar := PChar(LTemp); LStr := AnsiExtractQuotedStr(LPChar, '"'); {Do not Localize} {$ENDIF} AMsg.Date := GMTToLocalDateTime(LStr); ACmdResultStr := Copy(ACmdResultStr, I+2, MaxInt); end; //Extract envelope subject field AMsg.Subject := ''; {Do not Localize} if TextStartsWith(ACmdResultStr, 'NIL ') then begin {Do not Localize} ACmdResultStr := Copy(ACmdResultStr, 4, MaxInt); end else begin if TextStartsWith(ACmdResultStr, '{') then begin {Do not Localize} ACmdResultStr := Copy(ACmdResultStr, Pos('}', ACmdResultStr) + 1, MaxInt); {Do not Localize} I := Pos(' ', ACmdResultStr); {Do not Localize} LStr := Copy(ACmdResultStr, 1, I-1); AMsg.Subject := LStr; ACmdResultStr := Copy(ACmdResultStr, I+1, MaxInt); {Do not Localize} end else begin I := Pos('" ', ACmdResultStr); {Do not Localize} LTemp := Copy(ACmdResultStr, 1, I); {$IFDEF DOTNET} LStr := Copy(LTemp, 2, Length(LTemp)-2); {$ELSE} LPChar := PChar(LTemp); LStr := AnsiExtractQuotedStr(LPChar, '"'); {Do not Localize} {$ENDIF} AMsg.Subject := LStr; ACmdResultStr := Copy(ACmdResultStr, I+2, MaxInt); {Do not Localize} end; end; //Extract envelope from field AMsg.FromList.Clear; if TextStartsWith(ACmdResultStr, 'NIL ') then begin {Do not Localize} ACmdResultStr := Copy(ACmdResultStr, 5, MaxInt); end else begin I := Pos(')) ', ACmdResultStr); {Do not Localize} LStr := Copy(ACmdResultStr, 1, I+1); DecodeEnvelopeAddress(LStr, AMsg.FromList); ACmdResultStr := Copy(ACmdResultStr, I+3, MaxInt); end; //Extract envelope sender field AMsg.Sender.Name := ''; {Do not Localize} AMsg.Sender.Address := ''; {Do not Localize} if TextStartsWith(ACmdResultStr, 'NIL ') then begin {Do not Localize} ACmdResultStr := Copy(ACmdResultStr, 5, MaxInt); end else begin {CC5: Fix parsing of sender...} I := Pos(')) ', ACmdResultStr); LStr := Copy(ACmdResultStr, 2, I-1); DecodeEnvelopeAddress(LStr, AMsg.Sender); ACmdResultStr := Copy(ACmdResultStr, I+3, MaxInt); end; //Extract envelope reply-to field AMsg.ReplyTo.Clear; if TextStartsWith(ACmdResultStr, 'NIL ') then begin {Do not Localize} ACmdResultStr := Copy(ACmdResultStr, 5, MaxInt); end else begin I := Pos(')) ', ACmdResultStr); {Do not Localize} LStr := Copy(ACmdResultStr, 1, I+1); DecodeEnvelopeAddress(LStr, AMsg.ReplyTo); ACmdResultStr := Copy(ACmdResultStr, I+3, MaxInt); end; //Extract envelope to field AMsg.Recipients.Clear; if TextStartsWith(ACmdResultStr, 'NIL ') then begin {Do not Localize} ACmdResultStr := Copy(ACmdResultStr, 5, MaxInt); end else begin I := Pos(')) ', ACmdResultStr); {Do not Localize} LStr := Copy(ACmdResultStr, 1, I+1); DecodeEnvelopeAddress(LStr, AMsg.Recipients); ACmdResultStr := Copy(ACmdResultStr, I+3, MaxInt); end; //Extract envelope cc field AMsg.CCList.Clear; if TextStartsWith(ACmdResultStr, 'NIL ') then begin {Do not Localize} ACmdResultStr := Copy(ACmdResultStr, 5, MaxInt); end else begin I := Pos(')) ', ACmdResultStr); {Do not Localize} LStr := Copy(ACmdResultStr, 1, I+1); DecodeEnvelopeAddress(LStr, AMsg.CCList); ACmdResultStr := Copy(ACmdResultStr, I+3, MaxInt); end; //Extract envelope bcc field AMsg.BccList.Clear; if TextStartsWith(ACmdResultStr, 'NIL ') then begin {Do not Localize} ACmdResultStr := Copy(ACmdResultStr, 5, MaxInt); end else begin I := Pos(')) ', ACmdResultStr); {Do not Localize} LStr := Copy(ACmdResultStr, 1, I+1); DecodeEnvelopeAddress(LStr, AMsg.BccList); ACmdResultStr := Copy(ACmdResultStr, I+3, MaxInt); end; //Extract envelope in-reply-to field if TextStartsWith(ACmdResultStr, 'NIL ') then begin {Do not Localize} ACmdResultStr := Copy(ACmdResultStr, 5, MaxInt); end else begin I := Pos('" ', ACmdResultStr); {Do not Localize} LTemp := Copy(ACmdResultStr, 1, I); {$IFDEF DOTNET} LStr := Copy(LTemp, 2, Length(LTemp)-2); {$ELSE} LPChar := PChar(LTemp); LStr := AnsiExtractQuotedStr(LPChar, '"'); {Do not Localize} {$ENDIF} AMsg.InReplyTo := LStr; ACmdResultStr := Copy(ACmdResultStr, I+2, MaxInt); end; //Extract envelope message-id field AMsg.MsgId := ''; {Do not Localize} if TextStartsWith(ACmdResultStr, 'NIL ') then begin {Do not Localize} ACmdResultStr := Copy(ACmdResultStr, 5, MaxInt); end else begin {$IFDEF DOTNET} LStr := Copy(ACmdResultStr, 2, Length(ACmdResultStr)-2); {$ELSE} LPChar := PChar(ACmdResultStr); LStr := AnsiExtractQuotedStr(LPChar, '"'); {Do not Localize} {$ENDIF} AMsg.MsgId := Trim(LStr); end; end; function TIdIMAP4.ParseLastCmdResult(ALine: string; AExpectedCommand: string; AExpectedIMAPFunction: array of string): Boolean; var LPos: integer; LWord: string; LWords: TStringList; LN: Integer; LWordInExpectedIMAPFunction: Boolean; begin Result := False; LWordInExpectedIMAPFunction := False; FLineStruct.HasStar := False; FLineStruct.MessageNumber := ''; FLineStruct.Command := ''; FLineStruct.UID := ''; FLineStruct.Complete := True; FLineStruct.IMAPFunction := ''; FLineStruct.IMAPValue := ''; FLineStruct.ByteCount := -1; ALine := Trim(ALine); //Can get garbage like a spurious CR at start //Look for (optional) * at start... LPos := Pos(' ', ALine); {Do not Localize} if LPos < 1 then begin Exit; //Nothing on this line end; LWord := Copy(ALine, 1, LPos-1); if LWord = '*' then begin {Do not Localize} FLineStruct.HasStar := True; ALine := Copy(ALine, LPos+1, MaxInt); LPos := Pos(' ', ALine); {Do not Localize} if LPos < 1 then begin Exit; //Line ONLY had a * end; LWord := Copy(ALine, 1, LPos-1); end; //Look for (optional) message number next... if IsNumeric(LWord) then begin FLineStruct.MessageNumber := LWord; ALine := Copy(ALine, LPos+1, MaxInt); LPos := Pos(' ', ALine); {Do not Localize} if LPos < 1 then begin Exit; //Line ONLY had a * 67 end; LWord := Copy(ALine, 1, LPos-1); end; //We should have a valid IMAP command word now, like FETCH, LIST or SEARCH... if PosInStrArray(LWord, IMAP4Commands) = -1 then begin Exit; //Should have been a command, give up. end; FLineStruct.Command := LWord; if ((AExpectedCommand = '') or (FLineStruct.Command = AExpectedCommand)) then begin Result := True; end; ALine := Copy(ALine, Length(LWord)+2, MaxInt); if ALine[1] <> '(' then begin {Do not Localize} //This is a line like '* SEARCH 34 56', the '34 56' is the value (result)... FLineStruct.IMAPValue := ALine; Exit; end; //This is a line like '* 9 FETCH (UID 47 RFC822.SIZE 3456)', i.e. with a bracketted response. //See is it complete (has a closing bracket) or does it continue on other lines... ALine := Copy(ALine, 2, MaxInt); if Copy(ALine, Length(ALine), 1) = ')' then begin {Do not Localize} ALine := Copy(ALine, 1, Length(ALine) - 1); //Strip trailing bracket FLineStruct.Complete := True; end else begin FLineStruct.Complete := False; end; //These words left may occur in different order. Find & delete those we know. LWords := TStringList.Create; try ParseIntoBrackettedQuotedAndUnquotedParts(ALine, LWords, False); if LWords.Count > 0 then begin //See does it have a trailing byte count... LWord := LWords[LWords.Count-1]; if TextStartsWith(LWord, '{') and TextEndsWith(LWord, '}') then begin //It ends in a byte count... LWord := Copy(LWord, 2, Length(LWord)-2); if TextIsSame(LWord, 'NIL') then begin {do not localize} FLineStruct.ByteCount := 0; end else begin FLineStruct.ByteCount := IndyStrToInt(LWord); end; LWords.Delete(LWords.Count-1); end; end; if not FLineStruct.Complete then begin //The command in this case should be the last word... if LWords.Count > 0 then begin FLineStruct.IMAPFunction := LWords[LWords.Count-1]; LWords.Delete(LWords.Count-1); end; end; //See is the UID present... LPos := LWords.IndexOf(IMAP4FetchDataItem[fdUID]); {Do not Localize} if LPos <> -1 then begin //The UID is the word after 'UID'... if LPos < LWords.Count-1 then begin FLineStruct.UID := LWords[LPos+1]; LWords.Delete(LPos+1); LWords.Delete(LPos); end; if PosInStrArray(IMAP4FetchDataItem[fdUID], AExpectedIMAPFunction) > -1 then begin LWordInExpectedIMAPFunction := True; end; end; //See are the FLAGS present... LPos := LWords.IndexOf(IMAP4FetchDataItem[fdFlags]); {Do not Localize} if LPos <> -1 then begin //The FLAGS are in the "word" (really a string) after 'FLAGS'... if LPos < LWords.Count-1 then begin ParseMessageFlagString(LWords[LPos+1], FLineStruct.Flags); LWords.Delete(LPos+1); LWords.Delete(LPos); end; if PosInStrArray(IMAP4FetchDataItem[fdFlags], AExpectedIMAPFunction) > -1 then begin LWordInExpectedIMAPFunction := True; end; end; if Length(AExpectedIMAPFunction) > 0 then begin //See is what we want present. for LN := 0 to Length(AExpectedIMAPFunction)-1 do begin //First check if we got it already in IMAPFunction... if TextIsSame(FLineStruct.IMAPFunction, AExpectedIMAPFunction[LN]) then begin LWordInExpectedIMAPFunction := True; Break; end; //Now check if it is in any remaining words... LPos := LWords.IndexOf(AExpectedIMAPFunction[LN]); {Do not Localize} if LPos <> -1 then begin FLineStruct.IMAPFunction := LWords[LPos]; LWordInExpectedIMAPFunction := True; if LPos < LWords.Count-1 then begin //There is a parameter after our function... FLineStruct.IMAPValue := LWords[LPos+1]; end; Break; end; end; end else begin //See is there function/value items left. There may not be, such as //'* 9 FETCH (UID 45)' in response to a GetUID request. if FLineStruct.Complete then begin if LWords.Count > 1 then begin FLineStruct.IMAPFunction := LWords[LWords.Count-2]; FLineStruct.IMAPValue := LWords[LWords.Count-1]; end; end; end; Result := False; if (AExpectedCommand = '') or (FLineStruct.Command = AExpectedCommand) then begin //The AExpectedCommand is correct, now need to check the AExpectedIMAPFunction... if (Length(AExpectedIMAPFunction) = 0) or LWordInExpectedIMAPFunction then begin Result := True; end; end; finally FreeAndNil(LWords); end; end; {This ADDS any parseable info from ALine to FLineStruct (set up from a previous ParseLastCmdResult call)} procedure TIdIMAP4.ParseLastCmdResultButAppendInfo(ALine: string); var LPos: integer; LWords: TStringList; begin ALine := Trim(ALine); //Can get garbage like a spurious CR at start {We may have an initial or ending bracket, like ") UID 5" or "UID 5)"} if TextStartsWith(ALine, ')') then begin {Do not Localize} ALine := Trim(Copy(ALine, 2, MaxInt)); end; if TextEndsWith(ALine, ')') then begin {Do not Localize} ALine := Trim(Copy(ALine, 1, Length(ALine)-1)); end; //These words left may occur in different order. Find & delete those we know. LWords := TStringList.Create; try ParseIntoBrackettedQuotedAndUnquotedParts(ALine, LWords, False); //See is the UID present... LPos := LWords.IndexOf('UID'); {Do not Localize} if LPos <> -1 then begin //The UID is the word after 'UID'... FLineStruct.UID := LWords[LPos+1]; LWords.Delete(LPos+1); LWords.Delete(LPos); end; //See are the FLAGS present... LPos := LWords.IndexOf('FLAGS'); {Do not Localize} if LPos <> -1 then begin //The FLAGS are in the "word" (really a string) after 'FLAGS'... ParseMessageFlagString(LWords[LPos+1], FLineStruct.Flags); LWords.Delete(LPos+1); LWords.Delete(LPos); end; finally FreeAndNil(LWords); end; end; { ...Parser Functions } function TIdIMAP4.ArrayToNumberStr(const AMsgNumList: array of Integer): String; var Ln : Integer; begin for Ln := 0 to Length(AMsgNumList) - 1 do begin Result := Result + IntToStr(AMsgNumList[Ln]) + ','; {Do not Localize} end; SetLength(Result, (Length(Result) - 1 )); end; function TIdIMAP4.MessageFlagSetToStr(const AFlags: TIdMessageFlagsSet): String; begin Result := ''; if AFlags = [] then begin Exit; end; if mfAnswered in AFlags then begin Result := Result + MessageFlags[mfAnswered] + ' '; {Do not Localize} end; if mfFlagged in AFlags then begin Result := Result + MessageFlags[mfFlagged] + ' '; {Do not Localize} end; if mfDeleted in AFlags then begin Result := Result + MessageFlags[mfDeleted] + ' '; {Do not Localize} end; if mfDraft in AFlags then begin Result := Result + MessageFlags[mfDraft] + ' '; {Do not Localize} end; if mfSeen in AFlags then begin Result := Result + MessageFlags[mfSeen] + ' '; {Do not Localize} end; Result := Trim(Result); end; procedure TIdIMAP4.StripCRLFs(ASourceStream, ADestStream: TStream); var LByte: TIdBytes; LNumSourceBytes: TIdStreamSize; LBytesRead: Int64; begin SetLength(LByte, 1); ASourceStream.Position := 0; ADestStream.Size := 0; LNumSourceBytes := ASourceStream.Size; LBytesRead := 0; while LBytesRead < LNumSourceBytes do begin TIdStreamHelper.ReadBytes(ASourceStream, LByte, 1); if not ByteIsInEOL(LByte, 0) then begin TIdStreamHelper.Write(ADestStream, LByte, 1); end; Inc(LBytesRead); end; end; procedure TIdIMAP4.StripCRLFs(var AText: string); var LPos: integer; LLen: integer; LTemp: string; LDestPos: integer; begin //Optimised with the help of Guus Creuwels. LPos := 1; LLen := Length(AText); SetLength(LTemp, LLen); LDestPos := 1; while LPos <= LLen do begin if AText[LPos] = #13 then begin //Don't GPF if this is the last char in the string... if LPos < LLen then begin if AText[LPos+1] = #10 then begin Inc(LPos, 2); end else begin LTemp[LDestPos] := AText[LPos]; Inc(LPos); Inc(LDestPos); end; end else begin LTemp[LDestPos] := AText[LPos]; Inc(LPos); Inc(LDestPos); end; end else begin LTemp[LDestPos] := AText[LPos]; Inc(LPos); Inc(LDestPos); end; end; SetLength(LTemp, LDestPos - 1); AText := LTemp; end; procedure TIdIMAP4.ReceiveBody(AMsg: TIdMessage; const ADelim: string = '.'); {Do not Localize} var LMsgEnd: Boolean; LActiveDecoder: TIdMessageDecoder; LLine: string; LCheckForOptionalImapFlags: Boolean; LDelim: string; {CC7: The following define SContentType is from IdMessageClient. It is defined here also (with only local scope) because the one in IdMessageClient is defined locally there also, so we cannot get at it.} const SContentType = 'Content-Type'; {do not localize} // TODO - move this procedure into TIdIOHandler as a new Capture method? procedure CaptureAndDecodeCharset; var LMStream: TMemoryStream; begin LMStream := TMemoryStream.Create; try IOHandler.Capture(LMStream, LDelim, True, Indy8BitEncoding(){$IFDEF STRING_IS_ANSI}, Indy8BitEncoding(){$ENDIF}); LMStream.Position := 0; ReadStringsAsCharSet(LMStream, AMsg.Body, AMsg.CharSet{$IFDEF STRING_IS_ANSI}, Indy8BitEncoding(){$ENDIF}); finally LMStream.Free; end; end; procedure ProcessTextPart(var VDecoder: TIdMessageDecoder); var LDestStream: TMemoryStream; Li: integer; LTxt: TIdText; LNewDecoder: TIdMessageDecoder; begin LDestStream := TMemoryStream.Create; try LNewDecoder := VDecoder.ReadBody(LDestStream, LMsgEnd); try LDestStream.Position := 0; LTxt := TIdText.Create(AMsg.MessageParts); try LTxt.ContentType := VDecoder.Headers.Values[SContentType]; LTxt.ContentID := VDecoder.Headers.Values['Content-ID']; {Do not Localize} LTxt.ContentLocation := VDecoder.Headers.Values['Content-Location']; {Do not Localize} LTxt.ContentDescription := VDecoder.Headers.Values['Content-Description']; {Do not Localize} LTxt.ContentDisposition := VDecoder.Headers.Values['Content-Disposition']; {Do not Localize} LTxt.ContentTransfer := VDecoder.Headers.Values['Content-Transfer-Encoding']; {Do not Localize} LTxt.ExtraHeaders.NameValueSeparator := '='; {Do not Localize} for Li := 0 to VDecoder.Headers.Count-1 do begin if LTxt.Headers.IndexOfName(VDecoder.Headers.Names[Li]) < 0 then begin LTxt.ExtraHeaders.Add(VDecoder.Headers.Strings[Li]); end; end; ReadStringsAsCharset(LDestStream, LTxt.Body, LTxt.CharSet); except //this should also remove the Item from the TCollection. //Note that Delete does not exist in the TCollection. LTxt.Free; raise; end; except LNewDecoder.Free; raise; end; VDecoder.Free; VDecoder := LNewDecoder; finally FreeAndNil(LDestStream); end; end; procedure ProcessAttachment(var VDecoder: TIdMessageDecoder); var LDestStream: TStream; Li: integer; LAttachment: TIdAttachment; LNewDecoder: TIdMessageDecoder; begin AMsg.DoCreateAttachment(VDecoder.Headers, LAttachment); Assert(Assigned(LAttachment), 'Attachment must not be unassigned here!'); {Do not Localize} try LNewDecoder := nil; try LDestStream := LAttachment.PrepareTempStream; try LNewDecoder := VDecoder.ReadBody(LDestStream, LMsgEnd); finally LAttachment.FinishTempStream; end; LAttachment.ContentType := VDecoder.Headers.Values[SContentType]; LAttachment.ContentTransfer := VDecoder.Headers.Values['Content-Transfer-Encoding']; {Do not Localize} LAttachment.ContentDisposition := VDecoder.Headers.Values['Content-Disposition']; {Do not Localize} LAttachment.ContentID := VDecoder.Headers.Values['Content-ID']; {Do not Localize} LAttachment.ContentLocation := VDecoder.Headers.Values['Content-Location']; {Do not Localize} LAttachment.ContentDescription := VDecoder.Headers.Values['Content-Description']; {Do not Localize} LAttachment.Filename := VDecoder.Filename; LAttachment.ExtraHeaders.NameValueSeparator := '='; {Do not Localize} for Li := 0 to VDecoder.Headers.Count-1 do begin if LAttachment.Headers.IndexOfName(VDecoder.Headers.Names[Li]) < 0 then begin LAttachment.ExtraHeaders.Add(VDecoder.Headers.Strings[Li]); end; end; except LNewDecoder.Free; raise; end; except //this should also remove the Item from the TCollection. //Note that Delete does not exist in the TCollection. LAttachment.Free; raise; end; VDecoder.Free; VDecoder := LNewDecoder; end; Begin {CC3: If IMAP calls this ReceiveBody, it prepends IMAP to delim, e.g. 'IMAP)', to flag that this routine should expect IMAP FLAGS entries.} LCheckForOptionalImapFlags := False; {CC3: IMAP hack inserted lines start here...} LDelim := ADelim; if TextStartsWith(ADelim, 'IMAP') then begin {do not localize} LCheckForOptionalImapFlags := True; LDelim := Copy(ADelim, 5, MaxInt); end; {CC3: ...IMAP hack inserted lines end here} LMsgEnd := False; if AMsg.NoDecode then begin CaptureAndDecodeCharSet; end else begin BeginWork(wmRead); try LActiveDecoder := nil; try repeat LLine := IOHandler.ReadLn; {CC3: Check for optional flags before delimiter in the case of IMAP...} if LLine = LDelim then begin {CC3: IMAP hack ADelim -> LDelim} Break; end; {CC3: IMAP hack inserted lines start here...} if LCheckForOptionalImapFlags and TextStartsWith(LLine, ' FLAGS (\') {do not localize} and TextEndsWith(LLine, LDelim) then begin Break; end; if LActiveDecoder = nil then begin LActiveDecoder := TIdMessageDecoderList.CheckForStart(AMsg, LLine); end; if LActiveDecoder = nil then begin {CC9: Per RFC821, the sender is required to add a prefixed '.' to any line in an email that starts with '.' and the receiver is required to strip it off. This ensures that the end-of-message line '.' cannot appear in the message body.} if TextStartsWith(LLine, '..') then begin {Do not Localize} Delete(LLine,1,1); end; AMsg.Body.Add(LLine); end else begin while LActiveDecoder <> nil do begin LActiveDecoder.SourceStream := TIdTCPStream.Create(Self); LActiveDecoder.ReadHeader; case LActiveDecoder.PartType of mcptText: ProcessTextPart(LActiveDecoder); mcptAttachment: ProcessAttachment(LActiveDecoder); mcptIgnore: FreeAndNil(LActiveDecoder); mcptEOF: begin FreeAndNil(LActiveDecoder); LMsgEnd := True; end; end; end; end; until LMsgEnd; finally FreeAndNil(LActiveDecoder); end; finally EndWork(wmRead); end; end; end; {########### Following only used by CONNECT? ###############} function TIdIMAP4.GetResponse: string; {CC: The purpose of this is to keep reading & accumulating lines until we hit a line that has a valid response (that terminates the reading). We call "FLastCmdResult.FormattedReply := LResponse;" to parse out the response we received. The response sequences we need to deal with are: 1) Many commands just give a simple result to the command issued: C41 OK Completed 2) Some commands give you data first, then the result: * LIST (\UnMarked) "/" INBOX * LIST (\UnMarked) "/" Junk * LIST (\UnMarked) "/" Junk/Subbox1 C42 OK Completed 3) Some responses have a result but * instead of a command number (like C42): * OK CommuniGate Pro IMAP Server 3.5.7 ready 4) Some have neither a * nor command number, but start with a result: + Send the additional command text or: BAD Bad parameter Because you may get data first, which you need to skip, you need to accept all the above possibilities. We MUST stop when we find a valid response code, like OK. } var LLine: String; LResponse: TStringList; LWord: string; LPos: integer; LBuf: string; begin Result := ''; {Do not Localize} LResponse := TStringList.Create; try repeat LLine := IOHandler.ReadLnWait; if LLine <> '' then begin {Do not Localize} {It is not an empty line, add it to our list of stuff received (it is not our job to interpret it)} LResponse.Add(LLine); {See if the last LLine contained a response code like OK or BAD.} LPos := Pos(' ', LLine); {Do not Localize} if LPos <> 0 then begin {There are at least two words on this line...} LWord := Trim(Copy(LLine, 1, LPos-1)); LBuf := Trim(Copy(LLine, LPos+1, MaxInt)); {The rest of the line, without the 1st word} end else begin {No space, so this line is a single word. A bit weird, but it could be just an OK...} LWord := LLine; {A bit pedantic, but emphasises we have a word, not a line} LBuf := ''; {Do not Localize} end; LPos := PosInStrArray(LWord, VALID_TAGGEDREPLIES); {Do not Localize} if LPos > -1 then begin {We got a valid response code as the first word...} Result := LWord; FLastCmdResult.FormattedReply := LResponse; Exit; end; if Length(LBuf) = 0 then begin {Do not Localize} Continue; {We hit a line with just one word which is not a valid IMAP response} end; {In all other cases, any valid response should be the second word...} LPos := Pos(' ', LBuf); {Do not Localize} if LPos <> 0 then begin {There are at least three words on this line...} LWord := Trim(Copy(LBuf, 1, LPos-1)); LBuf := Trim(Copy(LBuf, LPos+1, MaxInt)); {The rest of the line, without the 1st word} end else begin {No space, so this line is two single words.} LWord := LLine; {A bit pedantic, but emphasises we have a word, not a line} LBuf := ''; {Do not Localize} end; LPos := PosInStrArray(LWord, VALID_TAGGEDREPLIES); {Do not Localize} if LPos > -1 then begin {We got a valid response code as the second word...} Result := LWord; FLastCmdResult.FormattedReply := LResponse; Exit; end; end; until False; finally FreeAndNil(LResponse); end; end; end.
unit aeHeightmapLoaderBase; (* Serves as a foundation class for loading heightmaps. *) interface uses windows, types; type TaeHeightMapLoaderType = (AE_LOADER_AION_H32); type TaeHeightmapLoaderBase = class public Constructor Create; Function GetHeightData: Pointer; Function GetHeightDataSize: integer; Function IsHeightDataSet: boolean; function GetLoaderType: TaeHeightMapLoaderType; protected _loaderType: TaeHeightMapLoaderType; procedure SetHeightData(p: Pointer; len: integer); overload; procedure AllocateMem(d_size: integer); Procedure FreeHeightData; private _data: Pointer; // pointer to the data. _dataLen: integer; end; implementation { TaeHeightmapLoaderBase } procedure TaeHeightmapLoaderBase.AllocateMem(d_size: integer); begin self._data := AllocMem(d_size); self._dataLen := d_size; end; constructor TaeHeightmapLoaderBase.Create; begin self._data := nil; self._dataLen := 0; end; procedure TaeHeightmapLoaderBase.FreeHeightData; begin FreeMem(self._data, self._dataLen); end; function TaeHeightmapLoaderBase.GetHeightData: Pointer; begin Result := self._data; end; function TaeHeightmapLoaderBase.GetHeightDataSize: integer; begin Result := self._dataLen; end; function TaeHeightmapLoaderBase.GetLoaderType: TaeHeightMapLoaderType; begin Result := self._loaderType; end; function TaeHeightmapLoaderBase.IsHeightDataSet: boolean; begin Result := (self._dataLen > 0); end; procedure TaeHeightmapLoaderBase.SetHeightData(p: Pointer; len: integer); begin CopyMemory(self._data, p, len); self._dataLen := len; end; end.
unit ncsServiceProviderParams; // Модуль: "w:\common\components\rtl\Garant\cs\ncsServiceProviderParams.pas" // Стереотип: "SimpleClass" // Элемент модели: "TncsServiceProviderParams" MUID: (54F044E00390) {$Include w:\common\components\rtl\Garant\cs\CsDefine.inc} interface {$If NOT Defined(Nemesis)} uses l3IntfUses , l3ProtoObject ; type TncsServiceProviderParams = class(Tl3ProtoObject) private f_ServerHostName: AnsiString; f_ServerPort: Integer; f_Login: AnsiString; f_Password: AnsiString; f_IsDeveloper: Boolean; f_StandAlone: Boolean; f_CorrectTempPath: Boolean; protected procedure InitFields; override; procedure ClearFields; override; public property ServerHostName: AnsiString read f_ServerHostName write f_ServerHostName; property ServerPort: Integer read f_ServerPort write f_ServerPort; property Login: AnsiString read f_Login write f_Login; property Password: AnsiString read f_Password write f_Password; property IsDeveloper: Boolean read f_IsDeveloper write f_IsDeveloper; property StandAlone: Boolean read f_StandAlone write f_StandAlone; property CorrectTempPath: Boolean read f_CorrectTempPath write f_CorrectTempPath; end;//TncsServiceProviderParams {$IfEnd} // NOT Defined(Nemesis) implementation {$If NOT Defined(Nemesis)} uses l3ImplUses //#UC START# *54F044E00390impl_uses* //#UC END# *54F044E00390impl_uses* ; procedure TncsServiceProviderParams.InitFields; //#UC START# *47A042E100E2_54F044E00390_var* //#UC END# *47A042E100E2_54F044E00390_var* begin //#UC START# *47A042E100E2_54F044E00390_impl* inherited; f_CorrectTempPath := True; //#UC END# *47A042E100E2_54F044E00390_impl* end;//TncsServiceProviderParams.InitFields procedure TncsServiceProviderParams.ClearFields; begin ServerHostName := ''; Login := ''; Password := ''; inherited; end;//TncsServiceProviderParams.ClearFields {$IfEnd} // NOT Defined(Nemesis) end.
{ Subroutine SST_FLAG_USED_DTYPE (DTYPE) * * Follow all symbols eventually referenced by the data type DTYPE, and flag * them as used. } module sst_FLAG_USED_DTYPE; define sst_flag_used_dtype; %include 'sst2.ins.pas'; procedure sst_flag_used_dtype ( {flag symbols eventually used from a dtype} in dtype: sst_dtype_t); {dtype descriptor that may reference symbols} const max_msg_parms = 1; {max parameters we can pass to a message} var sym_p: sst_symbol_p_t; {scratch symbol pointer} msg_parm: {references to paramters for messages} array[1..max_msg_parms] of sys_parm_msg_t; begin if dtype.symbol_p <> nil then begin {symbol exists for this data type ?} if sst_symflag_followed_k in dtype.symbol_p^.flags {already done this symbol ?} then return; if sst_symflag_following_dt_k in dtype.symbol_p^.flags {already doing dtype ?} then return; if {not already working on this symbol ?} not (sst_symflag_following_k in dtype.symbol_p^.flags) then begin sst_flag_used_symbol (dtype.symbol_p^); {flag data type's parent symbol} return; end; dtype.symbol_p^.flags := {indicate we are now doing this data type} dtype.symbol_p^.flags + [sst_symflag_following_dt_k]; end; case dtype.dtype of {what kind of data type is this ?} { * Data type is enumerated type. } sst_dtype_enum_k: begin sym_p := dtype.enum_first_p; {init current enumerated value to first} while sym_p <> nil do begin {once for each enumerated value} sst_flag_used_symbol (sym_p^); {flag each enumerated name as used} sym_p := sym_p^.enum_next_p; {advance to next enumerated name} end; end; { * Data type is a record. } sst_dtype_rec_k: begin sym_p := dtype.rec_first_p; {init curr symbol to first field name} while sym_p <> nil do begin {once for each field in record} sst_flag_used_dtype (sym_p^.field_dtype_p^); {process field's data type} sym_p := sym_p^.field_next_p; {advance to next field in record} end; end; { * Data type is an array. } sst_dtype_array_k: begin sst_flag_used_exp (dtype.ar_ind_first_p^); {process exp for subscript range start} if dtype.ar_ind_last_p <> nil then begin {fixed subscript ending exp exists ?} sst_flag_used_exp (dtype.ar_ind_last_p^); {process exp for subscript range end} end; if dtype.ar_dtype_rem_p = nil then begin {this is a one-dimensional array} sst_flag_used_dtype (dtype.ar_dtype_ele_p^); {process elements data type} end else begin {there is more than one subscript} sst_flag_used_dtype (dtype.ar_dtype_rem_p^); {process "rest" of array} end ; end; { * Data type is a set. } sst_dtype_set_k: begin sst_flag_used_dtype (dtype.set_dtype_p^); {declare base data type of set} end; { * Data type is a subrange of another data type. } sst_dtype_range_k: begin sst_flag_used_dtype (dtype.range_dtype_p^); {flag base data type as used} if dtype.range_first_p <> nil then begin sst_flag_used_exp (dtype.range_first_p^); {process expression for first value} end; if dtype.range_last_p <> nil then begin sst_flag_used_exp (dtype.range_last_p^); {process expression for last value} end; end; { * Data type is a procedure. } sst_dtype_proc_k: begin sst_flag_used_rout (dtype.proc_p^); {flag symbols used by this routine} end; { * Data type is a pointer. } sst_dtype_pnt_k: begin if dtype.pnt_dtype_p <> nil then begin {not a NIL pointer ?} sst_flag_used_dtype (dtype.pnt_dtype_p^); {flag pointed-to data type as used} end; end; { * Data type is a copy of another data type. } sst_dtype_copy_k: begin if dtype.copy_symbol_p <> nil then begin sst_flag_used_symbol (dtype.copy_symbol_p^); {flag copied symbol name} end; sst_flag_used_dtype (dtype.copy_dtype_p^); {flag copied data type} end; { * Undefined data type. This could happen under legal circumstances if * a symbol was defined that pointed to a data type that was never defined, * but also never used directly. In this case, we want to make sure the * undefined data type is not flagged as used. This would cause problems * for the back end by asking it to write an undefined symbol. } sst_dtype_undef_k: begin if dtype.symbol_p <> nil then begin {this data type has a symbol ?} dtype.symbol_p^.flags := dtype.symbol_p^.flags - {flag symbol as unused} [sst_symflag_used_k]; end; end; { * All the data types that require no special processing. } sst_dtype_int_k: ; sst_dtype_float_k: ; sst_dtype_bool_k: ; sst_dtype_char_k: ; otherwise sys_msg_parm_int (msg_parm[1], ord(dtype.dtype)); sys_message_bomb ('sst', 'dtype_unexpected_exp', msg_parm, 1); end; {end of data type cases} end;
// ********************************************************************** // // Copyright (c) 2001 - 2002 MT Tools. // // All Rights Reserved // // MT_DORB is based in part on the product DORB, // written by Shadrin Victor // // See Readme.txt for contact information // // ********************************************************************** {$I-} unit Yacclib; (* Yacc Library Unit for TP Yacc Version 3.0, 6-17-91 AG *) interface {$I dorb.inc} const yymaxdepth = 1024; (* default stack size of parser *) type YYSType = Integer; (* default value type, may be redefined in Yacc output file *) var yychar : Integer; (* current lookahead character *) yynerrs : Integer; (* current number of syntax errors reported by the parser *) yydebug : Boolean; (* set to true to enable debugging output of parser *) procedure yyerror ( msg : String ); (* error message printing routine used by the parser *) procedure yyclearin; (* delete the current lookahead token *) procedure yyaccept; (* trigger accept action of the parser; yyparse accepts returning 0, as if it reached end of input *) procedure yyabort; (* like yyaccept, but causes parser to return with value 1, as if an unrecoverable syntax error had been encountered *) procedure yyerrlab; (* causes error recovery to be started, as if a syntax error had been encountered *) procedure yyerrok; (* when in error mode, resets the parser to its normal mode of operation *) (* Flags used internally by the parser routine: *) var yyflag : ( yyfnone, yyfaccept, yyfabort, yyferror ); yyerrflag : Integer; implementation uses Lexlib,SysUtils,{$IFDEF MSWINDOWS}Windows{$ENDIF}{$IFDEF LINUX}Libc{$ENDIF},parser; procedure yyerror ( msg : String ); var fulltext : string; begin fulltext := current_file +'('+inttostr(idl_line_no)+ '):'+msg; {$IFDEF MSWINDOWS} FileWrite(GetStdHandle(STD_ERROR_HANDLE), PChar(fulltext)^, Length(fulltext)); {$ENDIF} {$IFDEF LINUX} FileWrite(STDERR_FILENO, fulltext, Length(fulltext)); {$ENDIF} end(*yyerrmsg*); procedure yyclearin; begin yychar := -1; end(*yyclearin*); procedure yyaccept; begin yyflag := yyfaccept; end(*yyaccept*); procedure yyabort; begin yyflag := yyfabort; end(*yyabort*); procedure yyerrlab; begin yyflag := yyferror; end(*yyerrlab*); procedure yyerrok; begin yyerrflag := 0; end(*yyerrork*); end(*YaccLib*).
program plantas; type _planta = record nombre :string; longevidad :integer; tipo :string; clima :string; cantidadPaises :integer; end; _tipo = record tipo :string; acumulador :integer; contador :integer; end; _pico = record ref :string; val :integer; end; _maximos = record primero :_pico; segundo :_pico; end; // Utilidades procedure incrementar(var c:integer); begin c := c + 1; end; procedure acumular(var a:integer; val:integer); begin a := a + val; end; // Datos procedure leer(var planta:_planta); begin with planta do begin write('Ingrese el nombre de la planta: '); readln(nombre); write('Ingrese la longevidad en meses: '); readln(longevidad); write('Ingrese el tipo de planta: '); readln(tipo); write('Ingres el clima: '); readln(clima); end; end; procedure leerPais(var pais:string; var c:integer); begin write('Ingrese el nombre de un pais: '); readln(pais); incrementar(c); end; // Cond 1 procedure comprobarCond1(var minimo:_pico; tipo:_tipo); begin if (tipo.contador <= minimo.val) then begin minimo.val := tipo.contador; minimo.ref := tipo.tipo; end; end; // Cond 2 procedure informarCond2(tipo:_tipo); begin with tipo do begin writeln( 'El promedio de vida de las plantas del tipo ', tipo, ' es ', acumulador/contador:8:2,'.' ); end; end; procedure reiniciarCond2(var tipo:_tipo; nuevoTipo:string); begin with tipo do begin tipo := nuevoTipo; acumulador := 0; contador := 0; end; end; // Cond 3 procedure comprobarCond3(var max:_maximos; p:_planta); begin if (p.longevidad >= max.primero.val) then begin max.segundo.val := max.primero.val; max.segundo.ref := max.primero.ref; max.primero.val := p.longevidad; max.primero.ref := p.nombre; end else if (p.longevidad >= max.segundo.val) then begin max.segundo.val := p.longevidad; max.segundo.ref := p.nombre; end; end; // Cond 4 procedure comprobarCond4(p :_planta; pais :string); begin if ((pais = 'Argentina') and (p.clima = 'Subtropical')) then writeln( 'La planta ', p.nombre, ' es nativa de Argentina y se encuentra en regiones con clima subtropical.' ); end; // Cond 5 procedure comprobarCond5(var max:_pico; p:_planta); begin if (p.cantidadPaises >= max.val) then begin max.val := p.cantidadPaises; max.ref := p.nombre; end; end; var i :integer; planta :_planta; pais :string; tipoActual :_tipo; minimo :_pico; maximo :_pico; maximos :_maximos; begin with tipoActual do begin tipo := ' '; acumulador := 0; contador := 0; end; minimo.val := 999; maximo.val := 0; maximos.primero.val := 0; maximos.segundo.val := 0; for i:=1 to 320 do begin leer(planta); leerPais(pais, planta.cantidadPaises); while (pais <> 'ZZZ') do begin comprobarCond4(planta,pais); leerPais(pais, planta.cantidadPaises); end; // Manejo cambio de tipo if (planta.tipo <> tipoActual.tipo) then begin comprobarCond1(minimo, tipoActual); // Cumple cond 1 informarCond2(tipoActual); // Cumple cond 2 reiniciarCond2(tipoActual, planta.tipo); end; acumular(tipoActual.acumulador, planta.longevidad); // Guardo los valores de longevidad del tipo incrementar(tipoActual.contador); // Incremento contador de plantas del tipo comprobarCond3(maximos, planta); // Cumple cond 3 comprobarCond5(maximo, planta); // Cumple cond 5 end; writeln('EL tipo de planta con menor cantidad de plantas es : ', minimo.ref); writeln( 'Las dos plantas más longevas son : ', maximos.primero.ref, ' y ', maximos.segundo.ref, '.' ); writeln('La planta que se encuentra en más paises es: ', maximo.ref); end.
unit uGSMainMenu; interface uses glr_core, glr_render, glr_render2d, glr_scene, glr_gui, glr_gamescreens, glr_utils, glr_tween; type { TglrMainMenu } TglrMainMenu = class (TglrGameScreen) protected Container: TglrNode; PaletteSprites: array of TglrSprite; pixelSize, rtw, rth: Single; GameName, AuthorName: TglrGuiLabel; NewGameBtn, SettingsBtn, ExitBtn: TglrGuiButton; GuiManager: TglrGuiManager; ActionManager: TglrActionManager; procedure ButtonInit(var Button: TglrGuiButton); procedure ButtonTween(aObject: TglrTweenObject; aValue: Single); procedure ButtonClicked(Sender: TglrGuiElement; Event: PglrInputEvent); procedure ButtonOver(Sender: TglrGuiElement; Event: PglrInputEvent); procedure ShowPalette(); procedure DoExit(); procedure ToSettings(); public constructor Create(ScreenName: UnicodeString); override; destructor Destroy; override; procedure OnInput(Event: PglrInputEvent); override; procedure OnRender; override; procedure OnUpdate (const DeltaTime: Double); override; procedure OnLoadStarted(); override; procedure OnUnloadStarted(); override; end; implementation uses uAssets, uGame, glr_math; { TglrMainMenu } procedure TglrMainMenu.ButtonInit(var Button: TglrGuiButton); begin Button := TglrGuiButton.Create(); with Button do begin SetVerticesColor(Colors.MenuButton); SetSize(Sizes.ButtonSize); TextLabel.Text := 'Button'; TextLabel.Position := Vec3f(Sizes.ButtonTextOffset, 0); TextLabel.Color := Colors.MenuButtonText; Position := Vec3f(Render.Width div 2, 240, 1); OnClick := ButtonClicked; OnMouseOver := ButtonOver; OnMouseOut := ButtonOver; Parent := Container; end; end; procedure TglrMainMenu.ButtonTween(aObject: TglrTweenObject; aValue: Single); var v: TglrVec3f; begin v := Vec3f(1,1,1); (aObject as TglrGuiButton).SetVerticesColor(Vec4f(v.Lerp(Vec3f(Colors.MenuButton), aValue), 1.0)); end; procedure TglrMainMenu.ButtonClicked(Sender: TglrGuiElement; Event: PglrInputEvent); begin Game.Tweener.AddTweenSingle(Sender, ButtonTween, tsExpoEaseIn, 0.0, 1.0, 2.0, 0.1); if (Sender = SettingsBtn) then ActionManager.AddIndependent(ToSettings, 0.2) else if (Sender = ExitBtn) then ActionManager.AddIndependent(DoExit, 0.2) else if (Sender = NewGameBtn) then begin end; end; procedure TglrMainMenu.ButtonOver(Sender: TglrGuiElement; Event: PglrInputEvent); begin if (Sender.IsMouseOver) then Sender.SetSize(Sizes.ButtonSizeOver) else Sender.SetSize(Sizes.ButtonSize); end; procedure TglrMainMenu.ShowPalette; var i: Integer; begin SetLength(PaletteSprites, Length(Colors.Palette) * 1); for i := 0 to Length(PaletteSprites) - 1 do begin PaletteSprites[i] := TglrSprite.Create(40, 40, Vec2f(0, 0)); PaletteSprites[i].SetVerticesColor(Colors.Palette[i mod Length(Colors.Palette)]); PaletteSprites[i].Position := Vec3f(5 + (i mod 15) * 45, (i div 15) * 45, 1); PaletteSprites[i].Parent := Container; end; end; procedure TglrMainMenu.DoExit; begin Core.Quit(); end; procedure TglrMainMenu.ToSettings; begin Game.GameScreenManager.SwitchTo('SettingsMenu'); end; procedure TglrMainMenu.OnInput(Event: PglrInputEvent); begin GuiManager.ProcessInput(Event, Assets.GuiCamera); end; procedure TglrMainMenu.OnRender; begin Assets.FrameBuffer.Bind(); Render.Clear(cmAll); Assets.GuiCamera.Update(); Assets.GuiMaterial.Bind(); Assets.GuiSpriteBatch.Start(); Assets.GuiSpriteBatch.Draw(PaletteSprites); Assets.GuiSpriteBatch.Finish(); GuiManager.Render(); Assets.FrameBuffer.Unbind(); Render.DrawScreenQuad(Assets.PixelateMaterial); end; procedure TglrMainMenu.OnUpdate(const DeltaTime: Double); begin GuiManager.Update(DeltaTime); ActionManager.Update(DeltaTime); end; procedure TglrMainMenu.OnLoadStarted; begin Render.SetClearColor(Colors.MenuBackground); Game.Tweener.AddTweenPSingle(@Container.Position.y, tsExpoEaseIn, -Render.Height, 0, 1.5); Game.Tweener.AddTweenPSingle(@pixelSize, tsSimple, 1, 8, 1.0, 2.0); inherited OnLoadStarted; end; procedure TglrMainMenu.OnUnloadStarted; begin Game.Tweener.AddTweenPSingle(@Container.Position.y, tsExpoEaseIn, 0, -Render.Height, 1.5); ActionManager.AddIndependent(UnloadCompleted, 0.5); end; constructor TglrMainMenu.Create(ScreenName: UnicodeString); begin inherited Create(ScreenName); ActionManager := TglrActionManager.Create(); Container := TglrNode.Create(); ButtonInit(NewGameBtn); ButtonInit(SettingsBtn); ButtonInit(ExitBtn); NewGameBtn.TextLabel.Text := Texts.MenuNewGame; SettingsBtn.TextLabel.Text := Texts.MenuSettings; ExitBtn.TextLabel.Text := Texts.MenuExit; SettingsBtn.Position += Vec3f(0, 70, 0); ExitBtn.Position += Vec3f(0, 140, 0); GameName := TglrGuiLabel.Create(); GameName.Position := Vec3f(Render.Width div 2, 70, 5); GameName.TextLabel.Text := Texts.MenuTitle; GameName.TextLabel.Scale := 1.2; GameName.TextLabel.PivotPoint := Vec2f(0.5, 0.0); GameName.TextLabel.ShadowEnabled := True; GameName.TextLabel.ShadowOffset := Vec2f(2,2); GameName.TextLabel.Color := Colors.MenuText; GameName.Parent := Container; AuthorName := TglrGuiLabel.Create(); AuthorName.Position := Vec3f(Render.Width div 2, Render.Height - 50, 5); AuthorName.TextLabel.Text := Texts.MenuAuthorName; AuthorName.TextLabel.Scale := 0.7; AuthorName.TextLabel.PivotPoint := Vec2f(0.5, 0.5); AuthorName.TextLabel.ShadowEnabled := True; AuthorName.TextLabel.ShadowOffset := Vec2f(3,3); AuthorName.TextLabel.Color := Colors.MenuText; AuthorName.Parent := Container; GuiManager := TglrGuiManager.Create(Assets.GuiMaterial, Assets.FontMain); GuiManager.Add(NewGameBtn); GuiManager.Add(SettingsBtn); GuiManager.Add(ExitBtn); GuiManager.Add(GameName); GuiManager.Add(AuthorName); ShowPalette(); pixelSize := 1; rtw := Render.Width; rth := Render.Height; Assets.PixelateShader.AddUniform(utVec1, 1, 'uPixelSize', @pixelSize); Assets.PixelateShader.AddUniform(utVec1, 1, 'uRTWidth', @rtw); Assets.PixelateShader.AddUniform(utVec1, 1, 'uRTHeight', @rth); end; destructor TglrMainMenu.Destroy(); begin Container.Free(); ActionManager.Free(); GuiManager.Free(True); inherited; end; end.
@model System.Web.Mvc.HandleErrorInfo @{ ViewBag.Title = "Error"; } <hgroup> <h1 class="text-error">Error.</h1> <h2 class="text-error">An error occurred while processing your request.</h2> </hgroup>
unit PositionUnit; interface type TPosition = record Latitude: double; Longitude: double; constructor Create(Latitude, Longitude: double); end; implementation { TPosition } constructor TPosition.Create(Latitude, Longitude: double); begin Self.Latitude := Latitude; Self.Longitude := Longitude; end; end.
unit EditRFileForma; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, FIBDataSet, pFIBDataSet, DBGridEh, StdCtrls, DBCtrls, Mask, DBCtrlsEh, DBLookupEh, CnErrorProvider, FIBQuery, PrjConst, System.UITypes, Vcl.Buttons, pFIBQuery; type TEditRFileForm = class(TForm) memNotice: TDBMemoEh; Label1: TLabel; CnErrors: TCnErrorProvider; btnOk: TBitBtn; btnCancel: TBitBtn; edtFILE: TDBEditEh; lblFileCh: TLabel; dlgOpen: TOpenDialog; qryFile: TpFIBQuery; procedure btnOkClick(Sender: TObject); procedure edtFILEEditButtons0Click(Sender: TObject; var Handled: Boolean); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private public end; function EditFile(const RQ_ID: Integer; const HOUSE_ID: Integer = -1): Boolean; implementation uses DM; {$R *.dfm} function EditFile(const RQ_ID: Integer; const HOUSE_ID: Integer = -1): Boolean; begin with TEditRFileForm.Create(Application) do try if ShowModal = mrOk then begin qryFile.ParamByName('RQ_ID').AsInteger := RQ_ID; qryFile.ParamByName('HOUSE_ID').AsInteger := HOUSE_ID; qryFile.ParamByName('Jpg').LoadFromFile(edtFILE.Hint); qryFile.ParamByName('Notice').AsString := memNotice.Lines.Text+'('+ExtractFileName(edtFILE.Hint)+')'; qryFile.ExecQuery; result := true; end else begin result := false; end; finally free end; end; procedure TEditRFileForm.btnOkClick(Sender: TObject); var errors: Boolean; begin errors := false; if (edtFILE.Text = '') then begin errors := true; CnErrors.SetError(edtFILE, rsEmptyFieldError, iaMiddleLeft, bsNeverBlink); end else CnErrors.Dispose(edtFILE); if not errors then ModalResult := mrOk else ModalResult := mrNone; end; procedure TEditRFileForm.edtFILEEditButtons0Click(Sender: TObject; var Handled: Boolean); begin if dlgOpen.Execute then begin edtFILE.Text := ExtractFileName(dlgOpen.FileName); edtFILE.Hint := dlgOpen.FileName; edtFILE.Tag := 1; end; Handled := True; end; procedure TEditRFileForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Shift = [ssCtrl]) and (Ord(Key) = VK_RETURN) then btnOkClick(Sender); end; end.
unit oPedido; interface uses Vcl.StdCtrls; type TPedido = class private FLabel: TLabel; class var TotPedido: Double; class var codigoCliente: Integer; public constructor Create(lblTotal: TLabel); procedure Soma(valor: Double); procedure Subtrai(valor: Double); class property Total: Double read TotPedido write TotPedido; class property Cliente: Integer read codigoCliente write codigoCliente; end; implementation uses System.SysUtils; constructor TPedido.Create(lblTotal: TLabel); begin inherited Create; FLabel := lblTotal; end; procedure TPedido.Soma(valor: Double); begin TotPedido := TotPedido + valor; if FLabel = nil then Exit; FLabel.Caption := FormatFloat('#,##0.00', TotPedido); end; procedure TPedido.Subtrai(valor: Double); begin TotPedido := TotPedido - valor; if FLabel = nil then Exit; FLabel.Caption := FormatFloat('#,##0.00', TotPedido); end; end.
{ Free Component miniLog Version 2.0 Copyright (©) 2010, by Sergiy Tkach (Apromix), bees@meta.ua } unit uLog; interface type TmLog = class private FAppName: string; FAppPath: string; LogFile: Text; protected function ExtractFilePath(const FileName: string): string; function ExtractFileName(const FileName: string): string; function Trim(const S: string): string; function LineStr(S: string; N: Integer): string; public //** Конструктор. constructor Create(AAppName: string = ''); destructor Destroy; override; procedure Log(LogMessage: string; AddDateTime: Boolean = False); overload; procedure Log(LogMessage, LogStrValue: string; AddDateTime: Boolean = False); overload; procedure Log(LogMessage: string; LogIntValue: Integer; AddDateTime: Boolean = False); overload; procedure LogDiv; property ApplicationName: string read FAppName; property ApplicationPath: string read FAppPath; end; var Log: TmLog; implementation uses SysUtils, uBox, uAdvStr; const DefaultLogFileEx = '.log'; // Расширение лога DefaultLogFileName = ''; // Название лога, если оставить пустым, то будет именем приложения LogDv = '-->'; // Разделитель в сообщениях лога MsgDivLength = 80; // Длина разделителя между сообщениями MsgDivStr = '-'; // Разделитель между сообщениями (звено) var DivMessage: string = ''; DTMsg: string = ''; const WinS = '\'; Empty = ''; Space = ' '; constructor TmLog.Create(AAppName: string = ''); var D, T, R: string; begin inherited Create; D := DateToStr(Date); R := TimeToStr(Time); AdvStr.AdvString := R; T := AdvStr.Replace(':', '.'); DivMessage := LineStr(MsgDivStr, MsgDivLength); if (Trim(AAppName) = Empty) then FAppName := ExtractFileName(ParamStr(0)) else FAppName := Trim(AAppName) + LineStr(Space, 4); FAppPath := ExtractFilePath(ParamStr(0)); ForceDirectories(FAppPath + 'Logs'); Assign(LogFile, FAppPath + 'Logs' + WinS + D + '.' + T + DefaultLogFileEx); Rewrite(LogFile); Log('File: ' + FAppName); Log('Path: ' + FAppPath); LogDiv; Log('Opening Log at ' + LogDv + Space + D + Space + R); end; destructor TmLog.Destroy; begin Log('Closing Log at ' + LogDv + Space + DateToStr(Date) + Space + TimeToStr(Time)); Close(LogFile); inherited Destroy; end; function TmLog.ExtractFileName(const FileName: string): string; var N: Integer; i: Integer; begin N := Length(FileName); Result := Empty; if (N = 0) then Exit; for i := N downto 1 do begin if (FileName[i] = WinS) then Exit; Result := FileName[i] + Result; end; end; function TmLog.ExtractFilePath(const FileName: string): string; var N: Integer; i: Integer; begin N := Length(FileName); Result := Empty; if (N = 0) then Exit; for i := N downto 1 do begin if (FileName[i] = WinS) then begin Result := Copy(FileName, 1, i); Exit; end; end; end; function TmLog.LineStr(S: string; N: Integer): string; var i: Integer; R: string; begin R := Empty; for i := 1 to N do R := R + Trim(S); Result := R; end; function TmLog.Trim(const S: string): string; var i, l: Integer; begin l := Length(S); i := 1; while (i <= l) and (S[i] <= Space) do inc(i); if (i > l) then Result := Empty else begin while S[l] <= Space do Dec(l); Result := Copy(S, i, l - i + 1); end; end; procedure TmLog.Log(LogMessage: string; AddDateTime: Boolean = False); begin DTMsg := Empty; if AddDateTime then DTMsg := DateToStr(Date) + Space + TimeToStr(Time) + ':' + Space; WriteLn(LogFile, Trim(DTMsg + LogMessage)); end; procedure TmLog.Log(LogMessage, LogStrValue: string; AddDateTime: Boolean = False); begin DTMsg := Empty; if AddDateTime then DTMsg := DateToStr(Date) + Space + TimeToStr(Time) + ':' + Space; WriteLn(LogFile, Trim(DTMsg + LogMessage) + Space + LogDv + Space + Trim(LogStrValue)); end; procedure TmLog.Log(LogMessage: string; LogIntValue: Integer; AddDateTime: Boolean = False); var V: string; begin DTMsg := Empty; if AddDateTime then DTMsg := DateToStr(Date) + Space + TimeToStr(Time) + ':' + Space; Str(LogIntValue, V); WriteLn(LogFile, Trim(DTMsg + LogMessage) + Space + LogDv + Space + V); end; procedure TmLog.LogDiv; begin WriteLn(LogFile, Trim(DivMessage)); end; initialization begin Log := TmLog.Create(DefaultLogFileName); with Log do begin LogDiv; Log('Initialization', 'Starting Application'); LogDiv; end; end; finalization begin with Log do begin LogDiv; Log('Finalization', 'Terminating Application'); LogDiv; Free; end; Log := nil; end; end.
unit progressfrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls; type TfProgress = class(TForm) Panel1: TPanel; lStatus: TLabel; pProgress: TPanel; pbProgress: TProgressBar; Label1: TLabel; Panel3: TPanel; pbOverallProgress: TProgressBar; bCancel: TButton; procedure bCancelClick(Sender: TObject); public Cancelled : boolean; lastUpdate : integer; lastOverall : Int64; procedure setStatus(s:string); procedure setValue(n:Int64); procedure setMax(n:Int64); procedure setOverallMax(n:Int64); procedure setOverallValue(n:Int64); procedure UpdateDisplay; end; function beginProgress(title:string; multi:boolean):TfProgress; implementation {$R *.dfm} procedure TfProgress.UpdateDisplay; var l:integer; begin l := GetTickCount; if l-lastUpdate > 500 then begin lastUpdate := l; Application.ProcessMessages; end; end; function beginProgress; begin Application.CreateForm(TfProgress,Result); with Result do begin pProgress.Visible := multi; Caption := title; Show; UpdateDisplay; end; end; procedure TfProgress.bCancelClick(Sender: TObject); begin Cancelled := true; end; procedure TfProgress.setMax(n: Int64); begin pbProgress.Max := n; end; procedure TfProgress.setOverallMax(n: Int64); begin pbOverallProgress.Max := n; end; procedure TfProgress.setOverallValue(n: Int64); begin pbOverallProgress.Position := n; end; procedure TfProgress.setStatus(s: string); begin lStatus.Caption := s; end; procedure TfProgress.setValue(n: Int64); begin pbProgress.Position := n; end; end.
unit GX_eAddToCaptitalization; interface uses SysUtils, Classes, GX_EditorExpert; type TAddToCapitalizationExpert = class(TEditorExpert) public // Internal name of expert for expert identification. class function GetName: string; override; function GetHelpString: string; override; procedure Execute(Sender: TObject); override; function GetDisplayName: string; override; function HasConfigOptions: Boolean; override; end; implementation uses ToolsAPI, GX_OtaUtils, GX_eCodeFormatter; { TAddToCapitalization } function TAddToCapitalizationExpert.GetDisplayName: string; resourcestring SAddToCapitalizationName = 'Add To Formatter Capitalization'; begin Result := SAddToCapitalizationName; end; function TAddToCapitalizationExpert.GetHelpString: string; resourcestring SAddToCapitalizationHelp = ' This expert adds the current word to the capitalization list ' + 'of the code formatter. It will overwrite existing entries.'; begin Result := SAddToCapitalizationHelp; end; class function TAddToCapitalizationExpert.GetName: string; begin Result := 'AddToCapitalization'; end; function TAddToCapitalizationExpert.HasConfigOptions: Boolean; begin Result := False; end; procedure TAddToCapitalizationExpert.Execute(Sender: TObject); var Identifier: string; Position: TOTAEditPos; begin if not assigned(gblCodeFormatter) then Exit; if not GxOtaGetCurrentIdentData(Identifier, Position) then Exit; gblCodeFormatter.AddToCapitalization(Identifier); end; initialization RegisterEditorExpert(TAddToCapitalizationExpert); end.
unit ZMIRec19; (* ZMIRec19.pas - Represents the 'Directory entry' of a Zip file Copyright (C) 2009, 2010 by Russell J. Peters, Roger Aelbrecht, Eric W. Engler and Chris Vleghert. This file is part of TZipMaster Version 1.9. TZipMaster is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. TZipMaster 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with TZipMaster. If not, see <http://www.gnu.org/licenses/>. contact: problems@delphizip.org (include ZipMaster in the subject). updates: http://www.delphizip.org DelphiZip maillist subscribe at http://www.freelists.org/list/delphizip modified 2010-05-12 ---------------------------------------------------------------------------*) interface uses Classes, Windows, ZipMstr19, ZMWorkFile19, ZMStructs19, ZMCompat19; type TZMRecStrings = (zrsName, zrsComment, zrsIName); TZipSelects = (zzsClear, zzsSet, zzsToggle); TZMStrEncOpts = (zseDOS, zseXName, zseXComment); TZMStrEncodes = set of TZMStrEncOpts; // ZipDirEntry status bit constants const zsbHashed = $100; // hash calculated zsbLocalDone = $200; // local data prepared zsbLocal64 = $400; // local header required zip64 zsbEncMask = $70000; // mask for bits holding how entry is encoded type TZSExtOpts = (zsxUnkown, zsxName, zsxComment, zsxName8, zsxComment8); TZStrExts = set of TZSExtOpts; type THowToEnc = (hteOEM, hteAnsi, hteUTF8); type TZMIRec = class(TZMDirRec) private fComprMethod: Word; //compression method(2) fComprSize: Int64; //compressed file size (8) fCRC32: Longword; //Cyclic redundancy check (4) fDiskStart: Cardinal; //starts on disk number xx(4) fExtFileAtt: Longword; //external file attributes(4) FExtraField: TZMRawBytes;//RawByteString; fFileName: TZMString; // cache for external filename fFileComLen: Word; //(2) fFileNameLen: Word; //(2) fFlag: Word; //generalPurpose bitflag(2) FHash: Cardinal; fHeaderComment: TZMRawBytes;//RawByteString; // internal comment fHeaderName: TZMRawBytes;//RawByteString; fIntFileAtt: Word; //internal file attributes(2) FLocalData: TZMRawBytes;//RawByteString; fModifDateTime: Longword; // dos date/time (4) fOrigHeaderName: TZMRawBytes;//RawByteString; fOwner: TZMWorkFile; fRelOffLocal: Int64; FSelectArgs: string; fStatusBits: Cardinal; fUnComprSize: Int64; //uncompressed file size (8) FVersionMadeBy: word; fVersionNeeded: Word; // version needed to extract(2) function GetEncodeAs: TZMEncodingOpts; function GetEncoding: TZMEncodingOpts; function GetHash: Cardinal; function GetHeaderComment: TZMRawBytes; function GetIsEncoded: TZMEncodingOpts; function GetSelected: Boolean; function GetStatusBit(Mask: Cardinal): Cardinal; procedure SetIsEncoded(const Value: TZMEncodingOpts); procedure SetSelected(const Value: Boolean); protected procedure Diag(const msg: TZMString); function FindDataTag(tag: Word; var idx, siz: Integer): Boolean; // function FindDuplicate(const Name: String): TZMIRec; function FixStrings(const NewName, NewComment: TZMString): Integer; function FixXData64: Integer; function GetCompressedSize: Int64; override; function GetCompressionMethod: Word; override; function GetCRC32: Cardinal; override; function GetDataString(Cmnt: Boolean): UTF8String; function GetDateTime: Cardinal; override; function GetDirty: Boolean; function GetEncoded: TZMEncodingOpts; override; function GetEncrypted: Boolean; override; function GetExtFileAttrib: Longword; override; function GetExtraData(Tag: Word): TZMRawBytes; override; function GetExtraField: TZMRawBytes; override; function GetExtraFieldLength: Word; override; function GetFileComment: TZMString; override; function GetFileCommentLen: Word; override; function GetFileName: TZMString; override; function GetFileNameLength: Word; override; function GetFlag: Word; override; function GetHeaderName: TZMRawBytes; override; function GetIntFileAttrib: Word; override; function GetRelOffLocalHdr: Int64; override; function GetStartOnDisk: Word; override; function GetStatusBits: Cardinal; override; function GetUncompressedSize: Int64; override; function GetVersionMadeBy: Word; override; function GetVersionNeeded: Word; override; function IsZip64: Boolean; procedure MarkDirty; //1 Set Minimum VersionMadeBy and VersionNeeded procedure FixMinimumVers(z64: boolean); //1 convert internal Filename/Comment from utf function Int2UTF(Field: TZMRecStrings; NoUD: Boolean = False): TZMString; //1 return true if Zip64 fields used procedure PrepareLocalData; procedure SetDateStamp(Value: TDateTime); procedure SetEncrypted(const Value: Boolean); procedure SetExtraData(Tag: Word; const data: TZMRawBytes); function StrToSafe(const aString: TZMString; ToOem: boolean): AnsiString; function StripDrive(const FName: TZMString; NoPath: Boolean): TZMString; function StrToHeader(const aString: TZMString; how: THowToEnc): TZMRawBytes; function StrToUTF8Header(const aString: TZMString): TZMRawBytes; function StrTo_UTF8(const aString: TZMString): UTF8String; function ToIntForm(const nname: TZMString; var iname: TZMString): Integer; function WriteAsLocal: Integer; function WriteAsLocal1(Stamp, crc: Cardinal): Integer; function WriteDataDesc(OutZip: TZMWorkFile): Integer; property LocalData: TZMRawBytes read FLocalData write FLocalData; //1 Header name before rename - needed to verify local header property OrigHeaderName: TZMRawBytes read fOrigHeaderName; public constructor Create(theOwner: TZMWorkFile); procedure AfterConstruction; override; procedure AssignFrom(const zr: TZMIRec); procedure BeforeDestruction; override; function CentralSize: Cardinal; function ChangeAttrs(nAttr: Cardinal): Integer; override; function ChangeComment(const ncomment: TZMString): Integer; override; function ChangeData(ndata: TZMRawBytes): Integer; override; function ChangeDate(ndosdate: Cardinal): Integer; override; function ChangeEncoding: Integer; override; function ChangeName(const nname: TZMString): Integer; override; procedure ClearCachedName; function ClearStatusBit(const values: Cardinal): Cardinal; function HasChanges: Boolean; function LocalSize: Cardinal; function Process: Int64; virtual; function ProcessSize: Int64; virtual; function Read(wf: TZMWorkFile): Integer; function SafeHeaderName(const IntName: TZMString): TZMString; function SeekLocalData: Integer; function Select(How: TZipSelects): Boolean; function SetStatusBit(const Value: Cardinal): Cardinal; function TestStatusBit(const mask: Cardinal): Boolean; function Write: Integer; property CompressedSize: Int64 Read fComprSize Write fComprSize; property ComprMethod: Word Read fComprMethod Write fComprMethod; property CRC32: Longword Read fCRC32 Write fCRC32; property DiskStart: Cardinal Read fDiskStart Write fDiskStart; property EncodeAs: TZMEncodingOpts Read GetEncodeAs; property Encoded: TZMEncodingOpts Read GetEncoded; property Encoding: TZMEncodingOpts Read GetEncoding; property Encrypted: Boolean Read GetEncrypted Write SetEncrypted; property ExtFileAttrib: Longword Read fExtFileAtt Write fExtFileAtt; property ExtraData[Tag: Word]: TZMRawBytes read GetExtraData write SetExtraData; property ExtraField: TZMRawBytes read FExtraField write FExtraField; property ExtraFieldLength: Word read GetExtraFieldLength; property FileComLen: Word Read fFileComLen Write fFileComLen; property FileComment: TZMString Read GetFileComment; property FileCommentLen: Word Read fFileComLen Write fFileComLen; property FileName: TZMString Read GetFileName; property FileNameLen: Word Read fFileNameLen Write fFileNameLen; property FileNameLength: Word Read fFileNameLen Write fFileNameLen; property Flag: Word Read fFlag Write fFlag; property Hash: Cardinal read GetHash; property HeaderComment: TZMRawBytes read GetHeaderComment; property HeaderName: TZMRawBytes read GetHeaderName write fHeaderName; property IntFileAttrib: Word Read fIntFileAtt Write fIntFileAtt; //1 the cached value in the status property IsEncoded: TZMEncodingOpts read GetIsEncoded write SetIsEncoded; property ModifDateTime: Longword Read fModifDateTime Write fModifDateTime; property Owner: TZMWorkFile Read fOwner; property RelOffLocal: Int64 Read fRelOffLocal Write fRelOffLocal; property SelectArgs: string read FSelectArgs write FSelectArgs; property Selected: Boolean Read GetSelected Write SetSelected; property StatusBit[Mask: Cardinal]: Cardinal read GetStatusBit; property StatusBits: Cardinal Read GetStatusBits Write fStatusBits; property UncompressedSize: Int64 read fUnComprSize write fUnComprSize; property VersionMadeBy: word read FVersionMadeBy write FVersionMadeBy; property VersionNeeded: Word Read fVersionNeeded Write fVersionNeeded; end; function XData(const x: TZMRawBytes; Tag: Word; var idx, size: Integer): Boolean; function XDataAppend(var x: TZMRawBytes; const src1; siz1: Integer; const src2; siz2: Integer): Integer; function XDataKeep(const x: TZMRawBytes; const tags: array of Integer): TZMRawBytes; function XDataRemove(const x: TZMRawBytes; const tags: array of Integer): TZMRawBytes; function HashFunc(const str: String): Cardinal; function IsInvalidIntName(const FName: TZMString): Boolean; implementation uses SysUtils, ZMZipFile19, ZMMsg19, ZMXcpt19, ZMMsgStr19, ZMUtils19, ZMUTF819, ZMMatch19, ZMCore19, ZMDelZip19; {$INCLUDE '.\ZipVers19.inc'} {$IFDEF VER180} {$WARN SYMBOL_PLATFORM OFF} {$ENDIF} const MAX_BYTE = 255; type Txdat64 = packed record tag: Word; siz: Word; vals: array [0..4] of Int64; // last only cardinal end; const ZipCenRecFields: array [0..17] of Integer = (4, 1, 1, 2, 2, 2, 2, 2, 4, 4, 4, 2, 2, 2, 2, 2, 4, 4); // P. J. Weinberger Hash function function HashFunc(const str : String) : Cardinal; var i : Cardinal; x : Cardinal; begin Result := 0; for i := 1 to Length(str) do begin Result := (Result shl 4) + Ord(str[i]); x := Result and $F0000000; if (x <> 0) then Result := (Result xor (x shr 24)) and $0FFFFFFF; end; end; // make safe version of external comment function SafeComment(const xcomment: String): string; var c: Char; i: integer; Begin if StrHasExt(xcomment) then Result := StrToOEM(xcomment) else Result := xcomment; for i := 1 to Length(Result) do begin c := Result[i]; if (c < ' ') or (c > #126) then Result[i] := '_'; end; End; { TZMIRec } constructor TZMIRec.Create(theOwner: TZMWorkFile); begin inherited Create; fOwner := theOwner; end; procedure TZMIRec.AssignFrom(const zr: TZMIRec); begin inherited; if (zr <> self) and (zr is TZMIRec) then begin VersionMadeBy := zr.VersionMadeBy; VersionNeeded := zr.VersionNeeded; Flag := zr.Flag; ComprMethod := zr.ComprMethod; ModifDateTime := zr.ModifDateTime; CRC32 := zr.CRC32; CompressedSize := zr.CompressedSize; UncompressedSize := zr.UncompressedSize; FileNameLength := zr.FileNameLength; FileCommentLen := zr.FileCommentLen; DiskStart := zr.DiskStart; IntFileAttrib := zr.IntFileAttrib; ExtFileAttrib := zr.ExtFileAttrib; RelOffLocal := zr.RelOffLocal; fOrigHeaderName := zr.OrigHeaderName; fHeaderName := zr.HeaderName; fHeaderComment := zr.HeaderComment; fExtraField := zr.fExtraField; StatusBits := zr.StatusBits; fHash := zr.FHash; end; end; function TZMIRec.CentralSize: Cardinal; begin Result := SizeOf(TZipCentralHeader); Inc(Result, FileNameLength + ExtraFieldLength + FileCommentLen); end; function TZMIRec.ChangeAttrs(nAttr: Cardinal): Integer; begin Result := 0; // always allowed if nAttr <> GetExtFileAttrib then begin ExtFileAttrib := nAttr; MarkDirty; end; end; function TZMIRec.ChangeComment(const ncomment: TZMString): Integer; begin Result := 0; // always allowed if ncomment <> GetFileComment then Result := FixStrings(FileName, ncomment); end; function TZMIRec.ChangeData(ndata: TZMRawBytes): Integer; var NewData: TZMRawBytes; OldData: TZMRawBytes; begin Result := 0; // always allowed if ndata <> GetExtraField then begin // preserve required tags OldData := XDataKeep(ExtraField, [Zip64_data_tag, UPath_Data_Tag, UCmnt_Data_Tag]); // do not allow changing fields NewData := XDataRemove(ndata, [Zip64_data_tag, UPath_Data_Tag, UCmnt_Data_Tag]); // will it fit? if (Length(OldData) + Length(NewData) + Length(GetFileComment) + Length(GetFileName)) < MAX_WORD then begin fExtraField := OldData + NewData; MarkDirty; end else Result := -CD_CEHDataSize; end; end; function TZMIRec.ChangeDate(ndosdate: Cardinal): Integer; begin Result := -CD_NoProtected; if Encrypted then exit; try // test if valid date/time will throw error if not FileDateToDateTime(ndosdate); except Result := -RN_InvalidDateTime; if Owner.Boss.Verbosity >= zvVerbose then Diag('Invalid date ' + GetFileName); exit; end; Result := 0; if ndosdate <> GetDateTime then begin ModifDateTime := ndosdate; MarkDirty; end; end; function TZMIRec.ChangeEncoding: Integer; begin Result := FixStrings(FileName, FileComment); end; function TZMIRec.ChangeName(const nname: TZMString): Integer; var iname: TZMString; begin Result := ToIntForm(nname, iname); if Result = 0 then begin Result := -CD_NoChangeDir; if IsFolder(iname) <> IsFolder(HeaderName) then exit; // dirOnly status must be same if iname <> FileName then Result := FixStrings(iname, FileComment); end; end; function TZMIRec.ClearStatusBit(const values: Cardinal): Cardinal; begin StatusBits := StatusBits and not values; Result := StatusBits; end; procedure TZMIRec.Diag(const msg: TZMString); begin if Owner.Boss.Verbosity >= zvVerbose then Owner.Boss.ShowMsg('Trace: ' + msg, 0, False); end; procedure TZMIRec.ClearCachedName; begin fFileName := ''; // force reconvert - settings have changed ClearStatusBit(zsbHashed); IsEncoded := zeoAuto; // force re-evaluate end; function TZMIRec.FindDataTag(tag: Word; var idx, siz: Integer): Boolean; begin Result := False; if XData(ExtraField, tag, idx, siz) then Result := True; end; //function TZMIRec.FindDuplicate(const Name: String): TZMIRec; //var // ix: Integer; //begin // ix := -1; // from start // repeat // Result := (Owner as TZMZipFile).FindName(Name, ix); // until Result <> self; //end; function IsOnlyDOS(const hstr: TZMRawBytes): Boolean; var i: Integer; begin Result := True; for i := 1 to Length(hstr) do if (hstr[i] > #126) or (hstr[i] < #32) then begin Result := False; Break; end; end; function TZMIRec.FixStrings(const NewName, NewComment: TZMString): Integer; var dup: TZMIRec; enc: TZMEncodingOpts; HasXComment: Boolean; HasXName: Boolean; hcomment: TZMRawBytes; IX: Integer; need64: Boolean; NeedU8Bit: Boolean; newdata: Boolean; NewHeaderName: TZMRawBytes; NewIntName: string; NewMadeFS: Word; UComment: UTF8String; UData: TZMRawBytes; uheader: TUString_Data_Header; UName: UTF8String; xlen: Integer; begin enc := EncodeAs; NewMadeFS := (FS_FAT * 256) or OUR_VEM; UName := ''; UComment := ''; NeedU8Bit := False; Result := -CD_DuplFileName; ix := -1; // from start dup := (Owner as TZMZipFile).FindName(NewName, ix, self); if dup <> nil then exit; // duplicate external name NewIntName := SafeHeaderName(NewName); // default convert new name and comment to OEM NewHeaderName := StrToHeader(NewIntName, hteOEM); hcomment := StrToHeader(NewComment, hteOEM); // make entry name HasXName := StrHasExt(NewName); HasXComment := StrHasExt(NewComment); // form required strings if HasXName or HasXComment then begin if enc = zeoAuto then begin enc := zeoUPATH; // unless both extended if HasXName and HasXComment then enc := zeoUTF8; end; // convert strings if enc = zeoUTF8 then begin NewHeaderName := StrToHeader(NewIntName, hteUTF8); hcomment := StrToHeader(NewComment, hteUTF8); NeedU8Bit := True; end else begin if enc = zeoUPath then begin // we want UPATH or/and UCOMMENT if HasXName then UName := StrTo_UTF8(NewIntName); if HasXComment then UComment := StrTo_UTF8(NewComment); end else if enc = zeoNone then begin // we want Ansi name and comment - NTFS NewHeaderName := StrToHeader(NewIntName, hteAnsi); hcomment := StrToHeader(NewComment, hteAnsi); if StrHasExt(NewHeaderName) or StrHasExt(hcomment) then NewMadeFS := (FS_NTFS * 256) or OUR_VEM; // wasn't made safe FAT end; end; end; // we now have the required strings // remove old extra strings UData := XDataRemove(GetExtraField, [UPath_Data_Tag, UCmnt_Data_Tag]); newdata := Length(UData) <> ExtraFieldLength; if UName <> '' then begin uheader.tag := UPath_Data_Tag; uheader.totsiz := sizeof(TUString_Data_Header) + Length(UName) - (2 * sizeof(Word)); uheader.version := 1; uheader.origcrc := CalcCRC32(NewHeaderName[1], length(NewHeaderName), 0); XDataAppend(UData, uheader, sizeof(uheader), UName[1], length(UName)); newdata := True; end; if UComment <> '' then begin // append UComment uheader.tag := UCmnt_Data_Tag; uheader.totsiz := sizeof(TUString_Data_Header) + Length(UComment) - (2 * sizeof(Word)); uheader.version := 1; uheader.origcrc := CalcCRC32(hcomment[1], length(hcomment), 0); XDataAppend(UData, uheader, sizeof(uheader), UComment[1], length(UComment)); newdata := True; end; // will it fit? Result := -CD_CEHDataSize; xlen := Length(HeaderComment) + Length(NewHeaderName) + Length(UData); if xlen < MAX_WORD then begin // ok - make change fHeaderName := NewHeaderName; fFileNameLen := Length(NewHeaderName); fHeaderComment := hcomment; fFileComLen := Length(hcomment); if newdata then ExtraField := UData; if NeedU8Bit then fFlag := fFlag or FLAG_UTF8_BIT else fFlag := fFlag and (not FLAG_UTF8_BIT); ClearCachedName; IsEncoded := zeoAuto; // unknown need64 := (UncompressedSize >= MAX_UNSIGNED) or (CompressedSize >= MAX_UNSIGNED); // set versions to minimum required FVersionMadeBy := NewMadeFS; FixMinimumVers(need64); MarkDirty; Result := 0; end; end; // 'fixes' the special Zip64 fields from extra data // return <0 error, 0 none, 1 Zip64 function TZMIRec.FixXData64: Integer; var idx: Integer; p: PAnsiChar; wsz: Integer; begin Result := 0; if (VersionNeeded and VerMask) < ZIP64_VER then exit; if not XData(FExtraField, Zip64_data_tag, idx, wsz) then Exit; p := @fExtraField[idx]; Result := -DS_Zip64FieldError; // new msg Inc(p, 4); // past header Dec(wsz, 4); // discount header if UncompressedSize = MAX_UNSIGNED then begin if wsz < 8 then exit; // error UncompressedSize := pInt64(p)^; Inc(p, sizeof(Int64)); Dec(wsz, sizeof(Int64)); end; if CompressedSize = MAX_UNSIGNED then begin if wsz < 8 then exit; // error CompressedSize := pInt64(p)^; Inc(p, sizeof(Int64)); Dec(wsz, sizeof(Int64)); end; if RelOffLocal = MAX_UNSIGNED then begin if wsz < 8 then exit; // error RelOffLocal := pInt64(p)^; Inc(p, sizeof(Int64)); Dec(wsz, sizeof(Int64)); end; if DiskStart = MAX_WORD then begin if wsz < 4 then exit; // error DiskStart := pCardinal(p)^; end; Result := 1; end; function TZMIRec.GetCompressedSize: Int64; begin Result := fComprSize; end; function TZMIRec.GetCompressionMethod: Word; begin Result := fComprMethod; end; function TZMIRec.GetCRC32: Cardinal; begin Result := fCRC32; end; // will return empty if not exists or invalid function TZMIRec.GetDataString(Cmnt: Boolean): UTF8String; var crc: Cardinal; field: TZMRawBytes; idx: Integer; pH: PUString_Data_Header; pS: PAnsiChar; siz: Integer; tag: Word; begin Result := ''; if Cmnt then begin tag := UCmnt_Data_Tag; Field := HeaderComment; if field = '' then Exit; // no point checking end else begin tag := UPath_Data_Tag; field := HeaderName; end; if FindDataTag(tag, idx, siz) then begin pS := @ExtraField[idx]; pH := PUString_Data_Header(pS); if pH^.version = 1 then begin crc := CalcCRC32(field[1], Length(field), 0); if pH^.origcrc = crc then begin siz := siz - sizeof(TUString_Data_Header); Inc(pS, sizeof(TUString_Data_Header)); if (siz > 0) and (ValidUTF8(pS, siz) >= 0) then begin SetLength(Result, siz); move(pS^, Result[1], siz); end; end; end; end; end; function TZMIRec.GetDateTime: Cardinal; begin Result := fModifDateTime; end; function TZMIRec.GetDirty: Boolean; begin Result := TestStatusBit(zsbDirty); end; function TZMIRec.GetEncodeAs: TZMEncodingOpts; begin Result := (Owner as TZMZipFile).EncodeAs; end; { Encoded as OEM for DOS (default) FS_FAT OS/2 FS_HPFS Win95/NT with Nico Mak's WinZip FS_NTFS && host = 5.0 UTF8 is flag is set except (someone always has to be different) PKZIP (Win) 2.5, 2.6, 4.0 - mark as FS_FAT but local is Windows ANSI (1252) PKZIP (Unix) 2.51 - mark as FS_FAT but are current code page } function TZMIRec.GetEncoded: TZMEncodingOpts; const WZIP = $0B32;//(FS_NTFS * 256) + 50; OS_HPFS = FS_HPFS * 256; OS_FAT = FS_FAT * 256; begin Result := zeoNone; if (Flag and FLAG_UTF8_BIT) <> 0 then Result := zeoUTF8 else if (GetDataString(false) <> '') or (GetDataString(True) <> '') then Result := zeoUPath else if ((VersionMadeBy and OSMask) = OS_FAT) or ((VersionMadeBy and OSMask) = OS_HPFS) or (VersionMadeBy = WZIP) then Result := zeoOEM; end; function TZMIRec.GetEncoding: TZMEncodingOpts; begin Result := (Owner as TZMZipFile).Encoding; end; function TZMIRec.GetEncrypted: Boolean; begin Result := (fFlag and 1) <> 0; end; function TZMIRec.GetExtFileAttrib: Longword; begin Result := fExtFileAtt; end; // returns the 'data' without the tag function TZMIRec.GetExtraData(Tag: Word): TZMRawBytes; var i: Integer; sz: Integer; x: TZMRawBytes; begin Result := ''; x := GetExtraField; if XData(x, Tag, i, sz) then Result := Copy(x, i + 4, sz - 4); end; function TZMIRec.GetExtraField: TZMRawBytes; begin Result := fExtraField; end; function TZMIRec.GetExtraFieldLength: Word; begin Result := Length(fExtraField); end; function TZMIRec.GetFileComment: TZMString; begin Result := Int2UTF(zrsComment, False); end; function TZMIRec.GetFileCommentLen: Word; begin Result := Length(HeaderComment); end; // returns the external filename interpretting the internal name by Encoding // still in internal form function TZMIRec.GetFileName: TZMString; begin if fFileName = '' then fFileName := Int2UTF(zrsName, False); Result := fFileName; end; function TZMIRec.GetFileNameLength: Word; begin Result := Length(HeaderName); end; function TZMIRec.GetFlag: Word; begin Result := fFlag; end; function TZMIRec.GetHash: Cardinal; begin if not TestStatusBit(zsbHashed) then begin fHash := HashFunc(FileName); SetStatusBit(zsbHashed); end; Result := fHash; end; function TZMIRec.GetHeaderComment: TZMRawBytes; begin Result := fHeaderComment; end; function TZMIRec.GetHeaderName: TZMRawBytes; begin Result := fHeaderName; end; function TZMIRec.GetIntFileAttrib: Word; begin Result := fIntFileAtt; end; function TZMIRec.GetIsEncoded: TZMEncodingOpts; var n: Integer; begin n := StatusBit[zsbEncMask] shr 16; if n > ord(zeoUPath) then n := 0; if n = 0 then begin // unknown - work it out and cache result Result := Encoded; SetIsEncoded(Result); end else Result := TZMEncodingOpts(n); end; function TZMIRec.GetRelOffLocalHdr: Int64; begin Result := fRelOffLocal; end; function TZMIRec.GetSelected: Boolean; begin Result := TestStatusBit(zsbSelected); end; function TZMIRec.GetStartOnDisk: Word; begin Result := fDiskStart; end; function TZMIRec.GetStatusBit(Mask: Cardinal): Cardinal; begin Result := StatusBits and mask; end; function TZMIRec.GetStatusBits: Cardinal; begin Result := fStatusBits; end; function TZMIRec.GetUncompressedSize: Int64; begin Result := fUnComprSize; end; function TZMIRec.GetVersionMadeBy: Word; begin Result := FVersionMadeBy; end; function TZMIRec.GetVersionNeeded: Word; begin Result := fVersionNeeded; end; function TZMIRec.HasChanges: Boolean; begin Result := (StatusBits and zsbDirty) <> 0; end; function TZMIRec.Int2UTF(Field: TZMRecStrings; NoUD: Boolean = False): TZMString; var Enc: TZMEncodingOpts; fld: TZMRawBytes; begin if Field = zrsComment then fld := HeaderComment else fld := HeaderName; Result := ''; Enc := Encoding; if Enc = zeoAuto then begin Enc := IsEncoded; // cached Encoded; // how entry is encoded if NoUD and (Enc = zeoUPath) then Enc := zeoOEM; // use header Field end; if (Enc = zeoUPath) or StrHasExt(fld) then begin {$IFDEF UNICODE} case Enc of // use UTF8 extra data string if available zeoUPath: Result := UTF8ToWide(GetDataString(Field = zrsComment)); zeoNone: // treat as Ansi (from somewhere) Result := StrToUTFEx(fld, TZMZipFile(Owner).Encoding_CP, -1); zeoUTF8: // treat Field as being UTF8 Result := PUTF8ToWideStr(PAnsiChar(fld), Length(fld)); zeoOEM: // convert to OEM Result := StrToUTFEx(fld, CP_OEMCP, -1); end; {$ELSE} if Owner.Worker.UseUtf8 then begin case Enc of // use UTF8 extra data string if available zeoUPath: Result := GetDataString(Field = zrsComment); zeoNone: // treat as Ansi (from somewhere) Result := StrToUTFEx(fld, TZMZipFile(Owner).Encoding_CP, -1); zeoUTF8: // treat Field as being UTF8 Result := fld; zeoOEM: // convert to OEM Result := StrToUTFEx(fld, CP_OEMCP, -1); end; end else begin case Enc of // use UTF8 extra data string if available zeoUPath: Result := UTF8ToSafe(GetDataString(Field = zrsComment), false); zeoNone: // treat as Ansi (from somewhere) Result := StrToWideEx(fld, TZMZipFile(Owner).Encoding_CP, -1); // will be converted zeoUTF8: // treat Field as being UTF8 Result := UTF8ToSafe(fld, false); zeoOEM: // convert to OEM Result := StrToWideEx(fld, CP_OEMCP, -1); // will be converted end; end; {$ENDIF} end; if length(Result) = 0 then Result := String(fld); // better than nothing if Field = zrsName then Result := SetSlash(Result, psdExternal); end; // test for invalid characters function IsInvalidIntName(const FName: TZMString): Boolean; var c: Char; clen: Integer; i: Integer; len: Integer; n: Char; p: Char; begin Result := True; len := Length(FName); if (len < 1) or (len >= MAX_PATH) then exit; // empty or too long c := FName[1]; if (c = PathDelim) or (c = '.') or (c = ' ') then exit; // invalid from root or below i := 1; clen := 0; p := #0; while i <= len do begin Inc(clen); if clen > 255 then exit; // component too long c := FName[i]; if i < len then n := FName[i + 1] else n := #0; case c of WILD_MULTI, DriveDelim, WILD_CHAR, '<', '>', '|', #0: exit; #1..#31: exit; // invalid PathDelimAlt: begin if p = ' ' then exit; // bad - component has Trailing space if (n = c) or (n = '.') or (n = ' ') then exit; // \\ . leading space invalid clen := 0; end; '.': begin n := FName[succ(i)]; if (n = PathDelim) or (n < ' ') then exit; end; ' ': if i = len then exit; // invalid end; p := c; Inc(i); end; Result := False; end; procedure TZMIRec.AfterConstruction; begin inherited; fStatusBits := 0; end; procedure TZMIRec.BeforeDestruction; begin fExtraField := ''; fHeaderName := ''; fHeaderComment := ''; inherited; end; function TZMIRec.IsZip64: Boolean; begin Result := (UncompressedSize >= MAX_UNSIGNED) or (CompressedSize >= MAX_UNSIGNED) or (RelOffLocal >= MAX_UNSIGNED) or (DiskStart >= MAX_WORD); end; // also calculate required version and create extra data function TZMIRec.LocalSize: Cardinal; begin Result := SizeOf(TZipLocalHeader); PrepareLocalData; // form local extra data Inc(Result, FileNameLength + Length(LocalData)); end; procedure TZMIRec.MarkDirty; begin SetStatusBit(zsbDirty); end; procedure TZMIRec.FixMinimumVers(z64: boolean); const OS_FAT: Word = (FS_FAT * 256); WZIP = (FS_NTFS * 256) + 50; var NewNeed: Word; begin if ((VersionMadeBy and VerMask) <= ZIP64_VER) and ((VersionNeeded and VerMask) <= ZIP64_VER) then begin // Enc := IsEncoded; if z64 then VersionMadeBy := (VersionMadeBy and OSMask) or ZIP64_VER else if (VersionMadeBy and VerMask) = ZIP64_VER then begin // zip64 no longer needed VersionMadeBy := (VersionMadeBy and OSMask) or OUR_VEM; end; // correct bad encodings - marked ntfs should be fat if VersionMadeBy = WZIP then VersionMadeBy := OS_FAT or OUR_VEM; case ComprMethod of 0: NewNeed := 10; // stored 1..8: NewNeed := 20; 9: NewNeed := 21; // enhanced deflate 10: NewNeed := 25; // DCL 12: NewNeed := 46; // BZip2 else NewNeed := ZIP64_VER; end; if ((Flag and 32) <> 0) and (NewNeed < 27) then NewNeed := 27; if z64 and (NewNeed < ZIP64_VER) then NewNeed := ZIP64_VER; // keep needed os VersionNeeded := (VersionNeeded and OSMask) + NewNeed; end; end; // process the record (base type does nothing) // returns bytes written, <0 _ error function TZMIRec.Process: Int64; begin Result := 0; // default, nothing done end; // size of data to process - excludes central directory (virtual) function TZMIRec.ProcessSize: Int64; begin Result := 0;// default nothing to process end; (*? TZMIRec.Read Reads directory entry returns >=0 = ok (1 = Zip64) <0 = -error *) function TZMIRec.Read(wf: TZMWorkFile): Integer; var CH: TZipCentralHeader; ExtraLen: Word; n: TZMRawBytes; r: Integer; v: Integer; begin StatusBits := zsbInvalid; // Diag('read central' ); r := wf.Reads(CH, ZipCenRecFields); if r <> SizeOf(TZipCentralHeader) then begin Result := -DS_CEHBadRead; exit; end; if CH.HeaderSig <> CentralFileHeaderSig then begin Result := -DS_CEHWrongSig; exit; end; VersionMadeBy := CH.VersionMadeBy; VersionNeeded := CH.VersionNeeded; Flag := CH.Flag; ComprMethod := CH.ComprMethod; ModifDateTime := CH.ModifDateTime; CRC32 := CH.CRC32; FileNameLength := CH.FileNameLen; ExtraLen := CH.ExtraLen; FileCommentLen := CH.FileComLen; DiskStart := CH.DiskStart; IntFileAttrib := CH.IntFileAtt; ExtFileAttrib := CH.ExtFileAtt; RelOffLocal := CH.RelOffLocal; CompressedSize := CH.ComprSize; UncompressedSize := CH.UncomprSize; // read variable length fields v := FileNameLen + ExtraLen + FileComLen; SetLength(n, v); r := wf.Reads(n[1], [FileNameLen, ExtraLen, FileComLen]); if r <> v then begin Result := -DS_CECommentLen; if r < FileNameLen then Result := -DS_CENameLen else if r < (FileNameLen + ExtraLen) then Result := -LI_ReadZipError; exit; end; if FileComLen > 0 then fHeaderComment := copy(n, FileNameLen + ExtraLen + 1, FileComLen); if ExtraLen > 0 then fExtraField := copy(n, FileNameLen + 1, ExtraLen); SetLength(n, FileNameLen); fHeaderName := n; fOrigHeaderName := n; ClearStatusBit(zsbInvalid); // record is valid if n[Length(n)] = PathDelimAlt then SetStatusBit(zsbDirOnly); // dir only entry Result := FixXData64; end; procedure TZMIRec.PrepareLocalData; var xd: Txdat64; Need64: Boolean; begin LocalData := ''; // empty ClearStatusBit(zsbLocal64); // check for Zip64 Need64 := (UncompressedSize >= MAX_UNSIGNED) or (CompressedSize >= MAX_UNSIGNED); FixMinimumVers(Need64); if Need64 then begin SetStatusBit(zsbLocal64); xd.tag := Zip64_data_tag; xd.siz := 16; xd.vals[0] := UncompressedSize; xd.vals[1] := CompressedSize; SetLength(fLocalData, 20); Move(xd.tag, PAnsiChar(LocalData)^, 20); end; // remove unwanted 'old' tags if ExtraFieldLength > 0 then LocalData := LocalData + XDataRemove(ExtraField, [Zip64_data_tag, Ntfs_data_tag, UCmnt_Data_Tag]); SetStatusBit(zsbLocalDone); end; function TZMIRec.SafeHeaderName(const IntName: TZMString): TZMString; const BadChars : TSysCharSet = [#0..#31, ':', '<', '>', '|', '*', '?', #39, '\']; var c: Char; i: integer; Begin Result := ''; for i := 1 to Length(IntName) do begin c := IntName[i]; if (c <= #255) and (AnsiChar(c) in BadChars) then begin if c = '\' then Result := Result + PathDelimAlt else Result := Result + '#$' + IntToHex(Ord(c),2); end else Result := Result + c; end; end; function TZMIRec.SeekLocalData: Integer; const // no signature LOHFlds: array [0..9] of Integer = (2, 2, 2, 2, 2, 4, 4, 4, 2, 2); var did: Int64; i: Integer; InWorkFile: TZMWorkFile; LOH: TZipLocalHeader; t: Integer; v: TZMRawBytes; begin ASSERT(assigned(Owner), 'no owner'); InWorkFile := Owner; // Diag('Seeking local'); Result := -DS_FileOpen; if not InWorkFile.IsOpen then exit; Result := -DS_LOHBadRead; try InWorkFile.SeekDisk(DiskStart); InWorkFile.Position := RelOffLocal; did := InWorkFile.Read(LOH, 4); if (did = 4) and (LOH.HeaderSig = LocalFileHeaderSig) then begin // was local header did := InWorkFile.Reads(LOH.VersionNeeded, LOHFlds); if did = (sizeof(TZipLocalHeader) - 4) then begin if LOH.FileNameLen = Length(OrigHeaderName) then begin t := LOH.FileNameLen + LOH.ExtraLen; SetLength(v, t); did := InWorkFile.Reads(v[1], [LOH.FileNameLen, LOH.ExtraLen]); if (did = t) then begin Result := 0; for i := 1 to LOH.FileNameLen do begin if v[i] <> OrigHeaderName[i] then begin Result := -DS_LOHWrongName; break; end; end; end; end; v := ''; end; end; if Result = -DS_LOHBadRead then Diag('could not read local header: ' + FileName); except on E: EZipMaster do begin Result := -E.ResId; exit; end; on E: Exception do begin Result := -DS_UnknownError; exit; end; end; end; // returns the new value function TZMIRec.Select(How: TZipSelects): Boolean; begin case How of zzsClear: Result := False; zzsSet: Result := True; // zzsToggle: else Result := not TestStatusBit(zsbSelected); end; SetSelected(Result); end; procedure TZMIRec.SetDateStamp(Value: TDateTime); begin DateTimeToFileDate(Value); end; procedure TZMIRec.SetEncrypted(const Value: Boolean); begin if Value then Flag := Flag or 1 else Flag := Flag and $FFFE; end; // assumes data contains the data with no header procedure TZMIRec.SetExtraData(Tag: Word; const data: TZMRawBytes); var after: Integer; afterLen: integer; nidx: Integer; ix: Integer; newXData: TZMRawBytes; dataSize: Word; sz: Integer; v: Integer; x: TZMRawBytes; begin x := GetExtraField; XData(x, Tag, ix, sz); // find existing Tag v := Length(x) - sz; // size after old tag removed if Length(data) > 0 then v := v + Length(data) + 4; if v > MAX_WORD then // new length too big? exit; // maybe give error dataSize := Length(data); SetLength(newXData, v); nidx := 1; // next index into newXData if (dataSize > 0) then begin // prefix required tag newXData[1] := AnsiChar(Tag and MAX_BYTE); newXData[2] := AnsiChar(Tag shr 8); newXData[3] := AnsiChar(dataSize and MAX_BYTE); newXData[4] := AnsiChar(dataSize shr 8); // add the data Move(data[1], newXData[5], dataSize); Inc(nidx, dataSize + 4); end; if ix >= 1 then begin // had existing data if ix > 1 then begin // append data from before existing tag Move(x[1], newXData[nidx], ix - 1); Inc(nidx, ix); end; after := ix + sz; // index after replaced tag if after < Length(x) then begin // append data from after existing afterLen := Length(x) + 1 - after; Move(x[after], newXData[nidx], afterLen); end; end else begin // did not exist if Length(x) > 0 then Move(x[1], newXData[nidx], Length(x)); // append old extra data end; ExtraField := newXData; end; procedure TZMIRec.SetIsEncoded(const Value: TZMEncodingOpts); var n: Integer; begin n := Ord(Value) shl 16; ClearStatusBit(zsbEncMask); // clear all SetStatusBit(n); // set new value end; procedure TZMIRec.SetSelected(const Value: Boolean); begin if Selected <> Value then begin if Value then SetStatusBit(zsbSelected) else begin ClearStatusBit(zsbSelected); SelectArgs := ''; end; end; end; function TZMIRec.SetStatusBit(const Value: Cardinal): Cardinal; begin StatusBits := StatusBits or Value; Result := StatusBits; end; function TZMIRec.StrToSafe(const aString: TZMString; ToOem: boolean): AnsiString; begin {$IFDEF UNICODE} Result := WideToSafe(aString, ToOem); {$ELSE} if Owner.Worker.UseUTF8 then Result := UTF8ToSafe(aString, ToOem) else Result := WideToSafe(aString, ToOem); {$ENDIF} end; // converts to internal delimiter function TZMIRec.StripDrive(const FName: TZMString; NoPath: Boolean): TZMString; var nam: Integer; posn: Integer; begin Result := SetSlash(FName, psdExternal); // Remove drive: or //host/share posn := 0; if length(Result) > 1 then begin if Result[1] = ':' then begin posn := 2; if (Length(Result) > 2) and (Result[3] = PathDelim{Alt}) then posn := 3; end else if (Result[1] = PathDelimAlt) and (Result[2] = PathDelim{Alt}) then begin posn := 3; while (posn < Length(Result)) and (Result[posn] <> PathDelim{Alt}) do Inc(posn); Inc(posn); while (posn < Length(Result)) and (Result[posn] <> PathDelimAlt) do Inc(posn); if posn >= Length(Result) then begin // error - invalid host/share Diag('Invalid filespec: ' + Result); Result := ''; exit;// { TODO : handle error } end; end; end; Inc(posn); // remove leading ./ if ((posn + 1) < Length(Result)) and (Result[posn] = '.') and (Result[posn + 1] = PathDelim) then posn := posn + 2; // remove path if not wanted if NoPath then begin nam := LastPos(Result, PathDelim); if nam > posn then posn := nam + 1; end; Result := Copy(Result, posn, MAX_PATH); end; function TZMIRec.StrToHeader(const aString: TZMString; how: THowToEnc): TZMRawBytes; begin {$IFDEF UNICODE} if how = hteUTF8 then Result := TZMRawBytes(WideToUTF8(aString, -1)) else Result := TZMRawBytes(WideToSafe(aString, how = hteOEM)); {$ELSE} if Owner.Worker.UseUTF8 then begin if how = hteUTF8 then Result := TZMRawBytes(aString) else Result := TZMRawBytes(WideToSafe(UTF8ToWide(aString), how = hteOEM)); end else begin case how of hteOEM: Result := TZMRawBytes(StrToOEM(aString)); hteAnsi: Result := TZMRawBytes(aString); hteUTF8: Result := TZMRawBytes(StrToUTF8(aString)); end; end; {$ENDIF} end; function TZMIRec.StrToUTF8Header(const aString: TZMString): TZMRawBytes; begin {$IFDEF UNICODE} Result := UTF8String(aString); {$ELSE} if Owner.Worker.UseUtf8 then Result := AsUTF8Str(aString) // make sure UTF8 else Result := StrToUTF8(aString); {$ENDIF} end; function TZMIRec.StrTo_UTF8(const aString: TZMString): UTF8String; begin {$IFDEF UNICODE} Result := UTF8String(aString); {$ELSE} if Owner.Worker.UseUtf8 then Result := AsUTF8Str(aString) // make sure UTF8 else Result := StrToUTF8(aString); {$ENDIF} end; function TZMIRec.TestStatusBit(const mask: Cardinal): Boolean; begin Result := (StatusBits and mask) <> 0; end; function TZMIRec.ToIntForm(const nname: TZMString; var iname: TZMString): Integer; var temp: TZMString; begin Result := 0; iname := StripDrive(nname, not (AddDirNames in Owner.Worker.AddOptions)); // truncate if too long if Length(iname) > MAX_PATH then begin temp := iname; SetLength(iname, MAX_PATH); Diag('Truncated ' + temp + ' to ' + iname); end; if IsInvalidIntName(iname) then Result := -AD_BadFileName; end; // write the central entry on it's owner // return bytes written (< 0 = -Error) function TZMIRec.Write: Integer; var CH: PZipCentralHeader; l: Integer; Need64: Boolean; ni: TZMRawBytes; p: pByte; pb: pByte; r: Integer; siz: Word; vals: array [0..4] of Int64; wf: TZMWorkFile; x: TZMRawBytes; begin wf := Owner; ASSERT(assigned(wf), 'no WorkFile'); // Diag('Write central'); Result := -1; if not wf.IsOpen then exit; fOrigHeaderName := HeaderName; // might have changed pb := wf.WBuffer(sizeof(TZipCentralHeader)); CH := PZipCentralHeader(pb); ni := HeaderName; CH^.HeaderSig := CentralFileHeaderSig; CH^.VersionMadeBy := VersionMadeBy; CH^.VersionNeeded := VersionNeeded; // assumes local was written - may be updated CH^.Flag := Flag; CH^.ComprMethod := ComprMethod; CH^.ModifDateTime := ModifDateTime; CH^.CRC32 := CRC32; CH^.FileNameLen := length(ni); CH^.FileComLen := Length(HeaderComment); CH^.IntFileAtt := IntFileAttrib; CH^.ExtFileAtt := ExtFileAttrib; siz := 0; if (UncompressedSize >= MAX_UNSIGNED) then begin vals[0] := UncompressedSize; siz := 8; CH^.UncomprSize := MAX_UNSIGNED; end else CH^.UncomprSize := Cardinal(UncompressedSize); if (CompressedSize >= MAX_UNSIGNED) then begin vals[siz div 8] := CompressedSize; Inc(siz, 8); CH^.ComprSize := MAX_UNSIGNED; end else CH^.ComprSize := Cardinal(CompressedSize); if (RelOffLocal >= MAX_UNSIGNED) then begin vals[siz div 8] := RelOffLocal; Inc(siz, 8); CH^.RelOffLocal := MAX_UNSIGNED; end else CH^.RelOffLocal := Cardinal(RelOffLocal); if (DiskStart >= MAX_WORD) then begin vals[siz div 8] := DiskStart; Inc(siz, 4); CH^.DiskStart := MAX_WORD; end else CH^.DiskStart := Word(DiskStart); Need64 := False; if siz > 0 then begin SetLength(x, siz); move(vals[0], x[1], siz); Need64 := True; if (VersionNeeded and MAX_BYTE) < ZIP64_VER then begin FixMinimumVers(True); CH^.VersionNeeded := VersionNeeded; CH^.VersionMadeBy := VersionMadeBy; end; ExtraData[Zip64_data_tag] := x; end else ExtraData[Zip64_data_tag] := ''; // remove old 64 data if (StatusBit[zsbLocalDone] = 0) or (Need64) then FixMinimumVers(Need64); CH^.VersionMadeBy := VersionMadeBy; CH^.VersionNeeded := VersionNeeded; x := ''; CH^.ExtraLen := ExtraFieldLength; Result := -DS_CEHBadWrite; l := sizeof(TZipCentralHeader) + CH^.FileNameLen + CH^.ExtraLen + CH^.FileComLen; pb := wf.WBuffer(l); p := pb; Inc(p, sizeof(TZipCentralHeader)); move(ni[1], p^, CH^.FileNameLen); Inc(p, CH^.FileNameLen); if CH^.ExtraLen > 0 then begin move(ExtraField[1], p^, CH^.ExtraLen); Inc(p, CH^.ExtraLen); end; if CH^.FileComLen > 0 then move(HeaderComment[1], p^, CH^.FileComLen); r := wf.Write(pb^, -l); if r = l then begin // Diag(' Write central ok'); Result := r; ClearStatusBit(zsbDirty); end//; else if r < 0 then Result := r; end; function TZMIRec.WriteAsLocal: Integer; begin Result := WriteAsLocal1(ModifDateTime, CRC32); end; // write local header using specified stamp and crc // return bytes written (< 0 = -Error) function TZMIRec.WriteAsLocal1(Stamp, crc: Cardinal): Integer; var cd: TZMRawBytes; fnlen: Integer; i: Integer; LOH: PZipLocalHeader; need64: Boolean; ni: TZMRawBytes; p: pByte; pb: pByte; t: Integer; wf: TZMWorkFile; begin wf := Owner; ASSERT(assigned(wf), 'no WorkFile'); if StatusBit[zsbLocalDone] = 0 then PrepareLocalData; LOH := PZipLocalHeader(wf.WBuffer(sizeof(TZipLocalHeader))); if ((Flag and 9) = 8) then Flag := Flag and $FFF7; // remove extended local data if not encrypted ni := HeaderName; fnlen := length(ni); LOH^.HeaderSig := LocalFileHeaderSig; LOH^.VersionNeeded := VersionNeeded; // may be updated LOH^.Flag := Flag; LOH^.ComprMethod := ComprMethod; LOH^.ModifDateTime := Stamp; LOH^.CRC32 := crc; LOH^.FileNameLen := fnlen; cd := LocalData; LOH^.ExtraLen := Length(cd); // created by LocalSize need64 := (LOH^.ExtraLen > 0) and (StatusBit[zsbLocal64] <> 0); if need64 then begin LOH^.UnComprSize := MAX_UNSIGNED; LOH^.ComprSize := MAX_UNSIGNED; end else begin if (Flag and 8) <> 0 then begin LOH^.UnComprSize := 0; LOH^.ComprSize := 0; if (VersionNeeded and MAX_BYTE) < ZIP64_VER then begin FixMinimumVers(True); LOH^.VersionNeeded := VersionNeeded; end; end else begin LOH^.UnComprSize := Cardinal(UncompressedSize); LOH^.ComprSize := Cardinal(CompressedSize); end; end; t := fnlen + Length(cd); pb := wf.WBuffer(sizeof(TZipLocalHeader) + t); p := pb; Inc(p, sizeof(TZipLocalHeader)); i := Sizeof(TZipLocalHeader); // i = destination index Move(ni[1], p^, fnlen); i := i + fnlen; Inc(p, fnlen); // copy any extra data if Length(cd) > 0 then begin Move(cd[1], p^, Length(cd)); Inc(i, Length(cd)); end; Result := wf.Write(pb^, -i); // must fit if Result = i then ClearStatusBit(zsbDirty) else Result := -DS_LOHBadWrite; end; // return bytes written (< 0 = -Error) function TZMIRec.WriteDataDesc(OutZip: TZMWorkFile): Integer; var d: TZipDataDescriptor; d64: TZipDataDescriptor64; r: Integer; begin ASSERT(assigned(OutZip), 'no WorkFile'); if (Flag and 8) <> 0 then begin Result := 0; exit; end; Result := -DS_DataDesc; if (VersionNeeded and MAX_BYTE) < ZIP64_VER then begin d.DataDescSig := ExtLocalSig; d.CRC32 := CRC32; d.ComprSize := Cardinal(CompressedSize); d.UnComprSize := Cardinal(UncompressedSize); r := OutZip.Write(d, -sizeof(TZipDataDescriptor)); if r = sizeof(TZipDataDescriptor) then Result := r; end else begin d64.DataDescSig := ExtLocalSig; d64.CRC32 := CRC32; d64.ComprSize := CompressedSize; d64.UnComprSize := UncompressedSize; r := OutZip.Write(d64, -sizeof(TZipDataDescriptor64)); if r = sizeof(TZipDataDescriptor64) then Result := r; end; end; // Return true if found // if found return idx --> tag, size = tag + data function XData(const x: TZMRawBytes; Tag: Word; var idx, size: Integer): Boolean; var i: Integer; l: Integer; wsz: Word; wtg: Word; begin Result := False; idx := 0; size := 0; i := 1; l := Length(x); while i < l - 4 do begin wtg := pWord(@x[i])^; wsz := pWord(@x[i + 2])^; if wtg = Tag then begin Result := (i + wsz + 4) <= l + 1; if Result then begin idx := i; size := wsz + 4; end; break; end; i := i + wsz + 4; end; end; function XData_HasTag(tag: Integer; const tags: array of Integer): Boolean; var ii: Integer; begin Result := False; for ii := 0 to HIGH(tags) do if tags[ii] = tag then begin Result := True; break; end; end; function XDataAppend(var x: TZMRawBytes; const src1; siz1: Integer; const src2; siz2: Integer): Integer; var newlen: Integer; begin Result := Length(x); if (siz1 < 0) or (siz2 < 0) then exit; newlen := Result + siz1 + siz2; SetLength(x, newlen); Move(src1, x[Result + 1], siz1); Result := Result + siz1; if siz2 > 0 then begin Move(src2, x[Result + 1], siz2); Result := Result + siz2; end; end; function XDataKeep(const x: TZMRawBytes; const tags: array of Integer): TZMRawBytes; var di: Integer; i: Integer; l: Integer; siz: Integer; wsz: Word; wtg: Word; begin Result := ''; siz := 0; l := Length(x); if l < 4 then exit; // invalid i := 1; while i <= l - 4 do begin wtg := pWord(@x[i])^; wsz := pWord(@x[i + 2])^; if (XData_HasTag(wtg, tags)) and ((i + wsz + 4) <= l + 1) then begin Inc(siz, wsz + 4); end; i := i + wsz + 4; end; SetLength(Result, siz); di := 1; i := 1; while i <= l - 4 do begin wtg := pWord(@x[i])^; wsz := pWord(@x[i + 2])^; if (XData_HasTag(wtg, tags)) and ((i + wsz + 4) <= l + 1) then begin wsz := wsz + 4; while wsz > 0 do begin Result[di] := x[i]; Inc(di); Inc(i); Dec(wsz); end; end else i := i + wsz + 4; end; end; function XDataRemove(const x: TZMRawBytes; const tags: array of Integer): TZMRawBytes; var di: Integer; i: Integer; l: Integer; siz: Integer; wsz: Word; wtg: Word; begin Result := ''; siz := 0; l := Length(x); if l < 4 then exit; // invalid i := 1; while i <= l - 4 do begin wtg := pWord(@x[i])^; wsz := pWord(@x[i + 2])^; if (not XData_HasTag(wtg, tags)) and ((i + wsz + 4) <= l + 1) then begin Inc(siz, wsz + 4); end; i := i + wsz + 4; end; SetLength(Result, siz); di := 1; i := 1; while i <= l - 4 do begin wtg := pWord(@x[i])^; wsz := pWord(@x[i + 2])^; if (not XData_HasTag(wtg, tags)) and ((i + wsz + 4) <= l + 1) then begin wsz := wsz + 4; while wsz > 0 do begin Result[di] := x[i]; Inc(di); Inc(i); Dec(wsz); end; end else i := i + wsz + 4; end; end; end.
unit QcurrEdit; { TCurrEdit: This is an usefull CLX component based on an Edit control for Currency ($-CA$H-$) input coded in Delphi 7.0. It should also work in Kylix X. Be free to Update, modify or distribute it (Please, dont remove the credits :-) ) and to send me your updates or changes... I'll be more happy..... Author: Matias Surdi (Matiass@interlap.com.ar) Created: 21/11/2002 Version: 1.1 License: you can freely use and distribute the included code for any purpouse, but you cannot remove this copyright notice. Send me any comment and update, they are really appreciated. Contact: matiass@interlap.com.ar ChangeLog: *21/11/2002 - Released V 1.00 *24/11/2002 - Added Regional Decimal separator support ( "." and ",") } interface uses SysUtils, Classes, QControls, QStdCtrls,Qdialogs,strUtils; type TcurrEdit = class(TEdit) private FPrefix : string; fSufix : string; sMask : string; FValue : real; procedure UptText; procedure SetValue(NewValue : real); protected procedure Loaded; override; procedure KeyPress(var Key: Char); override; procedure doEnter; override; procedure doExit; override; procedure Click; override; public constructor Create(Aowner : TComponent);override; procedure Clear; override; published property Value : real read Fvalue write SetValue; property Prefix : string read fPrefix write fPrefix; property Sufix : string read fSufix write fSufix; property Mask : string read sMask write sMask; end; procedure Register; implementation procedure Register; begin RegisterComponents('Standard', [TcurrEdit]); end; constructor TCurrEdit.create(Aowner:tcomponent); begin inherited Create(Aowner); Alignment := taRightJustify; Prefix := ''; Sufix := ''; Mask := '#,##0.00'; Text := FormatFloat(sMask,FValue); end; procedure TCurrEdit.Loaded; begin inherited; UptText; end; procedure TCurrEdit.Clear; var ch:char; begin ch := Chr(8); KeyPress(ch); end; procedure TCurrEdit.SetValue(NewValue : real); begin fValue := NewValue; Text := FloatToStr(fValue); Alignment:=taRightJustify; SelLength:=0; if (Text='') or (Text = DecimalSeparator) then Text:='0'; Fvalue := StrToFloat(Text); Text := Prefix + FormatFloat(sMask,FValue) + Sufix; if Focused then begin Alignment := taLeftJustify; Text := FloatToStr(fValue); SelStart := 0; SelLength := Length(Text); end; end; procedure TCurrEdit.UptText; begin Text := Prefix + FormatFloat(sMask,FValue) + Sufix; end; procedure TCurrEdit.Click; begin //Doenter; end; procedure TCurrEdit.DoEnter; begin if Alignment = taLeftJustify then Exit; {avoid double entering!!} Alignment := taLeftJustify; Text := FloatToStr(fValue); SelStart := 0; SelLength := Length(Text); inherited; end; procedure TCurrEdit.DoExit; begin Alignment:=taRightJustify; SelLength:=0; if (Text='') or (Text = DecimalSeparator) then Text:='0'; Fvalue := StrToFloat(Text); Text := Prefix + FormatFloat(sMask,FValue) + Sufix; inherited; end; procedure TCurrEdit.KeyPress(var Key: Char); begin if not (Ord(key) in [8, Ord(DecimalSeparator),45,48..57]) then begin Key := Chr(0); Exit; end; //Si la tecla pulsada es '-' ó separador de decimales y ya existe en el texto if ((Ord(Key) = 45) or (Key = DecimalSeparator)) and (Pos(Key,Text) > 0) then if(Length(Self.SelText) <> Length(Text)) then Key := Chr(0); inherited; end; end.
{ * CGDisplayFade.h * CoreGraphics * * API to fade displays to and from a solid color, without resorting * to playing with the gamma table APIs and losing ColorSync calibration. * * These APIs should be used in perference to manipulating the gamma tables * for purposes of performing fade effects. * * Copyright (c) 2002 Apple Computer, Inc. All rights reserved. * } { Pascal Translation: Peter N Lewis, <peter@stairways.com.au>, August 2005 } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit CGDisplayFades; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} uses MacTypes,CGBase,CGErrors,CGDirectDisplay,CGDisplayConfiguration; {$ALIGN POWER} type CGDisplayFadeReservationToken = UInt32; const kCGDisplayFadeReservationInvalidToken = 0; type CGDisplayBlendFraction = Float32; { * Values for the limits of the fade. * kCGDisplayBlendNormal represents a normal display state * kCGDisplayBlendSolidColor represents a display blended to a solid color } const kCGDisplayBlendNormal = 0.0; const kCGDisplayBlendSolidColor = 1.0; { * Time in seconds to perform a fade operation. } type CGDisplayFadeInterval = Float32; { * * Most fade operations done by apps and games are done around display * configuration changes. This API adds control over a built-in fade * effect when performing display configuration changes. * * The default fade effect on a display mode change uses a fade-out of * 0.3 seconds and a fade-in of 0.5 seconds. Color fades to French Blue * for a normal desktop, and black when displays are captured. * * CGConfigureDisplayFadeEffect sets the display fade time and color * for a display reconfigure operation. * Call after CGBeginDisplayConfiguration() and before * calling CGCompleteDisplayConfiguration(). * * When CGCompleteDisplayConfiguration() is called, a fade-out effect will be * done prior to the display reconfiguration. When the display reconfiguration * is complete, control returns to the calling program, while a fade-in effect * runs asynchronously. } function CGConfigureDisplayFadeEffect( configRef: CGDisplayConfigRef; fadeOutSeconds: CGDisplayFadeInterval; fadeInSeconds: CGDisplayFadeInterval; fadeRed: Float32; fadeGreen: Float32; fadeBlue: Float32 ): CGError; external name '_CGConfigureDisplayFadeEffect'; { * It may also be desirable to perform fade operations at other times, as when * transitioning between game play and cinematic sequences. The following API * provides a mechanism for controlling display fade operations outside of display * mode reconfigurations. } type CGDisplayReservationInterval = Float32; const kCGMaxDisplayReservationInterval = 15.0; { * Before performing fade operation, the caller must reserve the hardware * for the expected period of time that the program will be doing fades * * A reservation token is returned that must be passed in on subsequent calls. * * Failing to release the hardware by the end of the reservation interval will * result in the reservation token becomingn invalid, and the hardware being * unfaded back to a normal state. The reservation interval is limited (clipped) * to 15 seconds maximum, and should be greater than zero. * * Returns kCGErrorNoneAvailable if another reservation is in effect, * and kCGErrorSuccess on success. } function CGAcquireDisplayFadeReservation( seconds: CGDisplayReservationInterval; var pNewToken: CGDisplayFadeReservationToken ): CGError; external name '_CGAcquireDisplayFadeReservation'; { * Releases a display fade reservation, and unfades the display if needed * The reservation token myToken is no longer valid after this operation. * * CGReleaseDisplayFadeReservation may be safely called while an async fade * operation is running, and if the ending blend value is kCGDisplayBlendNormal, * will not disturb the running operation. The reservation is dropped when the * fade opertion completes. * * Returns kCGErrorIllegalArgument if myToken is not the valid reservation token, * and kCGErrorSuccess on success. } function CGReleaseDisplayFadeReservation( myToken: CGDisplayFadeReservationToken ): CGError; external name '_CGReleaseDisplayFadeReservation'; { * The actual fade mechanism: * * The function takes the current reservation token, * a time interval to perform the fade operation in seconds, * a starting and ending blend coefficient, an RGB color in device space, * and a boolean to indicate that the operation should be done synchronously. * * Over the fade operation time interval, the system will interpolate a * blending coefficient between the starting and ending values given, * applying a nonlinear (sine-based) bias term, and will blend the video output * with the specified color based on the resulting value. * * If the time interval is specifed as 0.0, then the ending state blend value is * applied at once and the function returns. * * The maximum allowable time interval is 15 seconds. * * If the parameter 'synchronous' is true, the function does not return * til the fade operation is complete. If false, the function returns at once, * and the fade operation runs asynchronously. * * CGReleaseDisplayFadeReservation may be safely called while an async fade * operation is running, and if the ending blend value is kCGDisplayBlendNormal, * will not disturb the running operation. The reservation is dropped when the * fade opertion completes. * * Invalid parameters result in a return value of kCGErrorIllegalArgument. * Trying to start a fade operation while an asynchronous fade operation is running * results in a return value of kCGErrorNoneAvailable. * * To perform a 2 second fade to black, waiting til complete: * * CGDisplayFade(myToken, * 2.0, // 2 seconds * kCGDisplayBlendNormal, // Starting state * kCGDisplayBlendSolidColor, // Ending state * 0.0, 0.0, 0.0, // black * true); // Wait for completion * * To perform a 2 second fade from black to normal, without waiting for completion: * * CGDisplayFade(myToken, * 2.0, // 2 seconds * kCGDisplayBlendSolidColor, // Starting state * kCGDisplayBlendNormal, // Ending state * 0.0, 0.0, 0.0, // black * false); // Don't wait for completion } function CGDisplayFade( myToken: CGDisplayFadeReservationToken; seconds: CGDisplayFadeInterval; startBlend: CGDisplayBlendFraction; endBlend: CGDisplayBlendFraction; redBlend: Float32; greenBlend: Float32; blueBlend: Float32; synchronous: boolean_t ): CGError; external name '_CGDisplayFade'; { * Returns true if a fade operation is currently in progress. } function CGDisplayFadeOperationInProgress: boolean_t; external name '_CGDisplayFadeOperationInProgress'; end.
unit uGioSetFilePropertyOperation; {$mode objfpc}{$H+} interface uses Classes, SysUtils, uFileSourceSetFilePropertyOperation, uFileSource, uFileSourceOperationOptions, uFile, uGio2, uGLib2, uFileProperty, uWfxPluginFileSource; type { TGioSetFilePropertyOperation } TGioSetFilePropertyOperation = class(TFileSourceSetFilePropertyOperation) private FFullFilesTree: TFiles; // source files including all files/dirs in subdirectories FStatistics: TFileSourceSetFilePropertyOperationStatistics; // local copy of statistics // Options. FSymLinkOption: TFileSourceOperationOptionSymLink; private function SetFileTime(AFile: PGFile; ATime: Pgchar; AValue: TDateTime): Boolean; protected function SetNewProperty(aFile: TFile; aTemplateProperty: TFileProperty): TSetFilePropertyResult; override; public constructor Create(aTargetFileSource: IFileSource; var theTargetFiles: TFiles; var theNewProperties: TFileProperties); override; destructor Destroy; override; procedure Initialize; override; procedure MainExecute; override; end; implementation uses DCBasicTypes, DCDateTimeUtils, uGioFileSourceUtil, uGObject2; constructor TGioSetFilePropertyOperation.Create(aTargetFileSource: IFileSource; var theTargetFiles: TFiles; var theNewProperties: TFileProperties); begin FSymLinkOption := fsooslNone; FFullFilesTree := nil; inherited Create(aTargetFileSource, theTargetFiles, theNewProperties); // Assign after calling inherited constructor. FSupportedProperties := [fpName, fpAttributes, fpModificationTime, fpCreationTime, fpLastAccessTime]; end; destructor TGioSetFilePropertyOperation.Destroy; begin inherited Destroy; if Recursive then begin if Assigned(FFullFilesTree) then FreeAndNil(FFullFilesTree); end; end; procedure TGioSetFilePropertyOperation.Initialize; var TotalBytes: Int64; begin // Get initialized statistics; then we change only what is needed. FStatistics := RetrieveStatistics; if not Recursive then begin FFullFilesTree := TargetFiles; FStatistics.TotalFiles:= FFullFilesTree.Count; end else begin FillAndCount(TargetFiles, True, FFullFilesTree, FStatistics.TotalFiles, TotalBytes); // gets full list of files (recursive) end; end; procedure TGioSetFilePropertyOperation.MainExecute; var aFile: TFile; aTemplateFile: TFile; CurrentFileIndex: Integer; begin for CurrentFileIndex := 0 to FFullFilesTree.Count - 1 do begin aFile := FFullFilesTree[CurrentFileIndex]; FStatistics.CurrentFile := aFile.FullPath; UpdateStatistics(FStatistics); if Assigned(TemplateFiles) and (CurrentFileIndex < TemplateFiles.Count) then aTemplateFile := TemplateFiles[CurrentFileIndex] else aTemplateFile := nil; SetProperties(CurrentFileIndex, aFile, aTemplateFile); with FStatistics do begin DoneFiles := DoneFiles + 1; UpdateStatistics(FStatistics); end; CheckOperationState; end; end; function TGioSetFilePropertyOperation.SetFileTime(AFile: PGFile; ATime: Pgchar; AValue: TDateTime): Boolean; begin Result:= g_file_set_attribute_uint64 (AFile, ATime, DateTimeToUnixFileTime(AValue), G_FILE_QUERY_INFO_NONE, nil, nil); end; function TGioSetFilePropertyOperation.SetNewProperty(aFile: TFile; aTemplateProperty: TFileProperty): TSetFilePropertyResult; var AGFile: PGFile; AGNewFile: PGFile; NewAttributes: TFileAttrs; begin Result := sfprSuccess; AGFile:= g_file_new_for_commandline_arg(Pgchar(aFile.FullPath)); case aTemplateProperty.GetID of fpName: if (aTemplateProperty as TFileNameProperty).Value <> aFile.Name then begin AGNewFile:= g_file_set_display_name(AGFile, Pgchar((aTemplateProperty as TFileNameProperty).Value), nil, nil); if (AGNewFile = nil) then Result := sfprError else begin g_object_unref(PGObject(AGNewFile)); end; end else Result := sfprSkipped; fpAttributes: if (aTemplateProperty as TFileAttributesProperty).Value <> (aFile.Properties[fpAttributes] as TFileAttributesProperty).Value then begin NewAttributes := (aTemplateProperty as TFileAttributesProperty).Value; if aTemplateProperty is TUnixFileAttributesProperty then begin if not g_file_set_attribute_uint32 (AGFile, FILE_ATTRIBUTE_UNIX_MODE, NewAttributes, G_FILE_QUERY_INFO_NONE, nil, nil) then Result := sfprError; end else raise Exception.Create('Unsupported file attributes type'); end else Result := sfprSkipped; fpModificationTime: if (aTemplateProperty as TFileModificationDateTimeProperty).Value <> (aFile.Properties[fpModificationTime] as TFileModificationDateTimeProperty).Value then begin if not SetFileTime(AGFile, FILE_ATTRIBUTE_TIME_MODIFIED, (aTemplateProperty as TFileModificationDateTimeProperty).Value) then Result := sfprError; end else Result := sfprSkipped; fpCreationTime: if (aTemplateProperty as TFileCreationDateTimeProperty).Value <> (aFile.Properties[fpCreationTime] as TFileCreationDateTimeProperty).Value then begin if not SetFileTime(AGFile, FILE_ATTRIBUTE_TIME_CREATED, (aTemplateProperty as TFileCreationDateTimeProperty).Value) then Result := sfprError; end else Result := sfprSkipped; fpLastAccessTime: if (aTemplateProperty as TFileLastAccessDateTimeProperty).Value <> (aFile.Properties[fpLastAccessTime] as TFileLastAccessDateTimeProperty).Value then begin if not SetFileTime(AGFile, FILE_ATTRIBUTE_TIME_ACCESS, (aTemplateProperty as TFileLastAccessDateTimeProperty).Value) then Result := sfprError; end else Result := sfprSkipped; else raise Exception.Create('Trying to set unsupported property'); end; g_object_unref(PGObject(AGFile)); end; end.
//https://edn.embarcadero.com/article/41374 //http://docwiki.embarcadero.com/RADStudio/Seattle/en/Using_Callbacks //http://docwiki.embarcadero.com/RADStudio/Seattle/en/REST_Heavyweight_Callbacks //Outro exemplo: C:\Users\Public\Documents\Embarcadero\Studio\20.0\Samples\Object Pascal\DataSnap\LtWeightCallbacks //http://www.youtube.com/watch?v=5zO3_g9Z-wc //http://www.youtube.com/watch?v=geEzwg8XX8k //http://www.youtube.com/watch?v=Hwode7a8O5k //https://mathewdelong.wordpress.com/2011/05/30/heavyweight-callbacks/ // //http://edn.embarcadero.com/article/41024 //http://edn.embarcadero.com/article/41025 unit FormClientUnit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, DBXJSON, Vcl.StdCtrls, Datasnap.DSCommon, Data.DB, Data.SqlExpr, Data.DBXDataSnap, Data.DBXCommon, IPPeerClient, System.JSON, Datasnap.DSSession; type TMyCallback = class(TDBXCallback) public function Execute(const Arg: TJSONValue): TJSONValue; override; end; TFormClient = class(TForm) MemoLog: TMemo; DSClientCallbackChannelManager1: TDSClientCallbackChannelManager; SQLConnection1: TSQLConnection; ButtonBroadcast: TButton; EditMsg: TEdit; LabelMessage: TLabel; EditLocalClientId: TEdit; EditLocalCallbackId: TEdit; EditDestinationClientId: TEdit; EditDestinationCallbackId: TEdit; ButtonNotifyCallback: TButton; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; procedure FormCreate(Sender: TObject); procedure ButtonBroadcastClick(Sender: TObject); procedure ButtonNotifyCallbackClick(Sender: TObject); private { Private declarations } FCallbackName: string; public { Public declarations } procedure LogMsg(const s: string); procedure QueueLogMsg(const s: string); end; var FormClient: TFormClient; implementation uses DSService, DSProxy; {$R *.dfm} { TMyCallback } function TMyCallback.Execute(const Arg: TJSONValue): TJSONValue; begin FormClient.QueueLogMsg(Arg.ToString); Result := TJSONTrue.Create; end; { TFormClient } procedure TFormClient.ButtonBroadcastClick(Sender: TObject); var AClient: TDSAdminClient; begin AClient := TDSAdminClient.Create(SQLConnection1.DBXConnection); try AClient.BroadcastToChannel( DSClientCallbackChannelManager1.ChannelName, TJSONString.Create(EditMsg.Text) ); finally AClient.Free; end; end; procedure TFormClient.ButtonNotifyCallbackClick(Sender: TObject); var AClient: TDSAdminClient; aResponse: TJSONValue; begin AClient := TDSAdminClient.Create(SQLConnection1.DBXConnection); try AClient.NotifyCallback( DSClientCallbackChannelManager1.ChannelName, EditDestinationClientId.Text, EditDestinationCallbackId.Text, TJSONString.Create(EditMsg.Text), aResponse ); finally AClient.Free; end; end; procedure TFormClient.FormCreate(Sender: TObject); begin DSClientCallbackChannelManager1.ManagerId := TDSTunnelSession.GenerateSessionId; FCallbackName := TDSTunnelSession.GenerateSessionId; DSClientCallbackChannelManager1.RegisterCallback(FCallbackName, TMyCallback.Create); EditLocalClientId.Text := DSClientCallbackChannelManager1.ManagerId; EditLocalCallbackId.Text := FCallbackName; EditDestinationClientId.Text := ''; EditDestinationCallbackId.Text := ''; end; procedure TFormClient.LogMsg(const s: string); begin MemoLog.Lines.Add(DateTimeToStr(Now) + ': ' + s); end; procedure TFormClient.QueueLogMsg(const s: string); begin TThread.Queue(nil, procedure begin LogMsg(s) end ); end; end.
unit uTools; interface {声明区域,此处声明外部可以引用} uses uDemo; type TPerson = class {字段,域} private FName: string; FAge:Integer; function GetAge():Integer; procedure SetAge(FAge:Integer); public {属性} // Name为外部可以访问的属性,它读就是调用FName,写就是写进FName; property Name: string read FName write FName; property Age:Integer read GetAge write SetAge; end; implementation {实现区域} { TPerson } function TPerson.GetAge: Integer; begin Result:=Self.FAge; end; procedure TPerson.SetAge(FAge: Integer); begin Self.FAge:=FAge; end; initialization {初始化区域} finalization {销毁区域} end.
unit SensorTypes; interface uses Classes; type CSensor = class of TSensor; TSensorFixed24=class; TSensorFloat32=class; {$IFDEF Sensor24} TMySensor = TSensorFixed24; {$ENDIF} {$IFDEF Sensor32} TMySensor = TSensorFloat32; {$ENDIF} TAnalogData=record case Cardinal of 0:(Value:Single); 1:(Flags:Cardinal); end; TSensor=class(TObject) Num:Byte; TrackID:Integer; constructor CreateSensor(aNum:Byte;aTrackID:Integer);virtual; constructor Create(aNum:Byte;aTrackID:Integer;ARecsPerDay:Integer);virtual;abstract; function FormatDataN(const SrcBuf; var DstBuf; SrcSize:Integer):TDateTime;virtual;abstract; function FormatData(const SrcBuf; var DstBuf):TDateTime;virtual;abstract; function GetRecsPerDay:Integer;virtual;abstract; class function GetRecSize:Integer;virtual;abstract; class procedure GetAD(const Data:WideString; i:Integer; var AD:TAnalogData);virtual;abstract; class procedure SetAD(var Data:WideString; i:Integer; const AD:TAnalogData);virtual;abstract; end; TSensorFixed24=class(TSensor) V2,V1:Single; NotFirst:Boolean; RecsPerDay:Integer; constructor Create(aNum:Byte;aTrackID:Integer;ARecsPerDay:Integer);override; function GetRecsPerDay:Integer;override; function FormatData(const SrcBuf; var DstBuf):TDateTime;override; function FormatDataN(const SrcBuf; var DstBuf; Cnt:Integer):TDateTime;override; class function GetRecSize:Integer;override; class procedure GetAD(const Data:WideString; i:Integer; var AD:TAnalogData);override; class procedure SetAD(var Data:WideString; i:Integer; const AD:TAnalogData);override; private class procedure SingleToFixed24(Src:Single; var Dst); end; TSensorFloat32=class(TSensor) V2,V1:Single; NotFirst:Boolean; RecsPerDay:Integer; constructor Create(aNum:Byte;aTrackID:Integer;ARecsPerDay:Integer);override; function FormatData(const SrcBuf; var DstBuf):TDateTime;override; function FormatDataN(const SrcBuf; var DstBuf; Cnt:Integer):TDateTime;override; class function GetRecSize:Integer;override; function GetRecsPerDay:Integer;override; class procedure GetAD(const Data:WideString; i:Integer; var AD:TAnalogData);override; class procedure SetAD(var Data:WideString; i:Integer; const AD:TAnalogData);override; end; TEventData=packed record TimeOffsetMs:Cardinal; Channel:Word; State:Byte; end; PEventData=^TEventData; TEventSource=class(TObject) Num:Byte; TrackID:Integer; RecsPerDay:Integer; constructor Create(aNum:Byte;aTrackID:Integer;ARecsPerDay:Integer); function GetRecsPerDay:Integer; class function GetRecSize:Integer; class procedure GetED(const Data:WideString; i:Integer; var ED:TEventData); class procedure SetED(var Data:WideString; i:Integer; const ED:TEventData); end; TPipTime = packed record Year,Month,Day,Hour,Min,Sec,Sec100:Byte; end; TLdrData=packed record Number:Byte; Time:TPipTime; p:Single; end; TLdrDataN=packed record Number:Byte; Time:TPipTime; p:array[0..255] of Single; end; function ValidAD(const AD:TAnalogData):Boolean; procedure SetSensorRepair(var AD:TAnalogData); procedure SetErrUnknown(var AD:TAnalogData); procedure SetErrAnalog(var AD:TAnalogData); procedure SetErrADCRange(var AD:TAnalogData); procedure SetErrADCComm(var AD:TAnalogData); function GetADMsg(const AD:TAnalogData):String; const MemSignedZero:Cardinal=$80000000; // constansts for Single smUnknown=0; smExpMask=$7FC00000; smSNaN =$7F800000; smErrMask =smExpMask or $0D; smErrUnknown =smSNaN or $01 or $00; smErrADCComm =smSNaN or $01 or $04; smErrADCRange =smSNaN or $01 or $08; smErrAnalog =smSNaN or $01 or $0C; smSensorRepair=smSNaN or $02; var JumpLimit:Single; SignedZero:Single absolute MemSignedZero; implementation uses Windows,SysUtils; const // Fixed24 flags sfStateMask =$F00000; sfUnknown =$000000; sfRepair =$C00000; sfNormal =$800000; sfError =$400000; sfErrUnknown =$400000; sfErrADCComm =$500000; sfErrADCRange =$600000; sfErrAnalog =$700000; function ValidAD(const AD:TAnalogData):Boolean; begin Result:=(AD.Flags<>0) and (AD.Flags and smExpMask<>smSNaN); end; function GetADMsg(const AD:TAnalogData):String; begin if ValidAD(AD) then Result:=FloatToStr(AD.Value) else if AD.Flags and smSensorRepair=smSensorRepair then Result:='ремонт' else begin case AD.Flags and smErrMask of smErrUnknown: Result:='сбой'; smErrADCComm: Result:='сбой связи с АЦП'; smErrADCRange:Result:='перегрузка АЦП'; smErrAnalog: Result:='аналоговый сбой'; else Result:='нет данных' end; end; end; procedure SetSensorRepair(var AD:TAnalogData); begin AD.Flags:=AD.Flags or smSensorRepair; end; procedure SetErrUnknown(var AD:TAnalogData); begin AD.Flags:=smErrUnknown; end; procedure SetErrAnalog(var AD:TAnalogData); begin AD.Flags:=smErrAnalog; end; procedure SetErrADCRange(var AD:TAnalogData); begin AD.Flags:=smErrADCRange; end; procedure SetErrADCComm(var AD:TAnalogData); begin AD.Flags:=smErrADCComm; end; { TSensorFixed24 } constructor TSensorFixed24.Create(aNum: Byte; aTrackID, ARecsPerDay: Integer); begin CreateSensor(aNum,aTrackID); RecsPerDay:=aRecsPerDay; end; function TSensorFixed24.FormatData; const Scale=1 shl 10; type TOutData=Byte; var LdrData:^TLdrData; OutData:^TOutData; OD:Cardinal; ST:TSystemTime; V0:Single; FlagsV0:Cardinal absolute V0; begin LdrData:=@SrcBuf; OutData:=@DstBuf; ST.wYear:=LdrData.Time.Year+1900; ST.wMonth:=LdrData.Time.Month; ST.wDay:=LdrData.Time.Day; ST.wHour:=LdrData.Time.Hour; ST.wMinute:=LdrData.Time.Min; ST.wSecond:=LdrData.Time.Sec; ST.wMilliseconds:=LdrData.Time.Sec100*10; Result:=SystemTimeToDateTime(ST); V0:=LdrData.p; if FlagsV0 and smExpMask=smSNAN then SingleToFixed24(V0,OD) else begin try if NotFirst=False then begin V2:=V0; V1:=V0; NotFirst:=True; end; OD:=(Round(V1*Scale) and $03FFFF); if (Abs(V2-V1)>JumpLimit) and (Abs(V2-V0)<JumpLimit) then OD:=OD or sfUnknown else begin OD:=OD or sfNormal; V2:=V1; end; V1:=V0; except NotFirst:=False; end; end; Move(OD,OutData^,3); end; class procedure TSensorFixed24.GetAD(const Data: WideString; i: Integer; var AD: TAnalogData); var P:PInteger; ip:Integer absolute P; V:Integer; begin P:=PInteger(@(Data[1])); Inc(ip,i*3); V:=P^ and $00FFFFFF; if V and sfStateMask=sfNormal then begin V:=V and $3FFFF; if V and $20000<>0 // если установлен знаковый бит then V:=V or Integer($FFFC0000); // то расширяем его AD.Value:=V*(1/(1 shl 10)); if AD.Flags=0 then AD.Value:=SignedZero; end else begin case V and sfStateMask of sfErrADCComm: AD.Flags:=smErrADCComm; sfErrADCRange: AD.Flags:=smErrADCRange; sfErrAnalog: AD.Flags:=smErrAnalog; sfUnknown: AD.Flags:=smUnknown; else AD.Flags:=smErrUnknown; end; if V and sfRepair=sfRepair then AD.Flags:=AD.Flags or smSensorRepair; end; end; class function TSensorFixed24.GetRecSize: Integer; begin Result:=3; end; class procedure TSensorFixed24.SingleToFixed24(Src: Single; var Dst); var iSrc:Cardinal absolute Src; V:Integer; begin if iSrc and smExpMask<>smSNaN then begin try if Src<-128 then Src:=-128 else if 128<Src then Src:=128; V:=Trunc(Src*(1 shl 10)); except V:=0; end; V:=sfNormal or (V and $03FFFF); end else begin V:=0; case iSrc and smErrMask of smErrADCComm: V:=sfErrADCComm; smErrADCRange: V:=sfErrADCRange; smErrAnalog: V:=sfErrAnalog; else V:=sfErrUnknown; end; // if iSrc and smSensorRepair<>0 then V:=sfRepair; end; Move(V,Dst,3); end; function TSensorFixed24.GetRecsPerDay: Integer; begin Result:=RecsPerDay; end; class procedure TSensorFixed24.SetAD(var Data: WideString; i: Integer; const AD: TAnalogData); var P:Pointer; ip:Integer absolute P; begin P:=@(Data[1]); Inc(ip,i*3); SingleToFixed24(AD.Value,P^); end; function TSensorFixed24.FormatDataN(const SrcBuf; var DstBuf; Cnt: Integer): TDateTime; const Scale=1 shl 10; type TOutData=Byte; var LdrData:^TLdrDataN; OutData:^TOutData; OD:Cardinal; ST:TSystemTime; V0:Single; FlagsV0:Cardinal absolute V0; i:Integer; begin LdrData:=@SrcBuf; OutData:=@DstBuf; ST.wYear:=LdrData.Time.Year+1900; ST.wMonth:=LdrData.Time.Month; ST.wDay:=LdrData.Time.Day; ST.wHour:=LdrData.Time.Hour; ST.wMinute:=LdrData.Time.Min; ST.wSecond:=LdrData.Time.Sec; ST.wMilliseconds:=LdrData.Time.Sec100*10; Result:=SystemTimeToDateTime(ST); for i:=0 to Cnt-1 do begin V0:=LdrData.p[i]; if FlagsV0 and smExpMask=smSNAN then SingleToFixed24(V0,OD) else begin try if NotFirst=False then begin V2:=V0; V1:=V0; NotFirst:=True; end; OD:=(Round(V1*Scale) and $03FFFF); if (Abs(V2-V1)>JumpLimit) and (Abs(V2-V0)<JumpLimit) then OD:=OD or sfUnknown else begin OD:=OD or sfNormal; V2:=V1; end; V1:=V0; except NotFirst:=False; end; end; Move(OD,OutData^,3); Inc(OutData,3); end; end; { TSensorFloat32 } constructor TSensorFloat32.Create(aNum: Byte; aTrackID, ARecsPerDay: Integer); begin CreateSensor(aNum,aTrackID); RecsPerDay:=aRecsPerDay; end; function TSensorFloat32.FormatData(const SrcBuf; var DstBuf): TDateTime; var LdrData:^TLdrData; ST:TSystemTime; OD:^Single; MemOD:^Cardinal absolute OD; V0:Single; MemV0:Cardinal absolute V0; begin LdrData:=@SrcBuf; OD:=@DstBuf; ST.wYear:=LdrData.Time.Year+1900; ST.wMonth:=LdrData.Time.Month; ST.wDay:=LdrData.Time.Day; ST.wHour:=LdrData.Time.Hour; ST.wMinute:=LdrData.Time.Min; ST.wSecond:=LdrData.Time.Sec; ST.wMilliseconds:=LdrData.Time.Sec100*10; Result:=SystemTimeToDateTime(ST); V0:=LdrData.p; if MemV0 and smExpMask<>smSNAN then begin if V0=0 then V0:=1.5e-45; if NotFirst=False then begin V2:=V0; V1:=V0; NotFirst:=True; end; if (Abs(V2-V1)>JumpLimit) and (Abs(V2-V0)<JumpLimit) then MemOD^:=smErrUnknown else begin OD^:=V1; V2:=V1; end; V1:=V0; end else OD^:=V0; end; function TSensorFloat32.FormatDataN(const SrcBuf; var DstBuf; Cnt: Integer): TDateTime; var LdrData:^TLdrDataN; ST:TSystemTime; OD:^Single; MemOD:^Cardinal absolute OD; V0:Single; MemV0:Cardinal absolute V0; i:Integer; begin LdrData:=@SrcBuf; OD:=@DstBuf; ST.wYear:=LdrData.Time.Year+1900; ST.wMonth:=LdrData.Time.Month; ST.wDay:=LdrData.Time.Day; ST.wHour:=LdrData.Time.Hour; ST.wMinute:=LdrData.Time.Min; ST.wSecond:=LdrData.Time.Sec; ST.wMilliseconds:=LdrData.Time.Sec100*10; Result:=SystemTimeToDateTime(ST); for i:=0 to Cnt-1 do begin V0:=LdrData.p[i]; if MemV0 and smExpMask<>smSNAN then begin if V0=0 then V0:=1.5e-45; if NotFirst=False then begin V2:=V0; V1:=V0; NotFirst:=True; end; if (Abs(V2-V1)>JumpLimit) and (Abs(V2-V0)<JumpLimit) then MemOD^:=smErrUnknown else begin OD^:=V1; V2:=V1; end; V1:=V0; end else OD^:=V0; Inc(OD); end; end; class procedure TSensorFloat32.GetAD(const Data: WideString; i: Integer; var AD: TAnalogData); var P:PSingle; begin P:=PSingle(@(Data[1])); Inc(P,i); AD.Value:=P^; end; class function TSensorFloat32.GetRecSize: Integer; begin Result:=4; end; function TSensorFloat32.GetRecsPerDay: Integer; begin Result:=RecsPerDay; end; class procedure TSensorFloat32.SetAD(var Data: WideString; i: Integer; const AD: TAnalogData); var P:PSingle; begin P:=PSingle(@(Data[1])); Inc(P,i); P^:=AD.Value; end; { TSensor } constructor TSensor.CreateSensor(aNum: Byte; aTrackID: Integer); begin inherited Create; Num:=aNum; TrackID:=aTrackID; end; { TEventSource } constructor TEventSource.Create(aNum: Byte; aTrackID, ARecsPerDay: Integer); begin Num:=aNum; TrackID:=aTrackID; RecsPerDay:=ARecsPerDay; end; class procedure TEventSource.GetED(const Data: WideString; i: Integer; var ED: TEventData); var P:PEventData; begin P:=PEventData(@(Data[1])); Inc(P,i); Move(P^,ED,SizeOf(ED)); end; class function TEventSource.GetRecSize: Integer; begin Result:=SizeOf(TEventData); end; function TEventSource.GetRecsPerDay: Integer; begin Result:=RecsPerDay; end; class procedure TEventSource.SetED(var Data: WideString; i: Integer; const ED: TEventData); var P:PEventData; begin P:=PEventData(@(Data[1])); Inc(P,i); Move(ED,P^,SizeOf(ED)); end; end.
unit evRowAndTableTypeSupport; {* Примесь для классификации таблиц и строк } // Модуль: "w:\common\components\gui\Garant\Everest\evRowAndTableTypeSupport.pas" // Стереотип: "SimpleClass" // Элемент модели: "TevRowAndTableTypeSupport" MUID: (5112379700A6) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface uses l3IntfUses , l3ProtoObject , evEditorInterfaces , evEditorInterfacesTypes , evCellsOffsetsPair ; type TevRowAndTableTypeSupport = class(Tl3ProtoObject) {* Примесь для классификации таблиц и строк } private f_TableStyle: TedTabelType; {* Стиль таблицы. Устанавливается в процессе анализа таблицы. В зависимости от него изменяется алгоритм выравнивания границ. } f_CurrentRowType: TedRowType; {* Тип текущей строки. } private procedure AnalizeTableStyle; procedure CheckRowType(const aRow: IedRow); protected procedure AnalizeRowType(const aRow: IedRow); procedure SaveRowType(const aPairList: TevCellsOffsetsPair); function GetPrevRowType: TedRowType; virtual; abstract; function GetCellsCountInPreviousRow: Integer; virtual; abstract; {* Возвращает число ячеек в последней выравненной строке } procedure Cleanup; override; {* Функция очистки полей объекта. } procedure InitFields; override; public property TableStyle: TedTabelType read f_TableStyle; {* Стиль таблицы. Устанавливается в процессе анализа таблицы. В зависимости от него изменяется алгоритм выравнивания границ. } property CurrentRowType: TedRowType read f_CurrentRowType; {* Тип текущей строки. } end;//TevRowAndTableTypeSupport implementation uses l3ImplUses //#UC START# *5112379700A6impl_uses* //#UC END# *5112379700A6impl_uses* ; procedure TevRowAndTableTypeSupport.AnalizeTableStyle; //#UC START# *5076B24B0038_5112379700A6_var* //#UC END# *5076B24B0038_5112379700A6_var* begin //#UC START# *5076B24B0038_5112379700A6_impl* case f_CurrentRowType of ed_rtNumericCels: f_TableStyle := ed_tsWithHeader; ev_rtFormCells: f_TableStyle := ed_tsForm; ed_rtChessTableRow: f_TableStyle := ed_tsChessTable; end; // case f_CurrentRowType of //#UC END# *5076B24B0038_5112379700A6_impl* end;//TevRowAndTableTypeSupport.AnalizeTableStyle procedure TevRowAndTableTypeSupport.AnalizeRowType(const aRow: IedRow); //#UC START# *511240880262_5112379700A6_var* //#UC END# *511240880262_5112379700A6_var* begin //#UC START# *511240880262_5112379700A6_impl* f_CurrentRowType := aRow.AnalizeRowCells; CheckRowType(aRow); AnalizeTableStyle; //#UC END# *511240880262_5112379700A6_impl* end;//TevRowAndTableTypeSupport.AnalizeRowType procedure TevRowAndTableTypeSupport.SaveRowType(const aPairList: TevCellsOffsetsPair); //#UC START# *51124284008E_5112379700A6_var* //#UC END# *51124284008E_5112379700A6_var* begin //#UC START# *51124284008E_5112379700A6_impl* aPairList.RowType := f_CurrentRowType; //#UC END# *51124284008E_5112379700A6_impl* end;//TevRowAndTableTypeSupport.SaveRowType procedure TevRowAndTableTypeSupport.CheckRowType(const aRow: IedRow); //#UC START# *5152CEDE0255_5112379700A6_var* //#UC END# *5152CEDE0255_5112379700A6_var* begin //#UC START# *5152CEDE0255_5112379700A6_impl* if f_CurrentRowType = ed_rtNumericCels then begin if aRow.CellsIterator.CellsCount <> GetCellsCountInPreviousRow then f_CurrentRowType := ed_rtSimpleWithoutEmpty; end; // if f_CurrentRowType = ed_NumericCels then //#UC END# *5152CEDE0255_5112379700A6_impl* end;//TevRowAndTableTypeSupport.CheckRowType procedure TevRowAndTableTypeSupport.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_5112379700A6_var* //#UC END# *479731C50290_5112379700A6_var* begin //#UC START# *479731C50290_5112379700A6_impl* f_TableStyle := ed_tsNone; inherited; //#UC END# *479731C50290_5112379700A6_impl* end;//TevRowAndTableTypeSupport.Cleanup procedure TevRowAndTableTypeSupport.InitFields; //#UC START# *47A042E100E2_5112379700A6_var* //#UC END# *47A042E100E2_5112379700A6_var* begin //#UC START# *47A042E100E2_5112379700A6_impl* f_TableStyle := ed_tsNone; inherited; //#UC END# *47A042E100E2_5112379700A6_impl* end;//TevRowAndTableTypeSupport.InitFields end.
unit udmContatos; interface uses Windows, System.UITypes,Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, udmPadrao, DBAccess, IBC, DB, MemDS; type TdmContatos = class(TdmPadrao) qryLocalizacaoCGC: TStringField; qryLocalizacaoDESTINO: TStringField; qryLocalizacaoEMAIL: TStringField; qryLocalizacaoOBS: TBlobField; qryLocalizacaoDT_ALTERACAO: TDateTimeField; qryLocalizacaoOPERADOR: TStringField; qryManutencaoCGC: TStringField; qryManutencaoDESTINO: TStringField; qryManutencaoEMAIL: TStringField; qryManutencaoOBS: TBlobField; qryManutencaoDT_ALTERACAO: TDateTimeField; qryManutencaoOPERADOR: TStringField; protected procedure MontaSQLBusca(DataSet: TDataSet = nil); override; procedure MontaSQLRefresh; override; private FContato: string; FCliente: string; function GetSqlDefault: string; public property Cliente: string read FCliente write FCliente; property Contato: string read FContato write FContato; function LocalizarPorCliente(DataSet: TDataSet = nil): Boolean; function LocalizarEmailCC(DataSet: TDataSet = nil): Boolean; property SqlDefault: string read GetSqlDefault; end; const SQL_DEFAULT = 'SELECT ' + ' CONT.CGC, ' + ' CONT.DESTINO, ' + ' CONT.EMAIL, ' + ' CONT.OBS, ' + ' CONT.DT_ALTERACAO, ' + ' CONT.OPERADOR ' + 'FROM STWOPETMALS CONT '; var dmContatos: TdmContatos; implementation {$R *.dfm} { TdmContatos } function TdmContatos.GetSqlDefault: string; begin result := SQL_DEFAULT; end; function TdmContatos.LocalizarEmailCC(DataSet: TDataSet): Boolean; begin if DataSet = nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin Close; SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE CONT.CGC = :CGC'); SQL.Add(' AND CONT.DESTINO CONTAINING :DESTINO'); SQL.Add('ORDER BY CONT.CGC, CONT.DESTINO'); ParamByName('CGC').AsString := FCliente; ParamByName('DESTINO').AsString := FContato; Open; Result := not IsEmpty; end; end; function TdmContatos.LocalizarPorCliente(DataSet: TDataSet): Boolean; begin if DataSet = nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin Close; FetchAll := True; SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE CONT.CGC = :CGC '); SQL.Add('ORDER BY CONT.CGC, CONT.DESTINO'); ParamByName('CGC').AsString := FCliente; Open; Result := not IsEmpty; end; end; procedure TdmContatos.MontaSQLBusca(DataSet: TDataSet); begin inherited; with (DataSet as TIBCQuery) do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('WHERE CONT.CGC = :CGC'); SQL.Add(' AND CONT.DESTINO = :DESTINO'); SQL.Add('ORDER BY CONT.CGC, CONT.DESTINO'); ParamByName('CGC').AsString := FCliente; ParamByName('DESTINO').AsString := FContato; end; end; procedure TdmContatos.MontaSQLRefresh; begin inherited; with qryManutencao do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add('ORDER BY CONT.CGC, CONT.DESTINO'); end; end; end.
{ *************************************************************************** Copyright (c) 2016-2022 Kike Pérez Unit : Quick.Log Description : Threadsafe Log Author : Kike Pérez Version : 1.19 Created : 10/04/2016 Modified : 10/02/2022 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************** } unit Quick.Log; {$i QuickLib.inc} interface uses {$IFDEF MSWINDOWS} Windows, {$ENDIF} Classes, Quick.Commons, {$IFNDEF FPC} System.IOUtils, {$IFDEF DELPHILINUX} Quick.SyncObjs.Linux.Compatibility, {$ENDIF} {$ELSE} Quick.Files, {$ENDIF} {$IF Defined(NEXTGEN) OR Defined(LINUX) or Defined(MACOS)} syncObjs, Posix.Unistd, {$ENDIF} SysUtils; type TMemoryLog = class private fLines : TStrings; fEnabled : Boolean; function GetLogText : string; public constructor Create; destructor Destroy; override; property Lines : TStrings read fLines write fLines; property Text : string read GetLogText; property Enabled : Boolean read fEnabled write fEnabled; end; TQuickLog = class private fLogFileName : string; fCurrentDateToFileName : Boolean; fHideHour : Boolean; fFMTName : string; fVerbose : TLogVerbose; fLimitLogSize : Int64; fCurrentLogSize : Int64; fShowEventTypes : Boolean; fShowHeaderInfo : Boolean; fCheckFileInUse : Boolean; fMemoryLog : TMemoryLog; function GetLogFileName : string; procedure WriteLog(cMsg : string); public property Verbose : TLogVerbose read fVerbose write fVerbose; property LogFileName : string read GetLogFileName; property HideHour : Boolean read fHideHour write fHideHour; property ShowEventType : Boolean read fShowEventTypes write fShowEventTypes; property ShowHeaderInfo : Boolean read fShowHeaderInfo write fShowHeaderInfo; property CheckFileInUse : Boolean read fCheckFileInUse write fCheckFileInUse; property MemoryLog : TMemoryLog read fMemoryLog write fMemoryLog; constructor Create; destructor Destroy; override; function SetLog(logname : string; AddCurrentDateToFileName : Boolean; LimitSizeInMB : Integer = 0) : Boolean; procedure Add(const cMsg : string; cEventType : TLogEventType = TLogEventType.etInfo); overload; procedure Add(const cFormat : string; cParams : array of TVarRec ; cEventType : TLogEventType = TLogEventType.etInfo); overload; end; var {$IF Defined(MACOS) OR Defined(ANDROID)} CS : TCriticalSection; {$ELSE} CS : TRTLCriticalSection; {$ENDIF} Log : TQuickLog; implementation constructor TMemoryLog.Create; begin inherited; fLines := TStringList.Create; fEnabled := False; end; destructor TMemoryLog.Destroy; begin if Assigned(fLines) then fLines.Free; inherited; end; function TMemoryLog.GetLogText : string; begin Result := fLines.Text; end; constructor TQuickLog.Create; begin inherited; fVerbose := LOG_ALL; fLimitLogSize := 0; fShowEventTypes := True; fShowHeaderInfo := True; fCheckFileInUse := False; fMemoryLog := TMemoryLog.Create; end; destructor TQuickLog.Destroy; begin if Assigned(fMemoryLog) then fMemoryLog.Free; inherited; end; {Returns date + time in english format (to add to filename} function TQuickLog.GetLogFileName : string; begin Result := ''; if fCurrentDateToFileName then begin try //Checks if needs to show time or not if HideHour then Result := FormatDateTime('yyyymmdd', Now()) else Result := FormatDateTime('yyyymmdd_hhmm', Now()); Result := Format(fFMTName,[Result]); except Result := 'Error'; end; end else Result := fLogFileName; end; {$IFDEF FPC} function OSVersion: String; begin Result:={$I %FPCTARGETOS%}+'-'+{$I %FPCTARGETCPU%}; end; {$ENDIF} function TQuickLog.SetLog(logname : string; AddCurrentDateToFileName : Boolean; LimitSizeInMB : Integer = 0) : Boolean; begin if logname = '' then logname := TPath.GetDirectoryName(ParamStr(0)) + PathDelim + TPath.GetFileNameWithoutExtension(ParamStr(0)) + '.log'; fFMTName := ExtractFilePath(logname) + ExtractFileNameWithoutExt(logname) + '_%s' + ExtractFileExt(logname); fHideHour := True; fCurrentDateToFileName := AddCurrentDateToFileName; fLogFileName := logname; //Checks if logfile is too big and deletes fLimitLogSize := LimitSizeInMB * 1024 * 1024; if (fLimitLogSize > 0) and (TFile.Exists(logname)) then begin try fCurrentLogSize := TFile.GetSize(logname); if fCurrentLogSize > fLimitLogSize then if DeleteFile(logname) then fCurrentLogSize := 0; except raise Exception.Create('can''t access to log file!'); end; end; //Checks if it's in use {$IF NOT Defined(MACOS) AND NOT Defined(ANDROID)} if (fCheckFileInUse) and (TFile.IsInUse(logname)) Then fLogFileName := Format('%s_(1).%s',[ExtractFileNameWithoutExt(logname),ExtractFileExt(logname)]); {$ENDIF} //writes header info if fShowHeaderInfo then begin try Self.WriteLog(FillStr('-',70)); Self.WriteLog(Format('Application : %s %s',[ExtractFilenameWithoutExt(ParamStr(0)),GetAppVersionFullStr])); Self.WriteLog(Format('Path : %s',[ExtractFilePath(ParamStr(0))])); Self.WriteLog(Format('CPU cores : %d',[CPUCount])); Self.WriteLog(Format('OS version : %s',{$IFDEF FPC}[OSVersion]{$ELSE}[TOSVersion.ToString]{$ENDIF})); Self.WriteLog(Format('Host : %s',[GetComputerName])); Self.WriteLog(Format('Username : %s',[Trim(GetLoggedUserName)])); Self.WriteLog(Format('Started : %s',[NowStr])); {$IFDEF MSWINDOWS} if IsService then Self.WriteLog('AppType : Service') else if System.IsConsole then Self.WriteLog('AppType : Console'); {$ENDIF} if IsDebug then Self.WriteLog('Debug mode : On'); Self.WriteLog(FillStr('-',70)); except on E : Exception do Self.WriteLog('Can''t get info: ' + e.message); end; end; Result := True; end; procedure TQuickLog.Add(const cMsg : string; cEventType : TLogEventType = TLogEventType.etInfo); begin //Check Log Verbose level if cEventType in fVerbose then begin if fShowEventTypes then Self.WriteLog(Format('%s [%s] %s',[DateTimeToStr(Now()),EventStr[Integer(cEventType)],cMsg])) else Self.WriteLog(Format('%s %s',[DateTimeToStr(Now()),cMsg])); end; end; procedure TQuickLog.WriteLog(cMsg : string); var stream: TFileStream; logname : string; LBuffer : TBytes; LByteOrderMark: TBytes; LOffset : Integer; LEncoding, DestEncoding: TEncoding; begin //Checks if need to add date to filename logname := GetLogFileName; {$IF Defined(MACOS) OR Defined(ANDROID)} CS.Enter; {$ELSE} EnterCriticalSection(CS); {$ENDIF} try cMsg := cMsg + #13#10; LEncoding:= TEncoding.Unicode; DestEncoding := TEncoding.Unicode; SetLength(LBuffer, length(cMsg) * sizeof(char)); if cMsg <> '' then Move(cMsg[1], lbuffer[0], Length(lbuffer)); LOffset := TEncoding.GetBufferEncoding(LBuffer, LEncoding); LBuffer := LEncoding.Convert(LEncoding, DestEncoding, LBuffer, LOffset, Length(LBuffer) - LOffset); if TFile.Exists(logname) then begin stream := TFileStream.Create(logname, fmOpenReadWrite or fmShareDenyWrite); stream.Position := stream.Size; end else begin stream := TFileStream.Create(logname, fmCreate or fmShareDenyWrite); LByteOrderMark := DestEncoding.GetPreamble; stream.Write(LByteOrderMark[0], Length(LByteOrderMark)); end; with stream do begin try Write(LBuffer[0], Length(LBuffer)); fCurrentLogSize := fCurrentLogSize + Length(LBuffer); finally Free; end; end; //writes internal log if fMemoryLog.Enabled then begin fMemoryLog.Lines.Add(cMsg); end; //check if limits max size try if (fLimitLogSize > 0) and (fCurrentLogSize > fLimitLogSize) then if DeleteFile(logname) then fCurrentLogSize := 0; except // end; finally {$IF Defined(MACOS) OR Defined(ANDROID)} CS.Leave; {$ELSE} LeaveCriticalSection(CS); {$ENDIF} end; end; procedure TQuickLog.Add(const cFormat : string; cParams : array of TVarRec ; cEventType : TLogEventType = TLogEventType.etInfo); begin Self.Add(Format(cFormat,cParams),cEventType); end; initialization {$IF DEFINED(FPC) AND DEFINED(LINUX)} InitCriticalSection(CS); {$ELSE} {$IF Defined(MACOS) OR Defined(ANDROID)} CS := TCriticalSection.Create; {$ELSE} {$IFDEF DELPHILINUX} CS := TRTLCriticalSection.Create; {$ELSE} InitializeCriticalSection(CS); {$ENDIF} {$ENDIF} {$ENDIF} finalization {$IF DEFINED(FPC) AND DEFINED(LINUX)} DoneCriticalsection(CS); {$ELSE} {$IF Defined(MACOS) OR Defined(ANDROID) OR Defined(DELPHILINUX)} CS.Free; {$ELSE} DeleteCriticalSection(CS); {$ENDIF} {$ENDIF} end.
{********************************************************************* * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Autor: Brovin Y.D. * E-mail: y.brovin@gmail.com * ********************************************************************} unit FGX.GradientEdit; interface uses System.UITypes, System.Types, FMX.Controls, FMX.Graphics, System.Classes, FGX.Consts; type { TfgGradientEdit } TfgCustomGradientEdit = class; TfgOnPointClick = procedure (AGradientEdit: TfgCustomGradientEdit; const AGradientPoint: TGradientPoint) of object; TfgOnPointAdded = procedure (AGradientEdit: TfgCustomGradientEdit; const AGradientPoint: TGradientPoint) of object; TfgCustomGradientEdit = class (TControl) public const DEFAULT_PICKER_SIZE = 12; const DEFAULT_BORDER_RADIUS = 0; const DEFAULT_BORDER_COLOR = TAlphaColorRec.Black; private FGradient: TGradient; FPickerSize: Single; FBorderRadius: Single; FBorderColor: TAlphaColor; FBackgroundBrush: TBrush; FIsPointMoving: Boolean; [weak] FSelectedPoint: TGradientPoint; { Events } FOnPointClick: TfgOnPointClick; FOnPointDblClick: TfgOnPointClick; FOnPointAdded: TfgOnPointAdded; FOnChangeTracking: TNotifyEvent; FOnChanged: TNotifyEvent; function IsPickerSizeStored: Boolean; function IsBorderRadiusStored: Boolean; procedure SetPickerSize(const Value: Single); procedure SetBorderRadius(const Value: Single); procedure SetGradient(const Value: TGradient); procedure SetBorderColor(const Value: TAlphaColor); protected FGradientChanged: Boolean; { Control events } procedure DoGradientChanged(Sender: TObject); virtual; procedure DoPointAdded(AGradientPoint: TGradientPoint); virtual; procedure DoPointClick(const AGradientPoint: TGradientPoint); virtual; procedure DoPointDblClick(const AGradientPoint: TGradientPoint); virtual; procedure DoChanged; virtual; procedure DoChangeTracking; virtual; /// <summary> /// This function insert |APoint| into sorted position by Offset value /// </summary> procedure UpdateGradientPointsOrder(APoint: TGradientPoint); { Hit Test } function FindPointAtPoint(const APoint: TPointF; var AIndex: Integer): Boolean; virtual; { Sizes } function GetDefaultSize: TSizeF; override; function GetGradientFieldSize: TRectF; virtual; { Painting } procedure Paint; override; procedure DrawBackground; virtual; procedure DrawGradient; virtual; procedure DrawPoint(const AIndex: Integer; const ASelected: Boolean = False); virtual; { Mouse events } procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X: Single; Y: Single); override; procedure MouseMove(Shift: TShiftState; X: Single; Y: Single); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X: Single; Y: Single); override; property IsPointMoving: Boolean read FIsPointMoving; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function Selected: Boolean; public property BorderRadius: Single read FBorderRadius write SetBorderRadius stored IsBorderRadiusStored; property BorderColor: TAlphaColor read FBorderColor write SetBorderColor default DEFAULT_BORDER_COLOR; property Gradient: TGradient read FGradient write SetGradient; property PickerSize: Single read FPickerSize write SetPickerSize stored IsPickerSizeStored; property SelectedPoint: TGradientPoint read FSelectedPoint; property OnPointAdded: TfgOnPointAdded read FOnPointAdded write FOnPointAdded; property OnPointClick: TfgOnPointClick read FOnPointClick write FOnPointClick; property OnPointDblClick: TfgOnPointClick read FOnPointDblClick write FOnPointDblClick; property OnChangeTracking: TNotifyEvent read FOnChangeTracking write FOnChangeTracking; property OnChanged: TNotifyEvent read FOnChanged write FOnChanged; end; [ComponentPlatformsAttribute(fgAllPlatform)] TfgGradientEdit = class (TfgCustomGradientEdit) published property BorderColor; property BorderRadius; property Gradient; property PickerSize; property OnPointAdded; property OnPointClick; property OnPointDblClick; property OnChanged; property OnChangeTracking; { inherited } property Align; property Anchors; property ClipChildren default False; property ClipParent default False; property Cursor default crDefault; property DragMode default TDragMode.dmManual; property EnableDragHighlight default True; property Enabled default True; property Locked default False; property Height; property HitTest default True; property Padding; property Opacity; property Margins; property PopupMenu; property Position; property RotationAngle; property RotationCenter; property Size; property Scale; property TabOrder; property TouchTargetExpansion; property Visible default True; property Width; property OnDragEnter; property OnDragLeave; property OnDragOver; property OnDragDrop; property OnDragEnd; property OnKeyDown; property OnKeyUp; property OnCanFocus; property OnClick; property OnDblClick; property OnEnter; property OnExit; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnMouseWheel; property OnMouseEnter; property OnMouseLeave; property OnPainting; property OnPaint; property OnResize; end; implementation uses System.Math.Vectors, System.SysUtils, System.Math, FMX.Colors, FMX.Types, FGX.Graphics, FGX.Helpers; { TfgCustomGradientEdit } constructor TfgCustomGradientEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); FGradient := TGradient.Create; FGradient.OnChanged := DoGradientChanged; FPickerSize := DEFAULT_PICKER_SIZE; FBorderRadius := DEFAULT_BORDER_RADIUS; FBorderColor := DEFAULT_BORDER_COLOR; FBackgroundBrush := TBrush.Create(TBrushKind.Bitmap, TAlphaColorRec.Null); MakeChessBoardBrush(FBackgroundBrush.Bitmap, 10); AutoCapture := True; SetAcceptsControls(False); end; destructor TfgCustomGradientEdit.Destroy; begin FreeAndNil(FBackgroundBrush); FreeAndNil(FGradient); inherited Destroy;; end; procedure TfgCustomGradientEdit.DoGradientChanged(Sender: TObject); begin Repaint; end; procedure TfgCustomGradientEdit.DoPointAdded(AGradientPoint: TGradientPoint); begin Assert(AGradientPoint <> nil); if Assigned(FOnPointAdded) then FOnPointAdded(Self, AGradientPoint); end; procedure TfgCustomGradientEdit.DoPointDblClick(const AGradientPoint: TGradientPoint); begin Assert(AGradientPoint <> nil); if Assigned(FOnPointDblClick) then FOnPointDblClick(Self, AGradientPoint); end; procedure TfgCustomGradientEdit.DoPointClick(const AGradientPoint: TGradientPoint); begin Assert(AGradientPoint <> nil); if Assigned(FOnPointClick) then FOnPointClick(Self, AGradientPoint); end; procedure TfgCustomGradientEdit.DrawBackground; var GradientRect: TRectF; begin GradientRect := GetGradientFieldSize; Canvas.FillRect(GradientRect, BorderRadius, BorderRadius, AllCorners, AbsoluteOpacity, FBackgroundBrush); end; procedure TfgCustomGradientEdit.DrawGradient; var GradientRect: TRectF; begin GradientRect := GetGradientFieldSize; Canvas.Fill.Kind := TBrushKind.Gradient; Canvas.Fill.Gradient.Assign(FGradient); Canvas.Fill.Gradient.Style := TGradientStyle.Linear; Canvas.Fill.Gradient.StartPosition.SetPointNoChange(TPointF.Create(0, 0)); Canvas.Fill.Gradient.StopPosition.SetPointNoChange(TPointF.Create(1, 0)); Canvas.FillRect(GradientRect, BorderRadius, BorderRadius, AllCorners, AbsoluteOpacity); Canvas.Stroke.Color := BorderColor; Canvas.Stroke.Kind := TBrushKind.Solid; Canvas.DrawRect(RoundToPixel(GradientRect), BorderRadius, BorderRadius, AllCorners, AbsoluteOpacity); end; procedure TfgCustomGradientEdit.DrawPoint(const AIndex: Integer; const ASelected: Boolean = False); var Outline: array of TPointF; SelectedTriangle: TPolygon; FillRect: TRectF; begin Assert(InRange(AIndex, 0, FGradient.Points.Count - 1)); Canvas.Stroke.Color := BorderColor; Canvas.StrokeThickness := 1; Canvas.Stroke.Kind := TBrushKind.Solid; Canvas.Fill.Kind := TBrushKind.Solid; // Вычисляем опорные точки контура SetLength(Outline, 5); Outline[0] := TPointF.Create(FGradient.Points[AIndex].Offset * (Width - PickerSize) + PickerSize / 2, Height - PickerSize * 1.5); Outline[1] := Outline[0] + PointF(PickerSize / 2, PickerSize / 2); Outline[2] := Outline[0] + PointF(PickerSize / 2, 3 * PickerSize / 2); Outline[3] := Outline[0] + PointF(-PickerSize / 2, 3 * PickerSize / 2); Outline[4] := Outline[0] + PointF(-PickerSize / 2, PickerSize / 2); // Заполняем контур Canvas.Fill.Color := TAlphaColorRec.White; Canvas.FillPolygon(TPolygon(Outline), 1); // Рисуем контур Canvas.DrawLine(RoundToPixel(Outline[0]), RoundToPixel(Outline[1]), Opacity); Canvas.DrawLine(RoundToPixel(Outline[1]), RoundToPixel(Outline[2]), Opacity); Canvas.DrawLine(RoundToPixel(Outline[2]), RoundToPixel(Outline[3]), Opacity); Canvas.DrawLine(RoundToPixel(Outline[3]), RoundToPixel(Outline[4]), Opacity); Canvas.DrawLine(RoundToPixel(Outline[4]), RoundToPixel(Outline[0]), Opacity); Canvas.DrawLine(RoundToPixel(Outline[1]), RoundToPixel(Outline[4]), Opacity); if ASelected then begin SetLength(SelectedTriangle, 3); SelectedTriangle[0] := Outline[0]; SelectedTriangle[1] := Outline[1]; SelectedTriangle[2] := Outline[4]; Canvas.Fill.Color := TAlphaColorRec.Gray; Canvas.FillPolygon(SelectedTriangle, 1); end; // Закрашиваем цвет опорной точки градиента Canvas.Fill.Color := FGradient.Points[AIndex].Color; FillRect := TRectF.Create(Outline[4].X + 1, Outline[4].Y + 1, Outline[2].X - 2, Outline[2].Y - 2); Canvas.FillRect(FillRect, 0, 0, AllCorners, Opacity); end; function TfgCustomGradientEdit.FindPointAtPoint(const APoint: TPointF; var AIndex: Integer): Boolean; var I: Integer; Found: Boolean; Offset: Extended; begin I := 0; Found := False; while (I < FGradient.Points.Count) and not Found do begin Offset := FGradient.Points[I].Offset * GetGradientFieldSize.Width; if InRange(APoint.X - PickerSize / 2, Offset - PickerSize / 2, Offset + PickerSize / 2) then begin AIndex := I; Found := True; end else Inc(I); end; Result := Found; end; function TfgCustomGradientEdit.GetDefaultSize: TSizeF; begin Result := TSizeF.Create(100, 35); end; function TfgCustomGradientEdit.GetGradientFieldSize: TRectF; begin Result := TRectF.Create(PickerSize / 2, 0, Width - PickerSize / 2, Height - 1.25 * PickerSize); end; function TfgCustomGradientEdit.IsBorderRadiusStored: Boolean; begin Result := not SameValue(BorderRadius, DEFAULT_BORDER_RADIUS, EPSILON_SINGLE); end; function TfgCustomGradientEdit.IsPickerSizeStored: Boolean; begin Result := not SameValue(PickerSize, DEFAULT_PICKER_SIZE, EPSILON_SINGLE); end; procedure TfgCustomGradientEdit.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); var PointIndex: Integer; NewGradientPoint: TGradientPoint; Offset: Extended; PointColor: TAlphaColor; begin inherited MouseDown(Button, Shift, X, Y); FIsPointMoving := False; FGradientChanged := False; if FindPointAtPoint(TPointF.Create(X, Y), PointIndex) then begin FIsPointMoving := True; FSelectedPoint := FGradient.Points[PointIndex]; if ssDouble in shift then DoPointDblClick(FSelectedPoint) else DoPointClick(FSelectedPoint); end else begin if InRange(Y, 0, GetGradientFieldSize.Height) then begin X := X - PickerSize / 2; // Normalizating X Offset := EnsureRange(X / GetGradientFieldSize.Width, 0, 1); PointColor := FGradient.InterpolateColor(Offset); { Create new gradient point } NewGradientPoint := Gradient.Points.Add as TGradientPoint; NewGradientPoint.Offset := Offset; NewGradientPoint.IntColor := PointColor; UpdateGradientPointsOrder(NewGradientPoint); FSelectedPoint := NewGradientPoint; FIsPointMoving := True; DoPointAdded(FSelectedPoint); DoChangeTracking; end; end; Repaint; end; procedure TfgCustomGradientEdit.MouseMove(Shift: TShiftState; X, Y: Single); var NewOffset: Extended; TmpPoint: TGradientPoint; begin inherited MouseMove(Shift, X, Y); if (FSelectedPoint <> nil) and Pressed and IsPointMoving then begin X := X - PickerSize / 2; // We return gradient point to field, if we move point into control frame if (Y <= Height) and (FSelectedPoint.Collection = nil) then FSelectedPoint.Collection := FGradient.Points; if (Y <= Height) and (FGradient.Points.Count >= 2) or (FGradient.Points.Count = 2) and (FSelectedPoint.Collection <> nil) then begin // We move gradient point NewOffset := X / GetGradientFieldSize.Width; NewOffset := EnsureRange(NewOffset, 0, 1); FSelectedPoint.Offset := NewOffset; UpdateGradientPointsOrder(FSelectedPoint); Repaint; end else begin // We remove gradient point if FGradient.Points.Count > 2 then begin TmpPoint := TGradientPoint.Create(nil); TmpPoint.Assign(FSelectedPoint); if FSelectedPoint.Collection <> nil then begin FGradient.Points.Delete(FSelectedPoint.Index); Repaint; end; FSelectedPoint := TmpPoint; end; end; Cursor := crDefault; DoChangeTracking; end else begin if GetGradientFieldSize.Contains(PointF(X, Y)) then Cursor := crHandPoint else Cursor := crDefault; end; end; procedure TfgCustomGradientEdit.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin inherited MouseUp(Button, Shift, X, Y); // If we manualy remove selected point, we should dispose of memory if (FSelectedPoint <> nil) and (FSelectedPoint.Collection = nil) then begin FSelectedPoint.Free; FSelectedPoint := nil; end; if FGradientChanged then DoChanged; FGradientChanged := False; FIsPointMoving := False; end; procedure TfgCustomGradientEdit.DoChanged; begin if Assigned(FOnChanged) then FOnChanged(Self); end; procedure TfgCustomGradientEdit.DoChangeTracking; begin FGradientChanged := True; if Assigned(FOnChangeTracking) then FOnChangeTracking(Self); end; procedure TfgCustomGradientEdit.Paint; procedure DrawPoints; var I: Integer; begin for I := 0 to FGradient.Points.Count - 1 do DrawPoint(I, (FSelectedPoint <> nil) and (FSelectedPoint.Index = I)); end; begin DrawBackground; DrawGradient; DrawPoints; end; function TfgCustomGradientEdit.Selected: Boolean; begin Result := FSelectedPoint <> nil; end; procedure TfgCustomGradientEdit.SetBorderColor(const Value: TAlphaColor); begin if BorderColor <> Value then begin FBorderColor := Value; Repaint; end; end; procedure TfgCustomGradientEdit.SetBorderRadius(const Value: Single); begin if not SameValue(BorderRadius, Value, EPSILON_SINGLE) then begin FBorderRadius := Value; Repaint; end; end; procedure TfgCustomGradientEdit.SetGradient(const Value: TGradient); begin Assert(Value <> nil); FGradient.Assign(Value); end; procedure TfgCustomGradientEdit.SetPickerSize(const Value: Single); begin if not SameValue(PickerSize, Value, EPSILON_SINGLE) then begin FPickerSize := Value; Repaint; end; end; procedure TfgCustomGradientEdit.UpdateGradientPointsOrder(APoint: TGradientPoint); var I: Integer; Found: Boolean; PointsCount: Integer; OldPointIndex: Integer; begin Assert(FGradient <> nil); Assert(APoint <> nil); Assert(APoint.Collection = FGradient.Points); I := 0; Found := False; PointsCount := Gradient.Points.Count; OldPointIndex := APoint.Index; while (I < PointsCount) and not Found do if (I <> OldPointIndex) and (APoint.Offset <= Gradient.Points[I].Offset) then Found := True else Inc(I); // If we found a new position, which differs from old position, we set new if I - 1 <> OldPointIndex then APoint.Index := IfThen(Found, I, PointsCount - 1); Assert((APoint.Index = 0) and (APoint.Offset <= FGradient.Points[1].Offset) or (APoint.Index = PointsCount - 1) and (FGradient.Points[PointsCount - 1].Offset <= APoint.Offset) or InRange(APoint.Index, 1, PointsCount - 2) and InRange(APoint.Offset, FGradient.Points[APoint.Index - 1].Offset, FGradient.Points[APoint.Index + 1].Offset), 'UpdateGradientPointsOrder returned wrong point order'); end; initialization RegisterFmxClasses([TfgCustomGradientEdit, TfgGradientEdit]); end.