text
stringlengths
14
6.51M
{$i deltics.interfacedobjects.inc} unit Deltics.InterfacedObjects; interface uses Classes, Deltics.InterfacedObjects.ObjectLifecycle, Deltics.InterfacedObjects.Interfaces.IInterfacedObject, Deltics.InterfacedObjects.Interfaces.IInterfacedObjectList, Deltics.InterfacedObjects.ComInterfacedObject, Deltics.InterfacedObjects.ComInterfacedPersistent, Deltics.InterfacedObjects.InterfacedObject, Deltics.InterfacedObjects.InterfacedObjectList, Deltics.InterfacedObjects.InterfacedPersistent, Deltics.InterfacedObjects.InterfaceReference, Deltics.InterfacedObjects.WeakInterfaceReference; type IInterfaceList = Classes.IInterfaceList; TInterfaceList = Classes.TInterfaceList; IInterfacedObject = Deltics.InterfacedObjects.Interfaces.IInterfacedObject.IInterfacedObject; IInterfacedObjectList = Deltics.InterfacedObjects.Interfaces.IInterfacedObjectList.IInterfacedObjectList; TComInterfacedObject = Deltics.InterfacedObjects.ComInterfacedObject.TComInterfacedObject; TComInterfacedPersistent = Deltics.InterfacedObjects.ComInterfacedPersistent.TComInterfacedPersistent; TInterfacedObject = Deltics.InterfacedObjects.InterfacedObject.TInterfacedObject; TInterfacedPersistent = Deltics.InterfacedObjects.InterfacedPersistent.TInterfacedPersistent; TInterfaceReference = Deltics.InterfacedObjects.InterfaceReference.TInterfaceReference; TWeakInterfaceReference = Deltics.InterfacedObjects.WeakInterfaceReference.TWeakInterfaceReference; TInterfacedObjectList = Deltics.InterfacedObjects.InterfacedObjectList.TInterfacedObjectList; type TObjectLifecycle = Deltics.InterfacedObjects.ObjectLifecycle.TObjectLifecycle; const olExplicit = Deltics.InterfacedObjects.ObjectLifecycle.olExplicit; olReferenceCounted = Deltics.InterfacedObjects.ObjectLifecycle.olReferenceCounted; function GetReferenceCount(const aInterface: IInterface): Integer; function InterfaceCast(const aInterface: IUnknown; const aIID: TGuid; var ref): Boolean; overload; function InterfaceCast(const aInterface: IUnknown; const aClass: TClass; var ref): Boolean; overload; implementation uses SysUtils; function GetReferenceCount(const aInterface: IInterface): Integer; var io: IInterfacedObject; begin if Supports(aInterface, IInterfacedObject, io) then result := io.ReferenceCount else begin aInterface._AddRef; result := aInterface._Release; end; end; function InterfaceCast(const aInterface: IUnknown; const aIID: TGuid; var ref): Boolean; begin result := Supports(aInterface, aIID, ref); end; function InterfaceCast(const aInterface: IUnknown; const aClass: TClass; var ref): Boolean; var objRef: TObject absolute ref; intf: IInterfacedObject; begin objRef := NIL; result := Supports(aInterface, IInterfacedObject, intf); result := result and (intf.AsObject is aClass); if result then objRef := intf.AsObject; end; end.
{*************************************************************************** * * Orion-project.org Lazarus Helper Library * Copyright (C) 2016-2017 by Nikolay Chunosov * * This file is part of the Orion-project.org Lazarus Helper Library * https://github.com/Chunosov/orion-lazarus * * This Library is free software: you can redistribute it and/or modify it * under the terms of the MIT License. See enclosed LICENSE.txt for details. * ***************************************************************************} unit OriCombos; interface uses Messages, SysUtils, Types, Classes, Controls, Graphics, StdCtrls; type TOriComboLook = (oclDefault, oclFlat); TOriComboBox = class(TComboBox) private FDroppedWidth: Integer; FLook: TOriComboLook; procedure SetLook(Value: TOriComboLook); procedure WMPaint(var Message: TWMPaint); message WM_PAINT; protected procedure CreateWnd; override; procedure Loaded; override; public procedure CalcDroppedWidth; published property DroppedWidth: Integer read FDroppedWidth write FDroppedWidth default 0; property Look: TOriComboLook read FLook write SetLook default oclDefault; property Align; end; (* { TCustomOriComboMRU } // this class implements a stack for keeping track of // most recently used items in the ComboBox TComboBoxMRUList = class protected FMaxItems : Integer; // maximum items to keep FList : TOriStrings; // the items themselves procedure SetMaxItems(Value: Integer); public constructor Create; destructor Destroy; override; procedure Clear; procedure Shrink; procedure NewItem(const Item: TOriString; Obj: TObject); function RemoveItem(const Item: TOriString) : Boolean; property Items: TOriStrings read FList; property MaxItems: Integer read FMaxItems write SetMaxItems; end; TOriComboStyle = (ocsDropDown, ocsDropDownList); TOriComboBoxMRU = class(TOriComboBoxBase) protected FDrawingEdit : Boolean; FDroppedWidth : Integer; FItemHeight : Integer; // hides inherited property FMRUListColor : TColor; FStyle : TOriComboStyle; FLook : TOriComboLook; // internal variables FMRUList : TComboBoxMRUList; FList : TOriStrings; // Items sans MRU Items, Fill in GetList protected // property methods procedure SetDroppedWidth(Value: Integer); procedure SetItemHeight(Value: Integer); reintroduce; function GetListIndex: Integer; procedure SetListIndex(Value: Integer); function GetList: TOriStrings; function GetMRUList: TOriStrings; function GetMRUListCount: Integer; procedure SetMRUListCount(Value: Integer); procedure SetComboStyle(Value: TOriComboStyle); procedure SetLook(Value: TOriComboLook); // internal methods procedure UpdateMRUList; procedure UpdateMRUListModified; procedure MRUListUpdate(Count : Integer); procedure CNCommand(var Message: TWmCommand); message CN_COMMAND; procedure CNDrawItem(var Msg: TWMDrawItem); message CN_DRAWITEM; procedure WMMeasureItem(var Message: TMessage); message WM_MEASUREITEM; procedure WMPaint(var Message: TWMPaint); message WM_PAINT; procedure CreateParams(var Params : TCreateParams); override; procedure CreateWindowHandle(const Params: TCreateParams); override; procedure DoExit; override; procedure DrawItem(Index: Integer; ItemRect: TRect; State: TOwnerDrawState); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function AddItem(const Item: TOriString; AObject: TObject): Integer; reintroduce; procedure AssignItems(Source: TPersistent); procedure ClearItems; procedure InsertItem(Index: Integer; const Item: TOriString; AObject: TObject); procedure RemoveItem(const Item: TOriString); procedure AddItemToMRUList(Index: Integer); procedure ClearMRUList; property DrawingEdit: Boolean read FDrawingEdit; property List: TOriStrings read GetList; property ListIndex: Integer read GetListIndex write SetListIndex; property MRUList: TOriStrings read GetMRUList; published property Style: TOriComboStyle read FStyle write SetComboStyle default ocsDropDown; property DroppedWidth: Integer read FDroppedWidth write SetDroppedWidth default 0; property ItemHeight: Integer read FItemHeight write SetItemHeight default 18; property MRUListColor: TColor read FMRUListColor write FMRUListColor default clWindow; property MRUListCount: Integer read GetMRUListCount write SetMRUListCount default 3; property Look: TOriComboLook read FLook write SetLook default oclDefault; property Align; end; procedure LoadComboMRUList(ACombo: TOriComboBoxMRU; const MRUString: String); type { TOriFontComboBox } TFontCategories = (fcAll, fcTrueType, fcDevice); TFontPitches = (fpAll, fpFixed, fpVariable); TOriFontComboBox = class(TOriComboBoxMRU) protected // property variables FPreviewFont : Boolean; // If True, fonts are previewed on list FCategories : TFontCategories; // Categories to list FPitchStyles : TFontPitches; // Pitches to list FPreviewControl : TControl; // Control used to preview font FListFontSize : Integer; // internal variables fcTTBitmap : TBitmap; // TrueType bitmap fcDevBitmap : TBitmap; // Device font bitmap // property methods function GetFontName: TOriString; procedure SetFontName(const FontName: TOriString); procedure SetPreviewControl(Value: TControl); // vcl message methods procedure CMFontChange(var Message: TMessage); message CM_FONTCHANGE; protected procedure Change; override; procedure DrawItem(Index: Integer; ItemRect: TRect; State: TOwnerDrawState); override; procedure Loaded; override; procedure Notification(Component: TComponent; Operation: TOperation); override; procedure DoPreview; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Populate; published property FontName: TOriString read GetFontName write SetFontName; property FontCategories: TFontCategories read FCategories write FCategories default fcAll; property FontPitchStyles: TFontPitches read FPitchStyles write FPitchStyles default fpAll; property PreviewControl: TControl read FPreviewControl write SetPreviewControl; property PreviewFont: Boolean read FPreviewFont write FPreviewFont default False; property ListFontSize: Integer read FListFontSize write FListFontSize; end; *) implementation //{$R *.res} //uses //Printers, //OriGraphics; const ButtonWidth = 18; procedure TOriComboBox.CreateWnd; begin inherited; CalcDroppedWidth; end; procedure TOriComboBox.Loaded; begin inherited; CalcDroppedWidth; end; procedure TOriComboBox.CalcDroppedWidth; var I, MaxW, W: Integer; C: TControlCanvas; begin if FDroppedWidth = 0 then begin MaxW := 0; C := TControlCanvas.Create; try C.Control := Self; C.Font.Assign(Font); for I := 0 to Items.Count - 1 do begin W := C.GetTextWidth(Items[I]); if W > MaxW then MaxW := W; end; finally C.Free; end; Inc(MaxW, 8); if Items.Count > DropDownCount then Inc(MaxW, GetSystemMetrics(SM_CXVSCROLL)); end else MaxW := FDroppedWidth; if MaxW > Width then SendMessage(Handle, CB_SETDROPPEDWIDTH, MaxW, 0); end; procedure TOriComboBox.SetLook(Value: TOriComboLook); begin if Value <> FLook then begin FLook := Value; Invalidate; end; end; procedure TOriComboBox.WMPaint(var Message: TWMPaint); var R: TRect; begin inherited; case FLook of // TODO: в стиле csDropDownList рисовать как кнопку со стрелкой oclFlat: with TControlCanvas.Create do try Control := Self; Lock; R := ClientRect; ExcludeClipRect(Handle, 2, 2, R.Right - 2 - ButtonWidth, R.Bottom - 2); if Enabled then Brush.Color := clWindow else Brush.Color := clBtnFace; Brush.Style := bsSolid; Pen.Color := clBtnShadow; Pen.Style := psSolid; Rectangle(R); R.Left := R.Right - ButtonWidth; R.Top := R.Top + 2; R.Bottom := R.Bottom - 2; R.Right := R.Right - 2; if Enabled then DrawFrameControl(Handle, R, DFC_SCROLL, DFCS_FLAT or DFCS_SCROLLCOMBOBOX) else DrawFrameControl(Handle, R, DFC_SCROLL, DFCS_FLAT or DFCS_SCROLLCOMBOBOX or DFCS_INACTIVE); finally Unlock; Free; end; end; end; (* //------------------------------------------------------------------------------ { TComboBoxMRUList } constructor TComboBoxMRUList.Create; begin FList := TOriStringList.Create; FMaxItems := 3; end; destructor TComboBoxMRUList.Destroy; begin FList.Free; inherited; end; procedure TComboBoxMRUList.NewItem(const Item: TOriString; Obj: TObject); var Index: Integer; begin Index := FList.IndexOf(Item); if Index > -1 then begin // If the item is already in the list, just bring it to the top FList.Delete(Index); FList.InsertObject(0, Item, Obj); end else begin FList.InsertObject(0, Item, Obj); // this may result in more items in the list than are allowed, // but a call to Shrink will remove the excess items Shrink; end; end; function TComboBoxMRUList.RemoveItem(const Item: TOriString) : Boolean; var Index : Integer; begin Index := FList.IndexOf(Item); Result := Index > -1; if Result then FList.Delete(Index); end; procedure TComboBoxMRUList.Shrink; begin while FList.Count > FMaxItems do FList.Delete(FList.Count - 1); end; procedure TComboBoxMRUList.Clear; begin FList.Clear; end; procedure TComboBoxMRUList.SetMaxItems(Value: Integer); begin FMaxItems := Value; Shrink; end; //------------------------------------------------------------------------------ { TCustomOriComboMRU } procedure LoadComboMRUList(ACombo: TOriComboBoxMRU; const MRUString: String); var strs: TStrings; i, index: Integer; begin strs := TStringList.Create; try strs.DelimitedText := MRUString; for i := strs.Count-1 downto 0 do begin index := ACombo.Items.IndexOf(strs[i]); if index <> -1 then ACombo.AddItemToMRUList(index); end; finally strs.Free; end; end; const cbxSeparatorHeight = 3; constructor TOriComboBoxMRU.Create(AOwner : TComponent); begin inherited; FItemHeight := 18; FList := TOriStringList.Create; FMRUList := TComboBoxMRUList.Create; FMRUList.MaxItems := 3; FDroppedWidth := 0; FMRUListColor := clWindow; end; procedure TOriComboBoxMRU.CreateWindowHandle(const Params: TCreateParams); begin inherited; DroppedWidth := FDroppedWidth; end; procedure TOriComboBoxMRU.CreateParams(var Params: TCreateParams); begin inherited; case FStyle of ocsDropDown: Params.Style := Params.Style or CBS_DROPDOWN or CBS_OWNERDRAWVARIABLE; ocsDropDownList: Params.Style := Params.Style or CBS_DROPDOWNLIST or CBS_OWNERDRAWVARIABLE; end; end; destructor TOriComboBoxMRU.Destroy; begin FreeAndNil(FMRUList); FreeAndNil(FList); inherited; end; procedure TOriComboBoxMRU.ClearItems; begin ClearMRUList; if HandleAllocated then Clear; end; procedure TOriComboBoxMRU.ClearMRUList; var I: Integer; begin if (FMRUList.Items.Count > 0) then begin for I := 1 to FMRUList.Items.Count do if (I <= Items.Count) then Items.Delete(0); FMRUList.Clear; end; end; // возвращает список строк без MRU-листа function TOriComboBoxMRU.GetList: TOriStrings; var I : Integer; begin FList.Clear; FList.Assign(Items); if FMRUList.Items.Count > 0 then for I := 0 to Pred(FMRUList.Items.Count) do FList.Delete(0); Result := FList; end; // возвращает спиок строк MRU-листа function TOriComboBoxMRU.GetMRUList: TOriStrings; begin Result := FMRUList.FList; end; // Value is the index into the list sans MRU items procedure TOriComboBoxMRU.SetListIndex(Value: Integer); var I: Integer; begin I := FMRUList.Items.Count; if (((Value + I) < Items.Count) and (Value >= 0)) then ItemIndex := Value + I else ItemIndex := -1; end; // Translates ItemIndex into index sans MRU Items function TOriComboBoxMRU.GetListIndex; begin Result := ItemIndex - FMRUList.Items.Count; end; procedure TOriComboBoxMRU.AssignItems(Source: TPersistent); begin Clear; Items.Assign(Source); end; function TOriComboBoxMRU.AddItem(const Item: TOriString; AObject: TObject): Integer; begin Result := -1; if (Items.IndexOf(Item) < 0) then begin Result := Items.AddObject(Item, AObject) - FMRUList.Items.Count; UpdateMRUList; end; end; procedure TOriComboBoxMRU.InsertItem(Index: Integer; const Item: TOriString; AObject: TObject); var I: Integer; begin I := FMRUList.Items.Count; if (Index> -1) and (Index < (Items.Count - I)) then begin Items.InsertObject(Index + I, Item, AObject); UpdateMRUList; end; end; procedure TOriComboBoxMRU.RemoveItem(const Item: TOriString); var I: Integer; begin if FMRUList.RemoveItem(Item) then UpdateMRUListModified; I := Items.IndexOf(Item); if (I > -1) then begin if ItemIndex = I then Text := ''; Items.Delete(I); UpdateMRUList; end; end; procedure TOriComboBoxMRU.AddItemToMRUList(Index: Integer); var I : Integer; begin I := FMRUList.Items.Count; if (I > -1) and (Index > -1) then begin FMRUList.NewItem(Items[Index], Items.Objects[Index]); if FMRUList.Items.Count > I then Items.InsertObject(0, Items[Index], Items.Objects[Index]); end; end; procedure TOriComboBoxMRU.UpdateMRUList; begin MRUListUpdate(FMRUList.Items.Count); end; // Use this to update MRUList after removing item from MRUList procedure TOriComboBoxMRU.UpdateMRUListModified; begin MRUListUpdate(FMRUList.Items.Count + 1); end; // удаляет из начала спика строки в количестве Count и вставляет туда MRU-лист procedure TOriComboBoxMRU.MRUListUpdate(Count: Integer); var I: Integer; Txt: TOriString; begin Txt := Text; // the first items are part of the MRU list if Count > 0 then for I := 1 to Count do Items.Delete(0); // make sure the MRU list is limited to its maximum size FMRUList.Shrink; if FMRUList.Items.Count > 0 then begin // add the MRU list items to the beginning of the combo list for I := Pred(FMRUList.Items.Count) downto 0 do Items.InsertObject(0, FMRUList.Items[I], FMRUList.Items.Objects[I]); // this is necessary because we are always inserting item 0 and Windows // thinks that it knows the height of all other items, so it only sends // a WM_MEASUREITEM for item 0. We need the last item of the MRU list // to be taller so we can draw a separator under it // При выставлении высоты одного элемента отличной от высоты остальных // возникает странный эффект: если подвести курсор к последнему видимому // элементу списка, то список проматывается на несколько элементов вниз. // Иногда это происходит один раз, а иногда, дергая мышь вниз-вверх над // последними видимыми элементами можно мотать до самого конца списка. // При ItemHeight = 18 и стандартном 8 шрифте разделитель смотрится // нормально и без дополнительной высоты элемента. //SendMessage(Handle, CB_SETITEMHEIGHT, wParam(FMRUList.Items.Count-1), lParam(FItemHeight+cbxSeparatorHeight)); end; ItemIndex := {$IFDEF USE_UNICODE}SendMessageW{$ELSE}SendMessage{$ENDIF} (Handle, CB_FINDSTRINGEXACT, FMRUList.Items.Count-1, LongInt(POriChar(Txt))); end; procedure TOriComboBoxMRU.CNDrawItem(var Msg: TWMDrawItem); begin // gather flag information that Borland left out FDrawingEdit := (ODS_COMBOBOXEDIT and Msg.DrawItemStruct.itemState) <> 0; inherited; end; procedure TOriComboBoxMRU.CNCommand(var Message: TWmCommand); begin if Message.NotifyCode = CBN_CLOSEUP then if ItemIndex > -1 then begin Text := Items[ItemIndex]; AddItemToMRUList(ItemIndex); UpdateMRUList; Click; end; inherited; end; procedure TOriComboBoxMRU.DoExit; begin AddItemToMRUList(ItemIndex); inherited DoExit; end; procedure TOriComboBoxMRU.DrawItem(Index: Integer; ItemRect: TRect; State: TOwnerDrawState); var SepRect : TRect; TxtRect : TRect; BkMode : Integer; begin with Canvas do begin if not (odSelected in State) then Brush.Color := clHighlight else if (FMRUList.Items.Count > 0) and (Index < FMRUList.Items.Count) then Brush.Color := FMRUListColor else Brush.Color := Color; FillRect(ItemRect); with ItemRect do TxtRect := Rect(Left + 2, Top, Right, Bottom); BkMode := SetBkMode(Canvas.Handle, TRANSPARENT); {$IFDEF USE_UNICODE}DrawTextW{$ELSE}DrawText{$ENDIF} (Canvas.Handle, POriChar(Items[Index]), Length(Items[Index]), TxtRect, DT_VCENTER or DT_LEFT); SetBkMode(Canvas.Handle, BkMode); if (FMRUList.Items.Count > 0) // draw separator between MRU and items and (Index = FMRUList.Items.Count - 1) and DroppedDown then begin SepRect := ItemRect; SepRect.Top := SepRect.Bottom - cbxSeparatorHeight; Pen.Color := clGrayText; if not DrawingEdit then with SepRect do Rectangle(Left-1, Top, Right+1, Bottom); end; end; end; procedure TOriComboBoxMRU.SetDroppedWidth(Value : Integer); begin if HandleAllocated then SendMessage(Handle, CB_SETDROPPEDWIDTH, Value, 0); FDroppedWidth := Value; end; function TOriComboBoxMRU.GetMRUListCount: Integer; begin Result := FMRUList.MaxItems; end; procedure TOriComboBoxMRU.SetMRUListCount(Value: Integer); begin if ([csDesigning, csLoading] * ComponentState) = [] then ClearMRUList; FMRUList.MaxItems := Value; end; procedure TOriComboBoxMRU.SetComboStyle(Value: TOriComboStyle); begin if Value <> FStyle then begin FStyle := Value; RecreateWnd; end; end; procedure TOriComboBoxMRU.SetItemHeight(Value : Integer); begin if Value <> FItemHeight then begin FItemHeight := Value; RecreateWnd; end; end; procedure TOriComboBoxMRU.WMMeasureItem(var Message : TMessage); begin with (PMeasureItemStruct(Message.lParam))^ do begin ItemWidth := ClientWidth; ItemHeight := FItemHeight; end; end; procedure TOriComboBoxMRU.WMPaint(var Message: TWMPaint); var R: TRect; begin inherited; // плоская отрисовка иммеет смысл тольк когда BevelKind = bvNone, тогда // в inherited выполняется только Paint от TWinControl'а. Если BevelKind <> bvNone // тогда в в inherited сначала отрисуется соответствующий bevel, и потом внутри // него плоская отрисовка (почему внутри (D10) непонятно - то ли при установке // bevel'а client-rect сужается) case FLook of oclFlat: with TControlCanvas.Create do try Control := Self; Lock; R := ClientRect; ExcludeClipRect(Handle, 2, 2, R.Right - 2 - ButtonWidth, R.Bottom - 2); if Enabled then Brush.Color := clWindow else Brush.Color := clBtnFace; Brush.Style := bsSolid; Pen.Color := clBtnShadow; Pen.Style := psSolid; Rectangle(R); R.Left := R.Right - ButtonWidth; R.Top := R.Top + 2; R.Bottom := R.Bottom - 2; R.Right := R.Right - 2; if Enabled then DrawFrameControl(Handle, R, DFC_SCROLL, DFCS_FLAT or DFCS_SCROLLCOMBOBOX) else DrawFrameControl(Handle, R, DFC_SCROLL, DFCS_FLAT or DFCS_SCROLLCOMBOBOX or DFCS_INACTIVE); finally Unlock; Free; end; end; end; procedure TOriComboBoxMRU.SetLook(Value: TOriComboLook); begin if Value <> FLook then begin FLook := Value; Invalidate; end; end; //------------------------------------------------------------------------------ { TOriFontComboBox } // callback used by FontIsSymbol() {function GetFontCharSet(lpLF : PLogFont; lpTM : PTextMetric; FontType : Integer; lParam : LongInt): Integer; far; stdcall; begin PByte(lParam)^ := lpLF^.lfCharSet; Result := 0; end;} // font family enumeration callbacks function EnumFontFamProc(lpLF: PEnumLogFont; lpTM: PNewTextMetric; FontType: Integer; lParam: LongInt) : Integer; far; stdcall; var FontCombo : TOriFontComboBox; Bitmap : TBitmap; begin FontCombo := TOriFontComboBox(lParam); with FontCombo do begin // Filter fonts according to properties if (FontType and TRUETYPE_FONTTYPE = TRUETYPE_FONTTYPE) then begin Bitmap := fcTTBitmap; if (FontCategories in [fcAll, fcTrueType]) then begin if ((lpLF^.elfLogFont.lfPitchAndFamily and VARIABLE_PITCH = VARIABLE_PITCH) and (FontPitchStyles in [fpAll, fpVariable])) or ((lpLF^.elfLogFont.lfPitchAndFamily and FIXED_PITCH = FIXED_PITCH) and (FontPitchStyles in [fpAll, fpFixed])) then if Items.IndexOf(lpLF^.elfLogFont.lfFaceName) = -1 then Items.AddObject(lpLF^.elfLogFont.lfFaceName, Bitmap) end; end else begin Bitmap := fcDevBitmap; if (FontCategories in [fcAll, fcDevice]) then begin if ((lpLF^.elfLogFont.lfPitchAndFamily and VARIABLE_PITCH = VARIABLE_PITCH) and (FontPitchStyles in [fpAll, fpVariable])) or ((lpLF^.elfLogFont.lfPitchAndFamily and FIXED_PITCH = FIXED_PITCH) and (FontPitchStyles in [fpAll, fpFixed])) then if Items.IndexOf(lpLF^.elfLogFont.lfFaceName) = -1 then Items.AddObject(lpLF^.elfLogFont.lfFaceName, Bitmap) end; end; end; Result := 1; end; function EnumPrinterFontFamProc(lpLF: PEnumLogFont; lpTM: PNewTextMetric; FontType: Integer; lParam: LongInt): Integer; far; stdcall; var FontCombo : TOriFontComboBox; Bitmap : TBitmap; FaceName : TOriString; begin FontCombo := TOriFontComboBox(lParam); FaceName := lpLF^.elfFullName; with FontCombo do begin if Items.IndexOf(FaceName) > -1 then begin Result := 1; Exit; end; // Filter fonts according to properties if (FontType and TRUETYPE_FONTTYPE = TRUETYPE_FONTTYPE) then begin Bitmap := fcTTBitmap; if (FontCategories in [fcAll, fcTrueType]) then if ((lpLF^.elfLogFont.lfPitchAndFamily and VARIABLE_PITCH = VARIABLE_PITCH) and (FontPitchStyles in [fpAll, fpVariable])) or ((lpLF^.elfLogFont.lfPitchAndFamily and FIXED_PITCH = FIXED_PITCH) and (FontPitchStyles in [fpAll, fpFixed])) then if Items.IndexOf(lpLF^.elfLogFont.lfFaceName) = -1 then Items.AddObject(lpLF^.elfLogFont.lfFaceName, Bitmap) end else begin Bitmap := fcDevBitmap; if (FontCategories in [fcAll, fcDevice]) then if ((lpLF^.elfLogFont.lfPitchAndFamily and VARIABLE_PITCH = VARIABLE_PITCH) and (FontPitchStyles in [fpAll, fpVariable])) or ((lpLF^.elfLogFont.lfPitchAndFamily and FIXED_PITCH = FIXED_PITCH) and (FontPitchStyles in [fpAll, fpFixed])) then if Items.IndexOf(lpLF^.elfLogFont.lfFaceName) = -1 then Items.AddObject(lpLF^.elfLogFont.lfFaceName, Bitmap) end; end; Result := 1; end; { TOriFontComboBox } constructor TOriFontComboBox.Create(AOwner: TComponent); begin inherited; FPreviewFont := False; FCategories := fcAll; FPitchStyles := fpAll; FListFontSize := Font.Size; fcTTBitmap := TBitmap.Create; fcDevBitmap := TBitmap.Create; //FPrinter := Printer(); end; destructor TOriFontComboBox.Destroy; begin fcTTBitmap.Free; fcDevBitmap.Free; inherited; end; procedure TOriFontComboBox.CMFontChange(var Message : TMessage); var Item: string; begin if ItemIndex > -1 then begin Item := Items[ItemIndex]; Populate; ItemIndex := Items.IndexOf(Item); // the selected font is no longer valid if ItemIndex < 0 then Change; end else begin Populate; Change; end; end; type TControlAccess = class(TControl); procedure TOriFontComboBox.DoPreview; begin if (Assigned(FPreviewControl)) and (ItemIndex > - 1) then TControlAccess(FPreviewControl).Font.Name := Items[ItemIndex]; end; procedure TOriFontComboBox.DrawItem(Index: Integer; ItemRect: TRect; State: TOwnerDrawState); var Bitmap : TBitmap; SepRect : TRect; TxtRect : TRect; BmpRect : TRect; BkMode : Integer; aTop : Integer; begin with Canvas do begin if odSelected in State then Brush.Color := clHighlight else if (FMRUList.Items.Count > 0) and (Index < FMRUList.Items.Count) then Brush.Color := FMRUListColor else Brush.Color := Color; FillRect(ItemRect); Bitmap := TBitmap(Items.Objects[Index]); if Assigned(Bitmap) then begin with ItemRect do begin aTop := ((Top+Bottom) div 2) - (Bitmap.Height div 2); BmpRect := Rect(Left+2, aTop, Left+Bitmap.Width+2, aTop+Bitmap.Height); end; BrushCopy(BmpRect, Bitmap, Rect(0, 0, Bitmap.Width, Bitmap.Height), clYellow); end; with ItemRect do TxtRect := Rect(Left+Bitmap.Width+6, Top+1, Right, Bottom); BkMode := SetBkMode(Canvas.Handle, TRANSPARENT); if FPreviewFont then {if Assigned(FPrinter) and (FPrinter.Printers.Count > 0) then begin // Do not draw symbol font names with the actual font - use the default if not FontIsSymbol(Items[Index]) then} Font.Name := Items[Index] {else Font.Name := Self.Font.Name; end}; Font.Size := FListFontSize; {$IFDEF USE_UNICODE}DrawTextW{$ELSE}DrawText{$ENDIF} (Canvas.Handle, POriChar(Items[Index]), Length(Items[Index]), TxtRect, DT_VCENTER or DT_LEFT); SetBkMode(Canvas.Handle, BkMode); if (FMRUList.Items.Count > 0) and (Index = FMRUList.Items.Count - 1) then begin SepRect := ItemRect; SepRect.Top := SepRect.Bottom - cbxSeparatorHeight; Pen.Color := clGrayText; if not DrawingEdit then with SepRect do Rectangle(Left-1, Top, Right+1, Bottom); end; end; end; {function TFontComboBoxAdv.FontIsSymbol(const FontName: TFlatString): Boolean; var CharSet: Byte; DC: hDC; FntStr: array [0..63] of char; begin DC := GetDC(0); CharSet := 0; StrPCopy(FntStr, FontName); try EnumFonts(DC, FntStr, @GetFontCharSet, PChar(@CharSet)); if CharSet = 0 then // It's a printer font EnumFonts(Printer.Handle, FntStr, @GetFontCharSet, PChar(@CharSet)); finally ReleaseDC(0, DC); end; Result := (CharSet = SYMBOL_CHARSET); end;} function TOriFontComboBox.GetFontName: TOriString; begin if ItemIndex > -1 then Result := Items[ItemIndex] else Result := ''; end; procedure TOriFontComboBox.Loaded; begin inherited Loaded; if not (csDesigning in ComponentState) then begin fcTTBitmap.LoadFromResourceName(HInstance, 'TRUETYPEFONT'); fcDevBitmap.LoadFromResourceName(HInstance, 'DEVICEFONT'); Populate; end; end; procedure TOriFontComboBox.Notification(Component: TComponent; Operation: TOperation); begin inherited Notification(Component, Operation); if (Component is TControl) and (Operation = opRemove) then if (Component as TControl) = FPreviewControl then PreviewControl := nil; end; procedure TOriFontComboBox.Populate; var DC : HDC; TempList : TOriStringList; begin Clear; DC := GetDC(0); TempList := TOriStringList.Create; try EnumFontFamilies(DC, nil, @EnumFontFamProc, Integer(Self)); try if (Printer.Printers.Count > 0) and (Printer.Handle > 0) then EnumFontFamilies(Printer.Handle, nil, @EnumPrinterFontFamProc, Integer(Self)); except // при недоступном сетевом принтере возникает ошибка: // EPrinter: Printer selected is not valid end; TempList.Assign(Items); TempList.Sort; Items.Assign(TempList); finally ReleaseDC(0, DC); TempList.Free; end; end; procedure TOriFontComboBox.Change; begin inherited; DoPreview; end; procedure TOriFontComboBox.SetPreviewControl(Value: TControl); begin if Value <> Self then begin FPreviewControl := Value; DoPreview; end; end; procedure TOriFontComboBox.SetFontName(const FontName: TOriString); var I: Integer; begin I := Items.IndexOf(FontName); if I > -1 then ItemIndex := I; end; *) end.
{$mode objfpc} program Parser; uses List, Tokenizer, AST; var toker: Tokenizer.TTokenizer; var toks : Tokenizer.TTokenList; var asTree : AST.TTree; var argi : integer; begin WriteLn('Hi! I''m RG''s parser!'); Write('Original expression: "'); for argi := 1 to ParamCount do begin Write(ParamStr(argi), ' '); end; WriteLn('"'); toker := Tokenizer.TTokenizer.CreateFromArgs; toks := toker.GetTokens; if toks = nil then begin WriteLn('Tokenizing failed. Quitting...'); halt; end; WriteLn('Tokenizing complete. Tokens count: ', toks.GetCount); asTree := AST.TTree.CreateFromTokenList( toks ); asTree.PrintParenthesised; asTree.PrintReversePolish; WriteLn('Bye!'); WriteLn; end.
{ Copyright (C) 2013-2017 Tim Sinaeve tim.sinaeve@gmail.com This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit ts.RichEditor.Manager; {$MODE Delphi} interface uses Classes, SysUtils, FileUtil, ActnList, Dialogs, Menus, Contnrs, Forms, Controls, ts.RichEditor.Interfaces; type TRichEditorViewList = TComponentList; { TdmRichEditorActions } TdmRichEditorActions = class(TDataModule, IRichEditorActions) {$region 'designer controls' /fold} aclActions : TActionList; actBold : TAction; actColor : TAction; actAlignRight : TAction; actAlignLeft : TAction; actAlignCenter: TAction; actFont : TAction; actIncFontSize: TAction; actDecFontSize: TAction; actCut : TAction; actCopy : TAction; actAlignJustify: TAction; actBkColor: TAction; actWordWrap : TAction; actUndo : TAction; actSelectAll : TAction; actPaste : TAction; actSaveAs : TAction; actSave : TAction; actOpen : TAction; actUnderline : TAction; actItalic : TAction; dlgColor : TColorDialog; dlgFont : TFontDialog; dlgOpen : TOpenDialog; dlgSave : TSaveDialog; imlMain : TImageList; MenuItem1: TMenuItem; MenuItem2: TMenuItem; MenuItem3: TMenuItem; MenuItem4: TMenuItem; MenuItem5: TMenuItem; N1 : TMenuItem; mniBold : TMenuItem; mniItalic : TMenuItem; mniUnderline : TMenuItem; mniOpen : TMenuItem; mniSave : TMenuItem; mniSaveAs : TMenuItem; ppmRichEditor : TPopupMenu; {$endregion} procedure actAlignCenterExecute(Sender: TObject); procedure actAlignJustifyExecute(Sender: TObject); procedure actAlignLeftExecute(Sender: TObject); procedure actAlignRightExecute(Sender: TObject); procedure actBkColorExecute(Sender: TObject); procedure actBoldExecute(Sender: TObject); procedure actColorExecute(Sender: TObject); procedure actCopyExecute(Sender: TObject); procedure actCutExecute(Sender: TObject); procedure actDecFontSizeExecute(Sender: TObject); procedure actFontExecute(Sender: TObject); procedure actIncFontSizeExecute(Sender: TObject); procedure actItalicExecute(Sender: TObject); procedure actOpenExecute(Sender: TObject); procedure actPasteExecute(Sender: TObject); procedure actSaveAsExecute(Sender: TObject); procedure actSaveExecute(Sender: TObject); procedure actUnderlineExecute(Sender: TObject); procedure actUndoExecute(Sender: TObject); procedure actWordWrapExecute(Sender: TObject); private FViews : TRichEditorViewList; FActiveView : IRichEditorView; function GetActions: TActionList; function GetActiveView: IRichEditorView; function GetEditorPopupMenu: TPopupMenu; function GetItem(AName: string): TContainedAction; function GetView(AIndex: Integer): IRichEditorView; function GetViewByName(AName: string): IRichEditorView; function GetViewCount: Integer; procedure SetActiveView(const AValue: IRichEditorView); procedure UpdateActions; public procedure AfterConstruction; override; procedure BeforeDestruction; override; procedure OpenFileAtCursor; function SaveFile: Boolean; procedure LoadFile; function AddView(const AName: string = ''; const AFileName: string = '') : IRichEditorView; function DeleteView(AIndex: Integer): Boolean; procedure ClearViews; property Actions: TActionList read GetActions; property ActiveView: IRichEditorView read GetActiveView write SetActiveView; property Items[AName: string]: TContainedAction read GetItem; default; property Views[AIndex: Integer]: IRichEditorView read GetView; property ViewByName[AName: string]: IRichEditorView read GetViewByName; property ViewCount: Integer read GetViewCount; property EditorPopupMenu: TPopupMenu read GetEditorPopupMenu; end; function RichEditorActions : IRichEditorActions; implementation {$R *.lfm} uses Graphics, RichMemo, ts.RichEditor.View; var dmRichEditorActions : TdmRichEditorActions; function RichEditorActions: IRichEditorActions; begin Result := dmRichEditorActions; end; {$region 'construction and destruction' /fold} procedure TdmRichEditorActions.AfterConstruction; begin inherited AfterConstruction; FViews := TRichEditorViewList.Create(False); FActiveView := nil; end; procedure TdmRichEditorActions.BeforeDestruction; begin FActiveView := nil; FreeAndNil(FViews); inherited BeforeDestruction; end; {$endregion} {$region 'property access mehods' /fold} function TdmRichEditorActions.GetActions: TActionList; begin Result := aclActions; end; function TdmRichEditorActions.GetActiveView: IRichEditorView; begin if not Assigned(FActiveView) then raise Exception.Create('No active view!'); Result := FActiveView; end; procedure TdmRichEditorActions.SetActiveView(const AValue: IRichEditorView); begin if AValue <> FActiveView then begin FActiveView := AValue; //ActiveViewUpdated; end; end; function TdmRichEditorActions.GetEditorPopupMenu: TPopupMenu; begin Result := ppmRichEditor; end; function TdmRichEditorActions.GetItem(AName: string): TContainedAction; begin Result := aclActions.ActionByName(AName); end; function TdmRichEditorActions.GetView(AIndex: Integer): IRichEditorView; begin if (AIndex > -1) and (AIndex < FViews.Count) then begin Result := TRichEditorView(FViews[AIndex]) as IRichEditorView; end else Result := nil; end; function TdmRichEditorActions.GetViewByName(AName: string): IRichEditorView; var I: Integer; B: Boolean; begin I := 0; B := False; while (I < FViews.Count) and not B do begin B := FViews[I].Name = AName; if not B then Inc(I); end; if B then Result := FViews[I] as IRichEditorView else Result := nil; end; function TdmRichEditorActions.GetViewCount: Integer; begin Result := FViews.Count; end; {$endregion} {$region 'action handlers' /fold} // File procedure TdmRichEditorActions.actOpenExecute(Sender: TObject); begin if dlgOpen.Execute then begin ActiveView.LoadFromFile(dlgOpen.FileName); ActiveView.FileName := dlgOpen.FileName; end; end; procedure TdmRichEditorActions.actPasteExecute(Sender: TObject); begin ActiveView.Paste; end; procedure TdmRichEditorActions.actSaveAsExecute(Sender: TObject); begin if dlgSave.Execute then begin ActiveView.SaveToFile(dlgSave.FileName); ActiveView.FileName := dlgSave.FileName; end; end; procedure TdmRichEditorActions.actSaveExecute(Sender: TObject); begin ActiveView.SaveToFile(ActiveView.FileName); end; // Style procedure TdmRichEditorActions.actBoldExecute(Sender: TObject); begin if Assigned(ActiveView) then begin ActiveView.TextAttributes.BeginUpdate; ActiveView.TextAttributes.Bold := actBold.Checked; ActiveView.TextAttributes.EndUpdate; end; end; procedure TdmRichEditorActions.actAlignRightExecute(Sender: TObject); begin ActiveView.TextAttributes.Alignment := paRight; end; procedure TdmRichEditorActions.actBkColorExecute(Sender: TObject); begin dlgColor.Width := 300; dlgColor.Handle := Application.MainForm.Handle; if dlgColor.Execute then begin; ActiveView.TextAttributes.HasBkColor := False; ActiveView.TextAttributes.HasBkColor := True; ActiveView.TextAttributes.BkColor := dlgColor.Color; end; end; procedure TdmRichEditorActions.actAlignLeftExecute(Sender: TObject); begin ActiveView.TextAttributes.Alignment := paLeft; end; procedure TdmRichEditorActions.actAlignCenterExecute(Sender: TObject); begin ActiveView.TextAttributes.Alignment := paCenter; end; procedure TdmRichEditorActions.actAlignJustifyExecute(Sender: TObject); begin ActiveView.TextAttributes.Alignment := paJustify; end; procedure TdmRichEditorActions.actColorExecute(Sender: TObject); begin dlgColor.Width := 300; dlgColor.Handle := Application.MainForm.Handle; if dlgColor.Execute then begin; ActiveView.TextAttributes.Color := dlgColor.Color; end; end; procedure TdmRichEditorActions.actCopyExecute(Sender: TObject); begin ActiveView.Copy; end; procedure TdmRichEditorActions.actCutExecute(Sender: TObject); begin ActiveView.Cut; end; procedure TdmRichEditorActions.actDecFontSizeExecute(Sender: TObject); begin if Assigned(ActiveView) then begin if ActiveView.TextAttributes.Size > 0 then ActiveView.TextAttributes.Size := ActiveView.TextAttributes.Size - 1; end; end; procedure TdmRichEditorActions.actFontExecute(Sender: TObject); begin if dlgFont.Execute then begin ActiveView.TextAttributes.BeginUpdate; ActiveView.TextAttributes.FontName := dlgFont.Font.Name; ActiveView.TextAttributes.Size := dlgFont.Font.Size; ActiveView.TextAttributes.EndUpdate; end; end; procedure TdmRichEditorActions.actIncFontSizeExecute(Sender: TObject); begin if Assigned(ActiveView) then begin ActiveView.TextAttributes.Size := ActiveView.TextAttributes.Size + 1; end; end; procedure TdmRichEditorActions.actItalicExecute(Sender: TObject); begin if Assigned(ActiveView) then begin ActiveView.TextAttributes.Italic := actItalic.Checked; end; end; procedure TdmRichEditorActions.actUnderlineExecute(Sender: TObject); begin if Assigned(ActiveView) then begin ActiveView.TextAttributes.Underline := actUnderline.Checked; end; end; procedure TdmRichEditorActions.actUndoExecute(Sender: TObject); begin ActiveView.Editor.Undo; end; procedure TdmRichEditorActions.actWordWrapExecute(Sender: TObject); begin ActiveView.WordWrap := actWordWrap.Checked; end; {$endregion} procedure TdmRichEditorActions.UpdateActions; begin if Assigned(ActiveView) then begin actBold.Checked := ActiveView.TextAttributes.Bold; actUnderline.Checked := ActiveView.TextAttributes.Underline; actItalic.Checked := ActiveView.TextAttributes.Italic; actUndo.Enabled := ActiveView.CanUndo; actCopy.Enabled := ActiveView.SelAvail; actCut.Enabled := ActiveView.SelAvail; actPaste.Enabled := ActiveView.CanPaste; case ActiveView.TextAttributes.Alignment of paLeft : actAlignLeft.Checked := True; paCenter : actAlignCenter.Checked := True; paRight : actAlignRight.Checked := True; paJustify : actAlignJustify.Checked := True; end; end; end; procedure TdmRichEditorActions.OpenFileAtCursor; begin // end; function TdmRichEditorActions.SaveFile: Boolean; begin Result := False; end; procedure TdmRichEditorActions.LoadFile; begin // end; function TdmRichEditorActions.AddView(const AName: string; const AFileName: string): IRichEditorView; var V : TRichEditorView; begin V := TRichEditorView.Create(Self); // if no name is provided, the view will get an automatically generated one. if AName <> '' then V.Name := AName; V.FileName := AFileName; V.Caption := ''; FViews.Add(V); Result := V as IRichEditorView; FActiveView := V; end; function TdmRichEditorActions.DeleteView(AIndex: Integer): Boolean; begin { TODO -oTS : Needs implementation } Result := False; end; procedure TdmRichEditorActions.ClearViews; begin FViews.Clear; end; initialization dmRichEditorActions := TdmRichEditorActions.Create(Application); end.
unit uModel; {$mode objfpc}{$H+} interface uses mORMot, uParty, uProduct, uOrder, uAccounting, uShipment, uMarketing, uWorkEffort, uManufacturing, uHumanres, uCommon, uContent, uSecurity, uService; //Classes, SysUtils; const ROOT_NAME_PARTY = 'party'; ROOT_NAME_PRODUCT = 'product'; ROOT_NAME_ORDER = 'order'; ROOT_NAME_ACCOUNTING = 'accounting'; ROOT_NAME_WORKEFFORT = 'workeffort'; ROOT_NAME_SHIPMENT = 'shipment'; ROOT_NAME_MARKETING = 'marketing'; ROOT_NAME_MANUFACTURING = 'manufacturing'; ROOT_NAME_HUMANRES = 'humanres'; ROOT_NAME_CONTENT = 'content'; ROOT_NAME_COMMON = 'common'; ROOT_NAME_SECURITY = 'security'; ROOT_NAME_SERVICE = 'service'; function CreatePartyModel: TSQLModel; function CreateProductModel: TSQLModel; function CreateOrderModel: TSQLModel; function CreateAccountingModel: TSQLModel; function CreateWorkEffortModel: TSQLModel; function CreateShipmentModel: TSQLModel; function CreateMarketingModel: TSQLModel; function CreateManufacturingModel: TSQLModel; function CreateHumanresModel: TSQLModel; function CreateContentModel: TSQLModel; function CreateCommonModel: TSQLModel; function CreateSecurityModel: TSQLModel; function CreateServiceModel: TSQLModel; implementation function CreatePartyModel: TSQLModel; begin result := TSQLModel.Create([ TSQLAddendum, TSQLAgreement, TSQLAgreementAttribute, TSQLAgreementGeographicalApplic, TSQLAgreementItem, TSQLAgreementItemAttribute, TSQLAgreementItemType, TSQLAgreementItemTypeAttr, TSQLAgreementContent, TSQLAgreementContentType, TSQLAgreementPartyApplic, TSQLAgreementProductAppl, TSQLAgreementPromoAppl, TSQLAgreementFacilityAppl,TSQLAgreementRole, TSQLAgreementTerm, TSQLAgreementTermAttribute, TSQLAgreementType, TSQLAgreementTypeAttr, TSQLAgreementWorkEffortApplic, TSQLTermType, TSQLTermTypeAttr, TSQLAgreementEmploymentAppl, TSQLCommContentAssocType, TSQLCommEventContentAssoc, TSQLCommunicationEvent, TSQLCommunicationEventProduct, TSQLCommunicationEventPrpTyp, TSQLCommunicationEventPurpose, TSQLCommunicationEventRole, TSQLCommunicationEventType, TSQLContactMech, TSQLContactMechAttribute, TSQLContactMechLink, TSQLContactMechPurposeType, TSQLContactMechType, TSQLContactMechTypeAttr, TSQLContactMechTypePurpose, TSQLEmailAddressVerification, TSQLPartyContactMech, TSQLPartyContactMechPurpose, TSQLPostalAddress, TSQLPostalAddressBoundary, TSQLTelecomNumber, TSQLValidContactMechRole, TSQLNeedType, TSQLPartyNeed, TSQLAddressMatchMap, TSQLAffiliate, TSQLParty, TSQLPartyIdentification, TSQLPartyIdentificationType, TSQLPartyGeoPoint, TSQLPartyAttribute, TSQLPartyCarrierAccount, TSQLPartyClassification, TSQLPartyClassificationGroup, TSQLPartyClassificationType, TSQLPartyContent, TSQLPartyContentType, TSQLPartyDataSource, TSQLPartyGroup, TSQLPartyIcsAvsOverride, TSQLPartyInvitation, TSQLPartyInvitationGroupAssoc, TSQLPartyInvitationRoleAssoc, TSQLPartyNameHistory, TSQLPartyNote, TSQLPartyProfileDefault, TSQLPartyRelationship, TSQLPartyRelationshipType, TSQLPartyRole, TSQLPartyStatus, TSQLPartyType, TSQLPartyTypeAttr, TSQLPerson, TSQLPriorityType, TSQLRoleType, TSQLRoleTypeAttr, TSQLVendor, TSQLUserLogin ], ROOT_NAME_PARTY); end; function CreateProductModel: TSQLModel; begin result := TSQLModel.Create([ TSQLProdCatalog, TSQLProdCatalogCategory, TSQLProdCatalogCategoryType, TSQLProdCatalogInvFacility, TSQLProdCatalogRole, TSQLProductCategory, TSQLProductCategoryAttribute, TSQLProductCategoryContent, TSQLProductCategoryContentType, TSQLProductCategoryGlAccount, TSQLProductCategoryLink, TSQLProductCategoryMember, TSQLProductCategoryRole, TSQLProductCategoryRollup, TSQLProductCategoryType, TSQLProductCategoryTypeAttr, TSQLProductConfig, TSQLProductConfigItem, TSQLProdConfItemContent, TSQLProdConfItemContentType, TSQLProductConfigOption, TSQLProductConfigOptionIactn, TSQLProductConfigProduct, TSQLProductConfigConfig, TSQLProductConfigStats, TSQLConfigOptionProductOption, TSQLCostComponent, TSQLCostComponentAttribute, TSQLCostComponentType, TSQLCostComponentTypeAttr, TSQLCostComponentCalc, TSQLProductCostComponentCalc, TSQLContainer, TSQLContainerType, TSQLContainerGeoPoint, TSQLFacility, TSQLFacilityAttribute, TSQLFacilityCalendar, TSQLFacilityCalendarType, TSQLFacilityCarrierShipment, TSQLFacilityContactMech, TSQLFacilityContactMechPurpose, TSQLFacilityGroup, TSQLFacilityGroupMember, TSQLFacilityGroupRole, TSQLFacilityGroupRollup, TSQLFacilityGroupType, TSQLFacilityLocation, TSQLFacilityLocationGeoPoint, TSQLFacilityParty, TSQLFacilityContent, TSQLFacilityType, TSQLFacilityTypeAttr, TSQLProductFacility, TSQLProductFacilityLocation, TSQLProductFeature, TSQLProductFeatureAppl, TSQLProductFeatureApplType, TSQLProductFeatureApplAttr, TSQLProductFeatureCategory, TSQLProductFeatureCategoryAppl, TSQLProductFeatureCatGrpAppl, TSQLProductFeatureDataResource, TSQLProductFeatureGroup, TSQLProductFeatureGroupAppl, TSQLProductFeatureIactn, TSQLProductFeatureIactnType, TSQLProductFeatureType, TSQLProductFeaturePrice, TSQLInventoryItem, TSQLInventoryItemAttribute, TSQLInventoryItemDetail, TSQLInventoryItemStatus, TSQLInventoryItemTempRes, TSQLInventoryItemType, TSQLInventoryItemTypeAttr, TSQLInventoryItemVariance, TSQLInventoryItemLabelType, TSQLInventoryItemLabel, TSQLInventoryItemLabelAppl, TSQLInventoryTransfer, TSQLLot, TSQLPhysicalInventory, TSQLVarianceReason, TSQLProductPaymentMethodType, TSQLProductPrice, TSQLProductPriceAction, TSQLProductPriceActionType, TSQLProductPriceAutoNotice, TSQLProductPriceChange, TSQLProductPriceCond, TSQLProductPricePurpose, TSQLProductPriceRule, TSQLProductPriceType, TSQLQuantityBreak, TSQLQuantityBreakType, TSQLSaleType, TSQLGoodIdentification, TSQLGoodIdentificationType, TSQLProduct, TSQLProductAssoc, TSQLProductAssocType, TSQLProductRole, TSQLProductAttribute, TSQLProductCalculatedInfo, TSQLProductContent, TSQLProductContentType, TSQLProductGeo, TSQLProductGlAccount, TSQLProductKeyword, TSQLProductMeter, TSQLProductMeterType, TSQLProductMaint, TSQLProductMaintType, TSQLProductReview, TSQLProductSearchConstraint, TSQLProductSearchResult, TSQLProductType, TSQLProductTypeAttr, TSQLVendorProduct, TSQLProductPromo, TSQLProductPromoAction, TSQLProductPromoCategory, TSQLProductPromoCode, TSQLProductPromoCodeEmail, TSQLProductPromoCodeParty, TSQLProductPromoCond, TSQLProductPromoProduct, TSQLProductPromoRule, TSQLProductPromoUse, TSQLProductStore, TSQLProductStoreCatalog, TSQLProductStoreEmailSetting, TSQLProductStoreFinActSetting, TSQLProductStoreFacility, TSQLProductStoreGroup, TSQLProductStoreGroupMember, TSQLProductStoreGroupRole, TSQLProductStoreGroupRollup, TSQLProductStoreGroupType, TSQLProductStoreKeywordOvrd, TSQLProductStorePaymentSetting, TSQLProductStorePromoAppl, TSQLProductStoreRole, TSQLProductStoreShipmentMeth, TSQLProductStoreSurveyAppl, TSQLProductStoreVendorPayment, TSQLProductStoreVendorShipment, TSQLWebSite, TSQLProductSubscriptionResource, TSQLSubscription, TSQLSubscriptionActivity, TSQLSubscriptionAttribute, TSQLSubscriptionFulfillmentPiece, TSQLSubscriptionResource, TSQLSubscriptionType, TSQLSubscriptionTypeAttr, TSQLSubscriptionCommEvent, TSQLMarketInterest, TSQLReorderGuideline, TSQLSupplierPrefOrder, TSQLSupplierProduct, TSQLSupplierProductFeature, TSQLSupplierRatingType, TSQLProductPromoContent ], ROOT_NAME_PRODUCT); end; function CreateOrderModel: TSQLModel; begin result := TSQLModel.Create([ TSQLOrderAdjustment, TSQLOrderAdjustmentAttribute, TSQLOrderAdjustmentType, TSQLOrderAdjustmentBilling, TSQLOrderAdjustmentTypeAttr, TSQLOrderAttribute, TSQLOrderBlacklist, TSQLOrderBlacklistType, TSQLCommunicationEventOrder, TSQLOrderContactMech, TSQLOrderContent, TSQLOrderContentType, TSQLOrderDeliverySchedule, TSQLOrderHeader, TSQLOrderHeaderNote, TSQLOrderHeaderWorkEffort, TSQLOrderItem, TSQLOrderItemAssoc, TSQLOrderItemAssocType, TSQLOrderItemAttribute, TSQLOrderItemBilling, TSQLOrderItemChange, TSQLOrderItemContactMech, TSQLOrderItemGroup, TSQLOrderItemGroupOrder, TSQLOrderItemPriceInfo, TSQLOrderItemRole, TSQLOrderItemShipGroup, TSQLOrderItemShipGroupAssoc, TSQLOrderItemShipGrpInvRes, TSQLOrderItemType, TSQLOrderItemTypeAttr, TSQLOrderNotification, TSQLOrderPaymentPreference, TSQLOrderProductPromoCode, TSQLOrderRole, TSQLOrderShipment, TSQLOrderStatus, TSQLOrderSummaryEntry, TSQLOrderTerm, TSQLOrderTermAttribute, TSQLOrderType, TSQLOrderTypeAttr, TSQLProductOrderItem, TSQLWorkOrderItemFulfillment, TSQLQuote, TSQLQuoteAttribute, TSQLQuoteCoefficient, TSQLQuoteItem, TSQLQuoteNote, TSQLQuoteRole, TSQLQuoteTerm, TSQLQuoteTermAttribute, TSQLQuoteType, TSQLQuoteTypeAttr, TSQLQuoteWorkEffort, TSQLQuoteAdjustment, TSQLCustRequest, TSQLCustRequestAttribute, TSQLCustRequestCategory, TSQLCustRequestCommEvent, TSQLCustRequestContent, TSQLCustRequestItem, TSQLCustRequestNote, TSQLCustRequestItemNote, TSQLCustRequestItemWorkEffort, TSQLCustRequestResolution, TSQLCustRequestParty, TSQLCustRequestStatus, TSQLCustRequestType, TSQLCustRequestTypeAttr, TSQLCustRequestWorkEffort, TSQLRespondingParty, TSQLDesiredFeature, TSQLOrderRequirementCommitment, TSQLRequirement, TSQLRequirementAttribute, TSQLRequirementBudgetAllocation, TSQLRequirementCustRequest, TSQLRequirementRole, TSQLRequirementStatus, TSQLRequirementType, TSQLRequirementTypeAttr, TSQLWorkReqFulfType, TSQLWorkRequirementFulfillment, TSQLReturnAdjustment, TSQLReturnAdjustmentType, TSQLReturnHeader, TSQLReturnHeaderType, TSQLReturnItem, TSQLReturnItemResponse, TSQLReturnItemType, TSQLReturnItemTypeMap, TSQLReturnReason, TSQLReturnStatus, TSQLReturnType, TSQLReturnItemBilling, TSQLReturnItemShipment, TSQLReturnContactMech, TSQLCartAbandonedLine, TSQLShoppingList, TSQLShoppingListItem, TSQLShoppingListItemSurvey, TSQLShoppingListType, TSQLShoppingListWorkEffort ], ROOT_NAME_ORDER); end; function CreateAccountingModel: TSQLModel; begin result := TSQLModel.Create([ TSQLBudget, TSQLBudgetAttribute, TSQLBudgetItem, TSQLBudgetItemAttribute, TSQLBudgetItemType, TSQLBudgetItemTypeAttr, TSQLBudgetReview, TSQLBudgetReviewResultType, TSQLBudgetRevision, TSQLBudgetRevisionImpact, TSQLBudgetRole, TSQLBudgetScenario, TSQLBudgetScenarioApplication, TSQLBudgetScenarioRule, TSQLBudgetStatus, TSQLBudgetType, TSQLBudgetTypeAttr, TSQLFinAccount, TSQLFinAccountAttribute, TSQLFinAccountAuth, TSQLFinAccountRole, TSQLFinAccountStatus, TSQLFinAccountTrans, TSQLFinAccountTransAttribute, TSQLFinAccountTransType, TSQLFinAccountTransTypeAttr, TSQLFinAccountType, TSQLFinAccountTypeAttr, TSQLFinAccountTypeGlAccount, TSQLFixedAsset, TSQLFixedAssetAttribute, TSQLFixedAssetDepMethod, TSQLFixedAssetGeoPoint, TSQLFixedAssetIdent, TSQLFixedAssetIdentType, TSQLFixedAssetMaint, TSQLFixedAssetMeter, TSQLFixedAssetProduct, TSQLFixedAssetProductType, TSQLFixedAssetTypeGlAccount, TSQLFixedAssetRegistration, TSQLFixedAssetStdCost, TSQLFixedAssetStdCostType, TSQLFixedAssetType, TSQLFixedAssetTypeAttr, TSQLPartyFixedAssetAssignment, TSQLFixedAssetMaintOrder, TSQLAccommodationClass, TSQLAccommodationSpot, TSQLAccommodationMap, TSQLAccommodationMapType, TSQLInvoice, TSQLInvoiceAttribute, TSQLInvoiceContent, TSQLInvoiceContentType, TSQLInvoiceContactMech, TSQLInvoiceItem, TSQLInvoiceItemAssoc, TSQLInvoiceItemAssocType, TSQLInvoiceItemAttribute, TSQLInvoiceItemType, TSQLInvoiceItemTypeAttr, TSQLInvoiceItemTypeGlAccount, TSQLInvoiceItemTypeMap, TSQLInvoiceRole, TSQLInvoiceStatus, TSQLInvoiceTerm, TSQLInvoiceTermAttribute, TSQLInvoiceType, TSQLInvoiceTypeAttr, TSQLInvoiceNote, TSQLAcctgTrans, TSQLAcctgTransAttribute, TSQLAcctgTransEntry, TSQLAcctgTransEntryType, TSQLAcctgTransType, TSQLAcctgTransTypeAttr, TSQLGlAccount, TSQLGlAccountClass, TSQLGlAccountGroup, TSQLGlAccountGroupMember, TSQLGlAccountGroupType, TSQLGlAccountHistory, TSQLGlAccountOrganization, TSQLGlAccountRole, TSQLGlAccountType, TSQLGlAccountTypeDefault, TSQLGlBudgetXref, TSQLGlFiscalType, TSQLGlJournal, TSQLGlReconciliation, TSQLGlReconciliationEntry, TSQLGlResourceType, TSQLGlXbrlClass, TSQLPartyAcctgPreference, TSQLProductAverageCost, TSQLProductAverageCostType, TSQLSettlementTerm, TSQLVarianceReasonGlAccount, TSQLBillingAccount, TSQLBillingAccountRole, TSQLBillingAccountTerm, TSQLBillingAccountTermAttr, TSQLCreditCard, TSQLCreditCardTypeGlAccount, TSQLDeduction, TSQLDeductionType, TSQLEftAccount, TSQLCheckAccount, TSQLGiftCard, TSQLGiftCardFulfillment, TSQLPayment, TSQLPaymentApplication, TSQLPaymentAttribute, TSQLPaymentBudgetAllocation, TSQLPaymentContent, TSQLPaymentContentType, TSQLPaymentMethod, TSQLPaymentMethodType, TSQLPaymentMethodTypeGlAccount, TSQLPaymentType, TSQLPaymentTypeAttr, TSQLPaymentGlAccountTypeMap, TSQLPaymentGatewayConfigType, TSQLPaymentGatewayConfig, TSQLPaymentGatewaySagePay, TSQLPaymentGatewayAuthorizeNet, TSQLPaymentGatewayEway, TSQLPaymentGatewayCyberSource, TSQLPaymentGatewayPayflowPro, TSQLPaymentGatewayPayPal, TSQLPaymentGatewayClearCommerce, TSQLPaymentGatewayWorldPay, TSQLPaymentGatewayOrbital, TSQLPaymentGatewaySecurePay, TSQLPaymentGatewayiDEAL, TSQLPaymentGatewayRespMsg, TSQLPaymentGatewayResponse, TSQLPaymentGroup, TSQLPaymentGroupType, TSQLPaymentGroupMember, TSQLPayPalPaymentMethod, TSQLValueLinkKey, TSQLPartyTaxAuthInfo, TSQLTaxAuthority, TSQLTaxAuthorityAssoc, TSQLTaxAuthorityAssocType, TSQLTaxAuthorityCategory, TSQLTaxAuthorityGlAccount, TSQLTaxAuthorityRateProduct, TSQLTaxAuthorityRateType, TSQLZipSalesRuleLookup, TSQLZipSalesTaxLookup, TSQLPartyGlAccount, TSQLRateType, TSQLRateAmount, TSQLPartyRate, TSQLGlAccountCategory, TSQLGlAccountCategoryMember, TSQLGlAccountCategoryType ], ROOT_NAME_ACCOUNTING); end; function CreateWorkEffortModel: TSQLModel; begin result := TSQLModel.Create([ TSQLTimeEntry, TSQLTimesheet, TSQLTimesheetRole, TSQLApplicationSandbox, TSQLCommunicationEventWorkEff, TSQLDeliverable, TSQLDeliverableType, TSQLWorkEffort, TSQLWorkEffortAssoc, TSQLWorkEffortAssocAttribute, TSQLWorkEffortAssocType, TSQLWorkEffortAssocTypeAttr, TSQLWorkEffortAttribute, TSQLWorkEffortBilling, TSQLWorkEffortContactMech, TSQLWorkEffortContent, TSQLWorkEffortContentType, TSQLWorkEffortDeliverableProd, TSQLWorkEffortEventReminder, TSQLWorkEffortFixedAssetAssign, TSQLWorkEffortFixedAssetStd, TSQLWorkEffortGoodStandard, TSQLWorkEffortGoodStandardType, TSQLWorkEffortIcalData, TSQLWorkEffortInventoryAssign, TSQLWorkEffortInventoryProduced, TSQLWorkEffortCostCalc, TSQLWorkEffortKeyword, TSQLWorkEffortNote, TSQLWorkEffortPartyAssignment, TSQLWorkEffortPurposeType, TSQLWorkEffortReview, TSQLWorkEffortSearchConstraint, TSQLWorkEffortSearchResult, TSQLWorkEffortSkillStandard, TSQLWorkEffortStatus, TSQLWorkEffortTransBox, TSQLWorkEffortType, TSQLWorkEffortTypeAttr, TSQLWorkEffortSurveyAppl ], ROOT_NAME_WORKEFFORT); end; function CreateShipmentModel: TSQLModel; begin result := TSQLModel.Create([ TSQLItemIssuance, TSQLItemIssuanceRole, TSQLPicklist, TSQLPicklistBin, TSQLPicklistItem, TSQLPicklistRole, TSQLPicklistStatusHistory, TSQLRejectionReason, TSQLShipmentReceipt, TSQLShipmentReceiptRole, TSQLCarrierShipmentMethod, TSQLCarrierShipmentBoxType, TSQLDelivery, TSQLShipment, TSQLShipmentAttribute, TSQLShipmentBoxType, TSQLShipmentContactMech, TSQLShipmentContactMechType, TSQLShipmentCostEstimate, TSQLShipmentGatewayConfigType, TSQLShipmentGatewayConfig, TSQLShipmentGatewayDhl, TSQLShipmentGatewayFedex, TSQLShipmentGatewayUps, TSQLShipmentGatewayUsps, TSQLShipmentItem, TSQLShipmentItemBilling, TSQLShipmentItemFeature, TSQLShipmentMethodType, TSQLShipmentPackage, TSQLShipmentPackageContent, TSQLShipmentPackageRouteSeg, TSQLShipmentRouteSegment, TSQLShipmentStatus, TSQLShipmentType, TSQLShipmentTypeAttr, TSQLShippingDocument ], ROOT_NAME_SHIPMENT); end; function CreateMarketingModel: TSQLModel; begin result := TSQLModel.Create([ TSQLMarketingCampaign, TSQLMarketingCampaignNote, TSQLMarketingCampaignPrice, TSQLMarketingCampaignPromo, TSQLMarketingCampaignRole, TSQLContactList, TSQLWebSiteContactList, TSQLContactListCommStatus, TSQLContactListParty, TSQLContactListPartyStatus, TSQLContactListType, TSQLSegmentGroup, TSQLSegmentGroupClassification, TSQLSegmentGroupGeo, TSQLSegmentGroupRole, TSQLSegmentGroupType, TSQLTrackingCode, TSQLTrackingCodeOrder, TSQLTrackingCodeOrderReturn, TSQLTrackingCodeType, TSQLTrackingCodeVisit, TSQLSalesOpportunity, TSQLSalesOpportunityHistory, TSQLSalesOpportunityRole, TSQLSalesOpportunityStage, TSQLSalesOpportunityWorkEffort, TSQLSalesOpportunityQuote, TSQLSalesForecast, TSQLSalesForecastDetail, TSQLSalesForecastHistory, TSQLSalesOpportunityCompetitor, TSQLSalesOpportunityTrckCode ], ROOT_NAME_MARKETING); end; function CreateManufacturingModel: TSQLModel; begin result := TSQLModel.Create([ TSQLProductManufacturingRule, TSQLTechDataCalendar, TSQLTechDataCalendarExcDay, TSQLTechDataCalendarExcWeek, TSQLTechDataCalendarWeek, TSQLMrpEventType, TSQLMrpEvent ], ROOT_NAME_MANUFACTURING); end; function CreateHumanresModel: TSQLModel; begin result := TSQLModel.Create([ TSQLPartyQual, TSQLPartyQualType, TSQLPartyResume, TSQLPartySkill, TSQLPerfRatingType, TSQLPerfReview, TSQLPerfReviewItem, TSQLPerfReviewItemType, TSQLPerformanceNote, TSQLPersonTraining, TSQLResponsibilityType, TSQLSkillType, TSQLTrainingClassType, TSQLBenefitType, TSQLEmployment, TSQLEmploymentApp, TSQLEmploymentAppSourceType, TSQLEmplLeave, TSQLEmplLeaveType, TSQLPartyBenefit, TSQLPayGrade, TSQLPayHistory, TSQLPayrollPreference, TSQLSalaryStep, TSQLTerminationReason, TSQLTerminationType, TSQLUnemploymentClaim, TSQLEmplPosition, TSQLEmplPositionClassType, TSQLEmplPositionFulfillment, TSQLEmplPositionReportingStruct, TSQLEmplPositionResponsibility, TSQLEmplPositionType, TSQLEmplPositionTypeClass, TSQLValidResponsibility, TSQLEmplPositionTypeRate, TSQLJobRequisition, TSQLJobInterview, TSQLJobInterviewType, TSQLTrainingRequest, TSQLEmplLeaveReasonType ], ROOT_NAME_HUMANRES); end; function CreateContentModel: TSQLModel; begin result := TSQLModel.Create([ TSQLContent, TSQLContentApproval, TSQLContentAssoc, TSQLContentAssocPredicate, TSQLContentAssocType, TSQLContentAttribute, TSQLContentMetaData, TSQLContentOperation, TSQLContentPurpose, TSQLContentPurposeOperation, TSQLContentPurposeType, TSQLContentRevision, TSQLContentRevisionItem, TSQLContentRole, TSQLContentType, TSQLContentTypeAttr, TSQLAudioDataResource, TSQLCharacterSet, TSQLDataCategory, TSQLDataResource, TSQLDataResourceAttribute, TSQLDataResourceMetaData, TSQLDataResourcePurpose, TSQLDataResourceRole, TSQLDataResourceType, TSQLDataResourceTypeAttr, TSQLDataTemplateType, TSQLElectronicText, TSQLFileExtension, TSQLImageDataResource, TSQLMetaDataPredicate, TSQLMimeType, TSQLMimeTypeHtmlTemplate, TSQLOtherDataResource, TSQLVideoDataResource, TSQLDocument, TSQLDocumentAttribute, TSQLDocumentType, TSQLDocumentTypeAttr, TSQLWebPreferenceType, TSQLWebUserPreference, TSQLSurvey, TSQLSurveyApplType, TSQLSurveyMultiResp, TSQLSurveyMultiRespColumn, TSQLSurveyPage, TSQLSurveyQuestion, TSQLSurveyQuestionAppl, TSQLSurveyQuestionCategory, TSQLSurveyQuestionOption, TSQLSurveyQuestionType, TSQLSurveyResponse, TSQLSurveyResponseAnswer, TSQLSurveyTrigger, TSQLWebSiteContent, TSQLWebSiteContentType, TSQLWebSitePathAlias, TSQLWebSitePublishPoint, TSQLWebSiteRole, TSQLContentKeyword, TSQLContentSearchConstraint, TSQLContentSearchResult, TSQLWebAnalyticsConfig, TSQLWebAnalyticsType ], ROOT_NAME_CONTENT); end; function CreateCommonModel: TSQLModel; begin result := TSQLModel.Create([ TSQLDataSource, TSQLDataSourceType, TSQLEmailTemplateSetting, TSQLEnumeration, TSQLEnumerationType, TSQLCountryCapital, TSQLCountryCode, TSQLCountryTeleCode, TSQLCountryAddressFormat, TSQLGeo, TSQLGeoAssoc, TSQLGeoAssocType, TSQLGeoPoint, TSQLGeoType, TSQLKeywordThesaurus, TSQLStandardLanguage, TSQLCustomMethod, TSQLCustomMethodType, TSQLNoteData, TSQLCustomTimePeriod, TSQLPeriodType, TSQLStatusItem, TSQLStatusType, TSQLStatusValidChange, TSQLUom, TSQLUomConversion, TSQLUomConversionDated, TSQLUomGroup, TSQLUomType, TSQLUserPreference, TSQLUserPrefGroupType, TSQLVisualThemeSet, TSQLVisualTheme, TSQLVisualThemeResource, TSQLPortalPortlet, TSQLPortletCategory, TSQLPortletPortletCategory, TSQLPortalPage, TSQLPortalPageColumn, TSQLPortalPagePortlet, TSQLPortletAttribute, TSQLSystemProperty ], ROOT_NAME_COMMON); end; function CreateSecurityModel: TSQLModel; begin result := TSQLModel.Create([ TSQLX509IssuerProvision, TSQLUserLogin, TSQLUserLoginPasswordHistory, TSQLUserLoginHistory, TSQLUserLoginSession, TSQLSecurityGroup, TSQLSecurityGroupPermission, TSQLSecurityPermission, TSQLUserLoginSecurityGroup, TSQLProtectedView, TSQLTarpittedLoginView, TSQLUserLoginSecurityQuestion ], ROOT_NAME_SECURITY); end; function CreateServiceModel: TSQLModel; begin result := TSQLModel.Create([ TSQLJobSandbox, TSQLRecurrenceInfo, TSQLRecurrenceRule, TSQLRuntimeData, TSQLTemporalExpression, TSQLTemporalExpressionAssoc, TSQLJobManagerLock, TSQLServiceSemaphore ], ROOT_NAME_SERVICE); end; end.
unit b02_denda; interface uses csv_parser, user_handler, peminjaman_handler, pengembalian_handler, utilitas, tipe_data, buku_handler; { DEKLARASI FUNGSI DAN PROSEDUR } procedure denda(awal, akhir: string); { IMPLEMENTASI FUNGSI DAN PROSEDUR } implementation procedure denda(awal, akhir: string); { DESKRIPSI : Prosedur untuk menangani denda pengguna berdasarkan tanggal awal dan akhir } { PARAMETER : tanggal awal dan akhir } { KAMUS LOKAL } var deltaHari : int64; { ALGORITMA } begin deltaHari := BedaHari(awal, akhir); if (deltaHari <= 0) then // Jika pengembalian dilakukan setelah tanggal peminjaman dan sebelum tenggat waktu begin writeln('Terima kasih sudah meminjam'); end else if (deltaHari > 0)// deltaHari > 0 then begin writeln('Anda terlambat mengembalikan buku.'); writeln('Anda terkena denda Rp', deltaHari * 2000 , '.'); end; end; end.
unit NtUtils.Svc; interface uses Winapi.WinNt, NtUtils.Exceptions, NtUtils.Objects, Winapi.Svc, DelphiUtils.AutoObject; type TScmHandle = Winapi.Svc.TScmHandle; IScmHandle = DelphiUtils.AutoObject.IHandle; TScmAutoHandle = class(TCustomAutoHandle, IScmHandle) destructor Destroy; override; end; TServiceConfig = record ServiceType: Cardinal; StartType: TServiceStartType; ErrorControl: TServiceErrorControl; TagId: Cardinal; BinaryPathName: String; LoadOrderGroup: String; ServiceStartName: String; DisplayName: String; end; // Open a handle to SCM function ScmxConnect(out hxScm: IScmHandle; DesiredAccess: TAccessMask; ServerName: String = ''): TNtxStatus; // Open a service function ScmxOpenService(out hxSvc: IScmHandle; ServiceName: String; DesiredAccess: TAccessMask; hxScm: IScmHandle = nil): TNtxStatus; // Create a service function ScmxCreateService(out hxSvc: IScmHandle; CommandLine, ServiceName, DisplayName: String; StartType: TServiceStartType = ServiceDemandStart; hxScm: IScmHandle = nil): TNtxStatus; // Start a service function ScmxStartService(hSvc: TScmHandle; Parameters: TArray<String> = nil): TNtxStatus; // Send a control to a service function ScmxControlService(hSvc: TScmHandle; Control: TServiceControl; out ServiceStatus: TServiceStatus): TNtxStatus; // Delete a service function ScmxDeleteService(hSvc: TScmHandle): TNtxStatus; // Query service config function ScmxQueryConfigService(hSvc: TScmHandle; out Config: TServiceConfig) : TNtxStatus; // Query service status and process information function ScmxQueryProcessStatusService(hSvc: TScmHandle; out Info: TServiceStatusProcess): TNtxStatus; type NtxService = class // Query fixed-size information class function Query<T>(hSvc: TScmHandle; InfoClass: TServiceConfigLevel; out Buffer: T): TNtxStatus; static; end; // Query variable-size service information function ScmxQueryService(hSvc: TScmHandle; InfoClass: TServiceConfigLevel; out xMemory: IMemory): TNtxStatus; // Set service information function ScmxSetService(hSvc: TScmHandle; InfoClass: TServiceConfigLevel; Buffer: Pointer): TNtxStatus; // Query service description function ScmxQueryDescriptionService(hSvc: TScmHandle; out Description: String): TNtxStatus; // Query list of requires privileges for a service function ScmxQueryRequiredPrivilegesService(hSvc: TScmHandle; out Privileges: TArray<String>): TNtxStatus; implementation uses NtUtils.Access.Expected, Ntapi.ntstatus, DelphiUtils.Arrays; destructor TScmAutoHandle.Destroy; begin if FAutoRelease then CloseServiceHandle(FHandle); inherited; end; function ScmxConnect(out hxScm: IScmHandle; DesiredAccess: TAccessMask; ServerName: String): TNtxStatus; var hScm: TScmHandle; pServerName: PWideChar; begin if ServerName <> '' then pServerName := PWideChar(ServerName) else pServerName := nil; Result.Location := 'OpenSCManagerW'; Result.LastCall.CallType := lcOpenCall; Result.LastCall.AccessMask := DesiredAccess; Result.LastCall.AccessMaskType := @ScmAccessType; hScm := OpenSCManagerW(pServerName, nil, DesiredAccess); Result.Win32Result := (hScm <> 0); if Result.IsSuccess then hxScm := TScmAutoHandle.Capture(hScm); end; function ScmxpEnsureConnected(var hxScm: IScmHandle; DesiredAccess: TAccessMask) : TNtxStatus; begin if not Assigned(hxScm) then Result := ScmxConnect(hxScm, DesiredAccess) else Result.Status := STATUS_SUCCESS end; function ScmxOpenService(out hxSvc: IScmHandle; ServiceName: String; DesiredAccess: TAccessMask; hxScm: IScmHandle): TNtxStatus; var hSvc: TScmHandle; begin Result := ScmxpEnsureConnected(hxScm, SC_MANAGER_CONNECT); if not Result.IsSuccess then Exit; Result.Location := 'OpenServiceW'; Result.LastCall.CallType := lcOpenCall; Result.LastCall.AccessMask := DesiredAccess; Result.LastCall.AccessMaskType := @ServiceAccessType; Result.LastCall.Expects(SC_MANAGER_CONNECT, @ScmAccessType); hSvc := OpenServiceW(hxScm.Handle, PWideChar(ServiceName), DesiredAccess); Result.Win32Result := (hSvc <> 0); if Result.IsSuccess then hxSvc := TScmAutoHandle.Capture(hSvc); end; function ScmxCreateService(out hxSvc: IScmHandle; CommandLine, ServiceName, DisplayName: String; StartType: TServiceStartType; hxScm: IScmHandle) : TNtxStatus; var hSvc: TScmHandle; begin Result := ScmxpEnsureConnected(hxScm, SC_MANAGER_CREATE_SERVICE); if not Result.IsSuccess then Exit; Result.Location := 'CreateServiceW'; Result.LastCall.Expects(SC_MANAGER_CREATE_SERVICE, @ScmAccessType); hSvc := CreateServiceW(hxScm.Handle, PWideChar(ServiceName), PWideChar(DisplayName), SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, StartType, ServiceErrorNormal, PWideChar(CommandLine), nil, nil, nil, nil, nil); Result.Win32Result := (hSvc <> 0); if Result.IsSuccess then hxSvc := TScmAutoHandle.Capture(hSvc); end; function ScmxStartService(hSvc: TScmHandle; Parameters: TArray<String>): TNtxStatus; var i: Integer; Params: TArray<PWideChar>; begin SetLength(Params, Length(Parameters)); for i := 0 to High(Params) do Params[i] := PWideChar(Parameters[i]); Result.Location := 'StartServiceW'; Result.LastCall.Expects(SERVICE_START, @ServiceAccessType); Result.Win32Result := StartServiceW(hSvc, Length(Params), Params); end; function ScmxControlService(hSvc: TScmHandle; Control: TServiceControl; out ServiceStatus: TServiceStatus): TNtxStatus; begin Result.Location := 'ControlService'; Result.LastCall.CallType := lcQuerySetCall; Result.LastCall.InfoClass := Cardinal(Control); Result.LastCall.InfoClassType := TypeInfo(TServiceControl); RtlxComputeServiceControlAccess(Result.LastCall, Control); Result.Win32Result := ControlService(hSvc, Control, ServiceStatus); end; function ScmxDeleteService(hSvc: TScmHandle): TNtxStatus; begin Result.Location := 'DeleteService'; Result.LastCall.Expects(_DELETE, @ServiceAccessType); Result.Win32Result := DeleteService(hSvc); end; function ScmxQueryConfigService(hSvc: TScmHandle; out Config: TServiceConfig) : TNtxStatus; var Buffer: PQueryServiceConfigW; BufferSize, Required: Cardinal; begin Result.Location := 'QueryServiceConfigW'; Result.LastCall.Expects(SERVICE_QUERY_CONFIG, @ServiceAccessType); BufferSize := 0; repeat Buffer := AllocMem(BufferSize); Required := 0; Result.Win32Result := QueryServiceConfigW(hSvc, Buffer, BufferSize, Required); if not Result.IsSuccess then FreeMem(Buffer); until not NtxExpandBuffer(Result, BufferSize, Required); if not Result.IsSuccess then Exit; Config.ServiceType := Buffer.ServiceType; Config.StartType := Buffer.StartType; Config.ErrorControl := Buffer.ErrorControl; Config.TagId := Buffer.TagId; Config.BinaryPathName := String(Buffer.BinaryPathName); Config.LoadOrderGroup := String(Buffer.LoadOrderGroup); Config.ServiceStartName := String(Buffer.ServiceStartName); Config.DisplayName := String(Buffer.DisplayName); FreeMem(Buffer); end; function ScmxQueryProcessStatusService(hSvc: TScmHandle; out Info: TServiceStatusProcess): TNtxStatus; var Required: Cardinal; begin Result.Location := 'QueryServiceStatusEx'; Result.LastCall.CallType := lcQuerySetCall; Result.LastCall.InfoClass := Cardinal(ScStatusProcessInfo); Result.LastCall.InfoClassType := TypeInfo(TScStatusType); Result.LastCall.Expects(SERVICE_QUERY_STATUS, @ServiceAccessType); Result.Win32Result := QueryServiceStatusEx(hSvc, ScStatusProcessInfo, @Info, SizeOf(Info), Required); end; class function NtxService.Query<T>(hSvc: TScmHandle; InfoClass: TServiceConfigLevel; out Buffer: T): TNtxStatus; var Required: Cardinal; begin Result.Location := 'QueryServiceConfig2W'; Result.LastCall.Expects(SERVICE_QUERY_CONFIG, @ServiceAccessType); Result.LastCall.CallType := lcQuerySetCall; Result.LastCall.InfoClass := Cardinal(InfoClass); Result.LastCall.InfoClassType := TypeInfo(TServiceConfigLevel); Result.Win32Result := QueryServiceConfig2W(hSvc, InfoClass, @Buffer, SizeOf(Buffer), Required); end; function ScmxQueryService(hSvc: TScmHandle; InfoClass: TServiceConfigLevel; out xMemory: IMemory): TNtxStatus; var Buffer: Pointer; BufferSize, Required: Cardinal; begin Result.Location := 'QueryServiceConfig2W'; Result.LastCall.Expects(SERVICE_QUERY_CONFIG, @ServiceAccessType); Result.LastCall.CallType := lcQuerySetCall; Result.LastCall.InfoClass := Cardinal(InfoClass); Result.LastCall.InfoClassType := TypeInfo(TServiceConfigLevel); BufferSize := 0; repeat Buffer := AllocMem(BufferSize); Required := 0; Result.Win32Result := QueryServiceConfig2W(hSvc, InfoClass, Buffer, BufferSize, Required); if not Result.IsSuccess then begin FreeMem(Buffer); Buffer := nil; end; until not NtxExpandBuffer(Result, BufferSize, Required); if Result.IsSuccess then xMemory := TAutoMemory.Capture(Buffer, BufferSize); end; function ScmxSetService(hSvc: TScmHandle; InfoClass: TServiceConfigLevel; Buffer: Pointer): TNtxStatus; begin Result.Location := 'ChangeServiceConfig2W'; Result.LastCall.Expects(SERVICE_CHANGE_CONFIG, @ServiceAccessType); Result.LastCall.CallType := lcQuerySetCall; Result.LastCall.InfoClass := Cardinal(InfoClass); Result.LastCall.InfoClassType := TypeInfo(TServiceConfigLevel); Result.Win32Result := ChangeServiceConfig2W(hSvc, InfoClass, Buffer); end; function ScmxQueryDescriptionService(hSvc: TScmHandle; out Description: String): TNtxStatus; var xMemory: IMemory; begin Result := ScmxQueryService(hSvc, ServiceConfigDescription, xMemory); if Result.IsSuccess then Description := String(PServiceDescription(xMemory.Address).Description); end; function ScmxQueryRequiredPrivilegesService(hSvc: TScmHandle; out Privileges: TArray<String>): TNtxStatus; var xMemory: IMemory; Buffer: PServiceRequiredPrivilegesInfo; begin Result := ScmxQueryService(hSvc, ServiceConfigRequiredPrivilegesInfo, xMemory); if Result.IsSuccess then begin Buffer := xMemory.Address; if Assigned(Buffer.RequiredPrivileges) and (xMemory.Size > SizeOf(TServiceRequiredPrivilegesInfo)) then Privileges := ParseMultiSz(Buffer.RequiredPrivileges, (xMemory.Size - SizeOf(TServiceRequiredPrivilegesInfo)) div SizeOf(WideChar)) else SetLength(Privileges, 0); end; end; end.
unit Plugins; interface uses {$IFDEF DPMI} { WinProcs, } WinApi, {$ENDIF} {$IFDEF WIN32} Windows, {$ENDIF} {$IFDEF OS2} OS2base, {$ENDIF} Types, Language, Video, Config, Semaphor, Consts_, Wizard, Strings; const Pool: PCollection = Nil; type PService = ^TService; TService = function(ServiceNumber: Longint; Buffer: Pointer): Longint; PPlugin = ^TPlugin; TPlugin = object(TObject) FName, Name, SearchName: PString; Service: TService; ErrorCode: Longint; {$IFDEF VIRTUALPASCAL} Handle: Longint; {$ELSE} Handle: Word; {$ENDIF} constructor Init(const AFName: String); function Load: Boolean; procedure Unload; procedure Boot; destructor Done; virtual; end; {$IFDEF SOLID} type TQueryPluginService = function(const FName: String): Pointer; const QueryPluginService: TQueryPluginService = Nil; {$ENDIF} { called by plugins & kernel } function pGet: PCollection; {$IFNDEF SOLID}export;{$ENDIF} function pSearch(Name: String): PPlugin; {$IFNDEF SOLID}export;{$ENDIF} procedure pQueryPluginInfo(const Plugin: Pointer; var FName, Name, SearchName: String; var Service: Pointer); {$IFNDEF SOLID}export;{$ENDIF} procedure srvBroadcast(const ServiceNumber: Longint; const Buffer: Pointer); {$IFNDEF SOLID}export;{$ENDIF} function srvExecute(const Name: String; const ServiceNumber: Longint; const Buffer: Pointer): Longint; {$IFNDEF SOLID}export;{$ENDIF} function srvExecuteDirect(const Plugin: Pointer; const ServiceNumber: Longint; const Buffer: Pointer): Longint; {$IFNDEF SOLID}export;{$ENDIF} implementation {$IFDEF SOLID} const MaxHandle: Longint = 0; {$ENDIF} constructor TPlugin.Init(const AFName: String); begin inherited Init; FName:=NewStr(AFName); Name:=Nil; SearchName:=Nil; Service:=Nil; end; function TPlugin.Load: Boolean; {$IFDEF SOLID} var FileName: String; begin FileName:=FName^; TrimEx(FileName); StUpCaseEx(FileName); FileName:=JustFileName(FileName); @Service:=QueryPluginService(FileName); if @Service = Nil then begin sSetSemaphore('Plugin.Subsystem.ErrorString', 'plugin.internal.x3'); Load:=False; Exit; end; Load:=True; Inc(MaxHandle); Handle:=MaxHandle; end; {$ELSE} var Temp, FileName: array[0..256] of Char; begin sSetSemaphore('Plugin.Subsystem.ErrorString', 'plugin.error.linking'); StrPCopy(@FileName, FName^); {$IFDEF OS2} ErrorCode:=DosLoadModule(Temp, SizeOf(Temp), FileName, Handle); if ErrorCode <> 0 then begin Load:=False; Exit; end; DosQueryProcAddr(Handle, 0, 'SERVICE', @Service); {$ELSE} Handle:=LoadLibrary(@FileName); {$IFDEF DPMI} if Handle < 22 then begin ErrorCode:=Handle; Load:=False; Exit; end; @Service:=GetProcAddress(Handle, 'Service'); {$ELSE} if Handle = 0 then begin ErrorCode:=GetLastError; Load:=False; Exit; end; @Service:=GetProcAddress(Handle, 'SERVICE'); {$ENDIF} {$ENDIF} if @Service = Nil then begin sSetSemaphore('Plugin.Subsystem.ErrorString', 'plugin.error.noservice'); Load:=False; Exit; end; Load:=True; end; {$ENDIF} procedure TPlugin.Unload; {$IFDEF SOLID} begin end; {$ELSE} begin {$IFDEF OS2} DosFreeModule(Handle); {$ELSE} FreeLibrary(Handle); {$ENDIF} end; {$ENDIF} procedure TPlugin.Boot; begin Service(snQueryName, Nil); DisposeStr(Name); DisposeStr(SearchName); Name:=NewStr(sGetSemaphore('Kernel.Plugins.Info.Name')); SearchName:=NewStr(StUpCase(Trim(Name^))); end; destructor TPlugin.Done; begin DisposeStr(FName); inherited Done; end; function pGet: PCollection; begin pGet:=Pool; end; function pSearch(Name: String): PPlugin; var K: Longint; begin StUpCaseEx(Name); for K:=1 to Pool^.Count do if PPlugin(Pool^.At(K))^.SearchName^ = Name then begin pSearch:=Pool^.At(K); Exit; end; pSearch:=Nil; end; procedure pQueryPluginInfo(const Plugin: Pointer; var FName, Name, SearchName: String; var Service: Pointer); begin GetPStringEx(PPlugin(Plugin)^.FName, FName); GetPStringEx(PPlugin(Plugin)^.Name, Name); GetPStringEx(PPlugin(Plugin)^.SearchName, SearchName); Service:=@PPlugin(Plugin)^.Service; end; procedure srvBroadcast(const ServiceNumber: Longint; const Buffer: Pointer); var K: Longint; begin for K:=1 to Pool^.Count do PPlugin(Pool^.At(K))^.Service(ServiceNumber, Buffer); end; function srvExecute(const Name: String; const ServiceNumber: Longint; const Buffer: Pointer): Longint; var P: PPlugin; begin P:=pSearch(Name); if P = Nil then srvExecute:=$FFFFFFFF else srvExecute:=P^.Service(ServiceNumber, Buffer); end; function srvExecuteDirect(const Plugin: Pointer; const ServiceNumber: Longint; const Buffer: Pointer): Longint; begin srvExecuteDirect:=PPlugin(Plugin)^.Service(ServiceNumber, Buffer); end; end.
{********************************************} { TeeChart Pro Charting Library } { Copyright (c) 1995-2004 by David Berneda } { All Rights Reserved } {********************************************} unit TeeEdiPeri; {$I TeeDefs.inc} interface uses {$IFDEF CLR} Borland.VCL.StdCtrls, Borland.VCL.Controls, SysUtils, {$ELSE} {$IFNDEF LINUX} Windows, Messages, {$ENDIF} SysUtils, Classes, {$IFDEF CLX} QGraphics, QControls, QForms, QDialogs, QExtCtrls, QStdCtrls, {$ELSE} Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, {$ENDIF} {$ENDIF} TeeProcs, TeEngine, TeCanvas, TeeBaseFuncEdit; type TTeeFunctionEditor = class(TBaseFunctionEditor) ENum: TEdit; BChange: TButton; Label1: TLabel; CBAlign: TComboFlat; Label2: TLabel; CBStyle: TComboFlat; Label3: TLabel; procedure BChangeClick(Sender: TObject); procedure ENumChange(Sender: TObject); procedure CBAlignChange(Sender: TObject); procedure CBStyleChange(Sender: TObject); private { Private declarations } protected procedure ApplyFormChanges; override; Procedure SetFunction; override; public { Public declarations } end; implementation {$IFNDEF CLX} {$R *.DFM} {$ELSE} {$R *.xfm} {$ENDIF} Uses {$IFDEF CLR} Classes, {$ELSE} Math, {$ENDIF} TeeAxisIncr, TeeConst; Procedure TTeeFunctionEditor.SetFunction; var CanRange : Boolean; begin inherited; CanRange:=not (IFunction is TTeeMovingFunction); With IFunction do begin if (PeriodStyle=psRange) and CanRange then CBStyle.ItemIndex:=2 else if Round(Period)=0 then CBStyle.ItemIndex:=0 else CBStyle.ItemIndex:=1; CBAlign.ItemIndex:=Ord(PeriodAlign); ENum.Enabled:=CBStyle.ItemIndex<>0; BChange.Enabled:=CBStyle.ItemIndex=2; CBStyleChange(Self); end; end; procedure TTeeFunctionEditor.BChangeClick(Sender: TObject); Function CalcIsDateTime:Boolean; begin With IFunction.ParentSeries do if Assigned(DataSource) and (DataSource is TChartSeries) then result:=TChartSeries(DataSource).XValues.DateTime else result:=False; end; var tmp : TAxisIncrement; begin tmp:=TAxisIncrement.Create(Self); with tmp do try IsDateTime :=CalcIsDateTime; IsExact :=True; Increment :=IFunction.Period; IStep :=FindDateTimeStep(IFunction.Period); Caption :=TeeMsg_PeriodRange; TeeTranslateControl(tmp); if ShowModal=mrOk then begin ENum.Text:=FloatToStr(Increment); // TheIsDateTime:=IsDateTime; end; finally Free; end; end; procedure TTeeFunctionEditor.ENumChange(Sender: TObject); begin EnableApply; end; procedure TTeeFunctionEditor.ApplyFormChanges; begin inherited; With IFunction do begin PeriodAlign:=TFunctionPeriodAlign(CBAlign.ItemIndex); if CBStyle.ItemIndex=2 then PeriodStyle:=psRange else PeriodStyle:=psNumPoints; Period:=StrToFloatDef(ENum.Text,0); end; end; procedure TTeeFunctionEditor.CBAlignChange(Sender: TObject); begin EnableApply; end; procedure TTeeFunctionEditor.CBStyleChange(Sender: TObject); var tmpMax : Double; begin ENum.Enabled:=CBStyle.ItemIndex<>0; BChange.Enabled:=CBStyle.ItemIndex=2; if Assigned(IFunction) then tmpMax:=IFunction.Period else tmpMax:=0; case CBStyle.ItemIndex of 0: ENum.Text:=''; 1: ENum.Text:=FloatToStr(Round(Math.Max(0,tmpMax))) else ENum.Text:=FloatToStr(tmpMax); end; if ENum.Enabled then ENum.SetFocus; EnableApply; end; initialization RegisterClass(TTeeFunctionEditor); end.
unit test_unit2; interface Const MAX_CANTIDAD_SERIES = 4;{predeterminado por la catedra ya que son cuatro series las que se piden} MAX_TEMPORADAS_POR_SERIE = 10;{Valor elejido por el equipo comparando esta cantidad en diferentes sitios} MAX_EPISODIOS_POR_TEMPORADA = 25;{Valor elejido comparando en distintos sitios cual usual es el numero de temporadas} MAX_USUARIOS = 60000;{predeterminado por el equipo} MAX_VISUALIZACIONES_POR_USUARIO = 1000;{predeterminado por el equipo} Type {Estructura de datos de las series} trVideo = record titulo : string[72]; descripcion : string[234]; duracionEnSegundos : longint; visualizaciones : longint end; tvVideo = array[1..MAX_EPISODIOS_POR_TEMPORADA] of trVideo; trTemp = record anioDeEmision : string[4]; cantEpiDeTemp : byte; vVideo : tvVideo end; tvTemp = array[1..MAX_TEMPORADAS_POR_SERIE] of trTemp; trSerie = record nombre : string[71]; descripcion : string[140]; cantTemp : byte; vTemp : tvTemp end; tvSerie = array[1..MAX_CANTIDAD_SERIES] of trSerie; {Estructura de datos del usuario} trVisualizacion = record posicionSerieEnArregloSerie : longint; numTempEnLaSerie : byte; numEpiDeLaTemp : byte; cantVisualizaciones : byte end; tvVisualizacion = array[1..MAX_VISUALIZACIONES_POR_USUARIO] of trVisualizacion; trUsuario = record nombreUsuario : string[8]; vVisualizacion : tvVisualizacion end; tvUsuario = array[1..MAX_USUARIOS] of trUsuario; procedure cargarSeries(var vSerie: tvSerie); procedure imprimir(vSerie : tvSerie); implementation procedure cargarSeries(var vSerie: tvSerie); {Pre: Se recibe el vector Series vacio o con datos} {Post: Se cargan las series al vector Series. En caso de haber tenido datos estos se eliminan} begin vSerie[1].nombre := 'Friends'; vSerie[1].descripcion := 'Friends fue una serie de television estadounidense creada y producida por Marta Kauffman y David Crane.'; vSerie[1].cantTemp := 3; vSerie[1].vTemp[1].anioDeEmision := '1994'; vSerie[1].vTemp[1].cantEpiDeTemp := 5; vSerie[1].vTemp[1].vVideo[1].titulo := 'En el que Monica tiene una nueva companiera'; vSerie[1].vTemp[1].vVideo[1].descripcion := 'S01E01 Friends'; vSerie[1].vTemp[1].vVideo[1].duracionEnSegundos := 1320; vSerie[1].vTemp[1].vVideo[1].visualizaciones := 0; vSerie[1].vTemp[1].vVideo[2].titulo := 'El de la ecografia al final'; vSerie[1].vTemp[1].vVideo[2].descripcion := 'S01E02 Friends'; vSerie[1].vTemp[1].vVideo[2].duracionEnSegundos := 1320; vSerie[1].vTemp[1].vVideo[2].visualizaciones := 0; vSerie[1].vTemp[1].vVideo[3].titulo := 'El del pulgar'; vSerie[1].vTemp[1].vVideo[3].descripcion := 'S01E03 Friends'; vSerie[1].vTemp[1].vVideo[3].duracionEnSegundos := 1320; vSerie[1].vTemp[1].vVideo[3].visualizaciones := 0; vSerie[1].vTemp[1].vVideo[4].titulo := 'El de George Stephanopoulos'; vSerie[1].vTemp[1].vVideo[4].descripcion := 'S01E04 Friends'; vSerie[1].vTemp[1].vVideo[4].duracionEnSegundos := 1320; vSerie[1].vTemp[1].vVideo[4].visualizaciones := 0; vSerie[1].vTemp[1].vVideo[5].titulo := 'El del detergente germano oriental extrafuerte '; vSerie[1].vTemp[1].vVideo[5].descripcion := 'S01E05 Friends'; vSerie[1].vTemp[1].vVideo[5].duracionEnSegundos := 1320; vSerie[1].vTemp[1].vVideo[5].visualizaciones := 0; vSerie[1].vTemp[2].anioDeEmision := '1995'; vSerie[1].vTemp[2].cantEpiDeTemp := 5; vSerie[1].vTemp[2].vVideo[1].titulo := 'El de la nueva novia de Ross'; vSerie[1].vTemp[2].vVideo[1].descripcion := 'S02E01 Friends'; vSerie[1].vTemp[2].vVideo[1].duracionEnSegundos := 1320; vSerie[1].vTemp[2].vVideo[1].visualizaciones := 0; vSerie[1].vTemp[2].vVideo[2].titulo := 'El de la leche materna '; vSerie[1].vTemp[2].vVideo[2].descripcion := 'S02E02 Friends'; vSerie[1].vTemp[2].vVideo[2].duracionEnSegundos := 1320; vSerie[1].vTemp[2].vVideo[2].visualizaciones := 0; vSerie[1].vTemp[2].vVideo[3].titulo := 'En el que Heckles muere'; vSerie[1].vTemp[2].vVideo[3].descripcion := 'S02E03 Friends'; vSerie[1].vTemp[2].vVideo[3].duracionEnSegundos := 1320; vSerie[1].vTemp[2].vVideo[3].visualizaciones := 0; vSerie[1].vTemp[2].vVideo[4].titulo := 'El del marido de Phoebe'; vSerie[1].vTemp[2].vVideo[4].descripcion := 'S02E04 Friends'; vSerie[1].vTemp[2].vVideo[4].duracionEnSegundos := 1320; vSerie[1].vTemp[2].vVideo[4].visualizaciones := 0; vSerie[1].vTemp[2].vVideo[5].titulo := 'El de los cinco filetes y la berenjena '; vSerie[1].vTemp[2].vVideo[5].descripcion := 'S02E05 Friends'; vSerie[1].vTemp[2].vVideo[5].duracionEnSegundos := 1320; vSerie[1].vTemp[2].vVideo[5].visualizaciones := 0; vSerie[1].vTemp[3].anioDeEmision := '1996'; vSerie[1].vTemp[3].cantEpiDeTemp := 5; vSerie[1].vTemp[3].vVideo[1].titulo := 'El de la fantasia de la princesa Leia' ; vSerie[1].vTemp[3].vVideo[1].descripcion := 'S03E01 Friends'; vSerie[1].vTemp[3].vVideo[1].duracionEnSegundos := 1320; vSerie[1].vTemp[3].vVideo[1].visualizaciones := 0; vSerie[1].vTemp[3].vVideo[2].titulo := 'En el que ninguno esta preparado'; vSerie[1].vTemp[3].vVideo[2].descripcion := 'S03E02 Friends'; vSerie[1].vTemp[3].vVideo[2].duracionEnSegundos := 1320; vSerie[1].vTemp[3].vVideo[2].visualizaciones := 0; vSerie[1].vTemp[3].vVideo[3].titulo := 'El de la mermelada'; vSerie[1].vTemp[3].vVideo[3].descripcion := 'S03E03 Friends'; vSerie[1].vTemp[3].vVideo[3].duracionEnSegundos := 1320; vSerie[1].vTemp[3].vVideo[3].visualizaciones := 0; vSerie[1].vTemp[3].vVideo[4].titulo := 'El del tunel metaforico'; vSerie[1].vTemp[3].vVideo[4].descripcion := 'S03E04 Friends'; vSerie[1].vTemp[3].vVideo[4].duracionEnSegundos := 1320; vSerie[1].vTemp[3].vVideo[4].visualizaciones := 0; vSerie[1].vTemp[3].vVideo[5].titulo := 'El de Frank Jr.'; vSerie[1].vTemp[3].vVideo[5].descripcion := 'S03E05 Friends'; vSerie[1].vTemp[3].vVideo[5].duracionEnSegundos := 1320; vSerie[1].vTemp[3].vVideo[5].visualizaciones := 0; vSerie[2].nombre := 'Futurama'; vSerie[2].descripcion := 'Futurama se desarrolla durante el siglo XXXI, un siglo lleno de maravillas tecnologicas'; vSerie[2].cantTemp := 3; vSerie[2].vTemp[1].anioDeEmision := '1999'; vSerie[2].vTemp[1].cantEpiDeTemp := 5; vSerie[2].vTemp[1].vVideo[1].titulo := 'Piloto espacial 3000 '; vSerie[2].vTemp[1].vVideo[1].descripcion := 'S01E01 Futurama'; vSerie[2].vTemp[1].vVideo[1].duracionEnSegundos := 1320; vSerie[2].vTemp[1].vVideo[1].visualizaciones := 0; vSerie[2].vTemp[1].vVideo[2].titulo := 'La serie ha aterrizado '; vSerie[2].vTemp[1].vVideo[2].descripcion := 'S01E02 Futurama'; vSerie[2].vTemp[1].vVideo[2].duracionEnSegundos := 1320; vSerie[2].vTemp[1].vVideo[2].visualizaciones := 0; vSerie[2].vTemp[1].vVideo[3].titulo := 'Yo, companiero de piso'; vSerie[2].vTemp[1].vVideo[3].descripcion := 'S01E03 Futurama'; vSerie[2].vTemp[1].vVideo[3].duracionEnSegundos := 1320; vSerie[2].vTemp[1].vVideo[3].visualizaciones := 0; vSerie[2].vTemp[1].vVideo[4].titulo := 'Obras de amor perdidas en el espacio'; vSerie[2].vTemp[1].vVideo[4].descripcion := 'S01E04 Futurama'; vSerie[2].vTemp[1].vVideo[4].duracionEnSegundos := 1320; vSerie[2].vTemp[1].vVideo[4].visualizaciones := 0; vSerie[2].vTemp[1].vVideo[5].titulo := 'Temor a un planeta robot '; vSerie[2].vTemp[1].vVideo[5].descripcion := 'S01E05 Futurama'; vSerie[2].vTemp[1].vVideo[5].duracionEnSegundos := 1320; vSerie[2].vTemp[1].vVideo[5].visualizaciones := 0; vSerie[2].vTemp[2].anioDeEmision := '1999'; vSerie[2].vTemp[2].cantEpiDeTemp := 5; vSerie[2].vTemp[2].vVideo[1].titulo := 'Yo siento esa mocion'; vSerie[2].vTemp[2].vVideo[1].descripcion := 'S02E01 Futurama'; vSerie[2].vTemp[2].vVideo[1].duracionEnSegundos := 1320; vSerie[2].vTemp[2].vVideo[1].visualizaciones := 0; vSerie[2].vTemp[2].vVideo[2].titulo := 'Brannigan, comienza de nuevo'; vSerie[2].vTemp[2].vVideo[2].descripcion := 'S02E02 Futurama'; vSerie[2].vTemp[2].vVideo[2].duracionEnSegundos := 1320; vSerie[2].vTemp[2].vVideo[2].visualizaciones := 0; vSerie[2].vTemp[2].vVideo[3].titulo := 'A la cabeza en las encuestas'; vSerie[2].vTemp[2].vVideo[3].descripcion := 'S02E03 Futurama'; vSerie[2].vTemp[2].vVideo[3].duracionEnSegundos := 1320; vSerie[2].vTemp[2].vVideo[3].visualizaciones := 0; vSerie[2].vTemp[2].vVideo[4].titulo := 'Cuento de Navidad'; vSerie[2].vTemp[2].vVideo[4].descripcion := 'S02E04 Futurama'; vSerie[2].vTemp[2].vVideo[4].duracionEnSegundos := 1320; vSerie[2].vTemp[2].vVideo[4].visualizaciones := 0; vSerie[2].vTemp[2].vVideo[5].titulo := '¿Por que debo ser un crustaceo enamorado?'; vSerie[2].vTemp[2].vVideo[5].descripcion := 'S02E05 Futurama'; vSerie[2].vTemp[2].vVideo[5].duracionEnSegundos := 1320; vSerie[2].vTemp[2].vVideo[5].visualizaciones := 0; vSerie[2].vTemp[3].anioDeEmision := '2001'; vSerie[2].vTemp[3].cantEpiDeTemp := 5; vSerie[2].vTemp[3].vVideo[1].titulo := 'Amazonas enamoradas'; vSerie[2].vTemp[3].vVideo[1].descripcion := 'S03E01 Futurama'; vSerie[2].vTemp[3].vVideo[1].duracionEnSegundos := 1320; vSerie[2].vTemp[3].vVideo[1].visualizaciones := 0; vSerie[2].vTemp[3].vVideo[2].titulo := 'Parasitos perdidos'; vSerie[2].vTemp[3].vVideo[2].descripcion := 'S03E02 Futurama'; vSerie[2].vTemp[3].vVideo[2].duracionEnSegundos := 1320; vSerie[2].vTemp[3].vVideo[2].visualizaciones := 0; vSerie[2].vTemp[3].vVideo[3].titulo := 'Historia de dos Santa Claus'; vSerie[2].vTemp[3].vVideo[3].descripcion := 'S03E03 Futurama'; vSerie[2].vTemp[3].vVideo[3].duracionEnSegundos := 1320; vSerie[2].vTemp[3].vVideo[3].visualizaciones := 0; vSerie[2].vTemp[3].vVideo[4].titulo := 'La suerte de los Fry'; vSerie[2].vTemp[3].vVideo[4].descripcion := 'S03E04 Futurama'; vSerie[2].vTemp[3].vVideo[4].duracionEnSegundos := 1320; vSerie[2].vTemp[3].vVideo[4].visualizaciones := 0; vSerie[2].vTemp[3].vVideo[5].titulo := 'El ave robot del Helacatraz'; vSerie[2].vTemp[3].vVideo[5].descripcion := 'S03E05 Futurama'; vSerie[2].vTemp[3].vVideo[5].duracionEnSegundos := 1320; vSerie[2].vTemp[3].vVideo[5].visualizaciones := 0; vSerie[3].nombre := 'Game of Thrones'; vSerie[3].descripcion := 'Esta basada en la serie de novelas Cancion de Hielo y Fuego del escritor George R. R. Martin.'; vSerie[3].cantTemp := 2; vSerie[3].vTemp[1].anioDeEmision := '2011'; vSerie[3].vTemp[1].cantEpiDeTemp := 5; vSerie[3].vTemp[1].vVideo[1].titulo := 'Se acerca el invierno'; vSerie[3].vTemp[1].vVideo[1].descripcion := 'S01E01 Game of Thrones'; vSerie[3].vTemp[1].vVideo[1].duracionEnSegundos := 1320; vSerie[3].vTemp[1].vVideo[1].visualizaciones := 0; vSerie[3].vTemp[1].vVideo[2].titulo := 'El camino real'; vSerie[3].vTemp[1].vVideo[2].descripcion := 'S01E02 Game of Thrones'; vSerie[3].vTemp[1].vVideo[2].duracionEnSegundos := 1320; vSerie[3].vTemp[1].vVideo[2].visualizaciones := 0; vSerie[3].vTemp[1].vVideo[3].titulo := 'Lord Nieve'; vSerie[3].vTemp[1].vVideo[3].descripcion := 'S01E03 Game of Thrones'; vSerie[3].vTemp[1].vVideo[3].duracionEnSegundos := 1320; vSerie[3].vTemp[1].vVideo[3].visualizaciones := 0; vSerie[3].vTemp[1].vVideo[4].titulo := 'Tullidos, bastardos y cosas rotas'; vSerie[3].vTemp[1].vVideo[4].descripcion := 'S01E04 Game of Thrones'; vSerie[3].vTemp[1].vVideo[4].duracionEnSegundos := 1320; vSerie[3].vTemp[1].vVideo[4].visualizaciones := 0; vSerie[3].vTemp[1].vVideo[5].titulo := 'El lobo y el leon'; vSerie[3].vTemp[1].vVideo[5].descripcion := 'S01E05 Game of Thrones'; vSerie[3].vTemp[1].vVideo[5].duracionEnSegundos := 1320; vSerie[3].vTemp[1].vVideo[5].visualizaciones := 0; vSerie[3].vTemp[2].anioDeEmision := '2012'; vSerie[3].vTemp[2].cantEpiDeTemp := 5; vSerie[3].vTemp[2].vVideo[1].titulo := 'El Norte no olvida'; vSerie[3].vTemp[2].vVideo[1].descripcion := 'S02E01 Game of Thrones'; vSerie[3].vTemp[2].vVideo[1].duracionEnSegundos := 1320; vSerie[3].vTemp[2].vVideo[1].visualizaciones := 0; vSerie[3].vTemp[2].vVideo[2].titulo := 'Las tierras de la noche'; vSerie[3].vTemp[2].vVideo[2].descripcion := 'S02E02 Game of Thrones'; vSerie[3].vTemp[2].vVideo[2].duracionEnSegundos := 1320; vSerie[3].vTemp[2].vVideo[2].visualizaciones := 0; vSerie[3].vTemp[2].vVideo[3].titulo := 'Lo que esta muerto no puede morir'; vSerie[3].vTemp[2].vVideo[3].descripcion := 'S02E03 Game of Thrones'; vSerie[3].vTemp[2].vVideo[3].duracionEnSegundos := 1320; vSerie[3].vTemp[2].vVideo[3].visualizaciones := 0; vSerie[3].vTemp[2].vVideo[4].titulo := 'Jardin de Huesos'; vSerie[3].vTemp[2].vVideo[4].descripcion := 'S02E04 Game of Thrones'; vSerie[3].vTemp[2].vVideo[4].duracionEnSegundos := 1320; vSerie[3].vTemp[2].vVideo[4].visualizaciones := 0; vSerie[3].vTemp[2].vVideo[5].titulo := 'El Fantasma de Harrenhal'; vSerie[3].vTemp[2].vVideo[5].descripcion := 'S02E05 Game of Thrones'; vSerie[3].vTemp[2].vVideo[5].duracionEnSegundos := 1320; vSerie[3].vTemp[2].vVideo[5].visualizaciones := 0; vSerie[3].vTemp[3].anioDeEmision := '2013'; vSerie[3].vTemp[3].cantEpiDeTemp := 5; vSerie[3].vTemp[3].vVideo[1].titulo := 'Valar Dohaeris'; vSerie[3].vTemp[3].vVideo[1].descripcion := 'S03E01 Game of Thrones'; vSerie[3].vTemp[3].vVideo[1].duracionEnSegundos := 1320; vSerie[3].vTemp[3].vVideo[1].visualizaciones := 0; vSerie[3].vTemp[3].vVideo[2].titulo := 'Alas negras, palabras negras'; vSerie[3].vTemp[3].vVideo[2].descripcion := 'S03E02 Game of Thrones'; vSerie[3].vTemp[3].vVideo[2].duracionEnSegundos := 1320; vSerie[3].vTemp[3].vVideo[2].visualizaciones := 0; vSerie[3].vTemp[3].vVideo[3].titulo := 'El Camino del Castigo'; vSerie[3].vTemp[3].vVideo[3].descripcion := 'S03E03 Game of Thrones'; vSerie[3].vTemp[3].vVideo[3].duracionEnSegundos := 1320; vSerie[3].vTemp[3].vVideo[3].visualizaciones := 0; vSerie[3].vTemp[3].vVideo[4].titulo := 'Y ahora su guardia ha terminado'; vSerie[3].vTemp[3].vVideo[4].descripcion := 'S03E04 Game of Thrones'; vSerie[3].vTemp[3].vVideo[4].duracionEnSegundos := 1320; vSerie[3].vTemp[3].vVideo[4].visualizaciones := 0; vSerie[3].vTemp[3].vVideo[5].titulo := 'Besado por el fuego'; vSerie[3].vTemp[3].vVideo[5].descripcion := 'S03E05 Game of Thrones'; vSerie[3].vTemp[3].vVideo[5].duracionEnSegundos := 1320; vSerie[3].vTemp[3].vVideo[5].visualizaciones := 0; vSerie[4].nombre := 'Los Simuladores'; vSerie[4].descripcion := 'Serie argentina acerca de un grupo de cuatro socios que mediante operativos de simulacro sofisticados resuelven los problemas de gente comun.'; vSerie[4].cantTemp := 2; vSerie[4].vTemp[1].anioDeEmision := '2002'; vSerie[4].vTemp[1].cantEpiDeTemp := 5; vSerie[4].vTemp[1].vVideo[1].titulo := 'Tarjeta de navidad'; vSerie[4].vTemp[1].vVideo[1].descripcion := 'S01E01 Los Simuladores'; vSerie[4].vTemp[1].vVideo[1].duracionEnSegundos := 1320; vSerie[4].vTemp[1].vVideo[1].visualizaciones := 0; vSerie[4].vTemp[1].vVideo[2].titulo := 'Diagnostico rectoscopico'; vSerie[4].vTemp[1].vVideo[2].descripcion := 'S01E02 Los Simuladores'; vSerie[4].vTemp[1].vVideo[2].duracionEnSegundos := 1320; vSerie[4].vTemp[1].vVideo[2].visualizaciones := 0; vSerie[4].vTemp[1].vVideo[3].titulo := 'Seguro de desempleo'; vSerie[4].vTemp[1].vVideo[3].descripcion := 'S01E03 Los Simuladores'; vSerie[4].vTemp[1].vVideo[3].duracionEnSegundos := 1320; vSerie[4].vTemp[1].vVideo[3].visualizaciones := 0; vSerie[4].vTemp[1].vVideo[4].titulo := 'El testigo espaniol'; vSerie[4].vTemp[1].vVideo[4].descripcion := 'S01E04 Los Simuladores'; vSerie[4].vTemp[1].vVideo[4].duracionEnSegundos := 1320; vSerie[4].vTemp[1].vVideo[4].visualizaciones := 0; vSerie[4].vTemp[1].vVideo[5].titulo := 'El joven simulador'; vSerie[4].vTemp[1].vVideo[5].descripcion := 'S01E05 Los Simuladores'; vSerie[4].vTemp[1].vVideo[5].duracionEnSegundos := 1320; vSerie[4].vTemp[1].vVideo[5].visualizaciones := 0; vSerie[4].vTemp[2].anioDeEmision := '2003'; vSerie[4].vTemp[2].cantEpiDeTemp := 5; vSerie[4].vTemp[2].vVideo[1].titulo := 'Los cuatro notables'; vSerie[4].vTemp[2].vVideo[1].descripcion := 'S02E01 Los Simuladores'; vSerie[4].vTemp[2].vVideo[1].duracionEnSegundos := 1320; vSerie[4].vTemp[2].vVideo[1].visualizaciones := 0; vSerie[4].vTemp[2].vVideo[2].titulo := 'Z-9000'; vSerie[4].vTemp[2].vVideo[2].descripcion := 'S02E02 Los Simuladores'; vSerie[4].vTemp[2].vVideo[2].duracionEnSegundos := 1320; vSerie[4].vTemp[2].vVideo[2].visualizaciones := 0; vSerie[4].vTemp[2].vVideo[3].titulo := 'La gargantilla de las cuatro estaciones'; vSerie[4].vTemp[2].vVideo[3].descripcion := 'S02E03 Los Simuladores'; vSerie[4].vTemp[2].vVideo[3].duracionEnSegundos := 1320; vSerie[4].vTemp[2].vVideo[3].visualizaciones := 0; vSerie[4].vTemp[2].vVideo[4].titulo := 'El Clan Motul'; vSerie[4].vTemp[2].vVideo[4].descripcion := 'S02E04 Los Simuladores'; vSerie[4].vTemp[2].vVideo[4].duracionEnSegundos := 1320; vSerie[4].vTemp[2].vVideo[4].visualizaciones := 0; vSerie[4].vTemp[2].vVideo[5].titulo := 'El vengador infantil'; vSerie[4].vTemp[2].vVideo[5].descripcion := 'S01E05 Los Simuladores'; vSerie[4].vTemp[2].vVideo[5].duracionEnSegundos := 1320; vSerie[4].vTemp[2].vVideo[5].visualizaciones := 0; end; procedure imprimir(vSerie : tvSerie); {Imprime los datos del vector} var i,j,k : integer; begin for i:=1 to MAX_CANTIDAD_SERIES do begin writeln; writeln('Nombre serie : ',vSerie[i].nombre); writeln('Descripcion : ',vSerie[i].descripcion); writeln('Cantidad de temporadas : ',vSerie[i].cantTemp); writeln; writeln; for j:=1 to vSerie[i].cantTemp do begin writeln('Anio de emision: ',vSerie[i].vTemp[j].anioDeEmision); writeln('Cantidad de episodios :',vSerie[i].vTemp[j].cantEpiDeTemp); writeln; for k:=1 to vSerie[i].vTemp[j].cantEpiDeTemp do begin writeln('Titulo : ', vSerie[i].vTemp[j].vVideo[k].titulo); writeln('Descripcion : ',vSerie[i].vTemp[j].vVideo[k].descripcion); writeln('Duracion en seg : ',vSerie[i].vTemp[j].vVideo[k].duracionEnSegundos); writeln('Visualizaciones : ',vSerie[i].vTemp[j].vVideo[k].visualizaciones); end; end; end; end; begin {ppal} end.
{ *************************************************************************** } { } { Delphi and Kylix Cross-Platform Visual Component Library } { } { Copyright (c) 2000-2002 Borland Software Corporation } { } { *************************************************************************** } unit QMenus; {$S-,W-,R-,T-,H+,X+} interface uses QTypes, SysUtils, Types, Classes, Qt, QGraphics, Contnrs, QActnList, QImgList; const ShortCutKeyMask = $0000FFFF; KeyMask = $1FFF; midSeparator = -1; midInvisible = 0; type EMenuError = class(Exception); TMenu = class; TMenuItem = class; { TMenuActionLink } TMenuActionLink = class(TActionLink) protected FClient: TMenuItem; procedure AssignClient(AClient: TObject); override; function IsCaptionLinked: Boolean; override; function IsCheckedLinked: Boolean; override; function IsEnabledLinked: Boolean; override; function IsHelpLinked: Boolean; override; function IsHintLinked: Boolean; override; function IsImageIndexLinked: Boolean; override; function IsShortCutLinked: Boolean; override; function IsVisibleLinked: Boolean; override; function IsOnExecuteLinked: Boolean; override; procedure SetCaption(const Value: TCaption); override; procedure SetChecked(Value: Boolean); override; procedure SetEnabled(Value: Boolean); override; procedure SetHelpContext(Value: THelpContext); override; procedure SetHelpKeyword(const Value: string); override; procedure SetHelpType(Value: THelpType); override; procedure SetHint(const Value: WideString); override; procedure SetImageIndex(Value: Integer); override; procedure SetShortCut(Value: TShortCut); override; procedure SetVisible(Value: Boolean); override; procedure SetOnExecute(Value: TNotifyEvent); override; end; TMenuActionLinkClass = class of TMenuActionLink; { TMenuItem } TMenuChangeEvent = procedure (Sender: TObject; Source: TMenuItem; Rebuild: Boolean) of object; TMenuItemAutoFlag = (maAutomatic, maManual, maParent); TMenuAutoFlag = maAutomatic..maManual; TMenuItem = class(THandleComponent) private FShortCut: TShortCut; FGroupIndex: Byte; FActionLink: TMenuActionLink; FAutoHotkeys: TMenuItemAutoFlag; FVisible: Boolean; FRadioItem: Boolean; FChecked: Boolean; FEnabled: Boolean; FID: Integer; FItems: TList; FBitmap: TBitmap; FCaption: WideString; FHint: WideString; FMenu: TMenu; FMenuData: QMenuDataH; FMerged: TMenuItem; FMergedWith: TMenuItem; FOnChange: TMenuChangeEvent; FParent: TMenuItem; FOnClick: TNotifyEvent; FOnHighlighted: TNotifyEvent; FOnShow: TNotifyEvent; FImageIndex: TImageIndex; FCurrentItem: TMenuItem; FMenuItemHandle: QMenuItemH; procedure ActivatedHook(ItemID: Integer); cdecl; procedure DoActionChange(Sender: TObject); procedure DoSetImageIndex(const Value: Integer); function GetAction: TBasicAction; procedure SetAction(Value: TBasicAction); function GetCount: Integer; function GetItem(Index: Integer): TMenuItem; function GetMenuIndex: Integer; procedure HighlightedHook(ItemID: Integer); cdecl; procedure ItemHandleNeeded; procedure MergeWith(Menu: TMenuItem); procedure RebuildMenu; procedure RemoveItemHandle; procedure SetBitmap(const Value: TBitmap); procedure SetCaption(const Value: WideString); procedure SetChecked(const Value: Boolean); procedure SetEnabled(const Value: Boolean); procedure SetGroupIndex(const Value: Byte); procedure SetMenuIndex(Value: Integer); procedure SetRadioItem(const Value: Boolean); procedure SetShortCut(const Value: TShortCut); procedure SetVisible(const Value: Boolean); procedure ShowHook; cdecl; procedure SubItemChanged(Sender: TObject; Source: TMenuItem; Rebuild: Boolean); function VisibleCount: Integer; procedure TurnSiblingsOff; procedure VerifyGroupIndex(Position: Integer; Value: Byte); function GetHandle: QPopupMenuH; procedure InitiateActions; procedure SetImageIndex(const Value: TImageIndex); procedure ChangePixmap(Value: QPixmapH); function IsBitmapStored: Boolean; function IsCaptionStored: Boolean; function IsCheckedStored: Boolean; function IsEnabledStored: Boolean; function IsHelpContextStored: Boolean; function IsHintStored: Boolean; function IsImageIndexStored: Boolean; function IsOnClickStored: Boolean; function IsShortCutStored: Boolean; function IsVisibleStored: Boolean; procedure UpdateItems; function InternalRethinkHotkeys(ForceRethink: Boolean): Boolean; procedure RemoveQtItemFromParent; procedure SetAutoHotkeys(const Value: TMenuItemAutoFlag); function GetAutoHotkeys: Boolean; protected procedure ActionChange(Sender: TObject; CheckDefaults: Boolean); dynamic; procedure AssignTo(Dest: TPersistent); override; procedure BitmapChanged(Sender: TObject); virtual; function FindItem(ItemID: Integer): TMenuItem; function GetActionLinkClass: TMenuActionLinkClass; dynamic; procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override; procedure Loaded; override; procedure CreateWidget; override; procedure DestroyWidget; override; function GetBitmap: TBitmap; function GetImageList: TCustomImageList; function MenuItemHandle: QMenuItemH; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure Highlighted; virtual; procedure HookEvents; override; procedure InvokeHelp; override; function InsertNewLine(ABefore: Boolean; AItem: TMenuItem): Integer; procedure MenuChanged(Rebuild: Boolean); virtual; procedure SetChildOrder(Child: TComponent; Order: Integer); override; procedure SetParentComponent(Value: TComponent); override; procedure Show; dynamic; function Showing: Boolean; function DisplayBitmap: Boolean; procedure WidgetDestroyed; override; property ActionLink: TMenuActionLink read FActionLink write FActionLink; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure InitiateAction; virtual; procedure Add(Item: TMenuItem); overload; procedure Add(const AItems: array of TMenuItem); overload; procedure Clear; procedure Click; virtual; procedure Delete(Index: Integer); function Find(const ACaption: WideString): TMenuItem; overload; function Find(AHandle: QMenuItemH): TMenuItem; overload; function GetParentComponent: TComponent; override; function GetParentMenu: TMenu; function HasBitmap: Boolean; function HasParent: Boolean; override; function IndexOf(Item: TMenuItem): Integer; function MenuData: QMenuDataH; procedure Insert(Index: Integer; Item: TMenuItem); function InsertNewLineBefore(AItem: TMenuItem): Integer; function InsertNewLineAfter(AItem: TMenuItem): Integer; function IsLine: Boolean; procedure Remove(Item: TMenuItem); function RethinkHotkeys: Boolean; property ID: Integer read FID; property Count: Integer read GetCount; property Handle: QPopupMenuH read GetHandle; property Items[Index: Integer]: TMenuItem read GetItem; default; property MenuIndex: Integer read GetMenuIndex write SetMenuIndex; property Parent: TMenuItem read FParent; published property Action: TBasicAction read GetAction write SetAction; property AutoHotkeys: TMenuItemAutoFlag read FAutoHotkeys write SetAutoHotkeys default maParent; property Bitmap: TBitmap read GetBitmap write SetBitmap stored IsBitmapStored; property Caption: WideString read FCaption write SetCaption stored IsCaptionStored; property Checked: Boolean read FChecked write SetChecked stored IsCheckedStored default False; property Enabled: Boolean read FEnabled write SetEnabled stored IsEnabledStored default True; property GroupIndex: Byte read FGroupIndex write SetGroupIndex default 0; property Hint: WideString read FHint write FHint stored IsHintStored; property ImageIndex: TImageIndex read FImageIndex write SetImageIndex stored IsImageIndexStored default -1; property RadioItem: Boolean read FRadioItem write SetRadioItem default False; property ShortCut: TShortCut read FShortCut write SetShortCut stored IsShortCutStored default 0; property Visible: Boolean read FVisible write SetVisible stored IsVisibleStored default True; property OnClick: TNotifyEvent read FOnClick write FOnClick stored IsOnClickStored; property OnHighlighted: TNotifyEvent read FOnHighlighted write FOnHighlighted; property OnShow: TNotifyEvent read FOnShow write FOnShow; property HelpKeyword stored IsHelpContextStored; property HelpType stored IsHelpContextStored; property HelpContext stored IsHelpContextStored; end; TFindItemKind = (fkID, fkHandle, fkShortCut); TMenu = class(THandleComponent) private FOnChange: TMenuChangeEvent; FItems: TMenuItem; FPalette: TWidgetPalette; FColor: TColor; FImages: TCustomImageList; FImageChangeLink: TChangeLink; FBitmap: TBitmap; procedure ActivatedHook(ItemID: Integer); cdecl; procedure ImageListChange(Sender: TObject); procedure HighlightedHook(ItemID: Integer); virtual; cdecl; procedure SetColor(const Value: TColor); procedure SetImages(const Value: TCustomImageList); procedure UpdateItemImages; function GetAutoHotkeys: TMenuAutoFlag; procedure SetAutoHotkeys(const Value: TMenuAutoFlag); function IsBitmapStored: Boolean; function GetBitmap: TBitmap; protected procedure BitmapChanged(Sender: TObject); virtual; procedure ColorChanged; virtual; procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override; procedure Loaded; override; procedure MenuChanged(Sender: TObject; Source: TMenuItem; Rebuild: Boolean); virtual; function MenuDataHandle: QMenuDataH; virtual; abstract; procedure DoChange(Source: TMenuItem; Rebuild: Boolean); virtual; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure PaletteChanged(Sender: TObject); virtual; procedure SetBitmap(Value: TBitmap); virtual; procedure SetChildOrder(Child: TComponent; Order: Integer); override; property AutoHotkeys: TMenuAutoFlag read GetAutoHotkeys write SetAutoHotkeys default maAutomatic; property Bitmap: TBitmap read GetBitmap write SetBitmap stored IsBitmapStored; property Color: TColor read FColor write SetColor default clButton; property OnChange: TMenuChangeEvent read FOnChange write FOnChange; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function FindItem(Value: Integer; Kind: TFindItemKind): TMenuItem; function IsShortCut(Key: Integer; Shift: TShiftState; const KeyText: WideString): Boolean; virtual; procedure SetForm(Value: TObject); property Images: TCustomImageList read FImages write SetImages; property Palette: TWidgetPalette read FPalette; published property Items: TMenuItem read FItems; end; TMainMenu = class(TMenu) private FAutoMerge: Boolean; function GetHandle: QMenuBarH; procedure ItemChanged; procedure SetAutoMerge(const Value: Boolean); protected procedure CreateWidget; override; procedure HookEvents; override; procedure MenuChanged(Sender: TObject; Source: TMenuItem; Rebuild: Boolean); override; function MenuDataHandle: QMenuDataH; override; public property Handle: QMenuBarH read GetHandle; function IsShortCut(Key: Integer; Shift: TShiftState; const KeyText: WideString): Boolean; override; procedure Merge(Menu: TMainMenu); procedure Unmerge(Menu: TMainMenu); published property AutoHotkeys; property AutoMerge: Boolean read FAutoMerge write SetAutoMerge default False; property Color; property Bitmap; property Images; property OnChange; property HelpType; property HelpKeyword; property HelpContext; end; TPopupAlignment = (paLeft, paRight, paCenter); TPopupMenu = class(TMenu) private FPopupPoint: TPoint; FAlignment: TPopupAlignment; FAutoPopup: Boolean; FPopupComponent: TComponent; FCurrentItem: TMenuItem; FOnPopup: TNotifyEvent; function GetHandle: QPopupMenuH; procedure HighlightedHook(ItemID: Integer); override; cdecl; procedure ShowHook; cdecl; protected function MenuDataHandle: QMenuDataH; override; procedure CreateWidget; override; procedure DoPopup(Sender: TObject); virtual; procedure HookEvents; override; procedure InvokeHelp; override; public constructor Create(AOwner: TComponent); override; procedure Popup(X, Y: Integer); virtual; property PopupComponent: TComponent read FPopupComponent write FPopupComponent; property Handle: QPopupMenuH read GetHandle; published property Alignment: TPopupAlignment read FAlignment write FAlignment default paLeft; property AutoHotkeys; property AutoPopup: Boolean read FAutoPopup write FAutoPopup default True; property Color; property Bitmap; property HelpContext; property HelpKeyword; property HelpType; property Images; property OnChange; property OnPopup: TNotifyEvent read FOnPopup write FOnPopup; end; PMenuItem = ^TMenuItem; TMenuItemStack = class(TStack) public procedure ClearItem(AItem: TMenuItem); end; const cHotkeyPrefix = '&'; cLineCaption = '-'; cDialogSuffix = '...'; var { These are the hotkeys that the auto-hotkey system will pick from. Change this global variable at runtime if you want to add or remove characters from the available characters. Notice that by default we do not do international characters. } ValidMenuHotkeys: string = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ'; { do not localize } ShortCutItems: TMenuItemStack; { StripHotkey removes the & escape char that marks the hotkey character(s) in the string. When the current locale is a Far East locale, this function also looks for and removes parens around the hotkey, common in Far East locales. } function StripHotkey(const Text: WideString): WideString; { GetHotkey will return the last hotkey that StripHotkey would strip. } function GetHotkey(const Text: WideString): WideString; { Similar to AnsiSameText but strips hotkeys before comparing } function AnsiSameCaption(const Text1, Text2: string): Boolean; function WideSameCaption(const Text1, Text2: WideString): Boolean; function ShortCut(Key: Word; Shift: TShiftState): TShortCut; procedure ShortCutToKey(ShortCut: TShortCut; var Key: Word; var Shift: TShiftState); function ShortCutToText(ShortCut: TShortCut): WideString; function TextToShortCut(const AText: string): TShortCut; function NewMenu(Owner: TComponent; const AName: string; const Items: array of TMenuItem): TMainMenu; function NewPopupMenu(Owner: TComponent; const AName: string; Alignment: TPopupAlignment; AutoPopup: Boolean; const Items: array of TMenuitem): TPopupMenu; function NewSubMenu(const ACaption: WideString; hCtx: THelpContext; const AName: string; const Items: array of TMenuItem; AEnabled: Boolean = True): TMenuItem; function NewItem(const ACaption: WideString; AShortCut: TShortCut; AChecked, AEnabled: Boolean; AOnClick: TNotifyEvent; hCtx: THelpContext; const AName: string): TMenuItem; function NewLine: TMenuItem; implementation {$IFDEF LINUX} uses QForms, QConsts, QControls, Libc; {$ENDIF} {$IFDEF MSWINDOWS} uses QForms, QConsts, QControls; {$ENDIF} const cMenuAutoFlagToItem: array [TMenuAutoFlag] of TMenuItemAutoFlag = (maAutomatic, maManual); cItemAutoFlagToMenu: array [TMenuItemAutoFlag] of TMenuAutoFlag = (maAutomatic, maManual, maAutomatic); cBooleanToItemAutoFlag: array [Boolean] of TMenuItemAutoFlag = (maManual, maAutomatic); cItemAutoFlagToBoolean: array [TMenuItemAutoFlag] of Boolean = (True, False, True); function ShortCutFlags(ShortCut: TShortCut): Integer; begin Result := ShortCut and KeyMask; if scShift and ShortCut = scShift then Result := Result or Integer(Modifier_SHIFT); if scCtrl and ShortCut = scCtrl then Result := Result or Integer(Modifier_CTRL); if scAlt and ShortCut = scAlt then Result := Result or Integer(Modifier_ALT); end; function StripHotkey(const Text: WideString): WideString; var I: Integer; begin Result := Text; for I := Length(Result) downto 1 do if Result[I] = cHotkeyPrefix then if SysLocale.FarEast and ((I > 2) and (Length(Result) - I >= 2) and (Result[I - 1] = '(') and (Result[I + 2] = ')')) then Delete(Result, I - 1, 4) else Delete(Result, I, 1); end; function GetHotkey(const Text: WideString): WideString; var I, L: Integer; begin Result := ''; I := 1; L := Length(Text) - 1; while I <= L do begin if Text[I] = cHotkeyPrefix then begin Inc(I); if Text[I] <> cHotkeyPrefix then Result := Text[I]; { keep going there may be another one } end; Inc(I); end; end; function AnsiSameCaption(const Text1, Text2: string): Boolean; begin Result := AnsiSameText(StripHotkey(Text1), StripHotkey(Text2)); end; function WideSameCaption(const Text1, Text2: WideString): Boolean; begin Result := WideSameText(StripHotkey(Text1), StripHotkey(Text2)); end; { Menu building functions } procedure InitMenuItems(AMenu: TMenu; const Items: array of TMenuItem); var I: Integer; procedure SetOwner(Item: TMenuItem); var I: Integer; begin if Item.Owner <> nil then AMenu.Owner.InsertComponent(Item); for I := 0 to Item.Count - 1 do SetOwner(Item[I]); end; begin for I := Low(Items) to High(Items) do begin SetOwner(Items[I]); AMenu.FItems.Add(Items[I]); end; end; function NewMenu(Owner: TComponent; const AName: string; const Items: array of TMenuItem): TMainMenu; begin Result := TMainMenu.Create(Owner); Result.Name := AName; InitMenuItems(Result, Items); end; function NewPopupMenu(Owner: TComponent; const AName: string; Alignment: TPopupAlignment; AutoPopup: Boolean; const Items: array of TMenuItem): TPopupMenu; begin Result := TPopupMenu.Create(Owner); Result.Name := AName; Result.AutoPopup := AutoPopup; Result.Alignment := Alignment; InitMenuItems(Result, Items); end; { should this also take a help string, maybe? APH } function NewSubMenu(const ACaption: WideString; hCtx: THelpContext; const AName: string; const Items: array of TMenuItem; AEnabled: Boolean): TMenuItem; var I: Integer; begin Result := TMenuItem.Create(nil); for I := Low(Items) to High(Items) do Result.Add(Items[I]); Result.Caption := ACaption; Result.HelpContext := hCtx; Result.Name := AName; Result.Enabled := AEnabled; end; { should this also take a help string, maybe? APH } function NewItem(const ACaption: WideString; AShortCut: TShortCut; AChecked, AEnabled: Boolean; AOnClick: TNotifyEvent; hCtx: THelpContext; const AName: string): TMenuItem; begin Result := TMenuItem.Create(nil); with Result do begin Caption := ACaption; ShortCut := AShortCut; OnClick := AOnClick; HelpContext := hCtx; Checked := AChecked; Enabled := AEnabled; Name := AName; end; end; function NewLine: TMenuItem; begin Result := TMenuItem.Create(nil); Result.Caption := cLineCaption; end; { TShortCut processing routines } function ShortCut(Key: Word; Shift: TShiftState): TShortCut; begin Result := 0; if (WordRec(Key).Hi <> 0) and not ((Key >= Key_Word_Lower) and (Key <= Key_Word_Upper)) then Exit; Result := Key; if ssShift in Shift then Inc(Result, scShift); if ssCtrl in Shift then Inc(Result, scCtrl); if ssAlt in Shift then Inc(Result, scAlt); end; procedure ShortCutToKey(ShortCut: TShortCut; var Key: Word; var Shift: TShiftState); begin Key := ShortCut and not (scShift + scCtrl + scAlt); Shift := []; if ShortCut and scShift <> 0 then Include(Shift, ssShift); if ShortCut and scCtrl <> 0 then Include(Shift, ssCtrl); if ShortCut and scAlt <> 0 then Include(Shift, ssAlt); end; type TMenuKeyCap = (mkcEsc, mkcTab, mkcBackTab, mkcBksp, mkcReturn, mkcEnter, mkcIns, mkcDel, mkcHome, mkcEnd, mkcLeft, mkcUp, mkcRight, mkcDown, mkcPgUp, mkcPgDn, mkcShift, mkcCtrl, mkcAlt, mkcSpace); var MenuKeyCaps: array[TMenuKeyCap] of string = ( SmkcEsc, SmkcTab, SmkcBackTab, SmkcBksp, SmkcReturn, SmkcEnter, SmkcIns, SmkcDel, SmkcHome, SmkcEnd, SmkcLeft, SmkcUp, SmkcRight, SmkcDown, SmkcPgUp, SmkcPgDn, SmkcShift, SmkcCtrl, SmkcAlt, SmkcSpace); function ShortCutToText(ShortCut: TShortCut): WideString; var Name: string; Key: Integer; begin Key := ShortCut and KeyMask; case Key of Key_Escape..Key_Delete: Name := MenuKeyCaps[TMenuKeyCap(Integer(Key) - Integer(Key_Escape))]; Key_Home..Key_Next: Name := MenuKeyCaps[TMenuKeyCap(Integer(Key) - Integer(Key_Home) + Ord(mkcHome))]; Key_F1..Key_F35: Name := 'F' + IntToStr(Integer(Key) - Integer(Key_F1) + 1); Key_Space: Name := MenuKeyCaps[mkcSpace]; Key_Exclam..Key_QuoteLeft, Key_BraceLeft..Key_AsciiTilde: Name := Chr(Key); $61..$7A: Name := Chr(Key - $20); end; if Name <> '' then begin Result := ''; if ShortCut and scCtrl <> 0 then Result := Result + MenuKeyCaps[mkcCtrl]; if ShortCut and scAlt <> 0 then Result := Result + MenuKeyCaps[mkcAlt]; if ShortCut and scShift <> 0 then Result := Result + MenuKeyCaps[mkcShift]; Result := Result + Name; end else Result := ''; end; { This function is *very* slow. Use sparingly. Return 0 if no VK code was found for the text } function TextToShortCut(const AText: string): TShortCut; { If the front of Text is equal to Front then remove the matching piece from Text and return True, otherwise return False } function CompareFront(var Text: string; const Front: string): Boolean; begin Result := False; if (Length(Text) >= Length(Front)) and (AnsiStrLIComp(PChar(Text), PChar(Front), Length(Front)) = 0) then begin Result := True; Delete(Text, 1, Length(Front)); end; end; var Key: TShortCut; Shift: TShortCut; Text: string; begin Result := 0; Shift := 0; Text := AText; while True do begin if CompareFront(Text, MenuKeyCaps[mkcShift]) then Shift := Shift or scShift else if CompareFront(Text, '^') then Shift := Shift or scCtrl else if CompareFront(Text, MenuKeyCaps[mkcCtrl]) then Shift := Shift or scCtrl else if CompareFront(Text, MenuKeyCaps[mkcAlt]) then Shift := Shift or scAlt else Break; end; if Text = '' then Exit; { bounds of these loops may change if Qt::Key enum changes. } for Key := TShortCut(Key_Space) to TShortCut(Key_AsciiTilde) do { Copy range from table in ShortCutToText } if AnsiCompareText(Text, ShortCutToText(Key)) = 0 then begin Result := Key or Shift; Exit; end; for Key := TShortCut(Key_Escape) to TShortCut(Key_Hyper_R) do { Copy range from table in ShortCutToText } if AnsiCompareText(Text, ShortCutToText(Key)) = 0 then begin Result := Key or Shift; Exit; end; end; { Used to populate or merge menus } procedure IterateMenus(Func: Pointer; Menu1, Menu2: TMenuItem); var I, J: Integer; IIndex, JIndex: Byte; Menu1Size, Menu2Size: Integer; Done: Boolean; function Iterate(var I: Integer; MenuItem: TMenuItem; AFunc: Pointer): Boolean; var Item: TMenuItem; begin if MenuItem = nil then Exit; Result := False; while not Result and (I < MenuItem.Count) do begin Item := MenuItem[I]; if Item.GroupIndex > IIndex then Break; asm MOV EAX,Item MOV EDX,[EBP+8] PUSH DWORD PTR [EDX] CALL DWORD PTR AFunc ADD ESP,4 MOV Result,AL end; Inc(I); end; end; begin I := 0; J := 0; Menu1Size := 0; Menu2Size := 0; if Menu1 <> nil then Menu1Size := Menu1.Count; if Menu2 <> nil then Menu2Size := Menu2.Count; Done := False; while not Done and ((I < Menu1Size) or (J < Menu2Size)) do begin IIndex := High(Byte); JIndex := High(Byte); if (I < Menu1Size) then IIndex := Menu1[I].GroupIndex; if (J < Menu2Size) then JIndex := Menu2[J].GroupIndex; if IIndex <= JIndex then Done := Iterate(I, Menu1, Func) else begin IIndex := JIndex; Done := Iterate(J, Menu2, Func); end; while (I < Menu1Size) and (Menu1[I].GroupIndex <= IIndex) do Inc(I); while (J < Menu2Size) and (Menu2[J].GroupIndex <= IIndex) do Inc(J); end; end; procedure Error(ResStr: PResStringRec); function ReturnAddr: Pointer; asm MOV EAX,[ESP+8] end; begin raise EMenuError.CreateRes(ResStr) at ReturnAddr; end; { TMenuItemStack } procedure TMenuItemStack.ClearItem(AItem: TMenuItem); var I: Integer; begin for I := 0 to List.Count - 1 do if PMenuItem(List[I])^ = AItem then PMenuItem(List[I])^ := nil; end; { TMenuActionLink } procedure TMenuActionLink.AssignClient(AClient: TObject); begin FClient := AClient as TMenuItem; end; function TMenuActionLink.IsCaptionLinked: Boolean; begin Result := inherited IsCaptionLinked and WideSameCaption(FClient.Caption, (Action as TCustomAction).Caption); end; function TMenuActionLink.IsCheckedLinked: Boolean; begin Result := inherited IsCheckedLinked and (FClient.Checked = (Action as TCustomAction).Checked); end; function TMenuActionLink.IsEnabledLinked: Boolean; begin Result := inherited IsEnabledLinked and (FClient.Enabled = (Action as TCustomAction).Enabled); end; function TMenuActionLink.IsHelpLinked: Boolean; begin Result := inherited IsHelpLinked and (FClient.HelpContext = (Action as TCustomAction).HelpContext) and (FClient.HelpKeyWord = (Action as TCustomAction).HelpKeyword) and (FClient.HelpType = (Action as TCustomAction).HelpType); end; function TMenuActionLink.IsHintLinked: Boolean; begin Result := inherited IsHintLinked and (FClient.Hint = (Action as TCustomAction).Hint); end; function TMenuActionLink.IsImageIndexLinked: Boolean; begin Result := inherited IsImageIndexLinked and (FClient.ImageIndex = (Action as TCustomAction).ImageIndex); end; function TMenuActionLink.IsShortCutLinked: Boolean; begin Result := inherited IsShortCutLinked and (FClient.ShortCut = (Action as TCustomAction).ShortCut); end; function TMenuActionLink.IsVisibleLinked: Boolean; begin Result := inherited IsVisibleLinked and (FClient.Visible = (Action as TCustomAction).Visible); end; function TMenuActionLink.IsOnExecuteLinked: Boolean; begin Result := inherited IsOnExecuteLinked and (@FClient.OnClick = @Action.OnExecute); end; procedure TMenuActionLink.SetCaption(const Value: TCaption); begin if IsCaptionLinked then FClient.Caption := Value; end; procedure TMenuActionLink.SetChecked(Value: Boolean); begin if IsCheckedLinked then FClient.Checked := Value; end; procedure TMenuActionLink.SetEnabled(Value: Boolean); begin if IsEnabledLinked then FClient.Enabled := Value; end; procedure TMenuActionLink.SetHelpContext(Value: THelpContext); begin if IsHelpLinked then FClient.HelpContext := Value; end; procedure TMenuActionLink.SetHelpKeyword(const Value: string); begin if IsHelpLinked then FCLient.HelpKeyword := Value; end; procedure TMenuActionLink.SetHelpType(Value: THelpType); begin if IsHelpLinked then FClient.HelpType := Value; end; procedure TMenuActionLink.SetHint(const Value: WideString); begin if IsHintLinked then FClient.Hint := Value; end; procedure TMenuActionLink.SetImageIndex(Value: Integer); begin if IsImageIndexLinked then FClient.ImageIndex := Value; end; procedure TMenuActionLink.SetShortCut(Value: TShortCut); begin if IsShortCutLinked then FClient.ShortCut := Value; end; procedure TMenuActionLink.SetVisible(Value: Boolean); begin if IsVisibleLinked then FClient.Visible := Value; end; procedure TMenuActionLink.SetOnExecute(Value: TNotifyEvent); begin if IsOnExecuteLinked then FClient.OnClick := Value; end; { TMenuItem } procedure TMenuItem.ActivatedHook(ItemID: Integer); var Item: TMenuItem; begin try Item := FindItem(ItemID); if Item <> nil then begin QApplication_postEvent(Handle, QCustomEvent_create(QEventType_MenuClick, Item)); if (csDesigning in ComponentState) and (Item.GetParentMenu <> nil) and (Item.GetParentMenu.Owner <> nil) then if (Item.GetParentMenu.Owner is TWidgetControl) then QApplication_postevent((Item.GetParentMenu.Owner as TWidgetControl).Handle, QCustomEvent_create(QEventType_DesignMenuClick, Item)) else if ((Item.GetParentMenu.Owner.Owner <> nil) and (Item.GetParentMenu.Owner.Owner is TWidgetControl)) then QApplication_postevent((Item.GetParentMenu.Owner.Owner as TWidgetControl).Handle, QCustomEvent_create(QEventType_DesignMenuClick, Item)) end; except Application.HandleException(Self); end; end; procedure TMenuItem.Add(const AItems: array of TMenuItem); var I: Integer; begin for I := Low(AItems) to High(AItems) do Add(AItems[I]); end; procedure TMenuItem.BitmapChanged(Sender: TObject); begin if (csLoading in ComponentState) and (Sender <> nil) and not (Sender as TBitmap).Transparent then (Sender as TBitmap).Transparent := True; if DisplayBitmap then ChangePixmap((Sender as TBitmap).Handle); end; function TMenuItem.GetAutoHotkeys: Boolean; var LAuto: TMenuItemAutoFlag; begin LAuto := FAutoHotkeys; if (LAuto = maParent) and (Parent <> nil) then LAuto := cBooleanToItemAutoFlag[Parent.GetAutoHotkeys]; Result := cItemAutoFlagToBoolean[LAuto]; end; procedure TMenuItem.ItemHandleNeeded; begin if (FMenuItemHandle = nil) and (Parent <> nil) then begin FMenuItemHandle := QMenuData_findItem(Parent.MenuData, FID); if FMenuItemHandle <> nil then QClxObjectMap_add(Pointer(FMenuItemHandle), Integer(Self)); end; end; function TMenuItem.MenuItemHandle: QMenuItemH; begin Result := FMenuItemHandle; end; procedure TMenuItem.InitiateAction; begin if FActionLink <> nil then FActionLink.Update; end; function TMenuItem.InternalRethinkHotkeys(ForceRethink: Boolean): Boolean; var LDid, LDoing, LToDo, LBest: TStringList; I, LIteration, LColumn, LAt, LBestCount: Integer; LChar, LCaption, LOrigAvailable, LAvailable, LBestAvailable: WideString; function IfHotkeyAvailable(const AHotkey: WideString): Boolean; var At: Integer; begin At := Pos(AHotkey, LAvailable); Result := At <> 0; if Result then System.Delete(LAvailable, At, 1); end; procedure CopyToBest; var I: Integer; begin LBest.Assign(LDid); LBestCount := LDid.Count; for I := 0 to LDoing.Count - 1 do LBest.AddObject(TMenuItem(LDoing.Objects[I]).FCaption, LDoing.Objects[I]); LBestAvailable := LAvailable; end; procedure InsertHotkeyFarEastFormat(var ACaption: WideString; const AHotKey: WideString; AColumn: Integer); var NonLatinCaption: Boolean; I: Integer; begin NonLatinCaption := False; for I := 1 to Length(ACaption) do if Integer(ACaption[I]) > $255 then begin NonLatinCaption := True; Break; end; if NonLatinCaption then begin if Copy(ACaption, (Length(ACaption) - Length(cDialogSuffix)) + 1, Length(cDialogSuffix)) = cDialogSuffix then ACaption := Copy(ACaption, 1, Length(ACaption) - Length(cDialogSuffix)) + '(' + cHotkeyPrefix + AHotKey + ')' + cDialogSuffix else ACaption := ACaption + '(' + cHotkeyPrefix + AHotKey + ')'; end else if AColumn <> 0 then System.Insert(cHotkeyPrefix, ACaption, AColumn); end; begin Result := False; if ForceRethink or (not (csDesigning in ComponentState) and GetAutoHotkeys) then begin LAvailable := ValidMenuHotkeys; LDid := nil; LDoing := nil; LToDo := nil; LBest := nil; LBestCount := 0; try LDid := TStringList.Create; LDoing := TStringList.Create; LToDo := TStringList.Create; LBest := TStringList.Create; for I := 0 to Count - 1 do if Items[I].Visible and (Items[I].FCaption <> cLineCaption) and (Items[I].FCaption <> '') then begin LChar := Uppercase(GetHotkey(Items[I].FCaption)); if LChar = '' then LToDo.InsertObject(0, Items[I].FCaption, Items[I]) else if (AnsiPos(LChar, ValidMenuHotkeys) <> 0) and not IfHotkeyAvailable(LChar) then begin Items[I].FCaption := StripHotkey(Items[I].FCaption); LToDo.InsertObject(0, Items[I].FCaption, Items[I]); end; end; LOrigAvailable := LAvailable; for LIteration := 0 to LToDo.Count - 1 do begin LAvailable := LOrigAvailable; LDoing.Assign(LToDo); LDid.Clear; for I := LDoing.Count - 1 downto 0 do begin LCaption := LDoing[I]; LColumn := 1; while LColumn <= Length(LCaption) do begin LChar := Uppercase(Copy(LCaption, LColumn, 1)); if IfHotkeyAvailable(LChar) then begin if SysLocale.FarEast then InsertHotkeyFarEastFormat(LCaption, LChar, LColumn) else System.Insert(cHotkeyPrefix, LCaption, LColumn); LDid.AddObject(LCaption, LDoing.Objects[I]); LDoing.Delete(I); System.Break; end; Inc(LColumn); end; end; if LDid.Count > LBestCount then CopyToBest; if LDoing.Count > 0 then for I := 0 to LDoing.Count - 1 do begin LAt := LToDo.IndexOfObject(LDoing.Objects[I]); LToDo.Move(LAt, LToDo.Count - 1); end else System.Break; end; if LBestCount = 0 then CopyToBest; Result := LBest.Count > 0; for I := 0 to LBest.Count - 1 do begin LCaption := LBest[I]; if SysLocale.FarEast and (Pos(cHotkeyPrefix, LCaption) = 0) and (LBestAvailable <> '') then begin if Pos(cHotkeyPrefix, LCaption) = 0 then begin InsertHotkeyFarEastFormat(LCaption, Copy(LBestAvailable, Length(LBestAvailable), 1), 0); System.Delete(LBestAvailable, length(LBestAvailable), 1); end; end; TMenuItem(LBest.Objects[I]).Caption := LCaption; end; finally LBest.Free; LToDo.Free; LDoing.Free; LDid.Free; end; end; end; function TMenuItem.RethinkHotkeys: Boolean; begin Result := InternalRethinkHotkeys(True); if Result then MenuChanged(False); end; procedure TMenuItem.RemoveItemHandle; begin if FMenuItemHandle <> nil then begin QClxObjectMap_remove(FMenuItemHandle); FMenuItemHandle := nil; end; end; procedure TMenuItem.SetAutoHotkeys(const Value: TMenuItemAutoFlag); begin if Value <> FAutoHotkeys then begin FAutoHotkeys := Value; MenuChanged(True); end; end; procedure TMenuItem.Add(Item: TMenuItem); begin Insert(GetCount, Item); end; procedure TMenuItem.Clear; var I: Integer; begin for I := Count - 1 downto 0 do Items[I].Free; end; procedure TMenuItem.Click; begin if Enabled then begin { Call OnClick if assigned and not equal to associated action's OnExecute. If associated action's OnExecute assigned then call it, otherwise, call OnClick. } try if Assigned(FOnClick) and (Action <> nil) and (@FOnClick <> @Action.OnExecute) then FOnClick(Self) else if not (csDesigning in ComponentState) and (ActionLink <> nil) then FActionLink.Execute else if Assigned(FOnClick) then FOnClick(Self); except Application.HandleException(Self); end; end; end; constructor TMenuItem.Create(AOwner: TComponent); begin inherited Create(AOwner); FChecked := False; FAutoHotkeys := maParent; FVisible := True; FEnabled := True; FGroupIndex := 0; FShortCut := 0; FImageIndex := -1; FRadioItem := False; end; function TMenuItem.GetBitmap: TBitmap; begin if FBitmap = nil then begin FBitmap := TBitmap.Create; FBitmap.OnChange := BitmapChanged; end; Result := FBitmap; end; procedure TMenuItem.GetChildren(Proc: TGetChildProc; Root: TComponent); var I: Integer; begin for I := 0 to Count - 1 do Proc(Items[I]); end; procedure TMenuItem.SetChildOrder(Child: TComponent; Order: Integer); begin (Child as TMenuItem).MenuIndex := Order; end; procedure TMenuItem.Loaded; begin inherited Loaded; if Action <> nil then ActionChange(Action, True); if DisplayBitmap then ChangePixmap(FBitmap.Handle); if Count > 0 then InternalRethinkHotkeys(False); end; procedure TMenuItem.CreateWidget; begin FHandle := QPopupMenu_create(ParentWidget, nil); if FMenu = nil then FMenuData := QPopupMenu_to_QMenuData(Handle); Hooks := QPopupMenu_hook_create(Handle); QWidget_setFocusPolicy(QWidgetH(Handle), QWidgetFocusPolicy_NoFocus); end; procedure TMenuItem.Delete(Index: Integer); var Cur: TMenuItem; begin if (Index < 0) or (FItems = nil) or (Index >= GetCount) then Error(@SMenuIndexError); Cur := FItems[Index]; if not (csDestroying in ComponentState) and (Index >= 0) then begin Cur.RemoveItemHandle; if Showing and (Cur.ID < 0) then begin QMenuData_removeItem(MenuData, Cur.ID); Cur.FID := 0; end; end; if Cur.FMergedWith = nil then begin Cur.FParent := nil; Cur.FOnChange := nil; end; FItems.Delete(Index); if not (csDestroying in ComponentState) and (Index >= 0) then MenuChanged((VisibleCount = 0) and Visible); end; destructor TMenuItem.Destroy; begin if Assigned(ShortCutItems) then ShortCutItems.ClearItem(Self); if FParent <> nil then FParent.Remove(Self); RemoveItemHandle; while Count > 0 do Items[0].Free; FItems.Free; FItems := nil; FreeAndNil(FActionLink); if Assigned(FBitmap) then FBitmap.Free; inherited Destroy; end; procedure TMenuItem.DestroyWidget; var I: Integer; begin if not Assigned(FHandle) then Exit; if Assigned(FItems) then for I := FItems.Count - 1 downto 0 do TMenuItem(FItems[I]).DestroyWidget; FMenuData := nil; inherited DestroyWidget; end; function TMenuItem.Find(const ACaption: WideString): TMenuItem; var I: Integer; LCaption: WideString; begin Result := nil; LCaption := StripHotkey(ACaption); for I := 0 to Count - 1 do if WideSameText(LCaption, StripHotkey(Items[I].Caption)) then begin Result := Items[I]; Break; end; end; function TMenuItem.Find(AHandle: QMenuItemH): TMenuItem; var I: Integer; begin Result := nil; for I := 0 to Count - 1 do if AHandle = Items[I].FMenuItemHandle then begin Result := Items[I]; Break; end; end; function TMenuItem.GetAction: TBasicAction; begin if FActionLink <> nil then Result := FActionLink.Action else Result := nil; end; function TMenuItem.GetActionLinkClass: TMenuActionLinkClass; begin Result := TMenuActionLink; end; function TMenuItem.GetCount: Integer; begin if FItems = nil then Result := 0 else Result := FItems.Count; end; function TMenuItem.GetHandle: QPopupMenuH; begin HandleNeeded; Result := QPopupMenuH(FHandle); end; function TMenuItem.GetItem(Index: Integer): TMenuItem; begin if FItems = nil then Error(@SMenuIndexError); Result := FItems[Index]; end; function TMenuItem.GetMenuIndex: Integer; begin Result := -1; if FParent <> nil then Result := FParent.IndexOf(Self); end; function TMenuItem.GetParentComponent: TComponent; begin if (FParent <> nil) and (FParent.FMenu <> nil) then Result := FParent.FMenu else Result := FParent; end; function TMenuItem.GetParentMenu: TMenu; var MenuItem: TMenuItem; begin MenuItem := Self; while Assigned(MenuItem.FParent) do MenuItem := MenuItem.FParent; Result := MenuItem.FMenu; end; function TMenuItem.HasParent: Boolean; begin Result := True; end; procedure TMenuItem.Highlighted; begin if Enabled and Assigned(FOnHighlighted) then FOnHighlighted(Self); Application.Hint := GetLongHint(Hint); // The OnClick event should get fired whenever a submenu item is present if Count > 0 then Click; end; procedure TMenuItem.HighlightedHook(ItemID: Integer); begin try FCurrentItem := FindItem(ItemID); if FCurrentItem <> nil then begin FCurrentItem.Highlighted; // Hotkeys need not be rethought if there are no submenu items if Count > 0 then FCurrentItem.InternalRethinkHotkeys(False); end; except Application.HandleException(Self); end; end; procedure TMenuItem.HookEvents; var Method: TMethod; begin QPopupMenu_activated_Event(Method) := ActivatedHook; QPopupMenu_hook_hook_activated(QPopupMenu_hookH(Hooks), Method); QPopupMenu_highlighted_Event(Method) := HighlightedHook; QPopupMenu_hook_hook_highlighted(QPopupMenu_hookH(Hooks), Method); QPopupMenu_aboutToShow_Event(Method) := ShowHook; QPopupMenu_hook_hook_aboutToShow(QPopupMenu_hookH(Hooks), Method); inherited HookEvents; end; function TMenuItem.IndexOf(Item: TMenuItem): Integer; begin Result := -1; if FItems <> nil then Result := FItems.IndexOf(Item); end; procedure TMenuItem.Insert(Index: Integer; Item: TMenuItem); begin if (csDestroying in ComponentState) then Exit; if (FMerged = nil) and (Item.FParent <> nil) then Error(@SMenuReinserted); if Item = Self then Error(@SNoMenuRecursion); if FItems = nil then FItems := TList.Create; if (Index - 1 >= 0) and (Index - 1 < FItems.Count) then if Item.GroupIndex < TMenuItem(FItems[Index - 1]).GroupIndex then Item.GroupIndex := TMenuItem(FItems[Index - 1]).GroupIndex; VerifyGroupIndex(Index, Item.GroupIndex); FItems.Insert(Index, Item); Item.FParent := Self; Item.FOnChange := SubItemChanged; if not Item.Showing then Exit; { Recreate this item as a QPopupMenu so it can accept subitems. } { if Count = 1 then RebuildMenu; } MenuChanged(VisibleCount = 1); if (Item.FHandle <> nil) then { this item has sub items (or will) and needs to be inserted as a QPopupMenu) } Item.FID := QMenuData_insertItem(MenuData, @(Item.Caption), QPopupMenuH(Item.FHandle), -1, Index) else if not Item.IsLine then begin Item.FID := QMenuData_insertItem(MenuData, @(Item.FCaption), -1, Index); QMenuData_setAccel(MenuData, ShortCutFlags(Item.FShortCut), Item.FID); end else Item.FID := QMenuData_insertSeparator(MenuData, Index); if not Item.IsLine then begin if (Item.ImageIndex > -1) then Item.DoSetImageIndex(Item.ImageIndex) else if Item.DisplayBitmap then Item.ChangePixmap(Item.FBitmap.Handle); end; Item.ItemHandleNeeded; if not Item.FEnabled then QMenuData_setItemEnabled(MenuData, Item.FID, False); if Item.FChecked then QMenuData_setItemChecked(MenuData, Item.FID, True); if ComponentState * [csLoading, csDesigning] = [] then InternalRethinkHotkeys(False); end; function TMenuItem.InsertNewLine(ABefore: Boolean; AItem: TMenuItem): Integer; begin if AItem.Parent <> Self then Error(@SMenuNotFound); if ABefore then begin if (AItem.MenuIndex > 0) and Items[AItem.MenuIndex - 1].IsLine then begin Result := AItem.MenuIndex - 1; Items[AItem.MenuIndex - 1].Visible := True; end else begin Result := AItem.MenuIndex; Insert(AItem.MenuIndex, NewLine); end; end else begin if (AItem.MenuIndex < Count - 1) and Items[AItem.MenuIndex + 1].IsLine then begin Result := AItem.MenuIndex + 2; Items[AItem.MenuIndex + 1].Visible := True; end else begin Result := AItem.MenuIndex + 2; Insert(AItem.MenuIndex + 1, NewLine); end; end; end; function TMenuItem.InsertNewLineAfter(AItem: TMenuItem): Integer; begin Result := InsertNewLine(False, AItem); end; function TMenuItem.InsertNewLineBefore(AItem: TMenuItem): Integer; begin Result := InsertNewLine(True, AItem); end; procedure TMenuItem.InvokeHelp; var Item: TMenuItem; begin if FCurrentItem <> nil then Item := FCurrentItem else Item := Self; while Item <> nil do begin case Item.HelpType of htKeyword: if Item.HelpKeyword <> '' then begin Application.KeywordHelp(Item.HelpKeyword); Exit; end; htContext: if Item.HelpContext <> 0 then begin Application.ContextHelp(Item.HelpContext); Exit; end; end; Item := Item.Parent; end; GetParentMenu.InvokeHelp; end; function TMenuItem.IsLine: Boolean; begin Result := FCaption = cLineCaption; end; procedure TMenuItem.MenuChanged(Rebuild: Boolean); var Source: TMenuItem; begin if Rebuild then RebuildMenu; if (Parent = nil) and (Owner is TMenu) then Source := nil else Source := Self; if Assigned(FOnChange) then FOnChange(Self, Source, Rebuild); end; function TMenuItem.MenuData: QMenuDataH; begin HandleNeeded; Result := FMenuData; end; procedure TMenuItem.MergeWith(Menu: TMenuItem); procedure InsertMerged(Index: Integer; Item: TMenuItem); begin if Index < 0 then Index := 0; Item.FMergedWith := FMerged; FMenu.FItems.Insert(Index, Item); end; var I, InsertAt, CurGroup: Integer; MergeItem, Item: TMenuItem; begin if FMerged <> Menu then begin if FMerged <> nil then FMerged.FMergedWith := nil; FMerged := Menu; if FMerged <> nil then begin FMerged.FMergedWith := Self; FMerged.FreeNotification(Self); end; if FMerged <> nil then begin InsertAt := FMenu.Items.Count; I := FMerged.Count - 1; while I >= 0 do begin Item := nil; if InsertAt > 0 then begin Item := FMenu.Items[InsertAt-1]; CurGroup := Item.GroupIndex; end else CurGroup := -1; MergeItem := FMerged.FMenu.Items[I]; while MergeItem.GroupIndex > CurGroup do begin InsertMerged(InsertAt, MergeItem); Dec(I); if I >= 0 then MergeItem := FMerged.FMenu.Items[I] else Break; end; if MergeItem.GroupIndex = CurGroup then begin InsertMerged(InsertAt, MergeItem); while MergeItem.GroupIndex = CurGroup do begin Item.Visible := False; Dec(InsertAt); if InsertAt > 0 then begin Item := FMenu.Items[InsertAt-1]; CurGroup := Item.GroupIndex; end else Break; end; Dec(I); end else Dec(InsertAt); end; end else begin for I := FMenu.FItems.Count - 1 downto 0 do begin Item := FMenu.Items[I]; if Item.FMergedWith <> nil then begin FMenu.FItems.Remove(Item); Item.FParent := Item.FMergedWith; Item.FOnChange := Item.FMergedWith.SubItemChanged; Item.FMergedWith := nil; end; end; if not (csDestroying in FMenu.Owner.ComponentState) then for I := 0 to FMenu.FItems.Count - 1 do FMenu.FItems[I].Visible := True; end; end; end; procedure TMenuItem.RebuildMenu; var ThisIndex: Integer; SaveParent: TMenuItem; begin ThisIndex := GetMenuIndex; if ThisIndex < 0 then Exit; SaveParent := Parent; if VisibleCount > 0 then begin HandleNeeded; if (Parent <> nil) then begin Parent.Delete(ThisIndex); SaveParent.Insert(ThisIndex, Self); end; end else begin if Parent <> nil then Parent.Delete(ThisIndex); DestroyWidget; FParent := nil; SaveParent.Insert(ThisIndex, Self); end; end; procedure TMenuItem.Remove(Item: TMenuItem); var I: Integer; begin I := IndexOf(Item); if I = -1 then Error(@SMenuNotFound); Delete(I); end; procedure TMenuItem.SetAction(Value: TBasicAction); begin if Value = nil then begin FActionLink.Free; FActionLink := nil; end else begin if FActionLink = nil then FActionLink := GetActionLinkClass.Create(Self); FActionLink.Action := Value; FActionLink.OnChange := DoActionChange; ActionChange(Value, csLoading in Value.ComponentState); Value.FreeNotification(Self); end; end; procedure TMenuItem.SetBitmap(const Value: TBitmap); begin if FBitmap <> Value then begin if Value <> nil then begin Bitmap.Assign(Value); Bitmap.Transparent := True; if DisplayBitmap then ChangePixmap(FBitmap.Handle); end else begin FBitmap.Free; FBitmap := nil; if ((ImageIndex < 0) or ((GetParentMenu <> nil) and not Assigned(GetParentMenu.Images))) then ChangePixmap(nil); end; end; end; procedure TMenuItem.InitiateActions; var I: Integer; begin for I := 0 to Count - 1 do Items[I].InitiateAction; end; procedure TMenuItem.SetCaption(const Value: WideString); var ThisIndex: Integer; SaveParent: TMenuItem; NeedRebuild: Boolean; begin if FCaption <> Value then begin NeedRebuild := (FCaption = cLineCaption) or (Value = cLineCaption); FCaption := Value; if Assigned(Parent) and (Showing or (csDesigning in ComponentState)) then begin if NeedRebuild then begin ThisIndex := GetMenuIndex; SaveParent := Parent; Parent.Delete(GetMenuIndex); SaveParent.Insert(ThisIndex, Self); end else QMenuData_changeItem(Parent.MenuData, FID, @FCaption); end; end; end; procedure TMenuItem.SetChecked(const Value: Boolean); begin if FChecked <> Value then begin FChecked := Value; if Assigned(Parent) and (Showing or (csDesigning in ComponentState)) then begin QMenuData_setItemChecked(Parent.MenuData, FID, FChecked); if FChecked and FRadioItem then TurnSiblingsOff; end; end; end; procedure TMenuItem.SetEnabled(const Value: Boolean); begin if FEnabled <> Value then begin FEnabled := Value; if Assigned(Parent) and (Showing or (csDesigning in ComponentState)) then QMenuData_setItemEnabled(Parent.MenuData, FID, FEnabled); end; end; procedure TMenuItem.SetGroupIndex(const Value: Byte); begin if FGroupIndex <> Value then begin if Parent <> nil then Parent.VerifyGroupIndex(Parent.IndexOf(Self), Value); FGroupIndex := Value; if FChecked and FRadioItem then TurnSiblingsOff; end; end; procedure TMenuItem.SetMenuIndex(Value: Integer); var Parent: TMenuItem; Count: Integer; begin if FParent <> nil then begin Count := FParent.Count; if Value < 0 then Value := 0; if Value >= Count then Value := Count - 1; if Value <> MenuIndex then begin Parent := FParent; Parent.Remove(Self); Parent.Insert(Value, Self); end; end; end; procedure TMenuItem.SetParentComponent(Value: TComponent); begin if FParent <> nil then FParent.Remove(Self); if Value <> nil then if Value is TMenu then TMenu(Value).Items.Add(Self) else if Value is TMenuItem then TMenuItem(Value).Add(Self); end; procedure TMenuItem.SetRadioItem(const Value: Boolean); begin if FRadioItem <> Value then begin FRadioItem := Value; if FChecked and FRadioItem then TurnSiblingsOff; { MenuChanged(True); } end; end; procedure TMenuItem.ActionChange(Sender: TObject; CheckDefaults: Boolean); begin if Action is TCustomAction then with TCustomAction(Sender) do begin if not CheckDefaults or (Self.Caption = '') then Self.Caption := Caption; if not CheckDefaults or (Self.Checked = False) then Self.Checked := Checked; if not CheckDefaults or (Self.Enabled = True) then Self.Enabled := Enabled; if not CheckDefaults or (Self.HelpContext = 0) then Self.HelpContext := HelpContext; if not CheckDefaults or (Self.HelpKeyWord = '') then Self.HelpKeyWord := HelpKeyWord; if not CheckDefaults then Self.HelpType := HelpType; if not CheckDefaults or (Self.Hint = '') then Self.Hint := Hint; if not CheckDefaults or (Self.ImageIndex = -1) then Self.ImageIndex := ImageIndex; if not CheckDefaults or (Self.ShortCut = scNone) then Self.ShortCut := ShortCut; if not CheckDefaults or (Self.Visible = True) then Self.Visible := Visible; if not CheckDefaults or not Assigned(Self.OnClick) then Self.OnClick := OnExecute; end; end; procedure TMenuItem.DoActionChange(Sender: TObject); begin if Sender = Action then ActionChange(Sender, False); end; function TMenuItem.IsCaptionStored: Boolean; begin Result := (ActionLink = nil) or not FActionLink.IsCaptionLinked; end; function TMenuItem.IsCheckedStored: Boolean; begin Result := (ActionLink = nil) or not FActionLink.IsCheckedLinked; end; function TMenuItem.IsEnabledStored: Boolean; begin Result := (ActionLink = nil) or not FActionLink.IsEnabledLinked; end; function TMenuItem.IsHintStored: Boolean; begin Result := (ActionLink = nil) or not FActionLink.IsHintLinked; end; function TMenuItem.IsHelpContextStored: Boolean; begin Result := (ActionLink = nil) or not FActionLink.IsHelpLinked; end; function TMenuItem.IsImageIndexStored: Boolean; begin Result := (ActionLink = nil) or not FActionLink.IsImageIndexLinked; end; function TMenuItem.IsShortCutStored: Boolean; begin Result := (ActionLink = nil) or not FActionLink.IsShortCutLinked; end; function TMenuItem.IsVisibleStored: Boolean; begin Result := (ActionLink = nil) or not FActionLink.IsVisibleLinked; end; function TMenuItem.IsOnClickStored: Boolean; begin Result := (ActionLink = nil) or not FActionLink.IsOnExecuteLinked; end; procedure TMenuItem.AssignTo(Dest: TPersistent); begin if Dest is TCustomAction then with TCustomAction(Dest) do begin Enabled := Self.Enabled; HelpContext := Self.HelpContext; HelpKeyWord := Self.HelpKeyWord; HelpType := Self.HelpType; Hint := Self.Hint; ImageIndex := Self.ImageIndex; Caption := Self.Caption; Visible := Self.Visible; OnExecute := Self.OnClick; end else inherited AssignTo(Dest); end; procedure TMenuItem.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if Operation = opRemove then if AComponent = Action then Action := nil else if AComponent = FMerged then MergeWith(nil); end; procedure TMenuItem.SetShortCut(const Value: TShortCut); begin if FShortCut <> Value then begin FShortCut := Value; if Assigned(Parent) and Showing then QMenuData_setAccel(Parent.MenuData, ShortCutFlags(FShortCut), FID); end; end; procedure TMenuItem.SetVisible(const Value: Boolean); begin if FVisible <> Value then begin FVisible := Value; if (Parent = nil) or (csDesigning in ComponentState) then Exit; if not FVisible then RemoveQtItemFromParent; Parent.UpdateItems; end; end; procedure TMenuItem.SubItemChanged(Sender: TObject; Source: TMenuItem; Rebuild: Boolean); begin if Rebuild then RebuildMenu; if Parent <> nil then Parent.SubItemChanged(Self, Source, False) else if Owner is TMainMenu then TMainMenu(Owner).ItemChanged; end; procedure TMenuItem.TurnSiblingsOff; var I: Integer; Item: TMenuItem; begin if FParent <> nil then for I := 0 to FParent.Count - 1 do begin Item := FParent[I]; if (Item <> Self) and Item.FRadioItem and (Item.GroupIndex = GroupIndex) then Item.SetChecked(False); end; end; procedure TMenuItem.UpdateItems; function UpdateItem(MenuItem: TMenuItem): Boolean; begin Result := False; MenuItem.ItemHandleNeeded; IterateMenus(@UpdateItem, MenuItem.FMerged, MenuItem); MenuItem.SubItemChanged(MenuItem, MenuItem, True); end; begin IterateMenus(@UpdateItem, nil, Self); end; procedure TMenuItem.VerifyGroupIndex(Position: Integer; Value: Byte); var I: Integer; begin for I := 0 to GetCount - 1 do if I < Position then begin if Items[I].GroupIndex > Value then Error(@SGroupIndexTooLow) end else { Ripple change to menu items at Position and after } if Items[I].GroupIndex < Value then Items[I].FGroupIndex := Value; end; procedure TMenuItem.WidgetDestroyed; begin inherited WidgetDestroyed; end; procedure TMenuItem.Show; begin if Assigned(FOnShow) then FOnShow(Self); end; function TMenuItem.HasBitmap: Boolean; begin Result := Assigned(FBitmap) and not FBitmap.Empty; end; function TMenuItem.IsBitmapStored: Boolean; begin Result := HasBitmap; end; function TMenuItem.DisplayBitmap: Boolean; begin Result := HasBitmap and ((ImageIndex < 0) or ((GetParentMenu <> nil) and not Assigned(GetParentMenu.Images))); end; function TMenuItem.FindItem(ItemID: Integer): TMenuItem; var MI: QMenuItemH; Index: Integer; begin Result := nil; if not Showing then Exit; MI := QMenuData_findItem(MenuData, ItemID); for Index := 0 to FItems.Count - 1 do if TMenuItem(FItems[Index]).FMenuItemHandle = MI then begin Result := FItems[Index]; Exit; end; end; procedure TMenuItem.RemoveQtItemFromParent; var ParentMenu: TMenu; ParentItem: TMenuItem; begin ParentItem := Parent; if ParentItem = nil then begin ParentMenu := GetParentMenu; if ParentMenu <> nil then ParentItem := ParentMenu.Items end; if (ParentItem <> nil) and ParentItem.Showing and (ID < 0) then begin QMenuData_removeItem(ParentItem.MenuData, ID); FID := 0; end; RemoveItemHandle; end; function TMenuItem.Showing: Boolean; var ParentItem: TMenuItem; begin Result := FVisible or (csDesigning in ComponentState); ParentItem := Parent; if Result then while (ParentItem <> nil) and Result do begin Result := Result and (ParentItem.Visible or (csDesigning in ComponentState)); ParentItem := ParentItem.Parent; end; end; procedure TMenuItem.ShowHook; var I: Integer; Menu: TMenu; begin try FCurrentItem := nil; Menu := GetParentMenu; QWidget_setPalette(Handle, Menu.FPalette.Handle, True); if not (csDesigning in ComponentState) then begin InitiateActions; InternalRethinkHotkeys(False); end; for I := 0 to FItems.Count - 1 do TMenuItem(FItems[I]).Show; except Application.HandleException(Self); end; end; procedure TMenuItem.SetImageIndex(const Value: TImageIndex); begin if FImageIndex <> Value then begin FImageIndex := Value; DoSetImageIndex(Value); end; end; procedure TMenuItem.ChangePixmap(Value: QPixmapH); var SaveParent: TMenuItem; ThisIndex: Integer; NewIconSet: QIconSetH; begin if (Parent <> nil) and (Showing or (csDesigning in ComponentState)) then begin if (Value <> nil) and not QPixmap_isNull(Value) {Value.Empty} then begin NewIconSet := QIconSet_create(Value, QIconSetSize_Small); try QMenuData_changeItem(Parent.MenuData, ID, NewIconSet, @FCaption); finally QIconSet_destroy(NewIconSet); end; end else if not (csDestroying in ComponentState) and (Parent <> nil) and (QMenuData_iconSet(Parent.MenuData, FID) <> nil) then begin ThisIndex := GetMenuIndex; SaveParent := Parent; Parent.Delete(GetMenuIndex); SaveParent.Insert(ThisIndex, Self); end; end; end; function TMenuItem.GetImageList: TCustomImageList; var LMenu: TMenu; begin Result := nil; LMenu := GetParentMenu; if LMenu <> nil then Result := LMenu.Images; end; procedure TMenuItem.DoSetImageIndex(const Value: Integer); var ImageList: TCustomImageList; Pixmap: QPixmapH; begin ImageList := GetImageList; if ImageList = nil then Exit; if (Value > -1) then begin Pixmap := ImageList.GetPixmap(Value); if (Pixmap <> nil) and not QPixmap_isNull(Pixmap) then ChangePixmap(Pixmap) else ChangePixmap(nil); end else if DisplayBitmap then ChangePixmap(FBitmap.Handle) else ChangePixmap(nil); end; function TMenuItem.VisibleCount: Integer; var I: Integer; begin if csDesigning in ComponentState then begin Result := Count; Exit; end; Result := 0; if FItems <> nil then for I := 0 to FItems.Count - 1 do if TMenuItem(FItems[I]).Visible then Inc(Result); end; { TMenu } procedure TMenu.ActivatedHook(ItemID: Integer); var Item: TMenuItem; begin try Item := Items.FindItem(ItemID); if Item <> nil then begin QApplication_postEvent(Handle, QCustomEvent_create(QEventType_MenuClick, Item)); if (csDesigning in ComponentState) and (Item.GetParentMenu <> nil) and (Item.GetParentMenu.Owner <> nil) then if (Item.GetParentMenu.Owner is TWidgetControl) then QApplication_postevent((Item.GetParentMenu.Owner as TWidgetControl).Handle, QCustomEvent_create(QEventType_DesignMenuClick, Item)) else if ((Item.GetParentMenu.Owner.Owner <> nil) and (Item.GetParentMenu.Owner.Owner is TWidgetControl)) then QApplication_postevent((Item.GetParentMenu.Owner.Owner as TWidgetControl).Handle, QCustomEvent_create(QEventType_DesignMenuClick, Item)) end; except Application.HandleException(Self); end; end; procedure TMenu.BitmapChanged(Sender: TObject); begin if (FHandle <> nil) then Palette.SetWidgetBitmap(FBitmap); end; constructor TMenu.Create(AOwner: TComponent); begin FItems := TMenuItem.Create(Self); FItems.FOnChange := MenuChanged; FItems.FMenu := Self; FImageChangeLink := TChangeLink.Create; FImageChangeLink.OnChange := ImageListChange; FItems.FAutoHotkeys := maParent; inherited Create(AOwner); ParentWidget := nil; HandleNeeded; QWidget_setFocusPolicy(QWidgetH(Handle), QWidgetFocusPolicy_NoFocus); FPalette := TWidgetPalette.Create; FPalette.OnChange := PaletteChanged; FPalette.ColorRole := crButton; FPalette.TextColorRole := crButtonText; FPalette.Widget := QWidgetH(FHandle); FColor := clButton; end; destructor TMenu.Destroy; begin FImageChangeLink.Free; FItems.Free; FPalette.Free; inherited Destroy; end; procedure TMenu.ColorChanged; begin HandleNeeded; if Bitmap.Empty then Palette.BaseColor := FColor; end; procedure TMenu.DoChange(Source: TMenuItem; Rebuild: Boolean); begin if Assigned(FOnChange) then FOnChange(Self, Source, Rebuild); end; function TMenu.FindItem(Value: Integer; Kind: TFindItemKind): TMenuItem; var FoundItem: TMenuItem; function Find(Item: TMenuItem): Boolean; var I: Integer; begin Result := False; if ((Kind = fkID) and (Value = Item.ID)) or ((Kind = fkHandle) and (Value = Integer(Item.FMenuItemHandle))) or ((Kind = fkShortCut) and (Value = Item.ShortCut)) then begin FoundItem := Item; Result := True; Exit; end else for I := 0 to Item.GetCount - 1 do if Find(Item[I]) then begin Result := True; Exit; end; end; begin FoundItem := nil; IterateMenus(@Find, Items.FMerged, Items); Result := FoundItem; end; function TMenu.GetAutoHotkeys: TMenuAutoFlag; begin Result := cItemAutoFlagToMenu[Items.FAutoHotkeys]; end; function TMenu.GetBitmap: TBitmap; begin if not Assigned(FBitmap) then begin FBitmap := TBitmap.Create; FBitmap.OnChange := BitmapChanged; end; Result := FBitmap; end; procedure TMenu.GetChildren(Proc: TGetChildProc; Root: TComponent); begin FItems.GetChildren(Proc, Root); end; procedure TMenu.SetChildOrder(Child: TComponent; Order: Integer); begin FItems.SetChildOrder(Child, Order); end; procedure TMenu.HighlightedHook(ItemID: Integer); var Item: TMenuItem; begin try Item := Items.FindItem(ItemID); if Item <> nil then begin Item.Highlighted; // Hotkeys need not be rethought if there are submenu items if Item.Count > 0 then Items.InternalRethinkHotkeys(False); end; except Application.HandleException(Self); end; end; procedure TMenu.ImageListChange(Sender: TObject); begin UpdateItemImages; end; function TMenu.IsBitmapStored: Boolean; begin Result := Assigned(FBitmap) and not FBitmap.Empty and not QPixmap_isNull(FBitmap.Handle); end; function TMenu.IsShortCut(Key: Integer; Shift: TShiftState; const KeyText: WideString): Boolean; type TClickResult = (crDisabled, crClicked, crShortCutMoved, crShortCutFreed); var ShortCut: TShortCut; ClickResult: TClickResult; ShortCutItem: TMenuItem; function NthParentOf(Item: TMenuItem; N: Integer): TMenuItem; begin Result := Item; while (N > 0) and (Result <> nil) do begin Result := Result.Parent; Dec(N); end; end; function DoClick(var Item: TMenuItem; Level: Integer): TClickResult; var ItemParent: TMenuItem; begin Result := crClicked; ItemParent := Item.Parent; Assert(Item = NthParentOf(ShortCutItem, Level)); if ItemParent <> nil then Result := DoClick(ItemParent, Level + 1); if Result in [crDisabled, crShortCutFreed] then Exit; if Result = crShortCutMoved then begin { Shortcut moved, we need to refind the shortcut and restore Item to point to the parent at the right level, if possible } if (ShortCutItem = nil) or (ShortCutItem.ShortCut <> ShortCut) then begin ShortCutItem := FindItem(ShortCut, fkShortCut); if ShortCutItem = nil then begin Result := crShortCutFreed; Exit; { Shortcut item could not be found } end; end; Item := NthParentOf(ShortCutItem, Level); if (Item = nil) or (Item.Parent <> ItemParent) then Exit; { Shortcut moved in structure, level not correct } if Level = 0 then Result := crClicked; end; if Item.Enabled then try if not (csDesigning in ComponentState) then Item.InitiateActions; Item.Click; if (ShortCutItem = nil) or ((Item <> ShortCutItem) and (ShortCutItem.ShortCut <> ShortCut)) then Result := crShortCutMoved; except Application.HandleException(Self); end else Result := crDisabled; end; begin ShortCut := QMenus.ShortCut(Key, Shift); if ShortCut = 0 then begin Result := False; Exit; end; repeat ClickResult := crDisabled; ShortCutItem := FindItem(ShortCut, fkShortCut); if ShortCutItem <> nil then begin ShortCutItems.Push(@ShortCutItem); try ClickResult := DoClick(ShortCutItem, 0); finally ShortCutItems.Pop; end; end; until ClickResult <> crShortCutMoved; Result := ShortCutItem <> nil; end; procedure TMenu.Loaded; begin inherited Loaded; DoChange(nil, False); Items.InternalRethinkHotkeys(False); end; procedure TMenu.MenuChanged(Sender: TObject; Source: TMenuItem; Rebuild: Boolean); begin if ComponentState * [csLoading, csDestroying] = [] then DoChange(Source, Rebuild); end; procedure TMenu.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (AComponent = FImages) and (Operation = opRemove) then Images := nil; end; procedure TMenu.PaletteChanged(Sender: TObject); begin QWidget_setPalette(QWidgetH(Handle), (Sender as TPalette).Handle, True); end; procedure TMenu.SetAutoHotkeys(const Value: TMenuAutoFlag); begin Items.FAutoHotkeys := cMenuAutoFlagToItem[Value]; end; procedure TMenu.SetBitmap(Value: TBitmap); begin Bitmap.Assign(Value); if Value = nil then ColorChanged; end; procedure TMenu.SetColor(const Value: TColor); begin if Color <> Value then begin FColor := Value; ColorChanged; end; end; procedure TMenu.SetForm(Value: TObject); var P: TPoint; begin if Self is TPopupMenu then Exit; if Value <> nil then begin if not (Value is TCustomForm) then Error(@SMenuSetFormError); ParentWidget := TCustomForm(Value).Handle; end else ParentWidget := nil; if not (csDestroying in ComponentState) then begin P := Point(0, 0); QWidget_reparent(QWidgetH(Handle), ParentWidget, @P, Value <> nil); end; end; procedure TMenu.SetImages(const Value: TCustomImageList); begin if FImages <> nil then FImages.UnRegisterChanges(FImageChangeLink); FImages := Value; if FImages <> nil then begin FImages.RegisterChanges(FImageChangeLink); FImages.FreeNotification(Self); end; UpdateItemImages; end; procedure TMenu.UpdateItemImages; function UpdateImage(MenuItem: TMenuItem): Boolean; var ImageList: TCustomImageList; begin Result := False; ImageList := MenuItem.GetImageList; if (ImageList <> nil) then MenuItem.DoSetImageIndex(MenuItem.ImageIndex) else if (MenuItem.FBitmap <> nil) and not MenuItem.FBitmap.Empty then MenuItem.ChangePixmap(MenuItem.FBitmap.Handle) else MenuItem.ChangePixmap(nil); IterateMenus(@UpdateImage, MenuItem.FMerged, MenuItem); end; begin IterateMenus(@UpdateImage, Items.FMerged, Items); end; { TMainMenu } function TMainMenu.GetHandle: QMenuBarH; begin HandleNeeded; Result := QMenuBarH(FHandle); end; {$IFDEF LINUX} type TKMenuBar_create = function (AParent: QWidgetH): QMenuBarH; cdecl; var KMenuBar_create: TKMenuBar_create = nil; {$ENDIF} procedure TMainMenu.CreateWidget; begin {$IFDEF LINUX} if Assigned(KMenuBar_create) then FHandle := KMenuBar_create(ParentWidget); if not Assigned(FHandle) then {$ENDIF} FHandle := QMenuBar_create(ParentWidget, nil); FItems.ParentWidget := Handle; FItems.FMenuData := MenuDataHandle; Hooks := QMenuBar_hook_create(Handle); end; procedure TMainMenu.HookEvents; var Method: TMethod; begin QMenuBar_activated_Event(Method) := ActivatedHook; QMenuBar_hook_hook_activated(QMenuBar_hookH(Hooks), Method); QMenuBar_highlighted_Event(Method) := HighlightedHook; QMenuBar_hook_hook_highlighted(QMenuBar_hookH(Hooks), Method); inherited HookEvents; end; function TMainMenu.MenuDataHandle: QMenuDataH; begin Result := QMenuBar_to_QMenuData(Handle); end; procedure TMainMenu.MenuChanged(Sender: TObject; Source: TMenuItem; Rebuild: Boolean); begin inherited MenuChanged(Sender, Source, Rebuild); end; procedure TMainMenu.ItemChanged; begin MenuChanged(nil, nil, False); end; function TMainMenu.IsShortCut(Key: Integer; Shift: TShiftState; const KeyText: WideString): Boolean; var I, J: Integer; begin Result := False; if Items.FMergedWith <> nil then Exit; //we have to manually "locate" the top level menu item with this shortcut. J := -1; for I := 0 to FItems.Count - 1 do begin Result := IsAccel(Key, Items[I].Caption) and (ssAlt in Shift) and Items[I].Visible; if Items[I].Visible then Inc(J); if Result then begin QMenuBar_activateItemAt(QMenuBarH(Handle), J); Exit; end; end; Result := inherited IsShortCut(Key, Shift, KeyText); end; procedure TMainMenu.SetAutoMerge(const Value: Boolean); begin FAutoMerge := Value; end; procedure TMainMenu.Merge(Menu: TMainMenu); begin if Menu <> nil then FItems.MergeWith(Menu.FItems) else FItems.MergeWith(nil); end; procedure TMainMenu.Unmerge(Menu: TMainMenu); begin FItems.MergeWith(nil); end; { TPopupMenu } constructor TPopupMenu.Create(AOwner: TComponent); begin inherited Create(AOwner); FAutoPopup := True; FItems.OnClick := DoPopup; HandleNeeded; end; procedure TPopupMenu.CreateWidget; begin FHandle := QPopupMenu_create(ParentWidget, nil); FItems.ParentWidget := Handle; FItems.FMenuData := MenuDataHandle; Hooks := QPopupMenu_hook_create(Handle); end; procedure TPopupMenu.DoPopup(Sender: TObject); begin Items.InitiateActions; if Assigned(FOnPopup) then FOnPopup(Sender); end; function TPopupMenu.GetHandle: QPopupMenuH; begin HandleNeeded; Result := QPopupMenuH(FHandle); end; procedure TPopupMenu.HighlightedHook(ItemID: Integer); begin try FCurrentItem := Items.FindItem(ItemID); if FCurrentItem <> nil then begin FCurrentItem.Highlighted; // Hotkeys need not be rethought if there are submenu items if FCurrentItem.Count > 0 then Items.InternalRethinkHotkeys(False); end; except Application.HandleException(Self); end; end; procedure TPopupMenu.HookEvents; var Method: TMethod; begin QPopupMenu_activated_Event(Method) := ActivatedHook; QPopupMenu_hook_hook_activated(QPopupMenu_hookH(Hooks), Method); QPopupMenu_highlighted_Event(Method) := HighlightedHook; QPopupMenu_hook_hook_highlighted(QPopupMenu_hookH(Hooks), Method); QPopupMenu_aboutToShow_Event(Method) := ShowHook; QPopupMenu_hook_hook_aboutToShow(QPopupMenu_hookH(Hooks), Method); inherited HookEvents; end; procedure TPopupMenu.InvokeHelp; var Item: TMenuItem; begin if FCurrentItem = nil then inherited else begin Item := FCurrentItem; while Item <> nil do begin case Item.HelpType of htKeyword: if Item.HelpKeyword <> '' then begin Application.KeywordHelp(Item.HelpKeyword); Exit; end; htContext: if Item.HelpContext <> 0 then begin Application.ContextHelp(Item.HelpContext); Exit; end; end; Item := Item.Parent; end; end; end; function TPopupMenu.MenuDataHandle: QMenuDataH; begin Result := QPopupMenu_to_QMenuData(Handle); end; procedure TPopupMenu.Popup(X, Y: Integer); var Size: TSize; begin if FItems.Count = 0 then Exit; { Qt will popup a menu with no items! } FPopupPoint := Types.Point(X, Y); DoPopup(Self); if Alignment in [paCenter, paRight] then begin QWidget_sizeHint(Handle, @Size); if Alignment = paRight then Dec(FPopupPoint.X, Size.cx) else Dec(FPopupPoint.X, Size.cx div 2); end; QPopupMenu_popup(Handle, @FPopupPoint, -1); FCurrentItem := nil; end; procedure TPopupMenu.ShowHook; var I: Integer; begin try for I := 0 to FItems.Count - 1 do TMenuItem(FItems[I]).Show; except Application.HandleException(Self); end; end; initialization ShortCutItems := TMenuItemStack.Create; StartClassGroup(TControl); GroupDescendentsWith(TMenu, QControls.TControl); GroupDescendentsWith(TMenuItem, QControls.TControl); RegisterClass(TMenuItem); {$IFDEF LINUX} if Assigned(LoadThemeHook) then KMenuBar_create := dlsym(LoadThemeHook(), 'KMenuBar_create'); {$ENDIF} finalization FreeAndNil(ShortCutItems); end.
unit PathsAndGroupsManager; interface uses sysUtils, SpecificPaths, ExtensionTypeManager, PathGroups; type TPathsAndGroupsManager = class private fPaths : TSpecificPaths; fPathNames : TSpecificPaths; fGroups : TPathGroups; public constructor Create(); destructor Destroy; override; procedure DumpPathsAndGroups(); procedure AddPath(Child : String; S: String); procedure AddPathName(Child : String; S: String); procedure AddSpecificGroup(S : String); procedure AddSpecificPathName(S : String); procedure AddSpecificPath(S: string); function FindGroupByPath(S : String) : string; function FindSpecificByPath(S : String) : string; function GetExtensionType(key : string; GName : String): String; function GetExceptIncludeRegExp(GName : String) : TExtensionTypeManager; property Paths: TSpecificPaths read fPaths; property PathNames: TSpecificPaths read fPathNames; property Groups: TPathGroups read fGroups; end; ESpecificGroupNotSet = class(Exception); ESpecificPathNameNotSet = class(Exception); ESpecificPathNotSet = class(Exception); implementation uses InternalTypes; constructor TPathsAndGroupsManager.Create(); begin fPaths := TSpecificPaths.create(); fPathNames := TSpecificPaths.create(); fGroups := TPathGroups.create(); end; destructor TPathsAndGroupsManager.Destroy; begin fPaths.free; fPathNames.free; fGroups.free; inherited Destroy; end; procedure TPathsAndGroupsManager.AddPath(Child : String; S: String); var i : Integer; begin // Writeln('On ajoute le path '+Child+', avec le specificpathname '+S); if PathNames.ReferenceExists(S) then begin Paths.AddSpecificPath(Child,S); end else raise ESpecificPathNotSet.create('['+S+'] not set.'); end; procedure TPathsAndGroupsManager.AddPathName(Child : String; S: String); var i : Integer; begin // Writeln('On ajoute le specificpathname '+Child+', avec le groupe '+S); if Groups.ReferenceExists(S) then PathNames.AddSpecificPath(Child,S) else raise ESpecificPathNameNotSet.create('['+S+'] not set.'); end; procedure TPathsAndGroupsManager.AddSpecificPathName(S : String); begin PathNames.AddUnique(S); end; procedure TPathsAndGroupsManager.AddSpecificPath(S : String); begin Paths.AddUnique(S); end; procedure TPathsAndGroupsManager.AddSpecificGroup(S : String); begin Groups.AddUnique(S); end; procedure TPathsAndGroupsManager.DumpPathsAndGroups(); var i : Integer; begin Writeln; Paths.dumpData('Paths'); PathNames.dumpData('PathNames'); Groups.dumpData('Groups'); end; function TPathsAndGroupsManager.FindGroupByPath(S : String) : string; var PathName : string; begin Result := ''; PathName := Paths.Values[NormalizePath(S)]; if PathName<>'' then Result := PathNames.Values[PathName]; end; function TPathsAndGroupsManager.FindSpecificByPath(S : String) : string; begin Result := Paths.Values[NormalizePath(S)]; end; function TPathsAndGroupsManager.GetExtensionType(key : string; GName : String): String; var Extensions : TExtensionTypeManager; begin Result := ''; if GName<>'' then begin Extensions := Groups.ExtensionTypeMan(GName); Result := Extensions.GetExtensionType(Key); end; end; function TPathsAndGroupsManager.GetExceptIncludeRegExp(GName : String) : TExtensionTypeManager; begin Result := nil; if GName<>'' then Result := Groups.ExtensionTypeMan(GName); end; end.
{*******************************************} { TeeChart Pro visual Themes } { Copyright (c) 2003-2004 by David Berneda } { All Rights Reserved } {*******************************************} unit TeeThemes; {$I TeeDefs.inc} interface uses Classes, {$IFDEF CLX} QGraphics, {$ELSE} Graphics, {$ENDIF} TeEngine, Chart, TeCanvas; type TDefaultTheme=class(TChartTheme) protected procedure ChangeAxis(Axis:TChartAxis); procedure ChangeSeries(Series:TChartSeries); procedure ChangeWall(Wall:TChartWall; AColor:TColor); procedure ResetGradient(Gradient:TTeeGradient); public procedure Apply; override; function Description:string; override; end; TExcelTheme=class(TDefaultTheme) public procedure Apply; override; function Description:string; override; end; TClassicTheme=class(TDefaultTheme) public procedure Apply; override; function Description:string; override; end; TBusinessTheme=class(TDefaultTheme) public procedure Apply; override; function Description:string; override; end; TWebTheme=class(TDefaultTheme) public procedure Apply; override; function Description:string; override; end; TWindowsXPTheme=class(TBusinessTheme) public procedure Apply; override; function Description:string; override; end; TBlueSkyTheme=class(TDefaultTheme) public procedure Apply; override; function Description:string; override; end; procedure ApplyChartTheme(Theme:TChartThemeClass; Chart:TCustomChart; PaletteIndex:Integer); overload; procedure ApplyChartTheme(Theme:TChartThemeClass; Chart:TCustomChart); overload; type TThemesList=class(TList) private function GetTheme(Index:Integer):TChartThemeClass; public property Theme[Index:Integer]:TChartThemeClass read GetTheme; default; end; var ChartThemes : TThemesList=nil; procedure RegisterChartThemes(const Themes:Array of TChartThemeClass); implementation uses {$IFDEF CLX} QControls, {$ELSE} Controls, {$ENDIF} TeeConst, TeeProCo, TeeProcs; { TDefaultTheme } function TDefaultTheme.Description: string; begin result:='TeeChart default'; end; procedure TDefaultTheme.ResetGradient(Gradient:TTeeGradient); begin with Gradient do begin Visible:=False; StartColor:=clWhite; Direction:=gdTopBottom; EndColor:=clYellow; MidColor:=clNone; Balance:=50; end; end; procedure TDefaultTheme.ChangeWall(Wall:TChartWall; AColor:TColor); begin with Wall do begin Pen.Visible:=True; Pen.Color:=clBlack; Pen.Width:=1; Pen.Style:=psSolid; Gradient.Visible:=False; Color:=AColor; Dark3D:=True; Size:=0; end; end; procedure TDefaultTheme.ChangeAxis(Axis:TChartAxis); begin with Axis do begin Axis.Width:=2; Axis.Color:=clBlack; Grid.Visible:=True; Grid.Color:=clGray; Grid.Style:=psDot; Grid.SmallDots:=False; Grid.Centered:=False; Ticks.Color:=clDkGray; TicksInner.Visible:=True; MinorTicks.Visible:=True; MinorGrid.Hide; MinorTickCount:=3; MinorTickLength:=2; TickLength:=4; TickInnerLength:=0; with LabelsFont do begin Name:=GetDefaultFontName; Size:=GetDefaultFontSize; Style:=[]; Color:=clBlack; end; Title.Font.Name:=GetDefaultFontName; end; end; procedure TDefaultTheme.ChangeSeries(Series:TChartSeries); begin with Series.Marks do begin Transparent:=False; Gradient.Visible:=False; Font.Name:=GetDefaultFontName; Font.Size:=GetDefaultFontSize; Arrow.Color:=clWhite; end; end; procedure TDefaultTheme.Apply; var t : Integer; begin inherited; Chart.BevelInner:=bvNone; Chart.BevelOuter:=bvRaised; Chart.BevelWidth:=1; Chart.Border.Hide; Chart.BorderRound:=0; Chart.Border.Hide; Chart.Shadow.Size:=0; Chart.Color:=clBtnFace; ResetGradient(Chart.Gradient); with Chart.Legend do begin Shadow.VertSize:=3; Shadow.HorizSize:=3; Shadow.Transparency:=0; Font.Name:=GetDefaultFontName; Font.Size:=GetDefaultFontSize; Symbol.DefaultPen:=True; Transparent:=False; Pen.Visible:=True; DividingLines.Hide; Gradient.Visible:=False; end; ChangeWall(Chart.Walls.Left,$0080FFFF); ChangeWall(Chart.Walls.Right,clSilver); ChangeWall(Chart.Walls.Back,clSilver); ChangeWall(Chart.Walls.Bottom,clWhite); Chart.Walls.Back.Transparent:=True; for t:=0 to Chart.Axes.Count-1 do ChangeAxis(Chart.Axes[t]); for t:=0 to Chart.SeriesCount-1 do ChangeSeries(Chart[t]); with Chart.Title do begin Font.Name:=GetDefaultFontName; Font.Size:=GetDefaultFontSize; Font.Color:=clBlue; end; ColorPalettes.ApplyPalette(Chart,0); end; { TClassicTheme } procedure TClassicTheme.Apply; const ClassicFont = 'Times New Roman'; procedure ChangeWall(Wall:TChartWall); begin with Wall do begin Pen.Visible:=True; Pen.Color:=clBlack; Pen.Width:=1; Pen.Style:=psSolid; Gradient.Visible:=False; Color:=clWhite; Dark3D:=False; Size:=8; end; end; procedure ChangeAxis(Axis:TChartAxis); begin Axis.Axis.Width:=1; Axis.Grid.Color:=clBlack; Axis.Grid.Style:=psSolid; Axis.Grid.Visible:=True; Axis.Ticks.Color:=clBlack; Axis.MinorTicks.Hide; Axis.TicksInner.Hide; with Axis.LabelsFont do begin Name:=ClassicFont; Size:=10; end; Axis.Title.Font.Name:=ClassicFont; end; procedure ChangeSeries(Series:TChartSeries); begin with Series.Marks do begin Gradient.Visible:=False; Transparent:=True; Font.Name:=ClassicFont; Font.Size:=10; Arrow.Color:=clBlack; end; end; var t : Integer; begin inherited; Chart.BevelInner:=bvNone; Chart.BevelOuter:=bvNone; Chart.BorderRound:=0; with Chart.Border do begin Visible:=True; Width:=1; Style:=psSolid; Color:=clBlack; end; Chart.Color:=clWhite; Chart.Gradient.Visible:=False; with Chart.Legend do begin Shadow.VertSize:=0; Shadow.HorizSize:=0; Font.Name:=ClassicFont; Font.Size:=10; Transparent:=True; Pen.Hide; Symbol.DefaultPen:=False; Symbol.Pen.Hide; end; ChangeWall(Chart.Walls.Left); ChangeWall(Chart.Walls.Right); ChangeWall(Chart.Walls.Back); ChangeWall(Chart.Walls.Bottom); Chart.Walls.Back.Transparent:=False; for t:=0 to Chart.Axes.Count-1 do ChangeAxis(Chart.Axes[t]); Chart.Axes.Bottom.Grid.Centered:=True; for t:=0 to Chart.SeriesCount-1 do ChangeSeries(Chart[t]); with Chart.Title do begin Font.Name:=ClassicFont; Font.Size:=12; Font.Color:=clBlack; end; ColorPalettes.ApplyPalette(Chart,5); end; function TClassicTheme.Description: string; begin result:='Classic'; end; { TBusinessTheme } procedure TBusinessTheme.Apply; var t : Integer; begin inherited; Chart.BevelInner:=bvNone; Chart.BevelOuter:=bvNone; Chart.Border.Visible:=True; Chart.BorderRound:=10; Chart.Border.Width:=6; Chart.Border.Color:=clNavy; ResetGradient(Chart.Gradient); Chart.Gradient.Visible:=True; Chart.Gradient.EndColor:=clDkGray; Chart.Color:=clBtnFace; with Chart.Legend do begin Shadow.VertSize:=3; Shadow.HorizSize:=3; Font.Name:=GetDefaultFontName; Font.Size:=GetDefaultFontSize; Symbol.DefaultPen:=True; Transparent:=False; Pen.Visible:=True; ResetGradient(Gradient); Gradient.Visible:=True; end; ChangeWall(Chart.Walls.Left,$0080FFFF); ChangeWall(Chart.Walls.Right,clSilver); ChangeWall(Chart.Walls.Back,clSilver); ChangeWall(Chart.Walls.Bottom,clWhite); Chart.Walls.Back.Transparent:=True; for t:=0 to Chart.Axes.Count-1 do ChangeAxis(Chart.Axes[t]); for t:=0 to Chart.SeriesCount-1 do begin ChangeSeries(Chart[t]); with Chart[t].Marks.Gradient do begin Visible:=True; StartColor:=clSilver; end; end; with Chart.Title do begin Font.Name:=GetDefaultFontName; Font.Size:=GetDefaultFontSize; Font.Color:=clBlue; end; ColorPalettes.ApplyPalette(Chart,2); end; function TBusinessTheme.Description: string; begin result:=TeeMsg_WizardTab; // Business end; { TExcelTheme } function TExcelTheme.Description: string; begin result:='Microsoft® Excel'; end; procedure TExcelTheme.Apply; procedure DoChangeWall(Wall:TChartWall; AColor:TColor); begin with Wall do begin Pen.Visible:=True; Pen.Color:=clDkGray; Pen.Width:=1; Pen.Style:=psSolid; Gradient.Visible:=False; Color:=AColor; Dark3D:=False; end; end; procedure DoChangeAxis(Axis:TChartAxis); begin Axis.Axis.Width:=1; Axis.Grid.Visible:=True; Axis.Grid.Color:=clBlack; Axis.Grid.Style:=psSolid; Axis.Grid.Centered:=False; Axis.Ticks.Color:=clBlack; Axis.MinorTicks.Hide; Axis.TicksInner.Hide; with Axis.LabelsFont do begin Name:='Arial'; Size:=10; end; end; procedure DoChangeSeries(Series:TChartSeries); begin with Series.Marks do begin Gradient.Visible:=False; Transparent:=True; Font.Name:='Arial'; Font.Size:=10; Arrow.Color:=clWhite; end; end; var t : Integer; begin inherited; Chart.BevelInner:=bvNone; Chart.BevelOuter:=bvNone; Chart.BorderRound:=0; with Chart.Border do begin Visible:=True; Width:=1; Style:=psSolid; Color:=clBlack; end; Chart.Color:=clWhite; Chart.Gradient.Visible:=False; with Chart.Legend do begin Shadow.VertSize:=0; Shadow.HorizSize:=0; DividingLines.Hide; Font.Name:='Arial'; Font.Size:=10; Pen.Color:=clBlack; Pen.Width:=1; Pen.Style:=psSolid; Pen.Visible:=True; Transparent:=False; Gradient.Visible:=False; end; DoChangeWall(Chart.Walls.Left,clSilver); DoChangeWall(Chart.Walls.Right,clSilver); DoChangeWall(Chart.Walls.Back,clSilver); DoChangeWall(Chart.Walls.Bottom,clDkGray); Chart.Walls.Back.Transparent:=False; for t:=0 to Chart.Axes.Count-1 do DoChangeAxis(Chart.Axes[t]); Chart.Axes.Top.Grid.Hide; Chart.Axes.Bottom.Grid.Hide; Chart.Axes.Bottom.Grid.Centered:=True; for t:=0 to Chart.SeriesCount-1 do DoChangeSeries(Chart[t]); Chart.Title.Font.Name:='Arial'; Chart.Title.Font.Size:=10; Chart.Title.Font.Color:=clBlack; ColorPalettes.ApplyPalette(Chart,1); end; { TWebTheme } procedure TWebTheme.Apply; Const clDarkSilver=$C4C4C4; WebFont='Lucida Console'; var t : Integer; begin inherited; Chart.BevelInner:=bvNone; Chart.BevelOuter:=bvNone; Chart.Border.Visible:=True; Chart.BorderRound:=0; Chart.Border.Width:=1; Chart.Border.Color:=clBlack; Chart.Gradient.Visible:=False; Chart.Color:=clDarkSilver; // dark clSilver with Chart.Legend do begin Shadow.VertSize:=3; Shadow.HorizSize:=3; Shadow.Color:=clDkGray; Font.Name:=WebFont; Font.Size:=9; Symbol.DefaultPen:=True; Transparent:=False; Pen.Visible:=True; Gradient.Visible:=False; end; ChangeWall(Chart.Walls.Left,clWhite); ChangeWall(Chart.Walls.Right,clWhite); ChangeWall(Chart.Walls.Back,clWhite); ChangeWall(Chart.Walls.Bottom,clWhite); Chart.Walls.Back.Transparent:=False; for t:=0 to Chart.Axes.Count-1 do with Chart.Axes[t] do begin Grid.Color:=clDarkSilver; Grid.Style:=psSolid; if Horizontal then Grid.Hide; MinorTickCount:=3; MinorTickLength:=-3; TickLength:=0; TickInnerLength:=6; TicksInner.Visible:=True; TicksInner.Color:=clBlack; LabelsFont.Name:=WebFont; MinorTicks.Visible:=True; MinorTicks.Color:=clBlack; end; for t:=0 to Chart.SeriesCount-1 do begin ChangeSeries(Chart[t]); Chart[t].Marks.Font.Name:=WebFont; with Chart[t].Marks.Gradient do begin Visible:=True; StartColor:=clSilver; end; end; with Chart.Title do begin Font.Name:=WebFont; Font.Size:=10; Font.Color:=clBlack; Font.Style:=[fsBold]; end; ColorPalettes.ApplyPalette(Chart,6); end; function TWebTheme.Description: string; begin result:='Web'; end; { TWindowsXPTheme } procedure TWindowsXPTheme.Apply; begin inherited; with Chart do begin BorderRound:=0; Border.Color:=$DF7A29; Border.Width:=7; Shadow.HorizSize:=10; Shadow.VertSize:=10; Shadow.Color:=clBlack; Gradient.MidColor:=clNone; Gradient.Direction:=gdDiagonalDown; Gradient.EndColor:=11645361; with Walls.Left.Gradient do begin Visible:=True; StartColor:=WindowsXPPalette[2]; EndColor:=WindowsXPPalette[1]; end; with Walls.Bottom.Gradient do begin Visible:=True; StartColor:=WindowsXPPalette[3]; EndColor:=WindowsXPPalette[4]; end; Walls.Back.Transparent:=False; ResetGradient(Walls.Back.Gradient); Walls.Back.Gradient.EndColor:=11118482; Walls.Back.Gradient.Visible:=True; Legend.Shadow.Transparency:=50; end; ColorPalettes.ApplyPalette(Chart,9); end; function TWindowsXPTheme.Description: string; begin result:='Windows XP'; end; { TBlueSkyTheme } procedure TBlueSkyTheme.Apply; begin inherited; with Chart do begin BackWall.Color := 13626620; BackWall.Pen.Visible := False; BackWall.Size := 5; BackWall.Transparent := False; Border.Color := 9423874; Border.Width := 7; Border.Visible := True; BottomWall.Color := 16550915; BottomWall.Pen.Visible := False; BottomWall.Size := 5; ResetGradient(Gradient); Gradient.Direction := gdFromCenter; Gradient.EndColor := clWhite; Gradient.MidColor := 16777088; Gradient.StartColor := 10814240; Gradient.Visible := True; LeftWall.Color := 16744576; LeftWall.Pen.Visible := False; LeftWall.Size := 5; Legend.DividingLines.Color := clSilver; Legend.DividingLines.Visible := True; Legend.Font.Color := 6553600; Legend.Frame.Visible := False; ResetGradient(Legend.Gradient); Legend.Gradient.Direction := gdTopBottom; Legend.Gradient.EndColor := 13556735; Legend.Gradient.MidColor := 14739177; Legend.Gradient.StartColor := 16774122; Legend.Gradient.Visible := True; Legend.Shadow.HorizSize := 4; Legend.Shadow.Transparency := 50; Legend.Shadow.VertSize := 5; Legend.Symbol.Squared := True; RightWall.Size := 5; Title.Color := clBlack; Title.Font.Color := clNavy; Title.Font.Height := -16; Title.Frame.Color := 10083835; Title.Frame.Width := 2; ResetGradient(Title.Gradient); Title.Gradient.Balance := 40; Title.Gradient.Direction := gdRightLeft; Title.Gradient.EndColor := clBlack; Title.Gradient.MidColor := 8388672; Title.Gradient.StartColor := clGray; Title.Gradient.Visible := True; Title.Shadow.HorizSize := 4; Title.Shadow.Transparency := 70; Title.Shadow.VertSize := 4; BottomAxis.Axis.Width := 1; BottomAxis.Grid.Color := 16759225; BottomAxis.Grid.SmallDots := True; BottomAxis.LabelsFont.Color := clNavy; BottomAxis.LabelsFont.Name := 'Tahoma'; BottomAxis.LabelsFont.Style := [fsBold]; BottomAxis.MinorGrid.Color := 15066597; BottomAxis.MinorGrid.Visible := True; BottomAxis.MinorTickCount := 7; BottomAxis.TickLength := 5; Frame.Visible := False; LeftAxis.Axis.Color := clNavy; LeftAxis.Axis.Width := 1; LeftAxis.Grid.Color := clBlue; LeftAxis.Grid.SmallDots := True; LeftAxis.LabelsFont.Color := clNavy; LeftAxis.LabelsFont.Name := 'Tahoma'; LeftAxis.LabelsFont.Style := [fsBold]; Shadow.Color := clBlack; Shadow.HorizSize := 7; Shadow.VertSize := 7; BevelInner := bvLowered; BevelOuter := bvNone; BevelWidth := 2; end; ColorPalettes.ApplyPalette(Chart,3); end; function TBlueSkyTheme.Description: string; begin result:='Blues'; end; procedure ApplyChartTheme(Theme:TChartThemeClass; Chart:TCustomChart); begin ApplyChartTheme(Theme,Chart,0); end; procedure ApplyChartTheme(Theme:TChartThemeClass; Chart:TCustomChart; PaletteIndex:Integer); begin with Theme.Create(Chart) do try Apply; finally Free; end; if PaletteIndex<>-1 then ColorPalettes.ApplyPalette(Chart,PaletteIndex); end; procedure RegisterChartThemes(const Themes:Array of TChartThemeClass); var t : Integer; begin for t:=0 to Length(Themes)-1 do ChartThemes.Add(TObject(Themes[t])); end; function TThemesList.GetTheme(Index:Integer):TChartThemeClass; begin result:=TChartThemeClass(Items[Index]); end; initialization ChartThemes:=TThemesList.Create; RegisterChartThemes([ TDefaultTheme, TExcelTheme, TClassicTheme, TBusinessTheme, TWebTheme, TWindowsXPTheme, TBlueSkyTheme]); finalization ChartThemes.Free; end.
//****************************************************************************** //*** LUA SCRIPT DELPHI UTILITIES *** //*** *** //*** (c) 2006 Jean-François Goulet *** //*** *** //*** *** //****************************************************************************** // File : LuaVirtualTrees.pas // // Description : ? // //****************************************************************************** //** See Copyright Notice in lua.h //Revision 0.1 // JF Adds : // LuaTableToVirtualTreeView // Unit LuaVirtualTrees; interface Uses SysUtils, Classes, lua, LuaUtils, VirtualTrees; type PBasicTreeData = ^TBasicTreeData; TBasicTreeData = record sName: String; sValue: String; end; procedure LuaTableToVirtualTreeView(L: Plua_State; Index: Integer; VTV: TVirtualStringTree; MaxTable: Integer; SubTableMax: Integer); var SubTableCount: Integer; SubTableCount2: Integer; implementation procedure LuaTableToVirtualTreeView(L: Plua_State; Index: Integer; VTV: TVirtualStringTree; MaxTable: Integer; SubTableMax: Integer); var pGLobalsIndexPtr: Pointer; // Go through all child of current table and create nodes procedure ParseTreeNode(TreeNode: PVirtualNode; Index: Integer); var Key: string; pData: PBasicTreeData; pNode: PVirtualNode; begin // Retreive absolute index Index := LuaAbsIndex(L, Index); lua_pushnil(L); while (lua_next(L, Index) <> 0) do begin Key := Dequote(LuaStackToStr(L, -2, MaxTable, SubTableMax)); if lua_type(L, -1) <> LUA_TTABLE then begin pData := VTV.GetNodeData(VTV.AddChild(TreeNode)); pData.sName := Key; pData.sValue := LuaStackToStr(L, -1, MaxTable, SubTableMax); end else begin if ((Key = '_G') or (lua_topointer(L, -1) = pGLobalsIndexPtr)) then begin pData := VTV.GetNodeData(VTV.AddChild(TreeNode)); pData.sName := Key; pData.sValue := '[LUA_GLOBALSINDEX]'; end else begin pNode := VTV.AddChild(TreeNode); pData := VTV.GetNodeData(pNode); pData.sName := Key; pData.sValue := LuaStackToStr(L, -1, MaxTable, SubTableMax); if SubTableCount < SubTableMax then begin SubTableCount := SubTableCount + 1; ParseTreeNode(pNode, -1); SubTableCount := SubTableCount - 1; end; end; end; lua_pop(L, 1); end; end; begin Assert(lua_type(L, Index) = LUA_TTABLE); lua_checkstack(L, SubTableMax * 3); // Ensure there is enough space on stack to work with according to user's setting pGLobalsIndexPtr := lua_topointer(L, LUA_GLOBALSINDEX); // Retrieve globals index pointer for later conditions VTV.BeginUpdate; VTV.Clear; try ParseTreeNode(nil, Index); finally VTV.EndUpdate; end; end; end.
unit UOrderClass; interface uses UMarkingClass; type TOrderClass = class private FIDOrder: Integer; Marking: TMarkingClass; function GetNameMarking: string; procedure SetIDorder(const Value: Integer); function GetNameKargo: string; function GetNameTrack: string; function GetNamePricooling: string; function GetIDKargo: Integer; function GetIDMarking: Integer; function GetIDPricooling: Integer; function GetIDTrack: Integer; procedure SetNameMarking(const Value: string); procedure SetIDMarking(const Value: Integer); procedure SetIDKargo(const Value: Integer); procedure SetIDPricooling(const Value: Integer); procedure SetIDTrack(const Value: Integer); public constructor Create(idMarking: Integer); property IDOrder: Integer read FIDOrder write SetIDorder; property NameMarking: string read GetNameMarking write SetNameMarking; property NameKargo: string read GetNameKargo; property NameTrack: string read GetNameTrack; property NamePricooling: string read GetNamePricooling; property idMarking: Integer read GetIDMarking write SetIDMarking; property IDKargo: Integer read GetIDKargo write SetIDKargo; property IDTrack: Integer read GetIDTrack write SetIDTrack; property IDPricooling: Integer read GetIDPricooling write SetIDPricooling; end; implementation constructor TOrderClass.Create(idMarking: Integer); begin idMarking := idMarking; Marking := TMarkingClass.Create; Marking.setNameById(idMarking); Marking.getDefaultParam; end; function TOrderClass.GetIDKargo: Integer; begin Result := Marking.IDKargo; end; function TOrderClass.GetIDMarking: Integer; begin // Result := Marking.id; end; function TOrderClass.GetIDPricooling: Integer; begin Result := Marking.IDPricooling; end; function TOrderClass.GetIDTrack: Integer; begin Result := Marking.IDTrack; end; function TOrderClass.GetNameKargo: string; begin Result := Marking.NameKargo; end; function TOrderClass.GetNameMarking: string; begin Result := Marking.getName; end; function TOrderClass.GetNameTrack: string; begin Result := Marking.NameTrack; end; function TOrderClass.GetNamePricooling: string; begin Result := Marking.NamePricooling; end; procedure TOrderClass.SetIDKargo(const Value: Integer); begin IDKargo:=value; end; procedure TOrderClass.SetIDMarking(const Value: Integer); begin idMarking := Value; end; procedure TOrderClass.SetIDorder(const Value: Integer); begin FIDOrder := Value; end; procedure TOrderClass.SetIDPricooling(const Value: Integer); begin IDPricooling:=value; end; procedure TOrderClass.SetIDTrack(const Value: Integer); begin IDTrack:=value; end; procedure TOrderClass.SetNameMarking(const Value: string); begin end; end.
{ Ultibo Font Builder Tool. Copyright (C) 2021 - SoftOz Pty Ltd. Arch ==== <All> Boards ====== <All> Licence ======= LGPLv2.1 with static linking exception (See COPYING.modifiedLGPL.txt) Credits ======= Information for this unit was obtained from: References ========== PC Screen Fonts (PSF) - https://en.wikipedia.org/wiki/PC_Screen_Font A number of PSF format fonts in various stlyes and sizes are available from: http://v3.sk/~lkundrak/fonts/kbd/ Note that this site also lists a number of other fonts in raw format (no header) which contain the font character data in the same format as the PSF files but cannot currently be converted by this tool. http://v3.sk/~lkundrak/fonts/ Font Builder ============ The fonts supported by Ultibo are a bitmap format that contains a block of data where each character is represented by a number of consecutive bytes. Fonts can either be statically compiled as a pascal unit and loaded during startup or can be dynamically loaded by passing a header and data block to the FontLoad() function. For an 8x16 (8 pixels wide and 16 pixels high) font the data contains 8 bits (1 byte) for each of the 16 rows that make up a character and each character would be 16 bytes long. For a 12x22 font the data contains 12 bits padded to 16 bits (2 bytes) for each of the 22 rows that make up a character. Therefore each character would be 44 bytes in length. The font unit can support any size font from 8x6 to 32x64 including every combination in between. For fonts where the bits per row is greater than one byte both little endian and big endian format is supported. This tool currently supports converting PC Screen Fonts (PSF) into a pascal unit suitable for including in an Ultibo project. Additional formats will be supported in future. } program FontBuilder; {$MODE Delphi} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Forms, Interfaces, Main in 'Main.pas' {frmMain}, DlgExport in 'DlgExport.pas' {frmExport}; {$R *.res} begin RequireDerivedFormResource:=True; Application.Initialize; Application.Title := 'Ultibo Font Builder'; Application.CreateForm(TfrmMain, frmMain); Application.CreateForm(TfrmExport, frmExport); Application.Run; end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects, FMX.ScrollBox, FMX.Memo, FMX.Layouts, FMX.StdCtrls, FMX.Controls.Presentation, System.Bluetooth, System.Bluetooth.Components; type TForm1 = class(TForm) ToolBar1: TToolBar; Label1: TLabel; Switch1: TSwitch; Layout1: TLayout; Memo1: TMemo; Text1: TText; Text2: TText; BluetoothLE1: TBluetoothLE; procedure Switch1Switch(Sender: TObject); procedure BluetoothLE1EndDiscoverDevices(const Sender: TObject; const ADeviceList: TBluetoothLEDeviceList); procedure BluetoothLE1EndDiscoverServices(const Sender: TObject; const AServiceList: TBluetoothGattServiceList); procedure BluetoothLE1CharacteristicRead(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; AGattStatus: TBluetoothGattStatus); private { Private declarations } FBLEDevice: TBluetoothLEDevice; // Ctrl + [space] FBLEGattService: TBluetoothGattService; FBLEGattChar: TBluetoothGattCharacteristic; procedure StartScale; procedure StopScale; // Shift + Ctrl + C public { Public declarations } end; var Form1: TForm1; implementation {$R *.fmx} const ScaleDeviceName = 'Wahoo'; WEIGHT_SERVICE: TBluetoothUUID = '{00001901-0000-1000-8000-00805F9B34FB}'; WEIGHT_CHARACTERISTIC: TBluetoothUUID = '{00002B01-0000-1000-8000-00805F9B34FB}'; procedure TForm1.Switch1Switch(Sender: TObject); begin if Switch1.IsChecked then StartScale else StopScale; end; procedure TForm1.StartScale; begin // 1, 장치발견 // DiscoverDivices > OnEndDisconverDevices // 2, 서비스 발견 // DiscoverServices > OnEndDiscoverServices // 3, 구독 // SubscribeToCharacteristics > OnCharacteristicRead BluetoothLE1.Enabled := True; // BluetoothLE1.DiscoverDevices(1000, [WEIGHT_SERVICE]); BluetoothLE1.DiscoverDevices(1000); end; procedure TForm1.BluetoothLE1EndDiscoverDevices(const Sender: TObject; const ADeviceList: TBluetoothLEDeviceList); var Device: TBluetoothLEDevice; begin if ADeviceList.Count = 0 then begin Memo1.Lines.Add('발견된 장치가 없습니다.'); Switch1.IsChecked := False; Exit; end; FBLEDevice := nil; // forin > Ctrl + J for Device in ADeviceList do begin Memo1.Lines.Add(' - ' + Device.DeviceName); if Device.DeviceName.StartsWith(ScaleDeviceName) then begin FBLEDevice := Device; Memo1.Lines.Add('장비를 찾았습니다.'); end; end; if FBLEDevice = nil then Exit; // [TIP] 서비스 발견이 실패하는 경우가 종종 있음 // 실패한 경우 한번더 발견요청 if not FBLEDevice.DiscoverServices then FBLEDevice.DiscoverServices; end; procedure TForm1.BluetoothLE1EndDiscoverServices(const Sender: TObject; const AServiceList: TBluetoothGattServiceList); begin FBLEGattService := BluetoothLE1.GetService(FBLEDevice, WEIGHT_SERVICE); if FBLEGattService = nil then begin Memo1.Lines.Add('WEIGHT 서비스를 찾지 못했습니다.'); Exit; end; // [TIP] 특성목록을 생성하기 위해 아래 코드 호출 BluetoothLE1.GetCharacteristics(FBLEGattService); FBLEGattChar := BluetoothLE1.GetCharacteristic(FBLEGattService, WEIGHT_CHARACTERISTIC); if FBLEGattChar = nil then begin Memo1.Lines.Add('WEIGHT 서비스 특성을 찾지 못했습니다.'); Exit; end; if BluetoothLE1.SubscribeToCharacteristic(FBLEDevice, FBLEGattChar) then Memo1.Lines.Add('WEIGHT 특성에 구독했습니다.'); end; procedure TForm1.BluetoothLE1CharacteristicRead(const Sender: TObject; const ACharacteristic: TBluetoothGattCharacteristic; AGattStatus: TBluetoothGattStatus); var Weight: Single; begin Weight := (ACharacteristic.GetValueAsInteger shr 8) / 10; Text1.Text := Format('%3.1f', [Weight]); end; procedure TForm1.StopScale; begin if Assigned(FBLEDevice) then BluetoothLE1.UnSubscribeToCharacteristic(FBLEDevice, FBLEGattChar); BluetoothLE1.Enabled := False; end; end.
unit ErrorLog; interface uses SysUtils, Logger, Windows; procedure ReportException(E:Exception); implementation uses jclDebug, Classes, JclHookExcept, Util, SyncObjs; var ReportEvent:TMutex; procedure LogException(E:Exception;const Msg:String); begin if ReportEvent.WaitFor(1000) <> wrSignaled then Exit; try if Log<>nil then Log.Error(Msg,E) else begin StringToFile(ExtractFilePath(ParamStr(0))+'asos-'+IntToStr(GetCurrentProcessId)+FormatDateTime(' yyyy-mm-dd hh-nn-ss zzz',now)+'.error.log',Msg); OutputDebugString(PChar(Msg)); Sleep(1); end; finally ReportEvent.Release; end; end; procedure ReportException(E:Exception); var Msg:String; S:TStrings; begin Msg:=''; try Msg:=E.Message+' ('+E.ClassName+')'; if JclLastExceptStackList<>nil then begin S:=TStringList.Create; try JclLastExceptStackList.AddToStrings(S); Msg:=Msg+#13#10+S.Text; finally S.Free; end; end; LogException(E,Msg); except on EE:Exception do begin LogException(EE,EE.Message+#13#10'Cause:'+Msg); end; end; end; procedure Notifier(ExceptObj: TObject; ExceptAddr: Pointer; OSException: Boolean); begin if Assigned(ExceptObj) and (not IsIgnoredException(ExceptObj.ClassType)) and (ExceptObj is Exception) then ReportException(Exception(ExceptObj)); end; initialization ReportEvent:=TMutex.Create; JclStackTrackingOptions:=JclStackTrackingOptions+[stExceptFrame,stStack,stAllModules,stRawMode]; JclStartExceptionTracking; JclAddExceptNotifier(Notifier,npNormal); finalization JclStopExceptionTracking; end.
unit UblTr; interface uses Contracts, Xml.XMLIntf, Xml.XMLDoc, System.SysUtils, System.TypInfo, System.Classes, EncdDecd; const PR_cbc = 'cbc'; NS_cbc = 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2'; PR_cac = 'cac'; NS_cac = 'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2'; procedure CreateUblTr(fatura: TFatura); procedure ChangeNode(parent: IXMLNode; name, namespace, value: String); procedure KalemEkle(node: IXMLNode; kalem: TKalem; BelgePB: String); function CreateChildNode(node: IXMLNode; namespace, name: String): IXMLNode; procedure AddChildNode(node: IXMLNode; namespace, name, value: String); procedure MuhatapBilgileri(node: IXMLNode; muhatap: TMuhatap); procedure VergiEkle(node: IXMLNode; vergiler: TVergiler; BelgePB: String); overload; procedure VergiEkle(node: IXMLNode; vergi: TVergi; BelgePB: String); overload; procedure DipToplam(node: IXMLNode; fatura: TFatura); procedure TutarDegistir(parent: IXMLNode; name, namespace, pb: String; value: Currency); procedure FaturaGorseli(node: IXMLNode; fatura: TFatura); function EncodeFile(const FileName: string): AnsiString; implementation procedure CreateUblTr(fatura: TFatura); var doc: IXMLDocument; parent: IXMLNode; faturatipi: IXMLNode; node: IXMLNode; new: IXMLNode; i: Integer; begin doc := LoadXMLDocument('base.xml'); doc.Options := doc.Options + [doNodeAutoIndent]; parent := doc.DocumentElement; // fatura no ChangeNode(parent, 'ID', NS_cbc, fatura.No); // ETTN ChangeNode(parent, 'UUID', NS_cbc, fatura.ETTN); // fatura tarihi ChangeNode(parent, 'IssueDate', NS_cbc, FormatDateTime('yyyy-mm-dd', fatura.Tarih)); // fatura senaryosu node := parent.ChildNodes.FindNode('ProfileID', NS_cbc); node.Text := GetEnumName(TypeInfo(TFaturaSenaryo), Ord(fatura.Senaryo)); // fatura tipi faturatipi := parent.ChildNodes.FindNode('InvoiceTypeCode', NS_cbc); faturatipi.Text := GetEnumName(TypeInfo(TFaturaTipi), Ord(fatura.Tipi)); // fatura görseli FaturaGorseli(parent, fatura); // satıcı if fatura.Gonderici <> nil then MuhatapBilgileri(parent.ChildNodes.FindNode('AccountingSupplierParty', NS_cac), fatura.Gonderici); // müşteri MuhatapBilgileri(parent.ChildNodes.FindNode('AccountingCustomerParty', NS_cac), fatura.Alici); // Fatura notu ekle new := doc.CreateElement(PR_cbc + ':Note', NS_cbc); new.Text := 'Fatura notu'; new.Attributes['languageID'] := 'tr-TR'; parent.ChildNodes.Insert(parent.ChildNodes.IndexOf(faturatipi) + 1, new); // Vergiler node := parent.ChildNodes.FindNode('TaxTotal', NS_cac); VergiEkle(node, fatura.vergiler, fatura.BelgePB); // Dip toplamlar DipToplam(parent, fatura); // Kalem ekle for i := 0 to fatura.Kalemler.Count - 1 do KalemEkle(parent, fatura.Kalemler[i], fatura.BelgePB); // Dosyaya kaydet doc.SaveToFile('sample.xml'); end; procedure ChangeNode(parent: IXMLNode; name, namespace, value: String); var node: IXMLNode; begin node := parent.ChildNodes.FindNode(name, namespace); if node = nil then exit; if value = '' then begin parent.ChildNodes.Remove(node); exit; end; node.Text := value; end; procedure AddChildNode(node: IXMLNode; namespace, name, value: String); var new: IXMLNode; begin new := node.OwnerDocument.CreateElement(name, namespace); if value <> '' then new.Text := value; node.ChildNodes.Add(new); end; function CreateChildNode(node: IXMLNode; namespace, name: String): IXMLNode; begin Result := node.OwnerDocument.CreateElement(name, namespace); node.ChildNodes.Add(Result); end; procedure MuhatapBilgileri(node: IXMLNode; muhatap: TMuhatap); var new: IXMLNode; child: IXMLNode; i: Integer; begin // party elemanına git node := node.ChildNodes.First; // tüm alt elemanları temizle node.ChildNodes.Clear; // web adresi AddChildNode(node, NS_cbc, PR_cbc + ':WebsiteURI', muhatap.WebURI); // VKN/TCKN new := CreateChildNode(node, NS_cac, PR_cac + ':PartyIdentification'); child := node.OwnerDocument.CreateElement(PR_cbc + ':ID', NS_cbc); child.Text := muhatap.VKNTCKN; if Length(muhatap.VKNTCKN) = 11 then child.Attributes['schemeID'] := 'TCKN' else if Length(muhatap.VKNTCKN) = 10 then child.Attributes['schemeID'] := 'VKN' else raise Exception.Create('VKNTCKN formatı uygun değil!'); new.ChildNodes.Add(child); // Tüzel şirket ünvan if Length(muhatap.VKNTCKN) = 10 then begin new := CreateChildNode(node, NS_cac, PR_cac + ':PartyName'); AddChildNode(new, NS_cbc, PR_cbc + ':Name', muhatap.Unvan); child := node.OwnerDocument.CreateElement(PR_cbc + ':Name', NS_cbc); end; // Adres new := CreateChildNode(node, NS_cac, PR_cac + ':PostalAddress'); AddChildNode(new, NS_cbc, PR_cbc + ':Room', ''); AddChildNode(new, NS_cbc, PR_cbc + ':StreetName', ''); AddChildNode(new, NS_cbc, PR_cbc + ':BuildingName', ''); AddChildNode(new, NS_cbc, PR_cbc + ':BuildingNumber', ''); AddChildNode(new, NS_cbc, PR_cbc + ':CitySubdivisionName', muhatap.Ilce); AddChildNode(new, NS_cbc, PR_cbc + ':CityName', muhatap.Il); AddChildNode(new, NS_cbc, PR_cbc + ':PostalZone', ''); AddChildNode(new, NS_cbc, PR_cbc + ':Region', ''); child := node.OwnerDocument.CreateElement(PR_cac + ':Country', NS_cac); new.ChildNodes.Add(child); AddChildNode(child, NS_cbc, PR_cbc + ':IdentificationCode', muhatap.UlkeKodu); AddChildNode(child, NS_cbc, PR_cbc + ':Name', muhatap.Ulke); // vergi dairesi child := CreateChildNode(node, NS_cac, PR_cac + ':PartyTaxScheme'); child := CreateChildNode(child, NS_cac, PR_cac + ':TaxScheme'); AddChildNode(child, NS_cbc, PR_cbc + ':Name', muhatap.VergiDairesi); // Contact child := CreateChildNode(node, NS_cac, PR_cac + ':Contact'); AddChildNode(child, NS_cbc, PR_cbc + ':Telephone', ''); AddChildNode(child, NS_cbc, PR_cbc + ':Telefax', ''); AddChildNode(child, NS_cbc, PR_cbc + ':ElectronicMail', ''); // Şahıs şirket sahibi if Length(muhatap.VKNTCKN) = 11 then begin child := CreateChildNode(node, NS_cac, PR_cac + ':Person'); // Unvan ad-soyad tespiti i := LastDelimiter(' ', muhatap.Unvan); if i < 2 then raise Exception.Create('Unvanın formatı uygun değil!'); AddChildNode(child, NS_cbc, PR_cbc + ':FirstName', Copy(muhatap.Unvan, 0, i - 1)); AddChildNode(child, NS_cbc, PR_cbc + ':FamilyName', Copy(muhatap.Unvan, i + 1, Length(muhatap.Unvan) - 2)); end; // <cac:PartyName> // <cbc:Name>ISIS Bilişim</cbc:Name> // </cac:PartyName> // <cac:PostalAddress> // <cbc:Room/> // <cbc:StreetName/> // <cbc:BuildingName/> // <cbc:BuildingNumber/> // <cbc:CitySubdivisionName>Alsancak</cbc:CitySubdivisionName> // <cbc:CityName>İZMİR</cbc:CityName> // <cbc:PostalZone/> // <cbc:Region/> // <cac:Country> // <cbc:Name>Türkiye</cbc:Name> // </cac:Country> // </cac:PostalAddress> // <cac:PartyTaxScheme> // <cac:TaxScheme> // <cbc:Name/> // </cac:TaxScheme> // </cac:PartyTaxScheme> // <cac:Contact> // <cbc:Telephone/> // <cbc:Telefax/> // <cbc:ElectronicMail/> // </cac:Contact> // <cac:Person> // <cbc:FirstName/> // <cbc:FamilyName/> // </cac:Person> end; procedure KalemEkle(node: IXMLNode; kalem: TKalem; BelgePB: String); var new: IXMLNode; child: IXMLNode; i: Integer; begin new := node.OwnerDocument.CreateElement(PR_cac + ':InvoiceLine', NS_cac); // Kalem numarası AddChildNode(new, NS_cbc, PR_cbc + ':ID', IntToStr(kalem.KalemNo)); node.ChildNodes.Add(new); // notlar if kalem.Notlar <> nil then for i := 0 to kalem.Notlar.Count do AddChildNode(new, NS_cbc, PR_cbc + ':Note', kalem.Notlar[i]); // miktar child := CreateChildNode(new, NS_cbc, PR_cbc + ':InvoicedQuantity'); child.Attributes['unitCode'] := StringReplace(GetEnumName(TypeInfo(TOlcuBirimleri), Ord(kalem.OlcuBirimi)), '_', '', []); child.Text := FloatToStr(kalem.Miktar); // Kalem tutarı child := CreateChildNode(new, NS_cbc, PR_cbc + ':LineExtensionAmount'); child.Attributes['currencyID'] := BelgePB; child.Text := FloatToStr(kalem.KalemTutar); // indirim if kalem.IndirimTutar.HasValue then begin child := CreateChildNode(new, NS_cac, PR_cac + ':AllowanceCharge'); AddChildNode(child, NS_cbc, PR_cbc + ':ChargeIndicator', 'false'); child := CreateChildNode(child, NS_cbc, PR_cbc + ':Amount'); child.Text := FloatToStr(kalem.IndirimTutar); child.Attributes['currencyID'] := BelgePB; end; // vergiler child := CreateChildNode(new, NS_cac, PR_cac + ':TaxTotal'); VergiEkle(child, kalem.vergiler, BelgePB); // Detay child := CreateChildNode(new, NS_cac, PR_cac + ':Item'); AddChildNode(child, NS_cbc, PR_cbc + ':Name', kalem.UrunAdi); if kalem.UrunKodu <> '' then begin child := CreateChildNode(child, NS_cac, PR_cac + ':SellersItemIdentification'); AddChildNode(child, NS_cbc, PR_cbc + ':ID', kalem.UrunKodu); end; // birim fiyat child := CreateChildNode(new, NS_cac, PR_cac + ':Price'); child := CreateChildNode(child, NS_cbc, PR_cbc + ':PriceAmount'); child.Text := FloatToStr(kalem.BirimFiyat); child.Attributes['currencyID'] := BelgePB; // <cac:InvoiceLine> // <cbc:ID>1</cbc:ID> // <cbc:Note/> // <cbc:InvoicedQuantity unitCode="C62">1</cbc:InvoicedQuantity> // <cbc:LineExtensionAmount currencyID="TRL">500</cbc:LineExtensionAmount> // <cac:AllowanceCharge> // <cbc:ChargeIndicator>false</cbc:ChargeIndicator> // <cbc:Amount currencyID="TRL">0</cbc:Amount> // </cac:AllowanceCharge> // <cac:TaxTotal> // <cbc:TaxAmount currencyID="TRL">90</cbc:TaxAmount> // <cac:TaxSubtotal> // <cbc:TaxAmount currencyID="TRL">90</cbc:TaxAmount> // <cbc:Percent>18</cbc:Percent> // <cac:TaxCategory> // <cbc:TaxExemptionReason/> // <cac:TaxScheme> // <cbc:TaxTypeCode>0015</cbc:TaxTypeCode> // </cac:TaxScheme> // </cac:TaxCategory> // </cac:TaxSubtotal> // </cac:TaxTotal> // <cac:Item> // <cbc:Name>Test</cbc:Name> // <cac:SellersItemIdentification> // <cbc:ID>Satıcı Kodu</cbc:ID> // </cac:SellersItemIdentification> // </cac:Item> // <cac:Price> // <cbc:PriceAmount currencyID="TRL">500</cbc:PriceAmount> // </cac:Price> // </cac:InvoiceLine> end; procedure VergiEkle(node: IXMLNode; vergiler: TVergiler; BelgePB: String); var child: IXMLNode; i: Integer; begin node.ChildNodes.Clear; child := CreateChildNode(node, NS_cbc, PR_cbc + ':TaxAmount'); child.Text := FloatToStr(vergiler.ToplamVergi); child.Attributes['currencyID'] := BelgePB; for i := 0 to vergiler.Count - 1 do VergiEkle(node, vergiler[i], BelgePB); // <cbc:TaxAmount currencyID="TRL">90</cbc:TaxAmount> end; procedure VergiEkle(node: IXMLNode; vergi: TVergi; BelgePB: String); var new: IXMLNode; child: IXMLNode; begin if vergi = nil then exit; child := CreateChildNode(node, NS_cac, PR_cac + ':TaxSubtotal'); // matrah if vergi.Matrah.HasValue then begin new := CreateChildNode(child, NS_cbc, PR_cbc + ':TaxableAmount'); new.Text := FloatToStr(vergi.Matrah); new.Attributes['currencyID'] := BelgePB; end; // vergi tutar new := CreateChildNode(child, NS_cbc, PR_cbc + ':TaxAmount'); new.Text := FloatToStr(vergi.Tutar); new.Attributes['currencyID'] := BelgePB; // oran if vergi.Oran.HasValue then AddChildNode(child, NS_cbc, PR_cbc + ':Percent', FloatToStr(vergi.Oran)); // vergi bilgileri new := CreateChildNode(child, NS_cac, PR_cac + ':TaxCategory'); // muhafiyet bilgisi if vergi.MuafiyetKodu <> '' then begin AddChildNode(new, NS_cbc, PR_cbc + ':TaxExemptionReasonCode', vergi.MuafiyetKodu); AddChildNode(new, NS_cbc, PR_cbc + ':TaxExemptionReason', vergi.MuafiyetAciklama); end; new := CreateChildNode(new, NS_cac, PR_cac + ':TaxScheme'); AddChildNode(new, NS_cbc, PR_cbc + ':Name', vergi.Adi); AddChildNode(new, NS_cbc, PR_cbc + ':TaxTypeCode', vergi.Kodu); // <cac:TaxSubtotal> // <cbc:TaxableAmount currencyID="TRL">100</cbc:TaxableAmount> // <cbc:TaxAmount currencyID="TRL">90</cbc:TaxAmount> // <cbc:Percent>18</cbc:Percent> // <cac:TaxCategory> // / <cbc:TaxExemptionReasonCode/> // / <cbc:TaxExemptionReason/> // / <cac:TaxScheme> // / / <cbc:Name>KDV</cbc:Name> // / / <cbc:TaxTypeCode>0015</cbc:TaxTypeCode> // / </cac:TaxScheme> // </cac:TaxCategory> // </cac:TaxSubtotal> end; procedure DipToplam(node: IXMLNode; fatura: TFatura); var child: IXMLNode; begin child := node.ChildNodes.FindNode('LegalMonetaryTotal', NS_cac); TutarDegistir(child, 'LineExtensionAmount', NS_cbc, fatura.BelgePB, fatura.KalemToplamTutar); TutarDegistir(child, 'TaxExclusiveAmount', NS_cbc, fatura.BelgePB, fatura.VergiHaricTutar); TutarDegistir(child, 'TaxInclusiveAmount', NS_cbc, fatura.BelgePB, fatura.VergiDahilTutar); TutarDegistir(child, 'AllowanceTotalAmount', NS_cbc, fatura.BelgePB, fatura.ToplamIndirim); TutarDegistir(child, 'PayableAmount', NS_cbc, fatura.BelgePB, fatura.OdenecekTutar); end; procedure TutarDegistir(parent: IXMLNode; name, namespace, pb: String; value: Currency); var node: IXMLNode; begin node := parent.ChildNodes.FindNode(name, namespace); if node = nil then exit; node.Text := FloatToStr(value); node.Attributes['currencyID'] := pb; end; procedure FaturaGorseli(node: IXMLNode; fatura: TFatura); var new, child: IXMLNode; begin if fatura.Gorsel = '' then exit; new := CreateChildNode(node, NS_cac, PR_cac + ':AdditionalDocumentReference'); // gönderi bilgilerinden öncesine ekleyelim node.ChildNodes.Insert(node.ChildNodes.IndexOf(node.ChildNodes.FindNode ('AccountingSupplierParty', NS_cac)), new); // görsel dosyasını yükleyelim AddChildNode(new, NS_cbc, PR_cbc + ':ID', '1'); AddChildNode(new, NS_cbc, PR_cbc + ':IssueDate', FormatDateTime('yyyy-mm-dd', fatura.Tarih)); AddChildNode(new, NS_cbc, PR_cbc + ':DocumentTypeCode', 'XSLT'); AddChildNode(new, NS_cbc, PR_cbc + ':DocumentType', 'XSLT'); child := CreateChildNode(new, NS_cac, PR_cac + ':Attachment'); child := CreateChildNode(child, NS_cbc, PR_cbc + ':EmbeddedDocumentBinaryObject'); child.Attributes['characterSetCode'] := 'UTF-8'; child.Attributes['encodingCode'] := 'Base64'; child.Attributes['filename'] := fatura.No + '.xslt'; child.Attributes['mimeCode'] := 'application/xml'; child.Text := EncodeFile(fatura.Gorsel); // <cac:AdditionalDocumentReference> // / <cbc:ID>1</cbc:ID> // / <cbc:IssueDate>2016-12-30</cbc:IssueDate> // / <cbc:DocumentTypeCode>XSLT</cbc:DocumentTypeCode> // / <cbc:DocumentType>XSLT</cbc:DocumentType> // / <cac:Attachment> // / / <cbc:EmbeddedDocumentBinaryObject characterSetCode="UTF-8" encodingCode="Base64" filename="H552017000000017.xslt" mimeCode="application/xml"> // / / Base64 // / / </cbc:EmbeddedDocumentBinaryObject> // / </cac:Attachment> // </cac:AdditionalDocumentReference> end; function EncodeFile(const FileName: string): AnsiString; var stream: TMemoryStream; begin stream := TMemoryStream.Create; try stream.LoadFromFile(FileName); Result := EncodeBase64(stream.Memory, stream.Size); finally stream.Free; end; end; end.
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+} {$M 65520,0,0} { by Behdad Esfahbod Algorithmic Problems Book September '1999 Problem 34 O(N^4) Matching Method } program BipartiteEdgeColoring; const MaxNum = 100; var M, N, K : Integer; G, H : array [0 .. MaxNum, 0 .. MaxNum] of Integer; Mark : array [1 .. MaxNum] of Boolean; M1, M2, D1, D2 : array [0 .. MaxNum] of Integer; I, J, C, Delta : Integer; Fl : Boolean; F : Text; TT : Longint; Time : Longint absolute $40:$6C; procedure ReadInput; begin Assign(F, 'input.txt'); Reset(F); Readln(F, M, N); for I := 1 to M do begin for J := 1 to N do begin Read(F, G[I, J]); Inc(D1[I], G[I, J]); Inc(D2[J], G[I, J]); end; Readln(F); end; Assign(F, 'output.txt'); ReWrite(F); if M > N then N := M; H := G; end; function ADfs (V : Integer) : Boolean; var I : Integer; begin Mark[V] := True; for I := 1 to N do if (G[V, I] > 0) and ((M2[I] = 0) or not Mark[M2[I]] and ADfs(M2[I])) then begin M2[I] := V; M1[V] := I; ADfs := True; Exit; end; ADfs := False; end; procedure BipMatch; begin FillChar(M1, SizeOf(M1), 0); FillChar(M2, SizeOf(M2), 0); repeat Fl := True; FillChar(Mark, SizeOf(Mark), 0); for I := 1 to N do if not Mark[I] and (M1[I] = 0) and ADfs(I) then Fl := False; until Fl; end; procedure BipColor; begin for I := 1 to N do if D1[I] > Delta then Delta := D1[I]; for I := 1 to N do if D2[I] > Delta then Delta := D2[I]; I := N; J := N; while (I > 0) or (J > 0) do begin while D1[I] = Delta do Dec(I); while D2[J] = Delta do Dec(J); Inc(G[I, J]); Inc(D1[I]); Inc(D2[J]); end; for C := Delta downto 1 do begin BipMatch; for I := 1 to N do if M1[I] > 0 then begin Dec(G[I, M1[I]]); if H[I, M1[I]] > 0 then Writeln(F, I, ' ', M1[I], ' ', C); end; end; end; begin ReadInput; TT := Time; BipColor; Writeln((Time - TT) / 18.2 : 0 : 2); Close(F); end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC resource options editing frame } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} unit FireDAC.VCLUI.ResourceOptions; interface uses {$IFDEF MSWINDOWS} Winapi.Messages, {$ENDIF} System.SysUtils, System.Classes, Vcl.Controls, Vcl.Forms, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Buttons, Data.DB, FireDAC.Stan.Option, FireDAC.Stan.Intf, FireDAC.VCLUI.Controls; type TfrmFDGUIxFormsResourceOptions = class(TFrame) ro_gbCmdTextProcess: TPanel; ro_rbConnection: TPanel; ro_cbAutoReconnect: TCheckBox; ro_gbCmdExecute: TPanel; ro_cbCreateParams: TCheckBox; ro_cbCreateMacros: TCheckBox; ro_Label1: TLabel; ro_edtMaxCursors: TEdit; ro_cbxCmdExecMode: TComboBox; ro_Label2: TLabel; ro_Label3: TLabel; ro_edtCmdExecTimeout: TEdit; ro_cbExpandParams: TCheckBox; ro_cbExpandMacros: TCheckBox; ro_cbExpandEscapes: TCheckBox; ro_Label4: TLabel; ro_cbxDefaultParamType: TComboBox; ro_gbPersistance: TPanel; ro_cbPersistent: TCheckBox; ro_cbBackup: TCheckBox; ro_Label6: TLabel; ro_edtDefaultStorageFolder: TEdit; ro_Label7: TLabel; ro_edtDefaultBackupFolder: TEdit; ro_Label8: TLabel; ro_Label9: TLabel; ro_edtDefaultStorageExt: TEdit; ro_edtDefaultBackupExt: TEdit; ro_btnFld1: TSpeedButton; ro_btnFld2: TSpeedButton; ro_Label10: TLabel; ro_edtArrayDMLSize: TEdit; ro_cbShowWaitCursor: TCheckBox; ro_cbServerOutput: TCheckBox; ro_Label5: TLabel; ro_edtServerOutputSize: TEdit; ro_Label11: TLabel; ro_cbDefaultStoreFormat: TComboBox; ro_cbAutoConnect: TCheckBox; ro_cbKeepConnection: TCheckBox; ro_cbUnifyParams: TCheckBox; procedure ro_Change(Sender: TObject); procedure ro_btnFld1Click(Sender: TObject); procedure ro_btnFld2Click(Sender: TObject); private { Private declarations } FOnModified: TNotifyEvent; FModifiedLocked: Boolean; public procedure LoadFrom(AOpts: TFDResourceOptions); procedure SaveTo(AOpts: TFDResourceOptions); published property OnModified: TNotifyEvent read FOnModified write FOnModified; end; implementation {$R *.dfm} uses FireDAC.Stan.Util, FireDAC.Stan.ResStrs; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFormsResourceOptions.LoadFrom(AOpts: TFDResourceOptions); var lTopVis: Boolean; begin FModifiedLocked := True; try lTopVis := AOpts is TFDTopResourceOptions; if lTopVis then begin ro_cbAutoConnect.Checked := TFDTopResourceOptions(AOpts).AutoConnect; ro_cbKeepConnection.Checked := TFDTopResourceOptions(AOpts).KeepConnection; ro_cbAutoReconnect.Checked := TFDTopResourceOptions(AOpts).AutoReconnect; ro_edtMaxCursors.Text := IntToStr(TFDTopResourceOptions(AOpts).MaxCursors); ro_cbServerOutput.Checked := TFDTopResourceOptions(AOpts).ServerOutput; ro_edtServerOutputSize.Text := IntToStr(TFDTopResourceOptions(AOpts).ServerOutputSize); end; ro_rbConnection.Visible := lTopVis; ro_cbAutoConnect.Visible := lTopVis; ro_cbKeepConnection.Visible := lTopVis; ro_cbAutoReconnect.Visible := lTopVis; ro_Label1.Visible := lTopVis; ro_edtMaxCursors.Visible := lTopVis; ro_cbServerOutput.Visible := lTopVis; ro_Label5.Visible := lTopVis; ro_edtServerOutputSize.Visible := lTopVis; ro_cbCreateParams.Checked := AOpts.ParamCreate; ro_cbCreateMacros.Checked := AOpts.MacroCreate; ro_cbExpandParams.Checked := AOpts.ParamExpand; ro_cbExpandMacros.Checked := AOpts.MacroExpand; ro_cbExpandEscapes.Checked := AOpts.EscapeExpand; ro_cbxDefaultParamType.ItemIndex := Integer(AOpts.DefaultParamType); ro_cbUnifyParams.Checked := AOpts.UnifyParams; ro_cbxCmdExecMode.ItemIndex := Integer(AOpts.CmdExecMode); ro_edtCmdExecTimeout.Text := IntToStr(Integer(AOpts.CmdExecTimeout)); ro_edtArrayDMLSize.Text := IntToStr(Integer(AOpts.ArrayDMLSize)); ro_cbShowWaitCursor.Checked := not AOpts.SilentMode; ro_cbPersistent.Checked := AOpts.Persistent; ro_cbBackup.Checked := AOpts.Backup; if lTopVis then begin ro_cbDefaultStoreFormat.ItemIndex := Integer(TFDTopResourceOptions(AOpts).DefaultStoreFormat); ro_edtDefaultStorageFolder.Text := TFDTopResourceOptions(AOpts).DefaultStoreFolder; ro_edtDefaultStorageExt.Text := TFDTopResourceOptions(AOpts).DefaultStoreExt; ro_edtDefaultBackupFolder.Text := TFDTopResourceOptions(AOpts).BackupFolder; ro_edtDefaultBackupExt.Text := TFDTopResourceOptions(AOpts).BackupExt; end; ro_Label11.Visible := lTopVis; ro_cbDefaultStoreFormat.Visible := lTopVis; ro_Label6.Visible := lTopVis; ro_edtDefaultStorageFolder.Visible := lTopVis; ro_Label7.Visible := lTopVis; ro_edtDefaultBackupFolder.Visible := lTopVis; ro_Label8.Visible := lTopVis; ro_edtDefaultStorageExt.Visible := lTopVis; ro_Label9.Visible := lTopVis; ro_edtDefaultBackupExt.Visible := lTopVis; finally FModifiedLocked := False; end; end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFormsResourceOptions.SaveTo(AOpts: TFDResourceOptions); begin if AOpts is TFDTopResourceOptions then begin if TFDTopResourceOptions(AOpts).AutoConnect <> ro_cbAutoConnect.Checked then TFDTopResourceOptions(AOpts).AutoConnect := ro_cbAutoConnect.Checked; if TFDTopResourceOptions(AOpts).KeepConnection <> ro_cbKeepConnection.Checked then TFDTopResourceOptions(AOpts).KeepConnection := ro_cbKeepConnection.Checked; if TFDTopResourceOptions(AOpts).AutoReconnect <> ro_cbAutoReconnect.Checked then TFDTopResourceOptions(AOpts).AutoReconnect := ro_cbAutoReconnect.Checked; if TFDTopResourceOptions(AOpts).MaxCursors <> StrToInt(ro_edtMaxCursors.Text) then TFDTopResourceOptions(AOpts).MaxCursors := StrToInt(ro_edtMaxCursors.Text); if TFDTopResourceOptions(AOpts).ServerOutput <> ro_cbServerOutput.Checked then TFDTopResourceOptions(AOpts).ServerOutput := ro_cbServerOutput.Checked; if TFDTopResourceOptions(AOpts).ServerOutputSize <> StrToInt(ro_edtServerOutputSize.Text) then TFDTopResourceOptions(AOpts).ServerOutputSize := StrToInt(ro_edtServerOutputSize.Text); end; if ro_cbCreateParams.Checked <> AOpts.ParamCreate then AOpts.ParamCreate := ro_cbCreateParams.Checked; if ro_cbCreateMacros.Checked <> AOpts.MacroCreate then AOpts.MacroCreate := ro_cbCreateMacros.Checked; if ro_cbExpandParams.Checked <> AOpts.ParamExpand then AOpts.ParamExpand := ro_cbExpandParams.Checked; if ro_cbExpandMacros.Checked <> AOpts.MacroExpand then AOpts.MacroExpand := ro_cbExpandMacros.Checked; if ro_cbExpandEscapes.Checked <> AOpts.EscapeExpand then AOpts.EscapeExpand := ro_cbExpandEscapes.Checked; if ro_cbxDefaultParamType.ItemIndex <> Integer(AOpts.DefaultParamType) then AOpts.DefaultParamType := TParamType(ro_cbxDefaultParamType.ItemIndex); if ro_cbUnifyParams.Checked <> AOpts.UnifyParams then AOpts.UnifyParams := ro_cbUnifyParams.Checked; if ro_cbxCmdExecMode.ItemIndex <> Integer(AOpts.CmdExecMode) then AOpts.CmdExecMode := TFDStanAsyncMode(ro_cbxCmdExecMode.ItemIndex); if StrToInt(ro_edtCmdExecTimeout.Text) <> Integer(AOpts.CmdExecTimeout) then AOpts.CmdExecTimeout := LongWord(StrToInt(ro_edtCmdExecTimeout.Text)); if ro_edtArrayDMLSize.Text <> IntToStr(Integer(AOpts.ArrayDMLSize)) then AOpts.ArrayDMLSize := StrToInt(ro_edtArrayDMLSize.Text); if ro_cbShowWaitCursor.Checked <> not AOpts.SilentMode then AOpts.SilentMode := not ro_cbShowWaitCursor.Checked; if AOpts.Persistent <> ro_cbPersistent.Checked then AOpts.Persistent := ro_cbPersistent.Checked; if AOpts.Backup <> ro_cbBackup.Checked then AOpts.Backup := ro_cbBackup.Checked; if AOpts is TFDTopResourceOptions then begin if TFDTopResourceOptions(AOpts).DefaultStoreFormat <> TFDStorageFormat(ro_cbDefaultStoreFormat.ItemIndex) then TFDTopResourceOptions(AOpts).DefaultStoreFormat := TFDStorageFormat(ro_cbDefaultStoreFormat.ItemIndex); if TFDTopResourceOptions(AOpts).DefaultStoreFolder <> ro_edtDefaultStorageFolder.Text then TFDTopResourceOptions(AOpts).DefaultStoreFolder := ro_edtDefaultStorageFolder.Text; if TFDTopResourceOptions(AOpts).DefaultStoreExt <> ro_edtDefaultStorageExt.Text then TFDTopResourceOptions(AOpts).DefaultStoreExt := ro_edtDefaultStorageExt.Text; if TFDTopResourceOptions(AOpts).BackupFolder <> ro_edtDefaultBackupFolder.Text then TFDTopResourceOptions(AOpts).BackupFolder := ro_edtDefaultBackupFolder.Text; if TFDTopResourceOptions(AOpts).BackupExt <> ro_edtDefaultBackupExt.Text then TFDTopResourceOptions(AOpts).BackupExt := ro_edtDefaultBackupExt.Text; end; end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFormsResourceOptions.ro_Change(Sender: TObject); begin if not FModifiedLocked and Assigned(FOnModified) then FOnModified(Self); end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFormsResourceOptions.ro_btnFld1Click(Sender: TObject); var s: String; begin s := FDBrowseForFolder(Handle, S_FD_ResOptsStorageFolder); if s <> '' then ro_edtDefaultStorageFolder.Text := s; end; { --------------------------------------------------------------------------- } procedure TfrmFDGUIxFormsResourceOptions.ro_btnFld2Click(Sender: TObject); var s: String; begin s := FDBrowseForFolder(Handle, S_FD_ResOptsBackupFolder); if s <> '' then ro_edtDefaultBackupFolder.Text := s; end; end.
{ Some useful procedures and functions } unit utils; {$mode objfpc}{$H+} interface uses Classes, SysUtils, dateutils, fileutil; function UnixTime(): int64; function OTFormatString(str: string):string; procedure Split (const Delimiter: Char;Input: string; const Strings: TStrings); function FileCopy(source,dest: String): Boolean; implementation function UnixTime(): int64; begin Result := DateTimetounix(Now); end; function OTFormatString(str: string):string; begin IF NeedRTLAnsi THEN BEGIN str := UTF8Encode(widestring(str)); END; result := str; end; procedure Split (const Delimiter: Char; Input: string; const Strings: TStrings) ; begin Assert(Assigned(Strings)) ; Strings.Clear; Strings.Delimiter := Delimiter; Strings.DelimitedText := Input; end; function FileCopy(source,dest: String): Boolean; var fSrc,fDst,len: Integer; ct,units,size: Longint; buffer: packed array [0..2047] of Byte; begin ct:=0; Result := False; { Assume that it WONT work } if source <> dest then begin fSrc := FileOpen(source,fmOpenRead); if fSrc >= 0 then begin size := FileSeek(fSrc,0,2); units:=size div 2048; FileSeek(fSrc,0,0); fDst := FileCreate(dest); if fDst >= 0 then begin while size > 0 do begin len := FileRead(fSrc,buffer,sizeof(buffer)); FileWrite(fDst,buffer,len); size := size - len; if units > 0 then ct:=ct+1; end; FileSetDate(fDst,FileGetDate(fSrc)); FileClose(fDst); FileSetAttr(dest,FileGetAttr(source)); Result := True; end; FileClose(fSrc); end; end; end; end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { Dataset Designer Save Attributes Dialog } { } { Copyright (c) 1997,99 Inprise Corporation } { } {*******************************************************} unit DSAttrS; interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, DRIntf, LibHelp; type TSaveAttributesAs = class(TForm) BasedOnList: TComboBox; AttributeNameEdit: TEdit; Label1: TLabel; Label2: TLabel; OKBtn: TButton; Bevel1: TBevel; CancelBtn: TButton; HelpBtn: TButton; procedure OKBtnClick(Sender: TObject); procedure CancelBtnClick(Sender: TObject); procedure HelpBtnClick(Sender: TObject); procedure FormCreate(Sender: TObject); private procedure AddToList(const Value: string); public function Execute(const TableName, FieldName: string; var AttributesName: string; var BasedOnID: TAttrID): Boolean; end; function SaveAttributesAsDlg(const TableName, FieldName: string; var Name: string; var BasedOnID: TAttrID): Boolean; implementation uses DsnDBCst; function SaveAttributesAsDlg(const TableName, FieldName: string; var Name: string; var BasedOnID: TAttrID): Boolean; var SaveAttributesAsForm: TSaveAttributesAs; begin SaveAttributesAsForm := TSaveAttributesAs.Create(Application); try Result := SaveAttributesAsForm.Execute(TableName, FieldName, Name, BasedOnID); finally SaveAttributesAsForm.Free; end; end; {$R *.DFM} procedure TSaveAttributesAs.OKBtnClick(Sender: TObject); var AttrID: TAttrID; begin AttrID := FindAttrID(AttributeNameEdit.Text); if not IsNullID(AttrID) then raise Exception.CreateResFmt(@SDSAttrExists, [AttributeNameEdit.Text]); ModalResult := mrOk; end; procedure TSaveAttributesAs.CancelBtnClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TSaveAttributesAs.HelpBtnClick(Sender: TObject); begin Application.HelpContext(HelpContext); end; procedure TSaveAttributesAs.AddToList(const Value: string); begin BasedOnList.Items.Add(Value); end; procedure TSaveAttributesAs.FormCreate(Sender: TObject); begin BasedOnList.Items.Add(SDSNone); GetAttrNames(AddToList); HelpContext := hcDSaveAttributesAs; end; function TSaveAttributesAs.Execute(const TableName, FieldName: string; var AttributesName: string; var BasedOnID: TAttrID): Boolean; var Index: Integer; function UniqueAttrName(const TableName, FieldName: string): string; var Template: string; I: Integer; AttrID: TAttrID; begin Template := TableName; I := Pos('.', Template); if I > 0 then Delete(Template, I, MaxInt); Template := Template + FieldName; for I := Length(Template) downto 1 do if Template[I] = ' ' then Delete(Template, I, 1); I := 0; Result := Template; while True do begin AttrID := FindAttrID(Result); if IsNullID(AttrID) then Exit; Inc(I); Result := Format('%s%d', [Template, I]); end; end; begin Caption := Format(Caption, [FieldName]); Index := BasedOnList.Items.IndexOf(GetAttrName(BasedOnID)); if Index < 0 then Index := 0; BasedOnList.ItemIndex := Index; AttributeNameEdit.Text := UniqueAttrName(TableName, FieldName); Result := ShowModal = mrOk; if Result then begin AttributesName := AttributeNameEdit.Text; BasedOnID := FindAttrID(BasedOnList.Text); end; end; end.
unit AddEditPadrao2; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, FMTBcd, DB, DBClient, Provider, SqlExpr, StdCtrls, cxButtons, ExtCtrls, cxClasses, cxStyles, cxGridTableView, cxContainer, cxEdit, Padrao1, cxControls, cxLabel, dxSkinsCore, dxSkinsDefaultPainters, dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis, dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray, dxSkinOffice2013White, dxSkinOffice2016Colorful, dxSkinOffice2016Dark, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinValentine, dxSkinVisualStudio2013Blue, dxSkinVisualStudio2013Dark, dxSkinVisualStudio2013Light, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue; type TfrmAddEditPadrao2 = class(TfrmPadrao1) PanelClient: TPanel; sds1: TSQLDataSet; dsp1: TDataSetProvider; cds1: TClientDataSet; ds1: TDataSource; Panel: TPanel; btnCancelar: TcxButton; btnGravar: TcxButton; lblPadrao: TcxLabel; procedure btnGravarClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure cds1AfterApplyUpdates(Sender: TObject; var OwnerData: OleVariant); private { Private declarations } //procedure HintInPanel(Sender: TObject); //esse é procedimento genérico public { Public declarations } pb_sFormCall: String; pb_sNovoNova, pb_sNomeTab, pb_sNomeCampoPK, pb_sNomeGenerator, pb_sTitJanela: String; pb_iId1, pb_iId2, pb_iIdRet : Integer; pb_lAdd : Boolean; pb_iIdAddEdit: Integer; Function Executa(sFormCall: String; iId1,iId2,iIdRet: Integer; lAdd: Boolean): Integer; end; var frmAddEditPadrao2: TfrmAddEditPadrao2; implementation uses UtilsDb, gsLib, udmPrincipal; {$R *.dfm} procedure TfrmAddEditPadrao2.btnGravarClick(Sender: TObject); Var lOk: Boolean; begin if (cds1.State in [dsInsert,dsEdit]) then begin if Not Confirma('Gravar '+iIf(CDS1.State=dsInsert,pb_sNovoNova + ' ' + pb_sTitJanela,'Alterações')+' ?') then exit; BeforePostClient(cds1); SalvaTransacao(cds1); //iIdAddEdit := cds1.FieldByName(g_sNomeCampoPK).Value; end; Close; end; procedure TfrmAddEditPadrao2.cds1AfterApplyUpdates(Sender: TObject; var OwnerData: OleVariant); begin dmPrincipal.GeraLog(cds1,iIf(pb_lAdd,'1','2'),pb_sNomeTab,pb_sFormCall,Self.Name); end; Function TfrmAddEditPadrao2.Executa(sFormCall: String; iId1,iId2,iIdRet: Integer; lAdd: Boolean): Integer; Begin pb_sFormCall := sFormCall; pb_iIdAddEdit:= 0; pb_lAdd := lAdd; pb_iId1 := iId1; pb_iId2 := iId2; pb_iIdRet := iIdRet; ShowModal; Result := pb_iIdAddEdit; End; procedure TfrmAddEditPadrao2.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; if (cds1.State in [dsInsert,dsEdit]) then begin cds1.Cancel; cds1.CancelUpdates; end; end; procedure TfrmAddEditPadrao2.FormCreate(Sender: TObject); begin inherited; pb_sNovoNova := 'NOVA'; end; procedure TfrmAddEditPadrao2.FormShow(Sender: TObject); Var i: Integer; begin inherited; { for i := 0 to ComponentCount - 1 do if Components[i] is TWinControl then TEdit(Components[i]).onEnter := HintInPanel; //to usando TEdit, pois em WinControl OnEnter é protegido } Caption := iIf(pb_lAdd,pb_sNovoNova,'ALTERANDO')+' '+pb_sTitJanela; end; { procedure TfrmAddEditPadrao2.HintInPanel(Sender: TObject); //esse é procedimento genérico begin if cds1.State = dsBrowse then exit; pnMsg.Caption := TWinControl(Sender).Hint; end; } end.
unit Financas.View.Produto; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, System.Rtti, FMX.Grid.Style, Data.Bind.Controls, Data.Bind.Components, Data.Bind.DBScope, FMX.Layouts, FMX.Bind.Navigator, FMX.ScrollBox, FMX.Grid, Data.DB, Data.Bind.EngExt, FMX.Bind.DBEngExt, FMX.Bind.Grid, System.Bindings.Outputs, FMX.Bind.Editors, Data.Bind.Grid, Financas.Controller.Entity.Interfaces; type TViewProduto = class(TForm) ToolBar: TToolBar; LabelTitle: TLabel; DataSource: TDataSource; StringGrid: TStringGrid; BindNavigator: TBindNavigator; BindSourceDB: TBindSourceDB; BindingsList: TBindingsList; LinkGridToDataSourceBindSourceDB: TLinkGridToDataSource; procedure FormCreate(Sender: TObject); private { Private declarations } FEntity: iControllerEntity; public { Public declarations } end; var ViewProduto: TViewProduto; implementation uses Financas.Controller.Entity.Factory; {$R *.fmx} procedure TViewProduto.FormCreate(Sender: TObject); begin FEntity := TControllerEntityFactory.New.Produto; // FEntity.Lista(DataSource); end; initialization RegisterFmxClasses([TViewProduto]); end.
unit UAplicacao; interface uses Dialogs, Messages, SysUtils, UInter,UGerente, UPais, UEstado, UCidade, UCliente, UFornecedor, UFuncionario, UMarca, UCategoria, UFormaPagamento, UProduto, UFrmConProduto, UCondicaoPagamento, UFrmConCondicaoPagamento, UVenda, UFrmConVenda, UCargo, UContasReceber, UCompra, UUsuario, UTransportadora, UContasPagar, UUnidade, UFrmAutenticacao, UVeiculo, UNcm, uCfop; type Aplicacao = class private protected umaInter : Interfaces; umGerente : TGerente; umPais : Pais; umEstado : Estado; umaCidade : Cidade; umCliente : Cliente; umFornecedor : Fornecedor; umFuncionario : Funcionario; umaMarca : Marca; umaCategoria : Categoria; umaFormaPagamento : FormaPagamento; umProduto : Produto; umaCondicaoPagamento : CondicaoPagamento; umaVenda : Venda; umCargo : Cargo; umaContasReceber : ContasReceber; umaContasPagar : ContasPagar; umaCompra : Compra; umUsuario : Usuario; umaTransportadora : Fornecedor; umaUnidade : Unidade; umFrmAutenticacao : TFrmAutenticacao; umVeiculo : Veiculo; umNcm : Ncm; umCfop : Cfop; public usuarioLogado : Usuario; constructor CrieObjeto; destructor Destrua_se; procedure Execute_se; end; var idLogado, idUserLogado : Integer; nomeLogado : string[100]; perfilUser : string[3]; implementation { Aplicacao } constructor Aplicacao.CrieObjeto; begin umaInter := Interfaces.CrieObj; umGerente := TGerente.create(nil); umPais := Pais.CrieObjeto; umEstado := Estado.CrieObjeto; umaCidade := Cidade.CrieObjeto; umCliente := Cliente.CrieObjeto; umFornecedor := Fornecedor.CrieObjeto; umFuncionario := Funcionario.CrieObjeto; umaMarca := Marca.CrieObjeto; umaCategoria := Categoria.CrieObjeto; umaFormaPagamento := FormaPagamento.CrieObjeto; umProduto := Produto.CrieObjeto; umaCondicaoPagamento := CondicaoPagamento.CrieObjeto; umaVenda := Venda.CrieObjeto; umCargo := Cargo.CrieObjeto; umaContasReceber := ContasReceber.CrieObjeto; umaContasPagar := ContasPagar.CrieObjeto; umaCompra := Compra.CrieObjeto; umUsuario := Usuario.CrieObjeto; umaTransportadora := Fornecedor.CrieObjeto; umaUnidade := Unidade.CrieObjeto; umVeiculo := Veiculo.CrieObjeto; umNcm := Ncm.CrieObjeto; umCfop := Cfop.CrieObjeto; end; destructor Aplicacao.Destrua_se; begin umaInter.Destrua_se; umGerente.free; umPais.Destrua_se; umEstado.Destrua_Se; umaCidade.Destrua_Se; umCliente.Destrua_se; umFornecedor.Destrua_se; umFuncionario.Destrua_se; umaMarca.Destrua_Se; umaCategoria.Destrua_Se; umaFormaPagamento.Destrua_Se; umProduto.Destrua_Se; umaCondicaoPagamento.Destrua_Se; umaVenda.Destrua_Se; umCargo.Destrua_se; umaContasReceber.Destrua_Se; umaContasPagar.Destrua_Se; umaCompra.Destrua_se; umUsuario.Destrua_Se; umaTransportadora.Destrua_se; umaUnidade.Destrua_Se; umVeiculo.Destrua_Se; umNcm.Destrua_Se; umCfop.Destrua_Se; end; procedure Aplicacao.Execute_se; begin umFrmAutenticacao := TFrmAutenticacao.Create(nil); umFrmAutenticacao.conhecaObj(umUsuario); umFrmAutenticacao.ShowModal; idUserLogado := umUsuario.getIdUsuario; idLogado := umUsuario.getUmFuncionario.getId; nomeLogado := umUsuario.getUmFuncionario.getNome_RazaoSoCial; perfilUser := umUsuario.getPerfil; if umFrmAutenticacao.permitido then begin umGerente.ConhecaObj(umaInter, umPais, umEstado, umaCidade, umCliente, umFornecedor, umFuncionario, umaMarca, umaCategoria, umaFormaPagamento, umProduto, umaCondicaoPagamento, umaVenda, umCargo, umaContasReceber, umaCompra, umUsuario, umaTransportadora, umaContasPagar, umaUnidade, umVeiculo, umNcm, umCfop); umGerente.showmodal; end; end; end.
unit ULogData; interface uses Forms, SysUtils, Classes, ULogType; type TLogData = class private class procedure LoadFile; class procedure SaveFile; public class procedure SaveLog(Msg, Routine : string; LogType : TLogType); end; var FLogDataAqr : TextFile; FData : TStringList; implementation { TLogData } class procedure TLogData.LoadFile; var LogLine : string; begin if not Assigned(FData) then FData := TStringList.Create; AssignFile(FLogDataAqr,(ExtractFileDir(Application.ExeName) + '\DataLogs.txt')); {$I-} Reset(FLogDataAqr); {$I+} if not (IOResult <> 0) then begin while (not eof(FLogDataAqr)) do begin Readln(FLogDataAqr,LogLine); FData.Add(LogLine); end; end; end; class procedure TLogData.SaveFile; var I : Integer; begin Rewrite(FLogDataAqr); for I := 0 to Pred(FData.Count) do begin Writeln(FLogDataAqr,FData[I]); end; CloseFile(FLogDataAqr); end; class procedure TLogData.SaveLog(Msg, Routine: string; LogType: TLogType); var FDataNew : TStringList; LogData : string; I : Integer; begin try if not Assigned(FData) then LoadFile; LogData := IntToStr(Ord(LogType)) + '|'; LogData := LogData + Routine + '|'; LogData := LogData + DateTimeToStr(Now) + '|'; LogData := LogData + Msg; FDataNew := TStringList.Create; FDataNew.Add(LogData); for I := 0 to Pred(FData.Count) do begin if I < 149 then FDataNew.Add(FData[I]) end; FData := FDataNew; SaveFile; finally FreeAndNil(FData); end; end; end.
unit import_FORMAT_proc; interface implementation uses VM_System, VM_SysUtils; var s: string; procedure Test; begin s := format('formatted string: %d', [5]); end; initialization Test(); finalization Assert(S = 'formatted string: 5'); end.
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+} {$M 65520,0,0} { by Behdad Esfahbod Algorithmic Problems Book January '2000 Problem 32 O(E) Flory Alg. } program EulerianTour; const MaxNum = 100; var N : Integer; G, H : array [1 .. MaxNum, 0 .. MaxNum] of Integer; D : array [1 .. MaxNum] of Integer; Mark : array [1 .. MaxNum] of Boolean; I, J : Integer; Fl : Boolean; F : Text; procedure ReadInput; begin Assign(F, 'input.txt'); Reset(F); Readln(F, N); for I := 2 to N do begin for J := 1 to I - 1 do begin Read(F, G[I, J]); G[J, I] := G[I, J]; if G[I, J] = 1 then begin Inc(D[I]); H[I, D[I]] := J; Inc(D[J]); H[J, D[J]] := I; end; end; Readln(F); end; Assign(F, 'output.txt'); ReWrite(F); for I := 1 to N do if Odd(D[I]) then begin Writeln(F, 'Graph is not eulerian.'); Close(F); Halt; end; end; procedure FindOtherCycles (V : Integer); var I : Integer; begin while (D[V] > 0) do begin while (D[V] > 0) and (G[V, H[V, D[V]]] <> 1) do Dec(D[V]); if D[V] > 0 then begin G[V, H[V, D[V]]] := 2; G[H[V, D[V]], V] := 2; FindOtherCycles (H[V, D[V]]); Write(F, ' ', V); end; end; end; function FindCycle (V : Integer) : Boolean; var I : Integer; begin for I := D[V] downto 1 do begin if not Mark[H[V, I]] then begin G[V, H[V, I]] := 2; G[H[V, I], V] := 2; Mark[H[V, I]] := True; if (H[V, I] = 1) or FindCycle(H[V, I]) then begin FindCycle := True; Write(F, ' ', V); FindOtherCycles(V); Exit; end; G[V, H[V, I]] := 1; G[H[V, I], V] := 1; end; end; FindCycle := False; end; begin ReadInput; if N > 0 then Write(F, '1'); FindCycle(1); {Find Main Cycle} Close(F); end.
unit fInput; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, uTokenizer; type TInputFrame = class(TFrame) InputEdit: TRichEdit; procedure InputEditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure InputEditKeyPress(Sender: TObject; var Key: Char); private FBackLog: TStrings; FBackLogIndex: Integer; FMatches: TStringList; FLastWord: string; procedure ParseCommand(const AInputText: string); procedure SendText(const AInputText: string); function HighOrderBitSet(theWord: Word): Boolean; procedure CompleteByTab; procedure ReplaceWordAtCursor(const ANewWord: string); function StripSignsFromName(const ANickname: string): string; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; implementation uses uCommandHandler, fMain, StrUtils; {$R *.dfm} constructor TInputFrame.Create(AOwner: TComponent); begin inherited; FLastWord := #0; FBackLogIndex := -1; FBackLog := TStringList.Create; FMatches := TStringList.Create; end; destructor TInputFrame.Destroy; begin FBackLog.Free; FMatches.Free; inherited; end; procedure TInputFrame.InputEditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var InputText: string; begin if ssShift in Shift then Exit; if InputEdit.Lines.Text <> '' then begin if Key = VK_RETURN then begin InputText := InputEdit.Text; FBackLog.Add(InputText); FBackLogIndex := FBackLog.Count; InputEdit.Text := ''; Application.ProcessMessages; if InputText[1] = '/' then begin ParseCommand(InputText); end else begin SendText(InputText); end; Key := 0; end; end; if Key = VK_UP then begin if FBackLog.Count > 0 then begin Dec(FBackLogIndex); if FBackLogIndex < 0 then FBackLogIndex := FBackLog.Count - 1; InputEdit.Text := FBackLog[FBackLogIndex]; InputEdit.SelStart := Length(InputEdit.Text); InputEdit.SelLength := 0; end; Key := 0; end else if Key = VK_DOWN then begin if FBackLog.Count > 0 then begin Inc(FBackLogIndex); if FBackLogIndex > FBackLog.Count - 1 then FBackLogIndex := 0; InputEdit.Text := FBackLog[FBackLogIndex]; InputEdit.SelStart := Length(InputEdit.Text); InputEdit.SelLength := 0; end; Key := 0; end else if Key = VK_TAB then begin CompleteByTab; end; end; function TInputFrame.StripSignsFromName(const ANickname: string): string; begin Result := StringReplace(StringReplace(StringReplace(ANickname, '@', '', []), '+', '', []), ' ', '', []); end; procedure TInputFrame.CompleteByTab; var I: Integer; TheWord: string; Tokenizer: TTokenizer; Nicknames: TStrings; NewWord, Nickname: string; begin TheWord := ''; Tokenizer := TTokenizer.Create(Copy(InputEdit.Text, 1, InputEdit.SelStart), ' '); try while Tokenizer.HasMoreTokens do TheWord := Tokenizer.NextToken; finally Tokenizer.Free; end; I := InputEdit.SelStart; while I <= Length(InputEdit.Text) - 1 do begin Inc(I); if InputEdit.Text[I] <> ' ' then TheWord := TheWord + InputEdit.Text[I] else Break; end; NewWord := ''; if TheWord <> FLastWord then begin FMatches.Clear; Nicknames := MainForm.ActiveChatFrame.Nicknames; for I := 0 to Nicknames.Count - 1 do begin Nickname := StripSignsFromName(Nicknames[I]); if StartsText(TheWord, Nickname) then begin FMatches.Add(Nickname); end; end; if FMatches.Count > 0 then begin FMatches.Sort; NewWord := FMatches[0]; end; end else begin I := FMatches.IndexOf(FLastWord); Inc(I); if I > FMatches.Count - 1 then I := 0; NewWord := FMatches[I]; end; if NewWord <> '' then begin ReplaceWordAtCursor(NewWord); FLastWord := NewWord; end; end; procedure TInputFrame.ReplaceWordAtCursor(const ANewWord: string); var StartIndex, EndIndex: Integer; begin StartIndex := InputEdit.SelStart; while (StartIndex > 0) and (InputEdit.Text[StartIndex] <> ' ') do begin StartIndex := StartIndex - 1; end; EndIndex := PosEx(' ', InputEdit.Text, InputEdit.SelStart); if EndIndex = 0 then EndIndex := InputEdit.SelStart else Dec(EndIndex); InputEdit.SelStart := StartIndex; InputEdit.SelLength := EndIndex - StartIndex; InputEdit.SelText := ANewWord; end; // Tests whether the high order bit of the given word is set. function TInputFrame.HighOrderBitSet (theWord: Word): Boolean; const HighOrderBit = 15; type BitSet = set of 0..15; begin Result := (HighOrderBit in BitSet(theWord)); end; procedure TInputFrame.InputEditKeyPress(Sender: TObject; var Key: Char); begin if HighOrderBitSet(Word(GetKeyState(VK_SHIFT))) then Exit; if (Key in [#9, #13]) then Key := #0; end; procedure TInputFrame.ParseCommand(const AInputText: string); var Tokenizer: TTokenizer; Command: string; begin Tokenizer := TTokenizer.Create(AInputText, ' '); Command := Tokenizer.NextToken; TCommandHandlerFactory.GetInstance.HandleCommand(MainForm.ActiveConnection, Command, MainForm.ActiveTarget, Tokenizer); end; procedure TInputFrame.SendText(const AInputText: string); begin MainForm.ActiveConnection.Say(MainForm.ActiveTarget, AInputText); end; end.
unit crc16_kermit; interface implementation type PByte = ^UInt8; function Crc16Kermit(Data: PByte; Length: UInt16): UInt16; var i: Int32; Val : UInt16; CRC : UInt16; LB, HB: UInt8; Begin CRC := 0; for i := 0 to Length - 1 do begin Val := (((Data + i)^ XOR CRC) AND $0F) * $1081; CRC := CRC SHR 4; CRC := CRC XOR Val; LB := (CRC and $FF); Val := ((((Data + i)^ SHR 4) XOR LB) AND $0F); CRC := CRC SHR 4; CRC := CRC XOR (Val * $1081); end; LB := (CRC and $FF); HB := (CRC shr 8); Result := (LB SHL 8) OR HB; end; var Data: Int64; CRC: UInt16; procedure Test; begin Data := $AABBCCDD99887766; CRC := Crc16Kermit(PByte(@Data), 8); end; initialization Test(); finalization Assert(CRC = 14171); end.
{*******************************************************} { } { Borland Delphi Visual Component Library } { } { Copyright (c) 1995,99 Inprise Corporation } { } {*******************************************************} unit FileIntf; interface uses ActiveX, SysUtils, VirtIntf; { This is the definition of the IDE's virtual file system. An expert, VCS manager, property editor, or component editor can register a new file system interface with the IDE. This allows for re-vectoring of file operations to the editor and form/data model designer. NOTE: Currently the only way to specify an alternate file system for a file, is to open it through the Tools API (See ToolIntf.pas). This is also only for saving/loading of files. The default file open/save dialogs and file system will always be used by the IDE except in the case mentioned above. All references to the term "file" depend on how it is defined by the file system. The "file" could be a Memo Blob field, SQL text, etc... A file system instance must provide the following; GetFileStream - This is the core of the file system. The file system must return an instance of a TIStream for reading/ writing according to the Mode (see Classes.pas for mode values). FileAge - This should return long value corresponding to the DOS file date format. RenameFile - Returns True if the file system was able to rename the file. IsReadonly - Return True if the given file is read only. IsFileBased - Return True if the file system closely matches the OS file system. If this is False, certain operations are not performed. DeleteFile - Return True is the file was successfully deleted. FileExists - Return True if the specifiedl file exists in this file system. GetTempFileName - Returns a Temporary file name based on the name given. GetBackupFileName - Returns a backup file name based on the name given. By convention, the extension is shifted one character to the right and a tilde '~' character is inserted. (eg unit1.pas -> unit1.~pa). GetIDString - Returns a unique ID string used to identify the file system. By conventions this string should be in the form <Vendor or Product>.<FileSystemName>. (eg. Borland.SQLFileSystem ). } type TIVirtualFileSystem = class(TInterface) public function GetFileStream(const FileName: TFileName; Mode: Integer): IStream; virtual; stdcall; abstract; function FileAge(const FileName: TFileName): Longint; virtual; stdcall; abstract; function RenameFile(const OldName, NewName: TFileName): Boolean; virtual; stdcall; abstract; function IsReadonly(const FileName: TFileName): Boolean; virtual; stdcall; abstract; function IsFileBased: Boolean; virtual; stdcall; abstract; function DeleteFile(const FileName: TFileName): Boolean; virtual; stdcall; abstract; function FileExists(const FileName: TFileName): Boolean; virtual; stdcall; abstract; function GetTempFileName(const FileName: TFileName): TFileName; virtual; stdcall; abstract; function GetBackupFileName(const FileName: TFileName): TFileName; virtual; stdcall; abstract; function GetIDString: string; virtual; stdcall; abstract; end; implementation end.
{ Invokable implementation File for Tusuario which implements Iusuario } unit usuarioImpl; interface uses Soap.InvokeRegistry, System.Types, Soap.XSBuiltIns, usuarioIntf; type { Tusuario } Tusuario = class(TInvokableClass, Iusuario) public function echoEnum(const Value: TEnumTest): TEnumTest; stdcall; function echoDoubleArray(const Value: TDoubleArray): TDoubleArray; stdcall; function echoMyEmployee(const Value: TMyEmployee): TMyEmployee; stdcall; function echoDouble(const Value: Double): Double; stdcall; end; implementation function Tusuario.echoEnum(const Value: TEnumTest): TEnumTest; stdcall; begin { TODO : Implement method echoEnum } Result := Value; end; function Tusuario.echoDoubleArray(const Value: TDoubleArray): TDoubleArray; stdcall; begin { TODO : Implement method echoDoubleArray } Result := Value; end; function Tusuario.echoMyEmployee(const Value: TMyEmployee): TMyEmployee; stdcall; begin { TODO : Implement method echoMyEmployee } Result := TMyEmployee.Create; end; function Tusuario.echoDouble(const Value: Double): Double; stdcall; begin { TODO : Implement method echoDouble } Result := Value; end; initialization { Invokable classes must be registered } InvRegistry.RegisterInvokableClass(Tusuario); end.
unit MEdit; {$mode objfpc}{$H+} interface uses Classes, SysUtils, StdCtrls, Graphics; type { TMedit } TMedit = class(TEdit) private fRegExpr : string; fValid : boolean; fStrict : boolean; procedure SetRegExpr(const AValue: string); procedure SetValid(const AValue: boolean); public constructor create(aOwner : TComponent); override; property IsValid : boolean read fValid write SetValid; procedure EditingDone; override; published property RegExpr : string read fRegExpr write SetRegExpr; property RegStrict : boolean read fStrict write fStrict; end; procedure Register; implementation uses RegExpr; procedure Register; begin RegisterComponents('xPL Components',[TMEdit]); end; procedure TMedit.SetRegExpr(const AValue: string); begin if aValue = fRegExpr then exit; fRegExpr := aValue; end; procedure TMedit.EditingDone; begin inherited; if RegExpr='' then exit; with TRegExpr.Create do try Expression := RegExpr; if RegStrict then Expression := '^' + Expression + '$'; IsValid := Exec(Text); finally free; end; end; procedure TMedit.SetValid(const AValue: boolean); begin fValid := aValue; if fValid then Self.Color := clWindow else Self.Color := clRed; end; constructor TMedit.create(aOwner : TComponent); begin inherited; RegExpr := ''; fStrict := True; end; end.
unit SpecificPaths; interface uses classes, sysUtils; type TSpecificPaths = class(TStringList) protected // (object associé) mysuminfo : Tsuminfo; private fReference : TStringList; function GetGroupName(Key : String) : String; procedure SetGroupName(Key : String; value : String); public constructor Create(); destructor Destroy; override; property GroupName[Key : String] : String read GetGroupName write SetGroupName; procedure AddSpecificPath(P: String; Gname: String); function AddUnique(S : String) : Integer; function ReferenceExists(S : String) : boolean; procedure dumpData(S : String); end; ESpecificPathsNotUnique = class(Exception); implementation constructor TSpecificPaths.Create(); begin fReference := TStringList.create(); fReference.Duplicates := dupError; fReference.Sorted := true; Duplicates := dupError; OwnsObjects := False; Sorted := True; end; destructor TSpecificPaths.Destroy; begin fReference.free; inherited Destroy; end; Procedure TSpecificPaths.AddSpecificPath(P: String; Gname: String); var Dup : string; begin try GroupName[LowerCase(P)] := Lowercase(GName); // writeln('SpecificPaths : on set Values[',P,'] := ',Gname) except on EStringListError do begin Dup := Values[LowerCase(P)]; raise ESpecificPathsNotUnique.create('['+Gname+'->'+P+'] duplicates on type ['+Dup+']'); end else raise; end; end; function TSpecificPaths.GetGroupName(Key : String) : String; begin result := Values[LowerCase(Key)]; end; procedure TSpecificPaths.SetGroupName(Key : String; value : String); begin Values[LowerCase(Key)] := LowerCase(Value); end; function TSpecificPaths.AddUnique(S : String) : Integer; begin try Result := fReference.Add(LowerCase(S)); except on EStringListError do raise ESpecificPathsNotUnique.create('['+S+'] Duplicates'); end; end; function TSpecificPaths.ReferenceExists(S : String) : Boolean; begin Result := fReference.indexOf(Lowercase(S))<>-1; end; procedure TSpecificPaths.dumpData(S : String); var i : Integer; begin Writeln(S:10,' Value:':25 , '':3, 'Name:':25); for i := 0 to pred(count) do Writeln(i:10,Names[i]:25, ' = ':3, ValueFromIndex[i]:25); end; end.
unit Rx.Observable.AdvancedOps; interface uses Rx, Rx.Implementations, Rx.Subjects, Rx.Observable.Map, Generics.Collections, Generics.Defaults, SyncObjs; type TScanObservable<CTX, T> = class(TMap<T, CTX>) strict private FContext: CTX; FContextHolder: TSmartVariable<CTX>; FScanRoutine: TScanRoutine<CTX, T>; protected function RoutineDecorator(const Data: T): CTX; override; public constructor Create(Source: IObservable<T>; const Initial: TSmartVariable<CTX>; const ScanRoutine: TScanRoutine<CTX, T>); end; TReduceObservable<ACCUM, T> = class(TMap<T, ACCUM>) strict private FAccum: TSmartVariable<ACCUM>; FReduceRoutine: TReduceRoutine<ACCUM, T>; FAccumIsEmpty: Boolean; protected function RoutineDecorator(const Data: T): ACCUM; override; public constructor Create(Source: IObservable<T>; const ReduceRoutine: TReduceRoutine<ACCUM, T>); procedure OnNext(const Data: T); override; end; TCollect1Observable<ITEM, VALUE> = class(TMap<VALUE, TList<ITEM>>) type TList = TList<ITEM>; TSmartList = TList<TSmartVariable<ITEM>>; strict private FList: TSmartVariable<TSmartList>; FAction: TCollectAction1<ITEM, VALUE>; protected function RoutineDecorator(const Data: VALUE): TList; override; public constructor Create(Source: IObservable<VALUE>; const Initial: TSmartList; const Action: TCollectAction1<ITEM, VALUE>); end; TCollect2Observable<KEY, ITEM, VALUE> = class(TMap<VALUE, TDictionary<KEY, ITEM>>) type TDict = TDictionary<KEY, ITEM>; TSmartDict = TDictionary<KEY, TSmartVariable<ITEM>>; strict private FDict: TSmartVariable<TSmartDict>; FAction: TCollectAction2<KEY, ITEM, VALUE>; protected function RoutineDecorator(const Data: VALUE): TDict; override; public constructor Create(Source: IObservable<VALUE>; const Initial: TSmartDict; const Action: TCollectAction2<KEY, ITEM, VALUE>); end; implementation { TScanObservable<CTX, T> } constructor TScanObservable<CTX, T>.Create(Source: IObservable<T>; const Initial: TSmartVariable<CTX>; const ScanRoutine: TScanRoutine<CTX, T>); begin inherited Create(Source, nil); FScanRoutine := ScanRoutine; FContext := Initial; FContextHolder := FContext; end; function TScanObservable<CTX, T>.RoutineDecorator(const Data: T): CTX; begin FScanRoutine(FContext, Data); Result := FContext; end; { TReduceObservable<CTX, T> } constructor TReduceObservable<ACCUM, T>.Create(Source: IObservable<T>; const ReduceRoutine: TReduceRoutine<ACCUM, T>); begin inherited Create(Source, nil); FReduceRoutine := ReduceRoutine; FAccumIsEmpty := True; end; procedure TReduceObservable<ACCUM, T>.OnNext(const Data: T); begin // inherited; end; function TReduceObservable<ACCUM, T>.RoutineDecorator(const Data: T): ACCUM; begin FAccum := FReduceRoutine(FAccum, Data); Result := FAccum; end; { TCollect1Observable<ITEM, VALUE> } constructor TCollect1Observable<ITEM, VALUE>.Create(Source: IObservable<VALUE>; const Initial: TSmartList; const Action: TCollectAction1<ITEM, VALUE>); begin inherited Create(Source, nil); FAction := Action; if Assigned(Initial) then FList := Initial else FList := TSmartList.Create; end; function TCollect1Observable<ITEM, VALUE>.RoutineDecorator( const Data: VALUE): TList; var I: Integer; NewList: TSmartList; begin Result := TList.Create; for I := 0 to FList.Get.Count-1 do Result.Add(FList.Get[I]); FAction(Result, Data); NewList := TSmartList.Create; for I := 0 to Result.Count-1 do NewList.Add(Result[I]); FList := NewList; end; { TCollect2Observable<KEY, ITEM, VALUE> } constructor TCollect2Observable<KEY, ITEM, VALUE>.Create( Source: IObservable<VALUE>; const Initial: TSmartDict; const Action: TCollectAction2<KEY, ITEM, VALUE>); begin inherited Create(Source, nil); FAction := Action; if Assigned(Initial) then FDict := Initial else FDict := TSmartDict.Create; end; function TCollect2Observable<KEY, ITEM, VALUE>.RoutineDecorator( const Data: VALUE): TDict; var I: Integer; NewDict: TSmartDict; KV1: TPair<KEY, TSmartVariable<ITEM>>; KV2: TPair<KEY, ITEM>; begin Result := TDict.Create; for KV1 in FDict.Get do begin Result.Add(KV1.Key, KV1.Value); end; FAction(Result, Data); NewDict := TSmartDict.Create; for KV2 in Result do begin NewDict.Add(KV2.Key, KV2.Value); end; FDict := NewDict; end; end.
unit MapLayerPropertiesDialogUnit; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Db, DBTables, Wwtable, StdCtrls, Mask, wwdbedit, Buttons, ExtCtrls, ComCtrls; type TMappingOptionsSetupAddLayerDialog = class(TForm) LayerInformationGroupBox: TGroupBox; Label1: TLabel; Label2: TLabel; FindLayerButton: TBitBtn; LocationEdit: TwwDBEdit; LayerNameEdit: TwwDBEdit; MapLayersAvailableTable: TwwTable; ClassificationOptionsRadioGroup: TRadioGroup; Label3: TLabel; LayerTypeEdit: TwwDBEdit; Panel1: TPanel; ClassificationNotebook: TNotebook; Label8: TLabel; Label9: TLabel; FillStyleComboBox: TComboBox; FillColorButton: TButton; EditSingleSymbolColor: TEdit; Panel2: TPanel; Label4: TLabel; Panel3: TPanel; Label5: TLabel; MapFieldComboBox: TComboBox; Label6: TLabel; UniqueValuesListView: TListView; Label7: TLabel; DisplayOutlineCheckBox: TCheckBox; DisplayTextCheckBox: TCheckBox; procedure ClassificationOptionsRadioGroupClick(Sender: TObject); private { Private declarations } public { Public declarations } Procedure Initialize(LayerName : String; EditMode : Char); end; var MappingOptionsSetupAddLayerDialog: TMappingOptionsSetupAddLayerDialog; implementation {$R *.DFM} uses GlblCnst, DataAccessUnit; const pgSingleSymbol = 0; pgUniqueValues = 1; pgClassBreaks = 2; pgStandardLabels = 3; pgNoOverlappingLabels = 4; {======================================================================} Procedure TMappingOptionsSetupAddLayerDialog.Initialize(LayerName : String; EditMode : Char); begin If (EditMode = emBrowse) then begin MapLayersTable.ReadOnly := True; end; MapLayersAvailableTable.Open; case EditMode of emEdit, emBrowse : _Locate(MapLayersAvailableTable, [LayerName], '', []); emInsert : begin end; end; {case EditMode of} end; {Initialize} {================================================================================} Procedure TMappingOptionsSetupAddLayerDialog.ClassificationOptionsRadioGroupClick(Sender: TObject); begin ClassificationNotebook.PageIndex := ClassificationOptionsRadioGroup.ItemIndex; end; end.
unit Unit1; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.PushNotification, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo, DW.PushClient; type TForm1 = class(TForm) Memo1: TMemo; private FPushClient: TPushClient; procedure PushClientChangeHandler(Sender: TObject; AChange: TPushService.TChanges); procedure PushClientReceiveNotificationHandler(Sender: TObject; const ANotification: TPushServiceNotification); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var Form1: TForm1; implementation {$R *.fmx} uses // Create the unit FCMConsts and declare consts for: // cFCMServerKey // cFCMSenderID // cFCMBundleID // These values are at a URL similar to: https://console.firebase.google.com/project/myproject-xxxxxx/settings/cloudmessaging // Where: myproject-xxxxxx is your project identifier on FCM. Go to: https://console.firebase.google.com and log in to check FCMConsts; { TForm1 } constructor TForm1.Create(AOwner: TComponent); begin inherited; FPushClient := TPushClient.Create; FPushClient.GCMAppID := cFCMSenderID; FPushClient.ServerKey := cFCMServerKey; FPushClient.BundleID := cFCMBundleID; FPushClient.UseSandbox := True; // Change this to False for production use! FPushClient.OnChange := PushClientChangeHandler; FPushClient.OnReceiveNotification := PushClientReceiveNotificationHandler; FPushClient.Active := True; end; destructor TForm1.Destroy; begin FPushClient.Free; inherited; end; procedure TForm1.PushClientChangeHandler(Sender: TObject; AChange: TPushService.TChanges); begin if TPushService.TChange.DeviceToken in AChange then begin Memo1.Lines.Add('DeviceID = ' + FPushClient.DeviceID); Memo1.Lines.Add('DeviceToken = ' + FPushClient.DeviceToken); end; end; procedure TForm1.PushClientReceiveNotificationHandler(Sender: TObject; const ANotification: TPushServiceNotification); begin Memo1.Lines.Add('Notification: ' + ANotification.DataObject.ToString); end; end.
unit account_impl; {This file was generated on 15 Jun 2000 20:42:11 GMT by version 03.03.03.C1.04} {of the Inprise VisiBroker idl2pas CORBA IDL compiler. } {Please do not edit the contents of this file. You should instead edit and } {recompile the original IDL which was located in the file account.idl. } {Delphi Pascal unit : account_impl } {derived from IDL module : default } interface uses SysUtils, CORBA, account_i, account_c; type TAccount = class; TAccount = class(TInterfacedObject, account_i.Account) protected _balance : Single; _YearOpened : SmallInt; _GotToaster : Boolean; function _get_YearOpened : SmallInt; procedure _set_YearOpened (const YearOpened : SmallInt); function _get_GotToaster : Boolean; public constructor Create; function balance : Single; property YearOpened : SmallInt read _get_YearOpened write _set_YearOpened; property GotToaster : Boolean read _get_GotToaster; end; implementation uses ServerMain; constructor TAccount.Create; begin inherited; _balance := Random * 1000; _YearOpened := 1995; _GotToaster := True; end; function TAccount._get_YearOpened : SmallInt; begin Result := _YearOpened; end; procedure TAccount._set_YearOpened ( const YearOpened : SmallInt); begin _YearOpened := YearOpened; end; function TAccount._get_GotToaster : Boolean; begin Result := _GotToaster; end; function TAccount.balance : Single; begin Result := _balance; Form1.Memo1.Lines.Add('Got a balance call from the client...'); end; initialization Randomize; end.
unit acCustomRelatorioDataUn; interface uses SysUtils, Classes, FMTBcd, Provider, osSQLDataSetProvider, DB, SqlExpr, osUtils, osCustomDataSetProvider, osSQLDataSet, osSqlQuery, acCustomReportUn; type TacCustomRelatorioData = class(TDataModule) MasterDataSet: TosSQLDataset; MasterProvider: TosSQLDataSetProvider; MasterDataSetIDRELATORIO: TIntegerField; MasterDataSetTITULO: TStringField; MasterDataSetDESCRICAO: TMemoField; MasterDataSetCOMPATIVELAPARTIRDAVERSAO: TStringField; MasterDataSetCOMPATIVELATEVERSAO: TStringField; MasterDataSetDATAIMPORTACAO: TSQLTimeStampField; MasterDataSetARQUIVOORIGEM: TStringField; MasterDataSetIDUSUARIOIMPORTACAO: TIntegerField; MasterDataSetITEM_ID: TIntegerField; MasterDataSetIDXFILTERDEF: TIntegerField; MasterDataSetCLASSEIMPRESSORA: TStringField; MasterDataSetIDTIPORELATORIO: TIntegerField; MasterDataSetCLASSERELATORIO: TStringField; private public procedure Validate(PDataSet: TDataSet); class function getItemIdByReportId(idRelatorio: integer): integer; class function getTitulo(IdRelatorio: integer): string; function isChangeable(className: string): boolean; virtual; class function getTemplateConfigForUser(className: string; var configImpressao: TConfigImpressao): integer; virtual; end; var acCustomRelatorioData: TacCustomRelatorioData; implementation uses osErrorHandler, acCustomSQLMainDataUn, osLogin, osReportUtils; {$R *.dfm} class function TacCustomRelatorioData.getTemplateConfigForUser( className: string; var configImpressao: TConfigImpressao): integer; {var qry: TosSQLQuery; nomeField: string; loginInfo: TLoginUsuario;} begin result := -1; //todo o código foi comentado para implementar o novo esquema de herança { className := UpperCase(className); nomeField := ''; if (classname = 'TPROTOCOLOREPORT') then nomeField := 'IdRelatorioProtocolo'; if (classname = 'TFICHAPACIENTEREPORT') then nomeField := 'IdRelatorioFichaTrabalho'; if (classname = 'TMAPALOTEREPORT') then nomeField := 'IdRelatorioMapaTrabalho'; if (classname = 'TLAUDOREPORT') then nomeField := 'IdRelatorioLaudoExame'; if (classname = 'TETIQUETAAMOSTRAREPORT') then nomeField := 'IdRelatorioEtiquetas'; if (classname = 'TORCAMENTOREPORT') then nomeField := 'IdRelatorioOrcamento'; if nomeField='' then result := -1 else begin loginInfo := TLoginUsuario.create; loginInfo.getInfoUsuarioLogadoSistema; qry := MainData.GetQuery; try qry.SQL.Text := ' Select '+ ' r.ITEM_ID ' + ' from '+ ' UsuarioRelatorio ur '+ ' JOIN Relatorio r' + ' ON r.IdRelatorio=ur.'+nomeField+ ' Where IdUsuario=' + IntToStr(loginInfo.IDUsuario); qry.Open; if qry.Eof then result := -1 else if qry.fields[0].AsString = '' then result := -1 else result := qry.fields[0].AsInteger; finally FreeAndNil(qry); end; end;} end; function TacCustomRelatorioData.isChangeable(className: string): boolean; begin result := false; end; class function TacCustomRelatorioData.getTitulo(IdRelatorio: integer): string; var qry: TosSQLQuery; begin qry := acCustomSQLMainData.GetQuery; try qry.SQL.Text := 'Select titulo from Relatorio Where IdRelatorio=' + IntToStr(IdRelatorio); qry.Open; if qry.Eof then result := '' else result := qry.fields[0].AsString; finally FreeAndNil(qry); end; end; procedure TacCustomRelatorioData.Validate(PDataSet: TDataSet); begin with PDataSet, HError do begin Clear; CheckEmpty(FieldByName('ITEM_ID')); CheckEmpty(FieldByName('Titulo')); CheckEmpty(FieldByName('IDTipoRelatorio')); CheckEmpty(FieldByName('ClasseImpressora')); WarningEmpty(FieldByName('CompativelAPartirDaVersao')); WarningEmpty(FieldByName('CompativelAteVersao')); WarningEmpty(FieldByName('Descricao')); Check; end; end; class function TacCustomRelatorioData.getItemIdByReportId( idRelatorio: integer): integer; var qry: TosSQLQuery; begin qry := acCustomSQLMainData.GetQuery; try qry.SQL.Text := ' Select '+ ' ITEM_ID ' + ' FROM Relatorio ' + ' WHERE IDRelatorio = ' + IntToStr(idRelatorio); qry.Open; result := qry.fields[0].AsInteger; finally acCustomSQLMainData.FreeQuery(qry); end; end; end.
unit AviWriter; ///////////////////////////////////////////////////////////////////////////// // // // AviWriter -- a component to create rudimentary AVI files // // by Elliott Shevin, with large pieces of code // // stolen from Anders Melander // // version 1.0. Please send comments, suggestions, and advice // // to shevine@aol.com. // ///////////////////////////////////////////////////////////////////////////// // // // AviWriter will build an AVI file containing one stream of any // // number of TBitmaps, plus a single WAV file. // // // // Properties: // // Bitmaps : A TList of pointers to TBitmap objects which become // // frames of the AVI video stream. The component // // allocates and frees the TList, but the caller // // is responsible for managing the TBitmaps themselves. // // Manipulate the list as you would any other TList. // // At least one bitmap is required. // // Height, Width: // // The dimensions of the AVI video, in pixels. // // FrameTime: // // The duration of each video frame, in milliseconds. // // Stretch: If TRUE, each TBitmap on the Bitmaps list is // // stretches to the dimensions specified in Height // // and Width. If FALSE, each TBitmap is copied from // // its upper left corner without stretching. // // FileName: The name of the AVI file to be written. // // WAVFileName: // // The name of a WAV file which will become the audio // // stream for the AVI. Optional. // // // // Method: // // Write: Creates the AVI file named by FileName. // ///////////////////////////////////////////////////////////////////////////// // Wish List: // // I'd like to be able to enhance this component in two ways, but // // don't know how. Please send ideas to shevine@aol.com. // // 1. So far, it's necessary to transform the video stream into // // and AVI file on disk. I'd prefer to do this in memory. // // 2. MIDI files for audio. // ///////////////////////////////////////////////////////////////////////////// interface uses Windows,Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, {$ifdef VER90} ole2; {$else} ActiveX; {$endif} //////////////////////////////////////////////////////////////////////////////// // // // Video for Windows // // // //////////////////////////////////////////////////////////////////////////////// // // // Adapted from Thomas Schimming's VFW.PAS // // (c) 1996 Thomas Schimming, schimmin@iee1.et.tu-dresden.de // // (c) 1998,99 Anders Melander // // // //////////////////////////////////////////////////////////////////////////////// // // // Ripped all COM/ActiveX stuff and added some AVI stream functions. // // // //////////////////////////////////////////////////////////////////////////////// type { TAVIFileInfoW record } LONG = Longint; PVOID = Pointer; // TAVIFileInfo dwFlag values const AVIF_HASINDEX = $00000010; AVIF_MUSTUSEINDEX = $00000020; AVIF_ISINTERLEAVED = $00000100; AVIF_WASCAPTUREFILE = $00010000; AVIF_COPYRIGHTED = $00020000; AVIF_KNOWN_FLAGS = $00030130; AVIERR_UNSUPPORTED = $80044065; // MAKE_AVIERR(101) AVIERR_BADFORMAT = $80044066; // MAKE_AVIERR(102) AVIERR_MEMORY = $80044067; // MAKE_AVIERR(103) AVIERR_INTERNAL = $80044068; // MAKE_AVIERR(104) AVIERR_BADFLAGS = $80044069; // MAKE_AVIERR(105) AVIERR_BADPARAM = $8004406A; // MAKE_AVIERR(106) AVIERR_BADSIZE = $8004406B; // MAKE_AVIERR(107) AVIERR_BADHANDLE = $8004406C; // MAKE_AVIERR(108) AVIERR_FILEREAD = $8004406D; // MAKE_AVIERR(109) AVIERR_FILEWRITE = $8004406E; // MAKE_AVIERR(110) AVIERR_FILEOPEN = $8004406F; // MAKE_AVIERR(111) AVIERR_COMPRESSOR = $80044070; // MAKE_AVIERR(112) AVIERR_NOCOMPRESSOR = $80044071; // MAKE_AVIERR(113) AVIERR_READONLY = $80044072; // MAKE_AVIERR(114) AVIERR_NODATA = $80044073; // MAKE_AVIERR(115) AVIERR_BUFFERTOOSMALL = $80044074; // MAKE_AVIERR(116) AVIERR_CANTCOMPRESS = $80044075; // MAKE_AVIERR(117) AVIERR_USERABORT = $800440C6; // MAKE_AVIERR(198) AVIERR_ERROR = $800440C7; // MAKE_AVIERR(199) type TAVIFileInfoW = record dwMaxBytesPerSec, // max. transfer rate dwFlags, // the ever-present flags dwCaps, dwStreams, dwSuggestedBufferSize, dwWidth, dwHeight, dwScale, dwRate, // dwRate / dwScale == samples/second dwLength, dwEditCount: DWORD; szFileType: array[0..63] of WideChar; // descriptive string for file type? end; PAVIFileInfoW = ^TAVIFileInfoW; // TAVIStreamInfo dwFlag values const AVISF_DISABLED = $00000001; AVISF_VIDEO_PALCHANGES= $00010000; AVISF_KNOWN_FLAGS = $00010001; type TAVIStreamInfoA = record fccType, fccHandler, dwFlags, // Contains AVITF_* flags dwCaps: DWORD; wPriority, wLanguage: WORD; dwScale, dwRate, // dwRate / dwScale == samples/second dwStart, dwLength, // In units above... dwInitialFrames, dwSuggestedBufferSize, dwQuality, dwSampleSize: DWORD; rcFrame: TRect; dwEditCount, dwFormatChangeCount: DWORD; szName: array[0..63] of AnsiChar; end; TAVIStreamInfo = TAVIStreamInfoA; PAVIStreamInfo = ^TAVIStreamInfo; { TAVIStreamInfoW record } TAVIStreamInfoW = record fccType, fccHandler, dwFlags, // Contains AVITF_* flags dwCaps: DWORD; wPriority, wLanguage: WORD; dwScale, dwRate, // dwRate / dwScale == samples/second dwStart, dwLength, // In units above... dwInitialFrames, dwSuggestedBufferSize, dwQuality, dwSampleSize: DWORD; rcFrame: TRect; dwEditCount, dwFormatChangeCount: DWORD; szName: array[0..63] of WideChar; end; PAVIStream = pointer; PAVIFile = pointer; TAVIStreamList = array[0..0] of PAVIStream; PAVIStreamList = ^TAVIStreamList; TAVISaveCallback = function (nPercent: integer): LONG; stdcall; TAVICompressOptions = packed record fccType : DWORD; fccHandler : DWORD; dwKeyFrameEvery : DWORD; dwQuality : DWORD; dwBytesPerSecond : DWORD; dwFlags : DWORD; lpFormat : pointer; cbFormat : DWORD; lpParms : pointer; cbParms : DWORD; dwInterleaveEvery : DWORD; end; PAVICompressOptions = ^TAVICompressOptions; // Palette change data record const RIFF_PaletteChange: DWORD = 1668293411; type TAVIPalChange = packed record bFirstEntry : byte; bNumEntries : byte; wFlags : WORD; peNew : array[byte] of TPaletteEntry; end; PAVIPalChange = ^TAVIPalChange; APAVISTREAM = array[0..1] of PAVISTREAM; APAVICompressOptions = array[0..1] of PAVICompressOptions; procedure AVIFileInit; stdcall; procedure AVIFileExit; stdcall; function AVIFileOpen(var ppfile: PAVIFile; szFile: PChar; uMode: UINT; lpHandler: pointer): HResult; stdcall; function AVIFileCreateStream(pfile: PAVIFile; var ppavi: PAVISTREAM; var psi: TAVIStreamInfo): HResult; stdcall; function AVIStreamSetFormat(pavi: PAVIStream; lPos: LONG; lpFormat: pointer; cbFormat: LONG): HResult; stdcall; function AVIStreamReadFormat(pavi: PAVIStream; lPos: LONG; lpFormat: pointer; var cbFormat: LONG): HResult; stdcall; function AVIStreamWrite(pavi: PAVIStream; lStart, lSamples: LONG; lpBuffer: pointer; cbBuffer: LONG; dwFlags: DWORD; var plSampWritten: LONG; var plBytesWritten: LONG): HResult; stdcall; function AVIStreamRelease(pavi: PAVISTREAM): ULONG; stdcall; function AVIFileRelease(pfile: PAVIFile): ULONG; stdcall; function AVIFileGetStream(pfile: PAVIFile; var ppavi: PAVISTREAM; fccType: DWORD; lParam: LONG): HResult; stdcall; function CreateEditableStream(var ppsEditable: PAVISTREAM; psSource: PAVISTREAM): HResult; stdcall; function AVISaveV(szFile: PChar; pclsidHandler: PCLSID; lpfnCallback: TAVISaveCallback; nStreams: integer; pavi: APAVISTREAM; lpOptions: APAVICompressOptions): HResult; stdcall; const AVIERR_OK = 0; AVIIF_LIST = $01; AVIIF_TWOCC = $02; AVIIF_KEYFRAME = $10; streamtypeVIDEO = $73646976; // DWORD( 'v', 'i', 'd', 's' ) streamtypeAUDIO = $73647561; // DWORD( 'a', 'u', 'd', 's' ) type TPixelFormat = (pfDevice, pf1bit, pf4bit, pf8bit, pf15bit, pf16bit, pf24bit, pf32bit, pfCustom); type TAviWriter = class(TComponent) private TempFileName : string; pFile : PAVIFile; fHeight : integer; fWidth : integer; fStretch : boolean; fFrameTime : integer; fFileName : string; fWavFileName : string; FrameCount : integer; VideoStream : PAVISTREAM; AudioStream : PAVISTREAM; procedure AddVideo; procedure AddAudio; procedure InternalGetDIBSizes(Bitmap: HBITMAP; var InfoHeaderSize: Integer; var ImageSize: longInt; PixelFormat: TPixelFormat); function InternalGetDIB(Bitmap: HBITMAP; Palette: HPALETTE; var BitmapInfo; var Bits; PixelFormat: TPixelFormat): Boolean; procedure InitializeBitmapInfoHeader(Bitmap: HBITMAP; var Info: TBitmapInfoHeader; PixelFormat: TPixelFormat); procedure SetWavFileName(value : string); { Private declarations } protected { Protected declarations } public Bitmaps : TList; constructor Create(AOwner : TComponent); override; destructor Destroy; override; procedure Write; { Public declarations } published property Height : integer read fHeight write fHeight; property Width : integer read fWidth write fWidth; property FrameTime: integer read fFrameTime write fFrameTime; property Stretch : boolean read fStretch write fStretch; property FileName : string read fFileName write fFileName; property WavFileName : string read fWavFileName write SetWavFileName; { Published declarations } end; procedure Register; implementation constructor TAviWriter.Create(AOwner : TComponent); var tempdir : string; l : integer; begin inherited Create(AOwner); fHeight := screen.height div 10; fWidth := screen.width div 10; fFrameTime := 1000; fStretch := true; fFileName := ''; Bitmaps := TList.create; AVIFileInit; setlength(tempdir,MAX_PATH + 1); l := GetTempPath(MAX_PATH,pchar(tempdir)); setlength(tempdir,l); if copy(tempdir,length(tempdir),1) <> '\' then tempdir := tempdir + '\'; TempFileName := tempdir + '~AWTemp.avi'; end; destructor TAviWriter.Destroy; begin Bitmaps.free; AviFileExit; inherited; end; procedure TAviWriter.Write; var Bitmap : TBitmap; ExtBitmap : TBitmap; nstreams : integer; i : integer; Streams : APAVISTREAM; CompOptions : APAVICompressOptions; AVIERR : integer; refcount : integer; begin AudioStream := nil; VideoStream := nil; // If no bitmaps are on the list, raise an error. if Bitmaps.count < 1 then raise Exception.Create('No bitmaps on the Bitmaps list'); // If anything on the Bitmaps TList is not a bitmap, raise // an error. for i := 0 to Bitmaps.count - 1 do begin ExtBitmap := Bitmaps[i]; if not(ExtBitmap is TBitmap) then raise Exception.Create('Bitmaps[' + inttostr(i) + '] is not a TBitmap'); end; try AddVideo; if WavFileName <> '' then AddAudio; // Create the output file. if WavFileName <> '' then nstreams := 2 else nstreams := 1; Streams[0] := VideoStream; Streams[1] := AudioStream; CompOptions[0] := nil; CompOptions[1] := nil; AVIERR := AVISaveV(pchar(FileName), nil, // File handler nil, // Callback nStreams, // Number of streams Streams, CompOptions); // Compress options for VideoStream if AVIERR <> AVIERR_OK then raise Exception.Create('Unable to write output file'); finally if assigned(VideoStream) then AviStreamRelease(VideoStream); if assigned(AudioStream) then AviStreamRelease(AudioStream); try repeat refcount := AviFileRelease(pFile); until refcount <= 0; except end; DeleteFile(TempFileName); end; end; procedure TAviWriter.AddVideo; var Pstream : PAVISTREAM; StreamInfo : TAVIStreamInfo; BitmapInfo : PBitmapInfoHeader; BitmapInfoSize : Integer; BitmapSize : longInt; BitmapBits : pointer; Bitmap : TBitmap; ExtBitmap : TBitmap; Samples_Written : LONG; Bytes_Written : LONG; AVIERR : integer; i : integer; startpos : DWORD; len : DWORD; begin // Open AVI file for write if (AVIFileOpen(pFile, pchar(TempFileName), OF_WRITE or OF_CREATE OR OF_SHARE_EXCLUSIVE, nil) <> AVIERR_OK) then raise Exception.Create('Failed to create AVI video work file'); // Allocate the bitmap to which the bitmaps on the Bitmaps Tlist // will be copied. Bitmap := TBitmap.create; Bitmap.Height := self.Height; Bitmap.Width := self.Width; // Write the stream header. try FillChar(StreamInfo, sizeof(StreamInfo), 0); // Set frame rate and scale StreamInfo.dwRate := 1000; StreamInfo.dwScale := fFrameTime; StreamInfo.fccType := streamtypeVIDEO; StreamInfo.fccHandler := 0; StreamInfo.dwFlags := 0; StreamInfo.dwSuggestedBufferSize := 0; StreamInfo.rcFrame.Right := self.width; StreamInfo.rcFrame.Bottom := self.height; // Open AVI data stream if (AVIFileCreateStream(pFile, pStream, StreamInfo) <> AVIERR_OK) then raise Exception.Create('Failed to create AVI video stream'); try // Write the bitmaps to the stream. for i := 0 to Bitmaps.count - 1 do begin try BitmapInfo := nil; BitmapBits := nil; // Copy the bitmap from the list to the AVI bitmap, // stretching if desired. If the caller elects not to // stretch, use the first pixel in the bitmap as a // background color in case either the height or // width of the source is smaller than the output. // If Draw fails, do a StretchDraw. ExtBitmap := Bitmaps[i]; if fStretch then Bitmap.Canvas.StretchDraw (Rect(0,0,self.width,self.height),ExtBitmap) else try with Bitmap.Canvas do begin Brush.Color := ExtBitmap.Canvas.Pixels[0,0]; Brush.Style := bsSolid; FillRect(Rect(0,0,Bitmap.Width,Bitmap.Height)); Draw(0,0,ExtBitmap); end; except Bitmap.Canvas.StretchDraw (Rect(0,0,self.width,self.height),ExtBitmap); end; // Determine size of DIB InternalGetDIBSizes(Bitmap.Handle, BitmapInfoSize, BitmapSize, pf8bit); if (BitmapInfoSize = 0) then raise Exception.Create('Failed to retrieve bitmap info'); // Get DIB header and pixel buffers GetMem(BitmapInfo, BitmapInfoSize); GetMem(BitmapBits, BitmapSize); InternalGetDIB (Bitmap.Handle, 0, BitmapInfo^, BitmapBits^, pf8bit); // On the first time through, set the stream format. if i = 0 then if (AVIStreamSetFormat(pStream, 0, BitmapInfo, BitmapInfoSize) <> AVIERR_OK) then raise Exception.Create('Failed to set AVI stream format'); // Write frame to the video stream AVIERR := AVIStreamWrite(pStream, i, 1, BitmapBits, BitmapSize, AVIIF_KEYFRAME, Samples_Written, Bytes_Written); if AVIERR <> AVIERR_OK then raise Exception.Create ('Failed to add frame to AVI. Err=' + inttohex(AVIERR,8)); finally if (BitmapInfo <> nil) then FreeMem(BitmapInfo); if (BitmapBits <> nil) then FreeMem(BitmapBits); end; end; // Create the editable VideoStream from pStream. if CreateEditableStream(VideoStream,pStream) <> AVIERR_OK then raise Exception.Create ('Could not create Video Stream'); finally AviStreamRelease(pStream); end; finally Bitmap.free; end; end; procedure TAviWriter.AddAudio; var InputFile : PAVIFILE; hr : integer; InputStream : PAVIStream; avisClip : TAVISTREAMINFO; l, selstart : DWORD; pastecode : integer; begin // Open the audio file. hr := AVIFileOpen(InputFile, pchar(WavFileName),OF_READ, nil); case hr of 0: ; AVIERR_BADFORMAT : raise Exception.Create('The file could not be read, indicating a corrupt file or an unrecognized format.'); AVIERR_MEMORY : raise Exception.Create('The file could not be opened because of insufficient memory.'); AVIERR_FILEREAD : raise Exception.Create('A disk error occurred while reading the audio file.'); AVIERR_FILEOPEN : raise Exception.Create('A disk error occurred while opening the audio file.'); REGDB_E_CLASSNOTREG : raise Exception.Create('According to the registry, the type of audio file specified in AVIFileOpen does not have a handler to process it.'); else raise Exception.Create('Unknown error opening audio file'); end; // Open the audio stream. try if (AVIFileGetStream(InputFile, InputStream, 0, 0) <> AVIERR_OK) then raise Exception.Create('Unable to get audio stream'); try // Create AudioStream as a copy of InputStream if (CreateEditableStream(AudioStream,InputStream) <> AVIERR_OK) then raise Exception.Create('Failed to create editable AVI audio stream'); finally AviStreamRelease(InputStream); end; finally AviFileRelease(InputFile); end; end; // -------------- // InternalGetDIB // -------------- // Converts a bitmap to a DIB of a specified PixelFormat. // // Parameters: // Bitmap The handle of the source bitmap. // Pal The handle of the source palette. // BitmapInfo The buffer that will receive the DIB's TBitmapInfo structure. // A buffer of sufficient size must have been allocated prior to // calling this function. // Bits The buffer that will receive the DIB's pixel data. // A buffer of sufficient size must have been allocated prior to // calling this function. // PixelFormat The pixel format of the destination DIB. // // Returns: // True on success, False on failure. // // Note: The InternalGetDIBSizes function can be used to calculate the // nescessary sizes of the BitmapInfo and Bits buffers. // function TAviWriter.InternalGetDIB(Bitmap: HBITMAP; Palette: HPALETTE; var BitmapInfo; var Bits; PixelFormat: TPixelFormat): Boolean; // From graphics.pas, "optimized" for our use var OldPal : HPALETTE; DC : HDC; begin InitializeBitmapInfoHeader(Bitmap, TBitmapInfoHeader(BitmapInfo), PixelFormat); OldPal := 0; DC := CreateCompatibleDC(0); try if (Palette <> 0) then begin OldPal := SelectPalette(DC, Palette, False); RealizePalette(DC); end; Result := (GetDIBits(DC, Bitmap, 0, abs(TBitmapInfoHeader(BitmapInfo).biHeight), @Bits, TBitmapInfo(BitmapInfo), DIB_RGB_COLORS) <> 0); finally if (OldPal <> 0) then SelectPalette(DC, OldPal, False); DeleteDC(DC); end; end; // ------------------- // InternalGetDIBSizes // ------------------- // Calculates the buffer sizes nescessary for convertion of a bitmap to a DIB // of a specified PixelFormat. // See the GetDIBSizes API function for more info. // // Parameters: // Bitmap The handle of the source bitmap. // InfoHeaderSize // The returned size of a buffer that will receive the DIB's // TBitmapInfo structure. // ImageSize The returned size of a buffer that will receive the DIB's // pixel data. // PixelFormat The pixel format of the destination DIB. // procedure TAviWriter.InternalGetDIBSizes(Bitmap: HBITMAP; var InfoHeaderSize: Integer; var ImageSize: longInt; PixelFormat: TPixelFormat); // From graphics.pas, "optimized" for our use var Info : TBitmapInfoHeader; begin InitializeBitmapInfoHeader(Bitmap, Info, PixelFormat); // Check for palette device format if (Info.biBitCount > 8) then begin // Header but no palette InfoHeaderSize := SizeOf(TBitmapInfoHeader); if ((Info.biCompression and BI_BITFIELDS) <> 0) then Inc(InfoHeaderSize, 12); end else // Header and palette InfoHeaderSize := SizeOf(TBitmapInfoHeader) + SizeOf(TRGBQuad) * (1 shl Info.biBitCount); ImageSize := Info.biSizeImage; end; // -------------------------- // InitializeBitmapInfoHeader // -------------------------- // Fills a TBitmapInfoHeader with the values of a bitmap when converted to a // DIB of a specified PixelFormat. // // Parameters: // Bitmap The handle of the source bitmap. // Info The TBitmapInfoHeader buffer that will receive the values. // PixelFormat The pixel format of the destination DIB. // {$IFDEF BAD_STACK_ALIGNMENT} // Disable optimization to circumvent optimizer bug... {$IFOPT O+} {$DEFINE O_PLUS} {$O-} {$ENDIF} {$ENDIF} procedure TAviWriter.InitializeBitmapInfoHeader(Bitmap: HBITMAP; var Info: TBitmapInfoHeader; PixelFormat: TPixelFormat); // From graphics.pas, "optimized" for our use var DIB : TDIBSection; Bytes : Integer; function AlignBit(Bits, BitsPerPixel, Alignment: Cardinal): Cardinal; begin Dec(Alignment); Result := ((Bits * BitsPerPixel) + Alignment) and not Alignment; Result := Result SHR 3; end; begin DIB.dsbmih.biSize := 0; Bytes := GetObject(Bitmap, SizeOf(DIB), @DIB); if (Bytes = 0) then raise Exception.Create('Invalid bitmap'); // Error(sInvalidBitmap); if (Bytes >= (sizeof(DIB.dsbm) + sizeof(DIB.dsbmih))) and (DIB.dsbmih.biSize >= sizeof(DIB.dsbmih)) then Info := DIB.dsbmih else begin FillChar(Info, sizeof(Info), 0); with Info, DIB.dsbm do begin biSize := SizeOf(Info); biWidth := bmWidth; biHeight := bmHeight; end; end; case PixelFormat of pf1bit: Info.biBitCount := 1; pf4bit: Info.biBitCount := 4; pf8bit: Info.biBitCount := 8; pf24bit: Info.biBitCount := 24; else // Error(sInvalidPixelFormat); raise Exception.Create('Invalid pixel foramt'); // Info.biBitCount := DIB.dsbm.bmBitsPixel * DIB.dsbm.bmPlanes; end; Info.biPlanes := 1; Info.biCompression := BI_RGB; // Always return data in RGB format Info.biSizeImage := AlignBit(Info.biWidth, Info.biBitCount, 32) * Cardinal(abs(Info.biHeight)); end; {$IFDEF O_PLUS} {$O+} {$UNDEF O_PLUS} {$ENDIF} procedure TAviWriter.SetWavFileName(value : string); begin if lowercase(fWavFileName) <> lowercase(value) then if lowercase(ExtractFileExt(value)) <> '.wav' then raise Exception.Create('WavFileName must name a file ' + 'with the .wav extension') else fWavFileName := value; end; procedure Register; begin RegisterComponents('Samples', [TAviWriter]); end; procedure AVIFileInit; stdcall; external 'avifil32.dll' name 'AVIFileInit'; procedure AVIFileExit; stdcall; external 'avifil32.dll' name 'AVIFileExit'; function AVIFileOpen; external 'avifil32.dll' name 'AVIFileOpenA'; function AVIFileCreateStream; external 'avifil32.dll' name 'AVIFileCreateStreamA'; function AVIStreamSetFormat; external 'avifil32.dll' name 'AVIStreamSetFormat'; function AVIStreamReadFormat; external 'avifil32.dll' name 'AVIStreamReadFormat'; function AVIStreamWrite; external 'avifil32.dll' name 'AVIStreamWrite'; function AVIStreamRelease; external 'avifil32.dll' name 'AVIStreamRelease'; function AVIFileRelease; external 'avifil32.dll' name 'AVIFileRelease'; function AVIFileGetStream; external 'avifil32.dll' name 'AVIFileGetStream'; function CreateEditableStream; external 'avifil32.dll' name 'CreateEditableStream'; function AVISaveV; external 'avifil32.dll' name 'AVISaveV'; end.
unit CSCTimer; interface uses Windows; {===Timer declarations===} type TCSCWord32 = type DWORD; {32-bit unsigned integer} TCSCTimer = packed record trStart : longint; trExpire : longint; trWrapped : boolean; trForEver : boolean; end; const CSCTimerInfinite = -1; CSCTimerMaxExpiry = 120000; procedure SetTimer(var T : TCSCTimer; Time : integer); {-Set a timer to expire in Time milliseconds. 1 <= Time <= 120000.} function HasTimerExpired(const T : TCSCTimer) : boolean; {-Return true if the timer has expired} function TimeToExpire(const T : TCSCTimer): Integer; function TimeToExpireTC(const T : TCSCTimer; TC: Cardinal): Integer; implementation function CmpDW(a, b : TCSCWord32) : integer; asm xor ecx, ecx cmp eax, edx ja @@GT je @@EQ @@LT: dec ecx dec ecx @@GT: inc ecx @@EQ: mov eax, ecx end; function ForceInRange(a, aLow, aHigh : longint) : longint; register; asm cmp eax, edx jg @@CheckHigh mov eax, edx jmp @@Exit @@CheckHigh: cmp eax, ecx jl @@Exit mov eax, ecx @@Exit: end; {===Timer routines===================================================} procedure SetTimer(var T : TCSCTimer; Time : integer); begin with T do begin if (Time = CSCTimerInfinite) then begin trForEver := true; trStart := 0; trExpire := 0; trWrapped := false; end else begin trForEver := false; Time := ForceInRange(Time, 1, CSCTimerMaxExpiry); trStart := GetTickCount; trExpire := trStart + Time; trWrapped := CmpDW(trStart, trExpire) < 0; end; end; end; function TimeToExpire(const T : TCSCTimer): Integer; begin Result := TimeToExpireTC(T, GetTickCount); end; function TimeToExpireTC(const T : TCSCTimer; TC: Cardinal): Integer; begin with T do if trForEver then Result := High(Integer) else if HasTimerExpired(T) then Result := 1 else begin if trWrapped then Result := trExpire + High(Cardinal) - TC else Result := trExpire - TC; end; end; {--------} function HasTimerExpired(const T : TCSCTimer) : boolean; asm push ebx xor ebx, ebx cmp [eax].TCSCTimer.trForEver, 0 jne @@Exit push eax call GetTickCount pop edx mov ecx, [edx].TCSCTimer.trExpire mov edx, [edx].TCSCTimer.trStart cmp edx, ecx jbe @@StartLEExpire @@StartGEExpire: cmp eax, edx jae @@Exit cmp eax, ecx jae @@Expired jmp @@Exit @@StartLEExpire: cmp eax, ecx jae @@Expired cmp eax, edx jae @@Exit @@Expired: inc ebx @@Exit: mov eax, ebx pop ebx end; {====================================================================} end.
unit connectionFormHelpersUnit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.ComCtrls, Vcl.WinXCtrls, TreeViewExUnit, plugin; type TSmallWinControlHelper = class helper for TWinControl procedure ShowMe; procedure HideMe; end; TSplitViewHelper = class helper for TSplitView private const constInCatalog = 'Initial Catalog=%s;'; const constConnectionMSSQL = 'Provider=SQLOLEDB.1;Password=%s;Persist Security Info=True;User ID=%s;%sData Source=%s'; const constConnectionSybase = 'Provider=ASEOLEDB.1;Password=%s;Persist Security Info=True;User ID=%s;Data Source=%s:%s;%sExtended Properties="LANGUAGE=us_english";Connect Timeout=3'; const constConnectionODBC = 'Provider=MSDASQL.1;Persist Security Info=False;Data Source=%s'; public class function GetConnectionString(DataSource: string; const DataBase: string = ''): string; function CurrentTreeView: TTreeViewEx; function CurrentNode: TTreeNode; function CurrentBase: string; function CurrentUser: string; function CurrentServer: string; function ConnectionString: string; function BdType: TBdType; end; implementation { TSplitViewHelper } function TSplitViewHelper.BdType: TBdType; var i: Integer; begin for i := 0 to Self.ControlCount-1 do begin if (Self.Controls[i] is TTreeViewEx) and TTreeViewEx(Self.Controls[i]).Visible then begin Result := TTreeViewEx(Self.Controls[i]).BdType; break; end; end; end; function TSplitViewHelper.ConnectionString: string; var Node: TTreeNode; begin Result := ''; Node := Self.CurrentNode; if Assigned(Node) then begin if Node.ItemType = itLogin then Exit; if Node.ItemType in [itServerMS,itServerSYB,itODBC] then Result := GetConnectionString(TTreeNodeEx(Node).DataSource); if Node.ItemType in [itBase,itBaseRTI] then Result := GetConnectionString(TTreeNodeEx(Node.Parent).DataSource,Node.Text); end; end; function TSplitViewHelper.CurrentBase: string; var Node: TTreeNode; begin Result := 'Unknown'; Node := Self.CurrentNode; if Assigned(Node) then begin if Node.ItemType in [itBase,itBaseRTI] then Result := Node.Text; end; end; function TSplitViewHelper.CurrentNode: TTreeNode; begin Result := CurrentTreeView.Selected; end; function TSplitViewHelper.CurrentServer: string; var Node: TTreeNode; begin Result := ''; Node := Self.CurrentNode; if Assigned(Node) then begin if Assigned(Node.Parent) then Node := Node.Parent; Result := Node.Text; end; end; function TSplitViewHelper.CurrentTreeView: TTreeViewEx; var i: Integer; begin Result := nil; for i := 0 to Self.ControlCount-1 do if (Self.Controls[i] is TTreeViewEx) and TTreeViewEx(Self.Controls[i]).Visible then begin Result := TTreeViewEx(Self.Controls[i]); break; end; end; function TSplitViewHelper.CurrentUser: string; var Node: TTreeNode; i: Integer; begin Result := 'Unknown'; Node := Self.CurrentNode; if Assigned(Node) then begin if Assigned(Node.Parent) then Node := Node.Parent; for i := 0 to Node.Count-1 do if Node.Item[i].ItemType = itLogin then begin Result := Node.Item[i].Text; Exit; end; end; end; class function TSplitViewHelper.GetConnectionString(DataSource: string; const DataBase: string = ''): string; var Strings: TStringList; DB,FServer,FPassword,FLogin,FDataSource,FPort: string; begin Strings := TStringList.Create; try Strings.Delimiter := '|'; Strings.DelimitedText := DataSource; DB := ''; FDataSource := Strings[0]; FServer := Strings.Values['Server']; FPort := Strings.Values['Port']; FLogin := Strings.Values['Login']; FPassword := Strings.Values['Password']; if DataBase <> '' then DB := Format(constInCatalog,[DataBase]); if TBdType(Strings.Values['BdType'].ToInteger) = bdMSSQL then Result := Format(constConnectionMSSQL,[FPassword,FLogin,DB,FDataSource]) else if TBdType(Strings.Values['BdType'].ToInteger) = bdSybase then Result := Format(constConnectionSybase,[FPassword,FLogin,FServer,FPort,DB]) else begin Result := Format(constConnectionODBC,[FDataSource]); if FLogin <> '' then Result := Result + ';User ID=' + FLogin; if FPassword <> '' then Result := Result + ';Password=' + FPassword; end; finally Strings.Free; end; end; { TSmallWinControlHelper } procedure TSmallWinControlHelper.HideMe; begin Self.Align := alNone; Self.Visible := False; end; procedure TSmallWinControlHelper.ShowMe; begin Self.Align := alClient; Self.Visible := True; end; end.
unit UNewContactUni; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, dxSkinsCore, Data.DB, MemDS, DBAccess, Uni, cxTextEdit, cxLabel, cxGroupBox, UFrameSave, dxSkinDevExpressStyle, dxSkinsDefaultPainters; type TFNewContactUni = class(TForm) FrameSave1: TFrameSave; cxGroupBox1: TcxGroupBox; lblName: TcxLabel; edtName: TcxTextEdit; edtDolgnost: TcxTextEdit; lblDolg: TcxLabel; lblMail: TcxLabel; edtEmail: TcxTextEdit; lblSkype: TcxLabel; edtSkype: TcxTextEdit; lblMessenger: TcxLabel; edtMessenger: TcxTextEdit; edtPhone1: TcxTextEdit; lblPhone2: TcxLabel; lblPhone3: TcxLabel; edtPhone3: TcxTextEdit; edtPhone2: TcxTextEdit; lblPhone1: TcxLabel; Query1: TUniQuery; procedure FormShow(Sender: TObject); procedure FrameSave1btnSaveClick(Sender: TObject); private { Private declarations } public procedure SetLang; { Public declarations } end; var FNewContactUni: TFNewContactUni; implementation {$R *.dfm} uses UPasswd; procedure TFNewContactUni.FormShow(Sender: TObject); begin SetLang; FrameSave1.SetLang; end; procedure TFNewContactUni.FrameSave1btnSaveClick(Sender: TObject); begin FrameSave1.btnSaveClick(Sender); Close; end; procedure TFNewContactUni.SetLang; begin case FPasswd.Lang of 2: begin Caption := 'Contactos'; lblName.Caption := 'Nombre:'; lblDolg.Caption := 'Puesto:'; lblPhone1.Caption := 'Teléfono 1:'; lblPhone2.Caption := 'Teléfвono 2:'; lblPhone3.Caption := 'Teléfono 3:'; lblMail.Caption := 'EMail:'; end; end; end; end.
unit SubBatch; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, OnFocusButton, ComCtrls, OnEditBaseCtrl, OnEditStdCtrl, OnEditBtnCtrl, OnShapeLabel, Db, MemDS, DBAccess, Ora, Datelib, Func, Grids, Comobj, OnScheme; type TFM_Batch = class(TForm) OpenDialog1: TOpenDialog; Ory_juminid: TOraQuery; OnShapeLabel4: TOnShapeLabel; P_helpinfo: TStatusBar; Panel2: TPanel; BT_Delete: TOnFocusButton; BT_exit: TOnFocusButton; BT_load: TOnFocusButton; BT_Insert: TOnFocusButton; Bt_Down: TOnFocusButton; cbx_down: TComboBox; StringGrid1: TStringGrid; ErrorPanel: TPanel; OnShapeLabel1: TOnShapeLabel; Memo1: TMemo; BT_ErrorClose: TOnFocusButton; P_Help: TPanel; Shape1: TShape; Label1: TLabel; Label2: TLabel; OnShapeLabel2: TOnShapeLabel; Label3: TLabel; Label4: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; BT_HelpClose: TOnFocusButton; SF_Main: TOnSchemeForm; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BT_exitClick(Sender: TObject); procedure BT_DeleteClick(Sender: TObject); procedure BT_loadClick(Sender: TObject); procedure BT_InsertClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure BT_ErrorCloseClick(Sender: TObject); procedure BT_HelpCloseClick(Sender: TObject); procedure Bt_DownClick(Sender: TObject); private LastEmpno : String; { Private declarations } gsJuminMsg : String; public { Public declarations } Function CheckComCode(ComCd:String):Boolean; Function CheckDeptCode(DeptCd:String):Boolean; Function CheckJumin(No:String):Boolean; Function CheckEmpno(ComCd, sEmpno:String):Boolean; Function AutoEmpno:String; procedure StringGrid_Clear; end; var FM_Batch: TFM_Batch; implementation uses SubPmas, PZN2000A1; {$R *.DFM} Function TFM_Batch.CheckJumin(No:String):Boolean; Const Weight : Packed Array [1..12] of Integer = ( 2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 4, 5 ); Var Loop, Sum, Rest : Integer; sJuminid : String; Begin sJuminid := copy(no,1, 6) + '-' + copy(no,7, 13); with Ory_juminid do // 재직중이면서 주민가 동일하면 저장 안되게 체크 begin Close; Sql.Clear; Sql.Add('Select kname '); Sql.Add(' From PZSUBMAS '); Sql.Add(' Where juminid = ''' + sJuminid + ''' '); Sql.Add(' And (Trim(Retdate) is null or trim(Retdate) = ''--'') '); Open; end; if Ory_juminid.RecordCount >= 1 then begin Result := False; gsJuminMsg := '중복된 주민번호 입력'+#13#10; end else If Length(No) <> 13 then begin Result:= False; gsJuminMsg := '자릿수가 틀린 주민번호 입력.'; end else begin Try Sum := 0; For Loop:= 1 to 12 do Sum:= Sum + StrToInt(No[Loop])*Weight[Loop]; Rest := 11-(Sum Mod 11); If Rest = 11 then Rest := 1; If Rest = 10 then Rest := 0; Result := Char(Rest+48) = No[13]; gsJuminMsg := '잘못된 주민번호 입력'; Except Result:= False; gsJuminMsg := '잘못된 주민번호 입력 Error'; End; end; End; Function TFM_Batch.CheckComCode(ComCd:String):Boolean; Begin Result:= False; with FM_MainMenu.Ora_Qry1 do begin Close; SQL.Clear; Sql.Add(' Select COUNT(CODENO) CNT '); Sql.Add(' From PZSUBCODE '); Sql.Add(' Where USEYN = ''Y'' '); Sql.Add(' And CODEID = ''A001'' '); Sql.Add(' And CODENO = '''+ComCd+''' '); Open; if FieldByName('CNT').AsInteger > 0 then Result:= True; end; End; Function TFM_Batch.CheckDeptCode(DeptCd:String):Boolean; Begin Result:= False; with FM_MainMenu.Ora_Qry1 do begin Close; SQL.Clear; Sql.Add(' Select COUNT(Deptcode) CNT '); Sql.Add(' From PYCDept '); Sql.Add(' Where Closedate is null '); Sql.Add(' And Orgnum = (Select Value1 From Pimvari Where gubun=''00'' And sgubun=''0001'') '); Sql.Add(' And Deptcode = '''+deptCd+''' '); Open; if FieldByName('CNT').AsInteger = 1 then Result:= True else Result:= False; end; End; Function TFM_Batch.CheckEmpno(ComCd, sEmpno:String):Boolean; Begin Try with FM_MainMenu.Ora_Qry1 do begin Close; SQL.Clear; Sql.Add(' Select count(*) CNT '); Sql.Add(' From PZSUBMAS '); Sql.Add(' Where EMPNO = '''+sEmpno+''''); Open; if FieldByName('CNT').AsInteger = 1 then Result:= True else Result:= False; end; Except Result:= False; End; End; procedure TFM_Batch.StringGrid_Clear; var i : integer; begin StringGrid1.ColCount := 10; StringGrid1.RowCount := 2; StringGrid1.Cells[ 0,0] := '회사코드'; StringGrid1.Cells[ 1,0] := '사원번호'; StringGrid1.Cells[ 2,0] := '사원성명'; StringGrid1.Cells[ 3,0] := '주민번호'; StringGrid1.Cells[ 4,0] := '부서코드'; StringGrid1.Cells[ 5,0] := '입사일'; StringGrid1.Cells[ 6,0] := '핸드폰'; StringGrid1.Cells[ 7,0] := '사무실Tel'; StringGrid1.Cells[ 8,0] := 'SK-Email'; StringGrid1.Cells[ 9,0] := '담당업무'; for i := 0 to 10 do StringGrid1.Cells[i,1] := ''; end; Function TFM_Batch.AutoEmpno : String; var i, ck , ick: integer; StEmpno : String; begin if LastEmpno = '0000' then begin with FM_MainMenu.Ora_Qry1 do begin Close; SQL.Clear; Sql.Add('Select decode(substr(max(empno),2,3),''999'', '); Sql.Add(' decode(substr(max(empno),1,2),''U9'',''UA00'', '); Sql.Add(' CHR(ASCII(substr(max(empno),1,1))+1)||''00''), '); Sql.Add(' substr(max(empno),1,1)|| '); Sql.Add(' Lpad(to_char(to_number(substr(max(empno),2,3))+1),3,''0'')) MAXEMPNO'); Sql.Add(' From PZSUBMAS '); Open; StEmpno := FieldByName('MAXEMPNO').AsString; LastEmpno := StEmpno; Result := StEmpno; end; // with end end //if end else begin StEmpno := InttoStr(StrToint(Copy(LastEmpno,2,3)) + 1) ; Case Length(StEmpno) of 1 : begin LastEmpno := Copy(LastEmpno,1,1) +'00'+ StEmpno; Result := Copy(LastEmpno,1,1) +'00'+ StEmpno; end; 2 : begin LastEmpno := Copy(LastEmpno,1,1) + '0'+ StEmpno; Result := Copy(LastEmpno,1,1) + '0'+ StEmpno; end; 3 : begin LastEmpno := Copy(LastEmpno,1,1) + StEmpno; Result := Copy(LastEmpno,1,1) + StEmpno; end; 4 : begin if Copy(LastEmpno,1,1) = '9' then begin LastEmpno := 'A000'; Result := 'A000'; end else begin StEmpno := Copy(LastEmpno,1,1); LastEmpno := CHR(ORD(StEmpno[1])+1)+'000'; Result := CHR(ORD(StEmpno[1])+1)+'000'; end; end; end; end; end; procedure TFM_Batch.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := CaFree; end; procedure TFM_Batch.BT_exitClick(Sender: TObject); begin Close; end; procedure TFM_Batch.BT_loadClick(Sender: TObject); var v : Variant ; iRow, iCol : integer ; CNT, Sg_RCnt, work : integer; sEmpno, sImsiEmpno, sJobcode : String; begin P_Help.Visible := True; Work := 0; StringGrid_Clear; BT_Insert.Enabled := False; BT_Delete.Enabled := False; LastEmpno := '0000'; Case MessageDlg('일괄저장할 데이터 업로드이면 Yes를 선택하세요.', mtConfirmation, [mbYes, mbCancel], 0) of mrYes : Work := 1; else System.Exit; end; try v:= CreateOleObject('Excel.application'); except ShowMessage('Excel이 설치되어 있어야 합니다.'); Exit; end; if OpenDialog1.Execute then begin v.WorkBooks.open(OpenDialog1.FileName); end else Exit; cnt := strToint(v.ActiveSheet.UsedRange.Rows.Count); if Work = 1 then begin Memo1.Lines.Text := ''; StringGrid1.ColCount := 10; StringGrid1.RowCount := cnt; For iRow := 2 to cnt do begin For iCol := 1 to StringGrid1.ColCount - 1 do begin Case iCol of 1: begin if not CheckComcode(UpperCase(v.cells[iRow, iCol])) then Memo1.Lines.Add(inttoStr(iRow)+', '+ Trim(v.cells[iRow, 1])+', '+ Trim(v.cells[iRow, 2])+' - 동일회사코드없음'); end; 2: begin if Trim(v.cells[iRow, iCol]) = '' then Memo1.Lines.Add(inttoStr(iRow)+', '+ Trim(v.cells[iRow, 1])+', '+ Trim(v.cells[iRow, 2])+' - 사원성명없음'); end; 3: begin if not CheckJumin(Copy(Trim(v.cells[iRow, iCol]),1,6) + Copy(Trim(v.cells[iRow, iCol]),8,7) ) then Memo1.Lines.Add(inttoStr(iRow)+', '+ Trim(v.cells[iRow, 1])+', '+ Trim(v.cells[iRow, 2]) + ' - ' + gsJuminMsg ); end; 4: begin if not CheckDeptcode(UpperCase(v.cells[iRow, iCol])) then Memo1.Lines.Add(inttoStr(iRow)+', '+ Trim(v.cells[iRow, 1])+', '+ Trim(v.cells[iRow, 2])+' - 동일부서코드없음'); end; end; if Memo1.Lines.text = '' then begin if (iCol = 1) then begin StringGrid1.Cells[iCol -1, iRow -1] := Uppercase(v.cells[iRow, iCol]) ; StringGrid1.Cells[iCol, iRow -1] := AutoEmpno; //AutoEmpno(Uppercase(v.cells[iRow, iCol])); end else if (iCol = 2) or (iCol = 3) then begin StringGrid1.Cells[iCol, iRow -1] := v.cells[iRow, iCol]; end else if (iCol = 4) then begin StringGrid1.Cells[iCol, iRow -1] := Uppercase(v.cells[iRow, iCol]); end else if (iCol = 5) or (iCol = 6) or (iCol = 7) or (iCol = 8) or (iCol = 9) then begin StringGrid1.Cells[iCol , iRow -1] := v.cells[iRow, iCol] ; end; end; end; end; end else begin Memo1.Lines.Text := ''; StringGrid1.ColCount := 3; StringGrid1.RowCount := cnt; For iRow := 2 to cnt do begin sImsiEmpno := v.cells[iRow, 2]; if length(sImsiEmpno) = 1 then sEmpno := '000' + sImsiEmpno else if length(sImsiEmpno) = 2 then sEmpno := '00' + sImsiEmpno else if length(sImsiEmpno) = 3 then sEmpno := '0' + sImsiEmpno else if length(sImsiEmpno) = 4 then sEmpno := sImsiEmpno else begin ShowMessage('사번을 정확히 입력하세요.'); Exit; end; if not CheckEmpno(Uppercase(v.cells[iRow, 1]),sEmpno) then Memo1.Lines.Add(inttoStr(iRow)+','+ Trim(v.cells[iRow, 1])+','+ Trim(v.cells[iRow, 2])+','+ Trim(v.cells[iRow, 3])+'-이 사원은 없습니다.'); if Memo1.Lines.text = '' then For iCol := 1 to StringGrid1.ColCount do begin if iCol = 2 then StringGrid1.Cells[iCol -1, iRow -1] := sEmpno else StringGrid1.Cells[iCol -1, iRow -1] := UpperCase(v.cells[iRow, iCol]) ; end; end; end; v.WorkBooks.Close; v.quit ; v:=unassigned; if Memo1.Lines.Text <> '' then begin Memo1.Lines.Add('=================================='); Memo1.Lines.Add('상기 오류 내역 수정후 재작업 요망.'); Memo1.Lines.Add('=================================='); Memo1.Lines.Add('중복된 주민번호 입력 오류사원에 경우 '); //재직중이면서 주민가 동일하면 저장 안되게 체크 Memo1.Lines.Add('재직중인 동일 사원이 존재함으로 해당사원 검색후 '); Memo1.Lines.Add('해당사번으로 사용해 주시기 바랍니다. '); StringGrid_Clear; ErrorPanel.Visible := True; P_Help.Visible := True; System.Exit; end; P_helpinfo.SimpleText := ('총 ' + IntTostr(Cnt -1) + ' 건의 엑셀파일 로드가 완료 되었습니다.'); if (Cnt - 1) <> 0 then begin if work = 1 then BT_Insert.Enabled := True else BT_Delete.Enabled := True; end else begin BT_Insert.Enabled := False; BT_Delete.Enabled := False; end; P_Help.Visible := False; end; procedure TFM_Batch.BT_InsertClick(Sender: TObject); var MRow, Cnt : integer ; begin P_helpinfo.SimpleText := ''; Cnt := 0; if MessageDlg('일괄저장 작업을 진행하시겠습니까?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then begin Memo1.Lines.Text := ''; For MRow := 1 to StringGrid1.RowCount -1 do begin if CheckEmpno(StringGrid1.Cells[0, MRow], StringGrid1.Cells[1, MRow]) Then Memo1.Lines.Add(IntToStr(MRow)+','+ Trim(StringGrid1.Cells[0, MRow])+','+ Trim(StringGrid1.Cells[1, MRow])+','+ Trim(StringGrid1.Cells[2, MRow])+'-사번중복오류'); end; //Row For End if Memo1.Lines.Text <> '' then begin Memo1.Lines.Add('=================================='); Memo1.Lines.Add('상기 오류 내역 수정후 재작업 요망.'); StringGrid_Clear; ErrorPanel.Visible := True; P_Help.Visible := True; System.Exit; end; //////////////////////////////////////////////////////////////////////////// For MRow := 1 to StringGrid1.RowCount -1 do begin with FM_MainMenu.Ora_Qry1 do begin Close; Sql.Clear; Sql.Add('Insert into PZSUBMAS (COMCODE, ');//P1 Sql.Add(' EMPNO, '); Sql.Add(' KNAME, '); Sql.Add(' JUMINID, '); Sql.Add(' ORGNUM, ');//P5 Sql.Add(' DEPTCODE, '); Sql.Add(' REGDATE, ');//7 Sql.Add(' EMPDATE, '); Sql.Add(' HAndP, '); Sql.Add(' OTEL, '); Sql.Add(' SKEMAIL, '); Sql.Add(' CJOB1, '); Sql.Add(' WRITEMAN, '); Sql.Add(' WRITETIME ) '); Sql.Add(' Values (:P1, '); Sql.Add(' :P2, '); Sql.Add(' :P3, '); Sql.Add(' :P4, '); Sql.Add(' :P5, '); Sql.Add(' :P6, '); Sql.Add(' :P7, '); Sql.Add(' :P8, '); Sql.Add(' :P9, '); Sql.Add(' :P10, '); Sql.Add(' :P11, '); Sql.Add(' :P12, '); Sql.Add(' :P13, '); Sql.Add(' :P14 ) '); ParamByName('P1' ).AsString := Trim(StringGrid1.Cells[ 0, MRow]); ParamByName('P2' ).AsString := Trim(StringGrid1.Cells[ 1, MRow]); ParamByName('P3' ).AsString := Trim(StringGrid1.Cells[ 2, MRow]); ParamByName('P4' ).AsString := Trim(StringGrid1.Cells[ 3, MRow]); ParamByName('P5' ).AsString := FM_MainMenu.FG_Orgnum; ParamByName('P6' ).AsString := Trim(StringGrid1.Cells[ 4, MRow]); ParamByName('P7' ).AsString := Copy(Fn_GetDateTimeStr,1,8); ParamByName('P8' ).AsString := Trim(StringGrid1.Cells[ 5, MRow]); ParamByName('P9' ).AsString := Trim(StringGrid1.Cells[ 6, MRow]); ParamByName('P10').AsString := Trim(StringGrid1.Cells[ 7, MRow]); ParamByName('P11').AsString := Trim(StringGrid1.Cells[ 8, MRow]); ParamByName('P12').AsString := Trim(StringGrid1.Cells[ 9, MRow]); ParamByName('P13').AsString := FM_MainMenu.FG_Empno; // 작업자 ParamByName('P14').AsString := Copy(Fn_GetDateTimeStr,1,14); ExecSql; //edit1.text := sql.text; Cnt := Cnt + 1; end; end; //Row For End StringGrid1.ColCount := 3; BT_Insert.Enabled := False; BT_Delete.Enabled := True; MessageDlg('총 ' + IntTostr(Cnt) + '건의 데이터 저장완료.', mtInformation,[mbOK],0); end; end; procedure TFM_Batch.BT_DeleteClick(Sender: TObject); var MRow, Cnt : integer ; sEmpno : String; begin Cnt := 0; if MessageDlg('일괄 삭제작업을 진행하시겠습니까?', mtConfirmation, [mbYes, mbNo], 0) <> mrYes then Exit; For MRow := 1 to StringGrid1.RowCount -1 do begin if length(Trim(StringGrid1.Cells[1, MRow])) = 1 then sEmpno := '000' + Trim(StringGrid1.Cells[1, MRow]) else if length(Trim(StringGrid1.Cells[1, MRow])) = 2 then sEmpno := '00' + Trim(StringGrid1.Cells[1, MRow]) else if length(Trim(StringGrid1.Cells[1, MRow])) = 3 then sEmpno := '0' + Trim(StringGrid1.Cells[1, MRow]) else if length(Trim(StringGrid1.Cells[1, MRow])) = 4 then sEmpno := Trim(StringGrid1.Cells[1, MRow]) else begin ShowMessage('사번을 정확히 입력하세요.'); Exit; end; with FM_MainMenu.Ora_Qry1 do begin Close; Sql.Clear; Sql.Add('Select Count(*) CNT From PZSUBMAS '); Sql.Add(' Where Comcode = '''+ Uppercase(Trim(StringGrid1.Cells[0, MRow])) +''' '); Sql.Add(' And Empno = '''+ sEmpno +''' '); Open; if FieldByName('CNT').AsInteger > 0 then begin Cnt := Cnt + 1; Close; Sql.Clear; Sql.Add('Delete From PZSUBMAS '); Sql.Add(' Where Comcode = '''+ Uppercase(Trim(StringGrid1.Cells[0, MRow])) +''' '); Sql.Add(' And Empno = '''+ sEmpno +''' '); ExecSQL; end; end; end; StringGrid_Clear; BT_Insert.Enabled := False; BT_Delete.Enabled := False; MessageDlg('총 ' + IntTostr(Cnt) + '건의 데이터 삭제완료.', mtInformation,[mbOK],0); end; procedure TFM_Batch.FormShow(Sender: TObject); begin FM_Batch.Left := FM_MainMenu.Left + 45; FM_Batch.Top := FM_MainMenu.Top + 55; StringGrid_Clear; cbx_down.ItemIndex := 0; end; procedure TFM_Batch.BT_ErrorCloseClick(Sender: TObject); begin ErrorPanel.Visible := False; end; procedure TFM_Batch.BT_HelpCloseClick(Sender: TObject); begin P_Help.Visible := False; end; procedure TFM_Batch.Bt_DownClick(Sender: TObject); var XL, XArr: Variant; i,j,k: integer; SavePlace: TBookmark; begin P_helpinfo.SimpleText := 'Excel이 설치되어 있는지 검색하고 있습니다.'; XArr := VarArrayCreate([1, 9], VarVariant); try XL := CreateOLEObject('Excel.Application'); except MessageDlg('Excel이 설치되어 있지 않습니다.', MtWarning, [mbok], 0); P_helpinfo.SimpleText := ''; Exit; end; XL.WorkBooks.Add; //새로운 페이지 생성 XL.Visible := false; if cbx_down.ItemIndex = 0 then begin //컬럼명 지정_서브타이블 지정 XArr[1] := '회사코드'; XArr[2] := '사원성명'; XArr[3] := '주민번호(''-''입력)'; XArr[4] := '부서코드'; XArr[5] := '입사일(ex. 20140101)'; XArr[6] := '핸드폰'; XArr[7] := '사무실Tel'; XArr[8] := 'SKemail'; XArr[9] := '담당업무'; XL.Range['A1', 'I1'].Value := XArr; XL.Range['A1', 'I1'].Borders.LineStyle := 1; //테두리선을 만든다. 1은 실선 XL.Range['A1', 'I1'].Interior.Color:= $00CBF0B3; XL.Range['A1', 'I1'].Select; //자료를 모두 Select한 후 --하는 이유: AutoFit 처리하기 위해서임 XL.Selection.Columns.AutoFit; //자동정렬 end else begin //컬럼명 지정_서브타이블 지정 XArr[1] := '회사코드'; XArr[2] := '사원번호'; XL.Range['A1', 'B1'].Value := XArr; XL.Range['A1', 'B1'].Borders.LineStyle := 1; //테두리선을 만든다. 1은 실선 XL.Range['A1', 'B1'].Interior.Color:= $00CBF0B3; end; XL.Visible := true; //엑셀자료 보여줌 P_helpinfo.SimpleText := ''; end; end.
{*******************************************************} { } { Delphi FireDAC Framework } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} unit FireDAC.Phys.SQLiteDef; interface uses System.SysUtils, System.Classes, FireDAC.Stan.Intf; type // TFDPhysSQLiteConnectionDefParams // Generated for: FireDAC SQLite driver TFDSQLiteOpenMode = (omCreateUTF8, omCreateUTF16, omReadWrite, omReadOnly); TFDSQLiteEncrypt = (enNo, enAes_128, enAes_192, enAes_256, enAes_ctr_128, enAes_ctr_192, enAes_ctr_256, enAes_ecb_128, enAes_ecb_192, enAes_ecb_256); TFDSQLiteLockingMode = (lmNormal, lmExclusive); TFDSQLiteSynchronous = (snFull, snNormal, snOff); TFDSQLiteJournalMode = (jmDelete, jmTruncate, jmPersist, jmMemory, jmWAL, jmOff); TFDSQLiteForeignKeys = (fkOn, fkOff); TFDSQLiteStringFormat = (sfChoose, sfUnicode, sfANSI); TFDSQLiteGUIDFormat = (guiString, guiBinary); TFDSQLiteDateTimeFormat = (dtfString, dtfBinary, dtfDateTime); const C_FDSQLiteEncrypt: array[TFDSQLiteEncrypt] of String = ('No', 'aes-128', 'aes-192', 'aes-256', 'aes-ctr-128', 'aes-ctr-192', 'aes-ctr-256', 'aes-ecb-128', 'aes-ecb-192', 'aes-ecb-256'); type /// <summary> TFDPhysSQLiteConnectionDefParams class implements FireDAC SQLite driver specific connection definition class. </summary> TFDPhysSQLiteConnectionDefParams = class(TFDConnectionDefParams) private function GetDriverID: String; procedure SetDriverID(const AValue: String); function GetOpenMode: TFDSQLiteOpenMode; procedure SetOpenMode(const AValue: TFDSQLiteOpenMode); function GetEncrypt: TFDSQLiteEncrypt; procedure SetEncrypt(const AValue: TFDSQLiteEncrypt); function GetBusyTimeout: Integer; procedure SetBusyTimeout(const AValue: Integer); function GetCacheSize: Integer; procedure SetCacheSize(const AValue: Integer); function GetSharedCache: Boolean; procedure SetSharedCache(const AValue: Boolean); function GetLockingMode: TFDSQLiteLockingMode; procedure SetLockingMode(const AValue: TFDSQLiteLockingMode); function GetSynchronous: TFDSQLiteSynchronous; procedure SetSynchronous(const AValue: TFDSQLiteSynchronous); function GetJournalMode: TFDSQLiteJournalMode; procedure SetJournalMode(const AValue: TFDSQLiteJournalMode); function GetForeignKeys: TFDSQLiteForeignKeys; procedure SetForeignKeys(const AValue: TFDSQLiteForeignKeys); function GetStringFormat: TFDSQLiteStringFormat; procedure SetStringFormat(const AValue: TFDSQLiteStringFormat); function GetGUIDFormat: TFDSQLiteGUIDFormat; procedure SetGUIDFormat(const AValue: TFDSQLiteGUIDFormat); function GetDateTimeFormat: TFDSQLiteDateTimeFormat; procedure SetDateTimeFormat(const AValue: TFDSQLiteDateTimeFormat); function GetExtensions: String; procedure SetExtensions(const AValue: String); function GetSQLiteAdvanced: String; procedure SetSQLiteAdvanced(const AValue: String); function GetMetaDefCatalog: String; procedure SetMetaDefCatalog(const AValue: String); function GetMetaCurCatalog: String; procedure SetMetaCurCatalog(const AValue: String); published property DriverID: String read GetDriverID write SetDriverID stored False; property OpenMode: TFDSQLiteOpenMode read GetOpenMode write SetOpenMode stored False default omCreateUTF8; property Encrypt: TFDSQLiteEncrypt read GetEncrypt write SetEncrypt stored False default enNo; property BusyTimeout: Integer read GetBusyTimeout write SetBusyTimeout stored False default 10000; property CacheSize: Integer read GetCacheSize write SetCacheSize stored False default 10000; property SharedCache: Boolean read GetSharedCache write SetSharedCache stored False; property LockingMode: TFDSQLiteLockingMode read GetLockingMode write SetLockingMode stored False default lmExclusive; property Synchronous: TFDSQLiteSynchronous read GetSynchronous write SetSynchronous stored False default snOff; property JournalMode: TFDSQLiteJournalMode read GetJournalMode write SetJournalMode stored False default jmDelete; property ForeignKeys: TFDSQLiteForeignKeys read GetForeignKeys write SetForeignKeys stored False default fkOn; property StringFormat: TFDSQLiteStringFormat read GetStringFormat write SetStringFormat stored False default sfChoose; property GUIDFormat: TFDSQLiteGUIDFormat read GetGUIDFormat write SetGUIDFormat stored False default guiString; property DateTimeFormat: TFDSQLiteDateTimeFormat read GetDateTimeFormat write SetDateTimeFormat stored False default dtfString; property Extensions: String read GetExtensions write SetExtensions stored False; property SQLiteAdvanced: String read GetSQLiteAdvanced write SetSQLiteAdvanced stored False; property MetaDefCatalog: String read GetMetaDefCatalog write SetMetaDefCatalog stored False; property MetaCurCatalog: String read GetMetaCurCatalog write SetMetaCurCatalog stored False; end; implementation uses FireDAC.Stan.Consts; // TFDPhysSQLiteConnectionDefParams // Generated for: FireDAC SQLite driver {-------------------------------------------------------------------------------} function TFDPhysSQLiteConnectionDefParams.GetDriverID: String; begin Result := FDef.AsString[S_FD_ConnParam_Common_DriverID]; end; {-------------------------------------------------------------------------------} procedure TFDPhysSQLiteConnectionDefParams.SetDriverID(const AValue: String); begin FDef.AsString[S_FD_ConnParam_Common_DriverID] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysSQLiteConnectionDefParams.GetOpenMode: TFDSQLiteOpenMode; var s: String; begin s := FDef.AsString[S_FD_ConnParam_SQLite_OpenMode]; if CompareText(s, 'CreateUTF8') = 0 then Result := omCreateUTF8 else if CompareText(s, 'CreateUTF16') = 0 then Result := omCreateUTF16 else if CompareText(s, 'ReadWrite') = 0 then Result := omReadWrite else if CompareText(s, 'ReadOnly') = 0 then Result := omReadOnly else Result := omCreateUTF8; end; {-------------------------------------------------------------------------------} procedure TFDPhysSQLiteConnectionDefParams.SetOpenMode(const AValue: TFDSQLiteOpenMode); const C_OpenMode: array[TFDSQLiteOpenMode] of String = ('CreateUTF8', 'CreateUTF16', 'ReadWrite', 'ReadOnly'); begin FDef.AsString[S_FD_ConnParam_SQLite_OpenMode] := C_OpenMode[AValue]; end; {-------------------------------------------------------------------------------} function TFDPhysSQLiteConnectionDefParams.GetEncrypt: TFDSQLiteEncrypt; var s: String; begin s := FDef.AsString[S_FD_ConnParam_SQLite_Encrypt]; if CompareText(s, 'No') = 0 then Result := enNo else if CompareText(s, 'aes-128') = 0 then Result := enAes_128 else if CompareText(s, 'aes-192') = 0 then Result := enAes_192 else if CompareText(s, 'aes-256') = 0 then Result := enAes_256 else if CompareText(s, 'aes-ctr-128') = 0 then Result := enAes_ctr_128 else if CompareText(s, 'aes-ctr-192') = 0 then Result := enAes_ctr_192 else if CompareText(s, 'aes-ctr-256') = 0 then Result := enAes_ctr_256 else if CompareText(s, 'aes-ecb-128') = 0 then Result := enAes_ecb_128 else if CompareText(s, 'aes-ecb-192') = 0 then Result := enAes_ecb_192 else if CompareText(s, 'aes-ecb-256') = 0 then Result := enAes_ecb_256 else Result := enNo; end; {-------------------------------------------------------------------------------} procedure TFDPhysSQLiteConnectionDefParams.SetEncrypt(const AValue: TFDSQLiteEncrypt); begin FDef.AsString[S_FD_ConnParam_SQLite_Encrypt] := C_FDSQLiteEncrypt[AValue]; end; {-------------------------------------------------------------------------------} function TFDPhysSQLiteConnectionDefParams.GetBusyTimeout: Integer; begin if not FDef.HasValue(S_FD_ConnParam_SQLite_BusyTimeout) then Result := 10000 else Result := FDef.AsInteger[S_FD_ConnParam_SQLite_BusyTimeout]; end; {-------------------------------------------------------------------------------} procedure TFDPhysSQLiteConnectionDefParams.SetBusyTimeout(const AValue: Integer); begin FDef.AsInteger[S_FD_ConnParam_SQLite_BusyTimeout] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysSQLiteConnectionDefParams.GetCacheSize: Integer; begin if not FDef.HasValue(S_FD_ConnParam_SQLite_CacheSize) then Result := 10000 else Result := FDef.AsInteger[S_FD_ConnParam_SQLite_CacheSize]; end; {-------------------------------------------------------------------------------} procedure TFDPhysSQLiteConnectionDefParams.SetCacheSize(const AValue: Integer); begin FDef.AsInteger[S_FD_ConnParam_SQLite_CacheSize] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysSQLiteConnectionDefParams.GetSharedCache: Boolean; begin if not FDef.HasValue(S_FD_ConnParam_SQLite_SharedCache) then Result := True else Result := FDef.AsBoolean[S_FD_ConnParam_SQLite_SharedCache]; end; {-------------------------------------------------------------------------------} procedure TFDPhysSQLiteConnectionDefParams.SetSharedCache(const AValue: Boolean); begin FDef.AsBoolean[S_FD_ConnParam_SQLite_SharedCache] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysSQLiteConnectionDefParams.GetLockingMode: TFDSQLiteLockingMode; var s: String; begin s := FDef.AsString[S_FD_ConnParam_SQLite_LockingMode]; if CompareText(s, 'Normal') = 0 then Result := lmNormal else if CompareText(s, 'Exclusive') = 0 then Result := lmExclusive else Result := lmExclusive; end; {-------------------------------------------------------------------------------} procedure TFDPhysSQLiteConnectionDefParams.SetLockingMode(const AValue: TFDSQLiteLockingMode); const C_LockingMode: array[TFDSQLiteLockingMode] of String = ('Normal', 'Exclusive'); begin FDef.AsString[S_FD_ConnParam_SQLite_LockingMode] := C_LockingMode[AValue]; end; {-------------------------------------------------------------------------------} function TFDPhysSQLiteConnectionDefParams.GetSynchronous: TFDSQLiteSynchronous; var s: String; begin s := FDef.AsString[S_FD_ConnParam_SQLite_Synchronous]; if CompareText(s, 'Full') = 0 then Result := snFull else if CompareText(s, 'Normal') = 0 then Result := snNormal else if CompareText(s, 'Off') = 0 then Result := snOff else Result := snOff; end; {-------------------------------------------------------------------------------} procedure TFDPhysSQLiteConnectionDefParams.SetSynchronous(const AValue: TFDSQLiteSynchronous); const C_Synchronous: array[TFDSQLiteSynchronous] of String = ('Full', 'Normal', 'Off'); begin FDef.AsString[S_FD_ConnParam_SQLite_Synchronous] := C_Synchronous[AValue]; end; {-------------------------------------------------------------------------------} function TFDPhysSQLiteConnectionDefParams.GetJournalMode: TFDSQLiteJournalMode; var s: String; begin s := FDef.AsString[S_FD_ConnParam_SQLite_JournalMode]; if CompareText(s, 'Delete') = 0 then Result := jmDelete else if CompareText(s, 'Truncate') = 0 then Result := jmTruncate else if CompareText(s, 'Persist') = 0 then Result := jmPersist else if CompareText(s, 'Memory') = 0 then Result := jmMemory else if CompareText(s, 'WAL') = 0 then Result := jmWAL else if CompareText(s, 'Off') = 0 then Result := jmOff else Result := jmDelete; end; {-------------------------------------------------------------------------------} procedure TFDPhysSQLiteConnectionDefParams.SetJournalMode(const AValue: TFDSQLiteJournalMode); const C_JournalMode: array[TFDSQLiteJournalMode] of String = ('Delete', 'Truncate', 'Persist', 'Memory', 'WAL', 'Off'); begin FDef.AsString[S_FD_ConnParam_SQLite_JournalMode] := C_JournalMode[AValue]; end; {-------------------------------------------------------------------------------} function TFDPhysSQLiteConnectionDefParams.GetForeignKeys: TFDSQLiteForeignKeys; var s: String; begin s := FDef.AsString[S_FD_ConnParam_SQLite_ForeignKeys]; if CompareText(s, 'On') = 0 then Result := fkOn else if CompareText(s, 'Off') = 0 then Result := fkOff else Result := fkOn; end; {-------------------------------------------------------------------------------} procedure TFDPhysSQLiteConnectionDefParams.SetForeignKeys(const AValue: TFDSQLiteForeignKeys); const C_ForeignKeys: array[TFDSQLiteForeignKeys] of String = ('On', 'Off'); begin FDef.AsString[S_FD_ConnParam_SQLite_ForeignKeys] := C_ForeignKeys[AValue]; end; {-------------------------------------------------------------------------------} function TFDPhysSQLiteConnectionDefParams.GetStringFormat: TFDSQLiteStringFormat; var s: String; begin s := FDef.AsString[S_FD_ConnParam_SQLite_StringFormat]; if CompareText(s, 'Choose') = 0 then Result := sfChoose else if CompareText(s, 'Unicode') = 0 then Result := sfUnicode else if CompareText(s, 'ANSI') = 0 then Result := sfANSI else Result := sfChoose; end; {-------------------------------------------------------------------------------} procedure TFDPhysSQLiteConnectionDefParams.SetStringFormat(const AValue: TFDSQLiteStringFormat); const C_StringFormat: array[TFDSQLiteStringFormat] of String = ('Choose', 'Unicode', 'ANSI'); begin FDef.AsString[S_FD_ConnParam_SQLite_StringFormat] := C_StringFormat[AValue]; end; {-------------------------------------------------------------------------------} function TFDPhysSQLiteConnectionDefParams.GetGUIDFormat: TFDSQLiteGUIDFormat; var s: String; begin s := FDef.AsString[S_FD_ConnParam_SQLite_GUIDFormat]; if CompareText(s, 'String') = 0 then Result := guiString else if CompareText(s, 'Binary') = 0 then Result := guiBinary else Result := guiString; end; {-------------------------------------------------------------------------------} procedure TFDPhysSQLiteConnectionDefParams.SetGUIDFormat(const AValue: TFDSQLiteGUIDFormat); const C_GUIDFormat: array[TFDSQLiteGUIDFormat] of String = ('String', 'Binary'); begin FDef.AsString[S_FD_ConnParam_SQLite_GUIDFormat] := C_GUIDFormat[AValue]; end; {-------------------------------------------------------------------------------} function TFDPhysSQLiteConnectionDefParams.GetDateTimeFormat: TFDSQLiteDateTimeFormat; var s: String; begin s := FDef.AsString[S_FD_ConnParam_SQLite_DateTimeFormat]; if CompareText(s, 'String') = 0 then Result := dtfString else if CompareText(s, 'Binary') = 0 then Result := dtfBinary else if CompareText(s, 'DateTime') = 0 then Result := dtfDateTime else Result := dtfString; end; {-------------------------------------------------------------------------------} procedure TFDPhysSQLiteConnectionDefParams.SetDateTimeFormat(const AValue: TFDSQLiteDateTimeFormat); const C_DateTimeFormat: array[TFDSQLiteDateTimeFormat] of String = ('String', 'Binary', 'DateTime'); begin FDef.AsString[S_FD_ConnParam_SQLite_DateTimeFormat] := C_DateTimeFormat[AValue]; end; {-------------------------------------------------------------------------------} function TFDPhysSQLiteConnectionDefParams.GetExtensions: String; begin Result := FDef.AsString[S_FD_ConnParam_SQLite_Extensions]; end; {-------------------------------------------------------------------------------} procedure TFDPhysSQLiteConnectionDefParams.SetExtensions(const AValue: String); begin FDef.AsString[S_FD_ConnParam_SQLite_Extensions] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysSQLiteConnectionDefParams.GetSQLiteAdvanced: String; begin Result := FDef.AsString[S_FD_ConnParam_SQLite_SQLiteAdvanced]; end; {-------------------------------------------------------------------------------} procedure TFDPhysSQLiteConnectionDefParams.SetSQLiteAdvanced(const AValue: String); begin FDef.AsString[S_FD_ConnParam_SQLite_SQLiteAdvanced] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysSQLiteConnectionDefParams.GetMetaDefCatalog: String; begin Result := FDef.AsString[S_FD_ConnParam_Common_MetaDefCatalog]; end; {-------------------------------------------------------------------------------} procedure TFDPhysSQLiteConnectionDefParams.SetMetaDefCatalog(const AValue: String); begin FDef.AsString[S_FD_ConnParam_Common_MetaDefCatalog] := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysSQLiteConnectionDefParams.GetMetaCurCatalog: String; begin Result := FDef.AsString[S_FD_ConnParam_Common_MetaCurCatalog]; end; {-------------------------------------------------------------------------------} procedure TFDPhysSQLiteConnectionDefParams.SetMetaCurCatalog(const AValue: String); begin FDef.AsString[S_FD_ConnParam_Common_MetaCurCatalog] := AValue; end; end.
unit ncgFrmFST; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ncgFormBase, cxPCdxBarPopupMenu, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxPC, ExtCtrls; type TFrmFST = class(TFormBaseGuard) Paginas: TcxPageControl; TimerOnTop: TTimer; procedure FormCreate(Sender: TObject); procedure TimerOnTopTimer(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormHide(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure PaginasChange(Sender: TObject); procedure PaginasPageChanging(Sender: TObject; NewPage: TcxTabSheet; var AllowChange: Boolean); procedure FormResize(Sender: TObject); private TicksVisible : Cardinal; function GetForm: TFormBaseGuard; procedure SetForm(const Value: TFormBaseGuard); function GetFormIndex(aForm: TFormBaseGuard): Integer; { Private declarations } protected procedure ForceTop(F: TFormBaseGuard); virtual; public function AddForm(aForm: TFormBaseGuard; aWinControl: TWinControl): Integer; { Public declarations } property ActiveForm: TFormBaseGuard read GetForm write SetForm; end; var FrmFST: TFrmFST; implementation uses ncgFrmPri, ncgPrevLogoff; {$R *.dfm} { TFrmFST } function TFrmFST.AddForm(aForm: TFormBaseGuard; aWinControl: TWinControl): Integer; var I: Integer; T: TcxTabSheet; begin Result := GetFormIndex(aForm); if Result>=0 then Exit; T := TcxTabSheet.Create(Self); T.PageControl := Paginas; T.Tag := Integer(aForm); aWinControl.Parent := T; end; procedure TFrmFST.ForceTop(F: TFormBaseGuard); var H : HWND; begin if FrmPri.StayOnTopOFF or ((F<>nil) and F.DontForceForeground and Application.Active) then Exit; ForceForegroundWindow(Handle, 'TFrmFST.ForceTop: '+Name); SetWindowPos(Handle, HWND_TOPMOST, 0, 0, 0, 0, (SWP_NOACTIVATE or SWP_NOMOVE or SWP_NOSIZE)); H := GetForeGroundWindow; ShowWindow(Handle, SW_SHOW); if (H <> Handle) and (H <> FindWindow('Shell_TrayWnd', nil)) and ((GetTickCount-TicksVisible)<6000) then begin keybd_event(VK_LWIN, Mapvirtualkey(VK_LWIN, 0), 0, 0); keybd_event(VK_LWIN, Mapvirtualkey(VK_LWIN, 0), KEYEVENTF_KEYUP, 0); keybd_event(VK_CONTROL, Mapvirtualkey(VK_CONTROL, 0), 0, 0); keybd_event(VK_ESCAPE, Mapvirtualkey(VK_ESCAPE, 0), 0, 0); keybd_event(VK_ESCAPE, Mapvirtualkey(VK_ESCAPE, 0), KEYEVENTF_KEYUP, 0); keybd_event(VK_CONTROL, Mapvirtualkey(VK_CONTROL, 0), KEYEVENTF_KEYUP, 0); SetForegroundWindow(Handle); end; end; procedure TFrmFST.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin inherited; CanClose := False; PrevLogoff; end; procedure TFrmFST.FormCreate(Sender: TObject); begin inherited; BorderStyle := bsNone; TicksVisible := 0; Left := 0; Top := 0; Width := Screen.Width; Height := Screen.Height; end; procedure TFrmFST.FormHide(Sender: TObject); begin inherited; TimerOnTop.Enabled := False; if (ActiveForm<>nil) and Assigned(ActiveForm.OnHide) then ActiveForm.OnHide(nil); end; procedure TFrmFST.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if (ActiveForm<>nil) and Assigned(ActiveForm.OnKeyDown) then ActiveForm.OnKeyDown(nil, Key, Shift); end; procedure TFrmFST.FormResize(Sender: TObject); begin inherited; if Visible and (ActiveForm<>nil) and Assigned(ActiveForm.OnResize) then ActiveForm.OnResize(nil); end; procedure TFrmFST.FormShow(Sender: TObject); begin inherited; TimerOnTop.Enabled := True; TicksVisible := GetTickCount; if (ActiveForm<>nil) and Assigned(ActiveForm.OnShow) then ActiveForm.OnShow(nil); end; function TFrmFST.GetForm: TFormBaseGuard; begin Result := TFormBaseGuard(Paginas.ActivePage.Tag); end; function TFrmFST.GetFormIndex(aForm: TFormBaseGuard): Integer; begin for Result := 0 to Paginas.PageCount-1 do if TFormBaseGuard(Paginas.Pages[Result].Tag)=aForm then Exit; Result := -1; end; procedure TFrmFST.PaginasChange(Sender: TObject); begin inherited; if Visible and (ActiveForm<>nil) and Assigned(ActiveForm.OnShow) then ActiveForm.OnShow(nil); end; procedure TFrmFST.PaginasPageChanging(Sender: TObject; NewPage: TcxTabSheet; var AllowChange: Boolean); begin inherited; AllowChange := True; if Visible and (ActiveForm<>nil) and Assigned(ActiveForm.OnHide) then ActiveForm.OnHide(nil); end; procedure TFrmFST.SetForm(const Value: TFormBaseGuard); var I : Integer; begin I := GetFormIndex(Value); Paginas.ActivePageIndex := I; end; procedure TFrmFST.TimerOnTopTimer(Sender: TObject); var H: HWND; F: TFormBaseGuard; begin inherited; if not Visible then Exit; Left := 0; Top := 0; Width := Screen.Width; Height := Screen.Height; F := ActiveForm; try if F<>nil then F.OnTimerTop; except end; if Visible and (F=ActiveForm) then ForceTop(F); end; end.
unit UDbGrid; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, JvBackgrounds, Grids, DBGrids, JvExDBGrids, JvDBGrid, JvDBUltimGrid, Menus, JvMenus, DB, ZAbstractRODataset, ZAbstractDataset, ZDataset, ZConnection , Clipbrd,USelCol,UnitExcepciones; type TicDbGrid=class private sfCadenaFiltro:String; OfdbGrid:TdbGrid; OfdbUGrid:TjvdbUltimGrid; ifGridColumn:Integer; pt: TGridcoord; // IcPopUp:TnotifyEvent; pop:TpopupMenu; OrigPop:TpopupMenu; procedure IcPopUp(Sender: TObject); // Procedimientos de copiado de registros para cualquier tipo de dbGrid Procedure dbGridCopy(grid: TDBGrid);Overload; Procedure dbGridCopy(grid: TJvDBUltimGrid);Overload; //Procedimientos de Inicializacion de PopUpMenu para cualquier tipo de DbGrid Procedure DBGridPopUp(grid: TDBGrid);overload; Procedure DBGridPopUp(grid: TJvDBUltimGrid);overload; //Procedimientos Para Filtrar los DbGrids Procedure DBGridFiltro(grid: TDBGrid;sender:Tobject);overload; Procedure DBGridFiltro(grid: TJvDBUltimGrid;sender:Tobject);overload; //Procedimientos para extraer informacion de dbgrid's Procedure DbGridValue(grid: TDBGrid;Lista:Tstringlist);Overload; Procedure DbGridValue(grid: TJvDBUltimGrid;Lista:Tstringlist);Overload; //procedure extraer datos del titulo en distintos grids Procedure DbGridTitle(grid: TDBGrid;Column: TColumn);Overload; Procedure DbGridTitle(grid: TJvDBUltimGrid;Column: TColumn);Overload; //Funciones para extraer Coordenadas de los grids Function DbGridCoord(grid: TDBGrid;x,y:Integer):Integer;Overload; Function DbGridCoord(grid: TJvDBUltimGrid;x,y:Integer):Integer;Overload; // Pegar Registros desde clipboard a grids procedure DbGridPasteFromClip(grid: TDBGrid);overload; procedure DbGridPasteFromClip(grid: TJvDBUltimGrid);overload; public procedure AddRowsFromClip; procedure CopyRowsToClip; procedure AddData(aDataset: TDataset; Lista:Tstrings);overload; procedure AddData(aDataset: TDataset; Lista:Tstrings;Orden:TstringList);overload; Function DbGridMouseMoveCoord(x,y:Integer):Integer; Procedure DbGridTitleClick(Column: TColumn); Procedure DbGridGetValue(Lista:Tstringlist); Procedure DbGridFiltrarClick(Sender:Tobject); Constructor create(Grid: TdbGrid);Overload; Constructor create(Grid: TjvdbUltimGrid);Overload; Procedure DbGridMouseUp(Sender: TObject;Button: TMouseButton; Shift: TShiftState; X, Y: Integer); property GridColumn:Integer Read ifGridColumn; end; function NumItems(const cadena:string;const separador:char):integer; function TraerItem(const cadena:string;const separador:char;const posicion:integer):string; type TStringListSortCompare = function(List: TStringList; Index1, Index2: Integer): Integer; implementation Procedure TicDbGrid.dbGridCopy(grid: TDBGrid); var col: Integer; sline: String; bm: TBookmark; List: TStrings; begin if Assigned(Grid.Datasource) and Assigned(Grid.Datasource.Dataset) then begin Clipboard.Clear; with Grid, Grid.DataSource.DataSet do begin DisableControls; try bm := GetBookmark; try First; List := TStringList.Create; sline := ''; if FieldList.Count=FieldDefList.Count then begin for col := 0 to FieldCount-1 do if col =FieldCount-1 then sline := sline + Fielddeflist.FieldDefs[col].Name else sline := sline + Fielddeflist.FieldDefs[col].Name + #9; end else begin for col := 0 to FieldList.Count-1 do if col=FieldList.Count-1 then sline := sline + FieldList.Fields[col].FieldName else sline := sline + FieldList.Fields[col].FieldName + #9; end; List.Add(sline); try while not EOF do begin if SelectedRows.CurrentRowSelected = true then begin sline := ''; for col := 0 to FieldCount-1 do if col=FieldCount-1 then sline := sline + Fields[col].AsString else sline := sline + Fields[col].AsString + #9; List.Add(sline); end; Next; end; Clipboard.AsText := List.Text; finally FreeAndNil(List); end; if BookmarkValid(bm) then GotoBookmark(bm); finally FreeBookmark(bm); end; finally EnableControls; end; end; end; end; Procedure TicDbGrid.dbGridCopy(grid: TJvDBUltimGrid); var xcol: Integer; sline: String; bm: TBookmark; List: TStrings; begin if Assigned(Grid.Datasource) and Assigned(Grid.Datasource.Dataset) then begin Clipboard.Clear; with Grid, Grid.DataSource.DataSet do begin DisableControls; try bm := GetBookmark; try First; List := TStringList.Create; sline := ''; if FieldList.Count=FieldDefList.Count then begin for xcol := 0 to FieldCount-1 do if xcol =FieldCount-1 then sline := sline + Fielddeflist.FieldDefs[xcol].Name else sline := sline + Fielddeflist.FieldDefs[xcol].Name + #9; end else begin for xcol := 0 to FieldList.Count-1 do if xcol=FieldList.Count-1 then sline := sline + FieldList.Fields[xcol].FieldName else sline := sline + FieldList.Fields[xcol].FieldName + #9; end; List.Add(sline); try while not EOF do begin if SelectedRows.CurrentRowSelected = true then begin sline := ''; for xcol := 0 to FieldCount-1 do if xcol=FieldCount-1 then sline := sline + Fields[xcol].AsString else sline := sline + Fields[xcol].AsString + #9; List.Add(sline); end; Next; end; Clipboard.AsText := List.Text; finally FreeAndNil(List); end; if BookmarkValid(bm) then GotoBookmark(bm); finally FreeBookmark(bm); end; finally EnableControls; end; end; end; end; Procedure TicDbGrid.DBGridPopUp(grid: TDBGrid); var Item: TMenuItem; Lista:TstringList; i:Integer; begin with Grid,Grid.DataSource.DataSet do begin Lista:=tstringList.Create; try //lobo if ifGridColumn > 0 then begin if not FieldList.FieldByName(columns[ifGridColumn-1].FieldName).Calculated then begin Item := TMenuItem.Create(Nil); Item.Caption := '< TODOS >'; Item.Hint := '.'; Item.OnClick :=DbGridFiltrarClick; Pop.Items.Add(Item); DbGridGetValue(Lista); Lista.BeginUpdate; for i := 0 to Lista.Count - 1 do begin Item := TMenuItem.Create(Nil); Item.Caption := Copy(lista[i],1,50); Item.Hint := lista[i]; Item.OnClick :=DbGridFiltrarClick; Pop.Items.Insert(Pop.Items.Count,Item); end; lista.EndUpdate; end else SendMessage(Pop.WindowHandle, WM_CANCELMODE, 0, 0 ); end else SendMessage(Pop.WindowHandle, WM_CANCELMODE, 0, 0 ); finally freeandnil(Lista); end; end; end; Procedure TicDbGrid.DBGridPopUp(grid: TJvDBUltimGrid); var Item: TMenuItem; Lista:TstringList; i:Integer; begin with Grid do begin Lista:=tstringList.Create; try if ifGridColumn > 0 then begin Item := TMenuItem.Create(Nil); Item.Caption := '< TODOS >'; Item.Hint := '.'; Item.OnClick :=DbGridFiltrarClick; Pop.Items.Add(Item); DbGridGetValue(Lista); Lista.BeginUpdate; for i := 0 to Lista.Count - 1 do begin Item := TMenuItem.Create(Nil); Item.Caption := Copy(lista[i],1,50); Item.Hint := lista[i]; Item.OnClick :=DbGridFiltrarClick; Pop.Items.Insert(Pop.Items.Count,Item); end; lista.EndUpdate; end else SendMessage(Pop.WindowHandle, WM_CANCELMODE, 0, 0 ); finally freeandnil(Lista); end; end; end; procedure TicDbGrid.DbGridMouseUp(Sender: TObject;Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var mPos: TPoint; begin if Button=mbRight then begin GetCursorPos(mPos); if (pt.Y=0) then begin pop.Popup(mpos.X,mpos.y); end else if OrigPop<>nil then OrigPop.Popup(mpos.X,mpos.y); end; end; procedure TicDbGrid.IcPopUp(Sender: TObject); begin Pop.Items.Clear; if OfdbGrid<>nil then DBGridPopUp(OfdbGrid); if OfdbUGrid<>nil then DBGridPopUp(OfdbUGrid); end; Procedure TicDbGrid.DBGridFiltro(grid: TDBGrid;sender:Tobject); {$J+} const PreviousFilter : integer = -1; {$J-} var aux:string; begin if Assigned(Grid.Datasource) and Assigned(Grid.Datasource.Dataset) then begin with Grid, Grid.DataSource.DataSet do begin try Columns[PreviousFilter].Title.Font.Color := clBlack; except end; Columns[ifGridColumn - 1].Title.Font.Color := clBlue; PreviousFilter := ifGridColumn - 1; Filtered := False; if TMenuItem(Sender).Hint = '.' then begin Columns[ifGridColumn - 1].Title.Font.Color := clBlack; PreviousFilter := -1; sfCadenaFiltro:=''; end else begin try aux:=formatdatetime('yyyy-mm-dd',strtodate(TMenuItem(Sender).Hint)); except aux:=TMenuItem(Sender).Hint; end; if sfCadenaFiltro='' then sfCadenaFiltro:=Columns[ifGridColumn - 1].FieldName + ' = ' + QuotedStr(aux) else sfCadenaFiltro:=sfCadenaFiltro + ' and ' +Columns[ifGridColumn - 1].FieldName + ' = ' + QuotedStr(aux); Filter := sfCadenaFiltro; Filtered := True; end; end; end; end; Procedure TicDbGrid.DBGridFiltro(grid: TJvDBUltimGrid;sender:Tobject); {$J+} const PreviousFilter : integer = -1; {$J-} var aux:string; begin if Assigned(Grid.Datasource) and Assigned(Grid.Datasource.Dataset) then begin with Grid, Grid.DataSource.DataSet do begin try Columns[PreviousFilter].Title.Font.Color := clBlack; except end; Columns[ifGridColumn - 1].Title.Font.Color := clBlue; PreviousFilter := ifGridColumn - 1; Filtered := False; if TMenuItem(Sender).Hint = '.' then begin Columns[ifGridColumn - 1].Title.Font.Color := clBlack; PreviousFilter := -1; sfCadenaFiltro:=''; end else begin try aux:=formatdatetime('yyyy-mm-dd',strtodate(TMenuItem(Sender).Caption)); except aux:=TMenuItem(Sender).Caption; end; if sfCadenaFiltro='' then sfCadenaFiltro:=Columns[ifGridColumn - 1].FieldName + ' = ' + QuotedStr(aux) else sfCadenaFiltro:=sfCadenaFiltro + ' and ' +Columns[ifGridColumn - 1].FieldName + ' = ' + QuotedStr(aux); Filter := sfCadenaFiltro; Filtered := True; end; end; end; end; Procedure TicDbGrid.DbGridFiltrarClick(Sender:Tobject); begin if Sender is TMenuItem then begin if OfdbGrid<>nil then DBGridFiltro(OfdbGrid,sender); if OfdbUGrid<>nil then DBGridFiltro(OfdbUGrid,sender); end; end; Constructor TicDbGrid.create(Grid: TdbGrid); begin OfdbGrid:=Grid; sfCadenaFiltro:=''; ifGridColumn:=-1; end; Constructor TicDbGrid.create(Grid: TjvdbUltimGrid); begin OfdbUGrid:=Grid; sfCadenaFiltro:=''; ifGridColumn:=-1; Pop:=TpopUpMenu.Create(nil); //pop.AutoHotkeys:=maManual; pop.OnPopup:=IcPopUp; if OfdbUGrid.PopupMenu<>nil then OrigPop:=OfdbUGrid.PopupMenu; OfdbUGrid.PopupMenu:=nil; OfdbUGrid.Options:=OfdbUGrid.Options+[dgmultiselect,dgindicator]; OfdbUGrid.Options:=OfdbUGrid.Options-[dgrowselect]; end; function CompareNumbers(List: TStringList; Index1, Index2: Integer): Integer; var N1, N2: Integer; F1,F2:double; begin if (TryStrToInt(List[Index1], N1) and TryStrToInt(List[Index2], N2)) then if N1 < N2 then Result := -1 else if N1 = N2 then Result := 0 else Result := 1 else if (TryStrTofloat(List[Index1], F1) and TryStrTofloat(List[Index2], F2))then if F1 < F2 then Result := -1 else if F1 = F2 then Result := 0 else Result := 1 else raise Exception.Create('La lista contiene valores incorrectos'); end; Procedure TicDbGrid.DbGridValue(grid: TDBGrid;Lista:Tstringlist); var bm:TbookMark; i:Integer; AuxLista:TstringList; begin if Assigned(Grid.Datasource) and Assigned(Grid.Datasource.Dataset) then begin with Grid, Grid.DataSource.DataSet do begin columns.BeginUpdate; DisableControls; bm := GetBookmark; first; while not eof do begin lista.Add(columns[ifGridColumn-1].Field.AsString); next; end; if not FieldList.FieldByName(columns[ifGridColumn-1].FieldName).Calculated then if (FieldDefList.FieldByName(columns[ifGridColumn-1].FieldName).DataType=ftInteger) or(FieldDefList.FieldByName(columns[ifGridColumn-1].FieldName).DataType=ftfloat) then begin lista.Sorted:=false; AuxLista:=TstringList.Create; try AuxLista.AddStrings(Lista); AuxLista.CustomSort(CompareNumbers); lista.Clear; lista.AddStrings(AuxLista); finally AuxLista.Free end; end; try try if BookmarkValid(bm) then GotoBookmark(bm); finally FreeBookmark(bm); end; finally EnableControls; columns.EndUpdate; end; end; end; end; Procedure TicDbGrid.DbGridValue(grid: TJvDBUltimGrid;Lista:Tstringlist); var bm:TbookMark; AuxLista:TstringList; begin if Assigned(Grid.Datasource) and Assigned(Grid.Datasource.Dataset) then begin with Grid, Grid.DataSource.DataSet do begin beginUpdate; DisableControls; bm := GetBookmark; first; while not eof do begin lista.Add(columns[ifGridColumn-1].Field.AsString); next; end; if (FieldDefList.FieldByName(columns[ifGridColumn-1].FieldName).DataType=ftInteger) or(FieldDefList.FieldByName(columns[ifGridColumn-1].FieldName).DataType=ftfloat) then begin lista.Sorted:=false; AuxLista:=TstringList.Create; try AuxLista.AddStrings(Lista); AuxLista.CustomSort(CompareNumbers); lista.Clear; lista.AddStrings(AuxLista); finally AuxLista.Free end; end; try try if BookmarkValid(bm) then GotoBookmark(bm); finally FreeBookmark(bm); end; finally EnableControls; EndUpdate; end; end; end; end; Procedure TicDbGrid.DbGridGetValue(Lista:Tstringlist); begin lista.clear; lista.Sorted:=true; if OfdbGrid<>nil then DbGridValue(OfdbGrid,Lista); if OfdbUGrid<>nil then DbGridValue(OfdbUGrid,Lista); end; Procedure TicDbGrid.DbGridTitle(grid: TDBGrid;Column: TColumn); {$J+} const PreviousColumnIndex : integer = -1; {$J-} begin with Grid do begin if DataSource.DataSet is TZReadOnlyQuery then with TZReadOnlyQuery(DataSource.DataSet) do begin try Columns[PreviousColumnIndex].title.Font.Style :=Columns[PreviousColumnIndex].title.Font.Style - [fsBold]; except end; Column.title.Font.Style := Column.title.Font.Style + [fsBold]; PreviousColumnIndex := Column.Index; if SortedFields = Columns.Items[Column.Index].Field.DisplayName then if SortType = stDescending then SortType := stAscending else SortType := stDescending else begin SortedFields := Columns.Items[Column.Index].Field.DisplayName; SortType := stAscending; end; First; end; if DataSource.DataSet is TZQuery then with TZQuery(DataSource.DataSet) do begin try Columns[PreviousColumnIndex].title.Font.Style :=Columns[PreviousColumnIndex].title.Font.Style - [fsBold]; except end; Column.title.Font.Style := Column.title.Font.Style + [fsBold]; PreviousColumnIndex := Column.Index; if SortedFields = Columns.Items[Column.Index].Field.DisplayName then if SortType = stDescending then SortType := stAscending else SortType := stDescending else begin SortedFields := Columns.Items[Column.Index].Field.DisplayName; SortType := stAscending; end; First; end; end; end; Procedure TicDbGrid.DbGridTitle(grid: TJvDBUltimGrid;Column: TColumn); {$J+} const PreviousColumnIndex : integer = -1; {$J-} begin with Grid do begin if DataSource.DataSet is TZReadOnlyQuery then with TZReadOnlyQuery(DataSource.DataSet) do begin try Columns[PreviousColumnIndex].title.Font.Style :=Columns[PreviousColumnIndex].title.Font.Style - [fsBold]; except end; Column.title.Font.Style := Column.title.Font.Style + [fsBold]; PreviousColumnIndex := Column.Index; if SortedFields = Columns.Items[Column.Index].Field.DisplayName then if SortType = stDescending then SortType := stAscending else SortType := stDescending else begin SortedFields := Columns.Items[Column.Index].Field.DisplayName; SortType := stAscending; end; First; end; if DataSource.DataSet is TZQuery then with TZQuery(DataSource.DataSet) do begin try Columns[PreviousColumnIndex].title.Font.Style :=Columns[PreviousColumnIndex].title.Font.Style - [fsBold]; except end; Column.title.Font.Style := Column.title.Font.Style + [fsBold]; PreviousColumnIndex := Column.Index; if SortedFields = Columns.Items[Column.Index].Field.DisplayName then if SortType = stDescending then SortType := stAscending else SortType := stDescending else begin SortedFields := Columns.Items[Column.Index].Field.DisplayName; SortType := stAscending; end; First; end; end; end; Procedure TicDbGrid.DbGridTitleClick(Column: TColumn); begin if OfdbGrid<>nil then DbGridTitle(OfdbGrid,Column); if OfdbUGrid<>nil then DbGridTitle(OfdbUGrid,Column); end; Function TicDbGrid.DbGridCoord(grid: TDBGrid;x,y:Integer):Integer; var Res:Integer; loquesea:TComponent; begin res:=-1; with Grid do begin pt:= MouseCoord(x, y); if pt.y = 0 then begin Cursor := crHandPoint; Pop:=TpopUpMenu.Create(nil); pop.AutoHotkeys:=maManual; pop.Name:='popUp_GayPatricio'; pop.OnPopup:=IcPopUp; if OfdbGrid.PopupMenu<>nil then begin OrigPop:=OfdbGrid.PopupMenu; OfdbGrid.PopupMenu.AutoPopUp := False; end; //OfdbGrid.PopupMenu:=nil; OfdbGrid.Options:= OfdbGrid.Options+[dgmultiselect,dgindicator]; OfdbGrid.Options:= OfdbGrid.Options-[dgrowselect]; res := pt.X; end else begin //OfdbGrid.PopupMenu:=PopupMenu.Name; {loquesea:=FindComponent('popUp_GayRangel'); ShowMessage(TPopUpMenu(loquesea).Name);} Cursor := crDefault; res := -1; end; end; result:=res; end; Function TicDbGrid.DbGridCoord(grid: TJvDBUltimGrid;x,y:Integer):Integer; var Res:Integer; begin res:=-1; with Grid do begin pt:= MouseCoord(x, y); if pt.y = 0 then begin Cursor := crHandPoint; res := pt.X; end else begin Cursor := crDefault; res := -1; end; end; Result:=res; end; Function TicDbGrid.DbGridMouseMoveCoord(x,y:Integer):Integer; var Res:Integer; begin res:=-1; if OfdbGrid<>nil then res:=DbGridCoord(OfdbGrid,x,y); if OfdbUGrid<>nil then res:=DbGridCoord(OfdbUGrid,x,y); ifGridColumn:=res; end; function NumItems(const cadena:string;const separador:char):integer; var res,Npos:integer; salir:boolean; cadAux:string; begin res:=0; salir:=false; cadAux:=cadena; while not salir do begin Npos:=pos(separador,cadAux); cadaux:=copy(cadaux,Npos+1,length(cadaux)); if Npos<>0 then Inc(res) else begin if res<>0 then inc(res); salir:=true; end; end; result:=res; end; function TraerItem(const cadena:string;const separador:char;const posicion:integer):string; var Item,CadAux:string; Npos,auxPos:integer; salir:boolean; begin Item:=''; cadAux:=cadena; salir:=false; auxPos:=0; while not salir do begin Npos:=pos(separador,cadaux); if Npos<>0 then begin item:=copy(cadAux,1,Npos-1); cadaux:=copy(cadaux,Npos+1,length(cadaux)); inc(auxPos); if auxpos=posicion then salir:=true; end else begin inc(auxPos); if auxpos=posicion then item:=cadAux else item:=''; Salir:=true; end; end; result:=item; end; (* procedure AddData(aDataset: TDataset; FirstName, LastName: string);overload; begin aDataset.Append; try aDataset.FieldByName('ID').Asstring := ''; aDataset.FieldByName('NAME').AsString := FirstName; aDataset.FieldByName('LASTNAME').AsString := LastName; finally aDataset.Post; end; end; *) procedure TicDbGrid.AddData(aDataset: TDataset; Lista:Tstrings); var registro:integer; sParametro:String; begin aDataset.Insert; if Adataset.FieldDefList.Count=aDataset.FieldList.Count then begin for registro := 0 to aDataset.fieldcount-1 do begin sparametro :=Adataset.FieldDefList.FieldDefs[registro].Name; //'param' + trim(inttostr(registro)) ; Adataset.FieldByName(sparametro).Value:=Lista[registro]; end ; end else begin for registro := 0 to aDataset.FieldList.Count-1 do begin sparametro :=Adataset.FieldList.Fields[registro].FieldName; //'param' + trim(inttostr(registro)) ; Adataset.FieldByName(sparametro).Value:=Lista[registro]; end ; end; try Adataset.Post; except on e:exception do begin //showmessage('Ocurrio un error al realizar esta operacion ' + e.ClassName + ', ' + e.Message); UnitExcepciones.manejarExcep(E.Message, E.ClassName, 'UDbGrid', 'Al Almacenar el registro', 0); Adataset.Cancel; end; end; end; procedure TicDbGrid.AddData(aDataset: TDataset; Lista:Tstrings;Orden:TstringList); var registro,i,pos,ex:integer; sParametro:String; error:boolean; begin aDataset.Insert; if Adataset.FieldDefList.Count=aDataset.FieldList.Count then begin for registro := 0 to aDataset.fieldcount-1 do begin sparametro :=Adataset.FieldDefList.FieldDefs[registro].Name; //'param' + trim(inttostr(registro)) ; pos:=-1; for I := 0 to orden.Count - 1 do if sparametro=orden.Values[orden.Names[i]] then pos:=strtoint(traerItem(orden.Names[i],':',1)); if pos<>-1 then Adataset.FieldByName(sparametro).Value:=Lista[pos] end ; end else begin for registro := 0 to aDataset.FieldList.Count-1 do begin if Adataset.FieldList.Fields[registro].FieldKind=fkData then begin sparametro :=Adataset.FieldList.Fields[registro].FieldName; //'param' + trim(inttostr(registro)) ; pos:=-1; for I := 0 to orden.Count - 1 do if sparametro=orden.Values[orden.Names[i]] then pos:=strtoint(traerItem(orden.Names[i],':',1)); if pos<>-1 then Adataset.FieldByName(sparametro).Value:=Lista[pos] else Adataset.FieldByName(sparametro).Required:=false; end; end; end; try Adataset.Post; except on e:exception do begin UnitExcepciones.manejarExcep(E.Message, E.ClassName, 'UDbGrid', 'Al Almacenar el registro', 0); Adataset.Cancel; end; end; end; procedure TicDbGrid.CopyRowsToClip; begin if OfdbGrid<>nil then dbGridCopy(OfdbGrid); if OfdbuGrid<>nil then dbGridCopy(OfdbuGrid); end; procedure TicDbGrid.DbGridPasteFromClip(grid: TDBGrid); var I,x,init: Integer; bm: TBookmark; List, Detail: TStrings; Aceptar,Primer:boolean; Orden:TstringList; begin if Assigned(grid.Datasource) and Assigned(grid.Datasource.Dataset) then begin with grid, grid.DataSource.DataSet do begin List := TStringList.Create; try List.Text := ClipBoard.AsText; if List.Count > 0 then begin application.CreateForm(TFrmColumnas,FrmColumnas); try with FrmColumnas do begin ListaDatos:=list; MyDataset:=grid.DataSource.DataSet; if ShowModal=mrcancel then aceptar:=false else begin Aceptar:=true; Orden:=TstringList.Create; Orden:=OrdenInsert; Primer:=OfCPrimer.Checked; end; end; finally freeandnil(FrmColumnas); end; if aceptar then begin Detail := TStringList.Create; try //Detail.Delimiter := #9; DisableControls; try bm := GetBookmark; try if primer then init:=1 else init:=0; for I := init to List.Count-1 do begin //Detail.DelimitedText := List[I]; detail.Clear; for x := 1 to NumItems(list[i],#9) do begin detail.Add(traerItem(list[i],#9,x)); end; AddData(grid.DataSource.DataSet,Detail,orden); end; if BookmarkValid(bm) then GotoBookmark(bm); finally FreeBookmark(bm); end; finally EnableControls; end; finally FreeAndNil(Detail); end; end; end; finally FreeAndNil(List); end; end; end; end; procedure TicDbGrid.DbGridPasteFromClip(grid: TJvDBUltimGrid); var I,x,init: Integer; bm: TBookmark; List, Detail: TStrings; Aceptar,Primer:boolean; Orden:TstringList; begin if Assigned(grid.Datasource) and Assigned(grid.Datasource.Dataset) then begin with grid, grid.DataSource.DataSet do begin List := TStringList.Create; try List.Text := ClipBoard.AsText; if List.Count > 0 then begin application.CreateForm(TFrmColumnas,FrmColumnas); try with FrmColumnas do begin ListaDatos:=list; MyDataset:=grid.DataSource.DataSet; if ShowModal=mrcancel then aceptar:=false else begin Aceptar:=true; Orden:=TstringList.Create; Orden:=OrdenInsert; Primer:=OfCPrimer.Checked; end; end; finally freeandnil(FrmColumnas); end; if aceptar then begin Detail := TStringList.Create; try //Detail.Delimiter := #9; DisableControls; try bm := GetBookmark; try if primer then init:=1 else init:=0; for I := init to List.Count-1 do begin //Detail.DelimitedText := List[I]; detail.Clear; for x := 1 to NumItems(list[i],#9) do begin detail.Add(traerItem(list[i],#9,x)); end; AddData(grid.DataSource.DataSet,Detail,orden); end; if BookmarkValid(bm) then GotoBookmark(bm); finally FreeBookmark(bm); end; finally EnableControls; end; finally FreeAndNil(Detail); end; end; end; finally FreeAndNil(List); end; end; end; end; procedure TicDbGrid.AddRowsFromClip; begin if OfdbGrid<>nil then if not (OfdbGrid.DataSource.DataSet is TZReadOnlyQuery) then DbGridPasteFromClip(OfdbGrid) else messagedlg('No se puede Pegar el registro, el grid es solo Lectura',mtinformation,[mbok],0); if OfdbuGrid<>nil then if not (OfdbGrid.DataSource.DataSet is TZReadOnlyQuery) then DbGridPasteFromClip(OfdbuGrid) else messagedlg('No se puede Pegar el registro, el grid es solo Lectura',mtinformation,[mbok],0); end; end.
unit CORBAServerForm; { This is the form that gets displayed when the server is running. A Counter is maintained on this Form to display the number of clients connected to it. For in-depth transfer of information between client and server, please refer to demos in MIDAS directory. } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TMainServerForm = class(TForm) ClientsLabel: TLabel; ClientCount: TLabel; private { Private declarations } FClientCount: Integer; public { Public declarations } procedure UpdateClientCount(Incr: Integer); end; var MainServerForm: TMainServerForm; implementation {$R *.dfm} procedure TMainServerForm.UpdateClientCount(Incr: Integer); begin FClientCount := FClientCount+Incr; ClientCount.Caption := IntToStr(FClientCount); end; end.
unit UDM; interface uses SysUtils, Classes, DB, SqlExpr, FMTBcd , UMensagens, DBXFirebird, DBXInterBase , DBXCommon, DBClient, Provider ; type TdmEntra21 = class(TDataModule) SQLConnection: TSQLConnection; SQLSelect: TSQLDataSet; procedure DataModuleCreate(Sender: TObject); private FTransaction: TDBXTransaction; public procedure AbortaTransacao; procedure FinalizaTransacao; procedure IniciaTransacao; procedure ValidaTransacaoAtiva; function TemTransacaoAtiva: Boolean; end; var dmEntra21: TdmEntra21; const CNT_DATA_BASE = 'Database'; implementation {$R *.dfm} uses Math ; procedure TdmEntra21.AbortaTransacao; begin if not TemTransacaoAtiva then raise Exception.CreateFmt(STR_NAO_EXISTE_TRANSACAO_ATIVA, [STR_ABORTAR]); SQLConnection.RollbackFreeAndNil(FTransaction); end; procedure TdmEntra21.FinalizaTransacao; begin if not TemTransacaoAtiva then raise Exception.CreateFmt(STR_NAO_EXISTE_TRANSACAO_ATIVA, [STR_FINALIZAR]); SQLConnection.CommitFreeAndNil(FTransaction); end; procedure TdmEntra21.IniciaTransacao; begin if TemTransacaoAtiva then raise Exception.Create(STR_JA_EXISTE_TRANSACAO_ATIVA); FTransaction := SQLConnection.BeginTransaction; end; function TdmEntra21.TemTransacaoAtiva: Boolean; begin Result := SQLConnection.InTransaction; end; procedure TdmEntra21.DataModuleCreate(Sender: TObject); begin SQLConnection.Connected := True; SQLConnection.Open; end; procedure TdmEntra21.ValidaTransacaoAtiva; begin if not TemTransacaoAtiva then raise Exception.Create(STR_VALIDA_TRANSACAO_ATIVA); end; end.
{*************************************************************** * * Project : FTPDemo * Unit Name: mainf * Purpose : This demo demonstrates the use of IdFTP and IdDebugLog components * : supports both UNIX and DOS directory listings * Version : 1.0 * Date : Wed 25 Apr 2001 - 01:15:09 * Author : Doychin Bondzhev <doichin@5group.com> * History : * Tested : Wed 25 Apr 2001 // Allen O'Neill <allen_oneill@hotmail.com> * ****************************************************************} unit mainf; interface uses {$IFDEF Linux} QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls, QComCtrls, QMenus, QTypes, {$ELSE} windows, messages, graphics, controls, forms, dialogs, stdctrls, extctrls, comctrls, menus, {$ENDIF} SysUtils, Classes, IdIntercept, IdLogBase, IdLogDebug, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdFTP, IdAntiFreezeBase, IdAntiFreeze; type TMainForm = class(TForm) DirectoryListBox: TListBox; IdFTP1: TIdFTP; IdLogDebug1: TIdLogDebug; DebugListBox: TListBox; Panel1: TPanel; FtpServerEdit: TEdit; ConnectButton: TButton; Splitter1: TSplitter; Label1: TLabel; UploadOpenDialog1: TOpenDialog; Panel3: TPanel; SaveDialog1: TSaveDialog; StatusBar1: TStatusBar; TraceCheckBox: TCheckBox; CommandPanel: TPanel; UploadButton: TButton; AbortButton: TButton; BackButton: TButton; DeleteButton: TButton; DownloadButton: TButton; UserIDEdit: TEdit; PasswordEdit: TEdit; Label2: TLabel; Label3: TLabel; IdAntiFreeze1: TIdAntiFreeze; ProgressBar1: TProgressBar; UsePassive: TCheckBox; CurrentDirEdit: TEdit; ChDirButton: TButton; CreateDirButton: TButton; PopupMenu1: TPopupMenu; Download1: TMenuItem; Upload1: TMenuItem; Delete1: TMenuItem; N1: TMenuItem; Back1: TMenuItem; procedure ConnectButtonClick(Sender: TObject); procedure IdLogDebug1LogItem(ASender: TComponent; var AText: String); procedure UploadButtonClick(Sender: TObject); procedure DirectoryListBoxDblClick(Sender: TObject); procedure DeleteButtonClick(Sender: TObject); procedure IdFTP1Disconnected(Sender: TObject); procedure AbortButtonClick(Sender: TObject); procedure BackButtonClick(Sender: TObject); procedure IdFTP1Status(axSender: TObject; const axStatus: TIdStatus; const asStatusText: String); procedure TraceCheckBoxClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure DirectoryListBoxClick(Sender: TObject); procedure IdFTP1Work(Sender: TObject; AWorkMode: TWorkMode; const AWorkCount: Integer); procedure IdFTP1WorkBegin(Sender: TObject; AWorkMode: TWorkMode; const AWorkCountMax: Integer); procedure IdFTP1WorkEnd(Sender: TObject; AWorkMode: TWorkMode); procedure UsePassiveClick(Sender: TObject); procedure ChDirButtonClick(Sender: TObject); procedure CreateDirButtonClick(Sender: TObject); private { Private declarations } AbortTransfer: Boolean; TransferrignData: Boolean; BytesToTransfer: LongWord; STime: TDateTime; procedure ChageDir(DirName: String); procedure SetFunctionButtons(AValue: Boolean); procedure SaveFTPHostInfo(Datatext, header: String); function GetHostInfo(header: String): String; public { Public declarations } end; var MainForm: TMainForm; implementation {$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF} Uses IniFiles; Var AverageSpeed: Double = 0; procedure TMainForm.SetFunctionButtons(AValue: Boolean); Var i: Integer; begin with CommandPanel do for i := 0 to ControlCount - 1 do if Controls[i].Name <> 'AbortButton' then Controls[i].Enabled := AValue; with PopupMenu1 do for i := 0 to Items.Count - 1 do Items[i].Enabled := AValue; ChDirButton.Enabled := AValue; CreateDirButton.Enabled := AValue; end; procedure TMainForm.ConnectButtonClick(Sender: TObject); begin ConnectButton.Enabled := false; if IdFTP1.Connected then try if TransferrignData then IdFTP1.Abort; IdFTP1.Quit; finally //Panel3.Caption := 'Current directory is: '; CurrentDirEdit.Text := '/'; DirectoryListBox.Items.Clear; SetFunctionButtons(false); ConnectButton.Caption := 'Connect'; ConnectButton.Enabled := true; ConnectButton.Default := true; end else with IdFTP1 do try User := UserIDEdit.Text; Password := PasswordEdit.Text; Host := FtpServerEdit.Text; Connect; Self.ChageDir(CurrentDirEdit.Text); SetFunctionButtons(true); SaveFTPHostInfo(FtpServerEdit.Text, 'FTPHOST'); finally ConnectButton.Enabled := true; if Connected then begin ConnectButton.Caption := 'Disconnect'; ConnectButton.Default := false; end; end; end; procedure TMainForm.IdLogDebug1LogItem(ASender: TComponent; var AText: String); begin DebugListBox.ItemIndex := DebugListBox.Items.Add(AText); end; procedure TMainForm.UploadButtonClick(Sender: TObject); begin if IdFTP1.Connected then begin if UploadOpenDialog1.Execute then try SetFunctionButtons(false); IdFTP1.TransferType := ftBinary; IdFTP1.Put(UploadOpenDialog1.FileName, ExtractFileName(UploadOpenDialog1.FileName)); ChageDir(idftp1.RetrieveCurrentDir); finally SetFunctionButtons(true); end; end; end; procedure TMainForm.ChageDir(DirName: String); begin try SetFunctionButtons(false); IdFTP1.ChangeDir(DirName); IdFTP1.TransferType := ftASCII; CurrentDirEdit.Text := IdFTP1.RetrieveCurrentDir; {Panel3.Caption := 'Current directory is: ' + IdFTP1.RetrieveCurrentDir + ' Remote system is ' + IdFTP1.SystemDesc;} DirectoryListBox.Items.Clear; IdFTP1.List(DirectoryListBox.Items); finally SetFunctionButtons(true); end; end; function GetNameFromDirLine(Line: String; Var IsDirectory: Boolean): String; Var i: Integer; DosListing: Boolean; begin IsDirectory := Line[1] = 'd'; DosListing := false; for i := 0 to 7 do begin if (i = 2) and not IsDirectory then begin IsDirectory := Copy(Line, 1, Pos(' ', Line) - 1) = '<DIR>'; if not IsDirectory then DosListing := Line[1] in ['0'..'9'] else DosListing := true; end; Delete(Line, 1, Pos(' ', Line)); While Line[1] = ' ' do Delete(Line, 1, 1); if DosListing and (i = 2) then break; end; Result := Line; end; procedure TMainForm.DirectoryListBoxDblClick(Sender: TObject); Var Name, Line: String; IsDirectory: Boolean; begin if not IdFTP1.Connected then exit; Line := DirectoryListBox.Items[DirectoryListBox.ItemIndex]; Name := GetNameFromDirLine(Line, IsDirectory); if IsDirectory then begin // Change directory SetFunctionButtons(false); ChageDir(Name); SetFunctionButtons(true); end else begin try SaveDialog1.FileName := Name; if SaveDialog1.Execute then begin SetFunctionButtons(false); IdFTP1.TransferType := ftBinary; BytesToTransfer := IdFTP1.Size(Name); IdFTP1.Get(Name, SaveDialog1.FileName, true); end; finally SetFunctionButtons(true); end; end; end; procedure TMainForm.DeleteButtonClick(Sender: TObject); Var Name, Line: String; IsDirectory: Boolean; begin if not IdFTP1.Connected then exit; Line := DirectoryListBox.Items[DirectoryListBox.ItemIndex]; Name := GetNameFromDirLine(Line, IsDirectory); if IsDirectory then try SetFunctionButtons(false); idftp1.RemoveDir(Name); ChageDir(idftp1.RetrieveCurrentDir); finally end else try SetFunctionButtons(false); idftp1.Delete(Name); ChageDir(idftp1.RetrieveCurrentDir); finally end; end; procedure TMainForm.IdFTP1Disconnected(Sender: TObject); begin StatusBar1.Panels[1].Text := 'Disconnected.'; end; procedure TMainForm.AbortButtonClick(Sender: TObject); begin AbortTransfer := true; end; procedure TMainForm.BackButtonClick(Sender: TObject); begin if not IdFTP1.Connected then exit; try ChageDir('..'); finally end; end; procedure TMainForm.IdFTP1Status(axSender: TObject; const axStatus: TIdStatus; const asStatusText: String); begin DebugListBox.ItemIndex := DebugListBox.Items.Add(asStatusText); StatusBar1.Panels[1].Text := asStatusText; end; procedure TMainForm.TraceCheckBoxClick(Sender: TObject); begin IdLogDebug1.Active := TraceCheckBox.Checked; DebugListBox.Visible := TraceCheckBox.Checked; if DebugListBox.Visible then Splitter1.Top := DebugListBox.Top + 5; end; procedure TMainForm.FormCreate(Sender: TObject); begin SetFunctionButtons(false); IdLogDebug1.Active := true; FtpServerEdit.Text := GetHostInfo('FTPHOST'); ProgressBar1.Parent := StatusBar1; ProgressBar1.Top := 2; ProgressBar1.Left := 1; {$IFDEF Linux} ProgressBar1.Width := 142; {$ENDIF} end; procedure TMainForm.DirectoryListBoxClick(Sender: TObject); Var Line: String; IsDirectory: Boolean; begin if not IdFTP1.Connected then exit; Line := DirectoryListBox.Items[DirectoryListBox.ItemIndex]; GetNameFromDirLine(Line, IsDirectory); if IsDirectory then DownloadButton.Caption := 'Change dir' else DownloadButton.Caption := 'Download'; end; procedure TMainForm.IdFTP1Work(Sender: TObject; AWorkMode: TWorkMode; const AWorkCount: Integer); Var S: String; TotalTime: TDateTime; H, M, Sec, MS: Word; DLTime: Double; begin TotalTime := Now - STime; DecodeTime(TotalTime, H, M, Sec, MS); Sec := Sec + M * 60 + H * 3600; DLTime := Sec + MS / 1000; if DLTime > 0 then AverageSpeed := {(AverageSpeed + }(AWorkCount / 1024) / DLTime{) / 2}; S := FormatFloat('0.00 KB/s', AverageSpeed); case AWorkMode of wmRead: StatusBar1.Panels[1].Text := 'Download speed ' + S; wmWrite: StatusBar1.Panels[1].Text := 'Uploade speed ' + S; end; if AbortTransfer then IdFTP1.Abort; ProgressBar1.Position := AWorkCount; AbortTransfer := false; end; procedure TMainForm.IdFTP1WorkBegin(Sender: TObject; AWorkMode: TWorkMode; const AWorkCountMax: Integer); begin TransferrignData := true; AbortButton.Visible := true; AbortTransfer := false; STime := Now; if AWorkCountMax > 0 then ProgressBar1.Max := AWorkCountMax else ProgressBar1.Max := BytesToTransfer; AverageSpeed := 0; end; procedure TMainForm.IdFTP1WorkEnd(Sender: TObject; AWorkMode: TWorkMode); begin AbortButton.Visible := false; StatusBar1.Panels[1].Text := 'Transfer complete.'; BytesToTransfer := 0; TransferrignData := false; ProgressBar1.Position := 0; AverageSpeed := 0; end; procedure TMainForm.UsePassiveClick(Sender: TObject); begin IdFTP1.Passive := UsePassive.Checked; end; procedure TMainForm.ChDirButtonClick(Sender: TObject); begin SetFunctionButtons(false); ChageDir(CurrentDirEdit.Text); SetFunctionButtons(true); end; procedure TMainForm.CreateDirButtonClick(Sender: TObject); Var S: String; begin S := InputBox('Make new directory', 'Name', ''); if S <> '' then try SetFunctionButtons(false); IdFTP1.MakeDir(S); ChageDir(CurrentDirEdit.Text); finally SetFunctionButtons(true); end; end; procedure TMainForm.SaveFTPHostInfo(Datatext, header: String); var ServerIni: TIniFile; begin ServerIni := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'FtpHost.ini'); ServerIni.WriteString('Server', header, Datatext); ServerIni.UpdateFile; ServerIni.Free; end; function TMainForm.GetHostInfo(header: String): String; var ServerName: String; ServerIni: TIniFile; begin ServerIni := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'FtpHost.ini'); ServerName := ServerIni.ReadString('Server', header, header); ServerIni.Free; result := ServerName; end; end.
(**************************************************************************** (c) 1992 by Michelangelo Policarpo per Sound Blaster Digest Italia Unit FM per la gestione diretta della sezione FM di una qualsiasi scheda AdLib compatibile. Versione 1.0 7/10/92 Primo rilascio al Pubblico Dominio L'autore ha posto ogni cura (e tempo) nella realizzazione di queste routines, testandole sotto svariate condizioni di uso. A causa della varieta` delle condizioni e dell' hardware con cui queste pos- sono essere utilizzate, non e` pero` possibile offrire alcuna garanzia sul loro corretto funzionamento. Chi usa questo pacchetto (o direttamente derivato) accetta implicitamente tutte le le clausole qui riportate : 1. L' utente si assume ogni responsabilita` per gli eventuali danni che le routines possono provocare, soprattutto a causa di un uso improprio del prodotto. 2. L' utente deve riportare nella documentazione di accompagnamento del software da lui prodotto il copyright sopra riportato o equivalente nota di utilizzo di questo pacchetto. QUESTO PACCHETTO VIENE RILASCIATO AL PUBBLICO DOMINIO E PERTANTO DEVE ESSERE DISTRIBUITO LIBERAMENTE E GRATUITAMENTE. TALE PACCHETTO PUO` ANCHE ESSERE MODIFICATO PURCHE` RIMANGA INTATTA LA NOTA DI COPYRIGHT E QUESTA PARTE DI COMMENTO. ****************************************************************************) unit FM; interface const Melodic = 0; Rhythmic = 1; Undefined = $FF; OFF = false; ON = true; const FMErrorMsg : array[1..10] of string[31] = ('AdLib or SB card not present', 'Invalid note', 'Invalid voice', '', '', '', '', '', '', '' ); {.BNK entry file structure} type Operator = record KSL, FreqMult, Feedback, Attack, SustLevel, EG, Decay, Release, Output, AM, Vib, KSR, FM : byte end; type InsDataPtr = ^InsData; InsData = record Mode, PercVoice : byte; Op0, Op1 : Operator; Wave0, Wave1 : byte end; {.INS file structure} type OPER = record KSL, FreqMult, Feedback, Attack, SustLevel, EG, Decay, Release, Output, AM, Vib, KSR, FM : word end; INS = record Mode : byte; PercVoice : byte; OPER0,OPER1 : OPER; end; INSEXT = record INSBase : INS; Wave0,Wave1 : word; Pad : array[1..10] of word; One : word; end; var FMError : integer; CurrentFMMode : byte; BaseReg : word; AdLibInstalled : boolean; WaveFormEnabled, CSMModeEnabled, KBDSplitEnabled, AMDepthEnabled, VIBDepthEnabled : boolean; {Global variables} procedure SetMelRhythm(State : boolean); procedure SetWaveForm (State : boolean); procedure SetCSMMode (State : boolean); procedure SetKBDSplit (State : boolean); procedure SetAMDepth (State : boolean); procedure SetVIBDepth (State : boolean); {Operator cells parameters} {For any} procedure SetAM (Ofs,Data : byte); procedure SetVib (Ofs,Data : byte); procedure SetEG (Ofs,Data : byte); procedure SetKSR (Ofs,Data : byte); procedure SetFreqMult (Ofs,Data : byte); procedure SetKSL (Ofs,Data : byte); procedure SetOutput (Ofs,Data : byte); procedure SetAttack (Ofs,Data : byte); procedure SetDecay (Ofs,Data : byte); procedure SetSustLevel (Ofs,Data : byte); procedure SetRelease (Ofs,Data : byte); procedure SetWaveSel (Ofs,Data : byte); {Only for modulator} procedure SetFeedback (Ofs,Data : byte); procedure SetFM (Ofs,Data : byte); {For direct register access, CMF} function ModOfs(channel : byte) : byte; function CarOfs(channel : byte) : byte; procedure SetSC(Ofs, Data : byte); procedure SetSO(Ofs, Data : byte); procedure SetAD(Ofs, Data : byte); procedure SetSR(Ofs, Data : byte); procedure SetWS(Ofs, Data : byte); procedure SetFC(Ofs, Data : byte); {General routines} procedure SetFMMode (FMMode : byte); procedure AssignVoice (Voice : byte; Ins : InsData); procedure AllKeyOff; procedure KeyOn (Voice, Note : byte); procedure KeyOff (Voice : byte); procedure QuitVoices; procedure QuitVoice (Voice: byte); procedure ResetVoice (Voice: byte); procedure ResetSynth; function FMStatus (voice : byte) : InsDataPtr; procedure FMInit(Base : word); function FindBasePort : boolean; function FindSBPBasePort : word; function IsAdLib : boolean; implementation type InsArray = array[0..29] of byte; const FNumbers : array[0..11] of word = (363,385,408,432,458,485,514,544,577,611,647,686); {Offsets in registers array} M_OpCell : array[1..9,0..1] of byte = (($00,$03),($01,$04),($02,$05), ($08,$0B),($09,$0C),($0A,$0D), ($10,$13),($11,$14),($12,$15)); R_OpCell : array[1..11,0..1] of byte = (($00,$03),($01,$04),($02,$05), ($08,$0B),($09,$0C),($0A,$0D), ($10,$13),($14,$FF),($12,$FF), ($15,$FF),($11,$FF)); Octave : array[0..95] of byte = (0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1, 2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3, 4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5, 6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7); Semitone : array[0..95] of byte = (0,1,2,3,4,5,6,7,8,9,10,11,0,1,2,3,4,5,6,7,8,9,10,11, 0,1,2,3,4,5,6,7,8,9,10,11,0,1,2,3,4,5,6,7,8,9,10,11, 0,1,2,3,4,5,6,7,8,9,10,11,0,1,2,3,4,5,6,7,8,9,10,11, 0,1,2,3,4,5,6,7,8,9,10,11,0,1,2,3,4,5,6,7,8,9,10,11); {M/PV-1} {Op0} {v--caution!} {Op1} {WS} Piano1 : InsArray = ( 0,00, 1, 1, 3,15, 5, 0, 1, 3,15, 0, 0, 0, 0, 0, 1, 0,13, 7, 0, 2, 4,16, 0, 0, 1, 0, 0,0); BDrum1 : InsArray = ( 1,06, 0, 0, 0,10, 4, 0, 8,12,11, 0, 0, 0, 0, 0, 0,47,13, 4, 0, 6,15,16, 0, 0, 0, 1, 0,0); Snare1 : InsArray = ( 1,07, 0,12, 0,15,11, 0, 8, 5,16, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0); Tom1 : InsArray = ( 1,08, 0, 4, 0,15,11, 0, 7, 5,16, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0); Cymbal1: InsArray = ( 1,09, 0, 1, 0,15,11, 0, 5, 5,16, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0); HiHat1 : InsArray = ( 1,10, 0, 1, 0,15,11, 0, 7, 5,16, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0); const {Register offsets} {Range} {First group : general} R_TEST : byte = $01; {Test} {001h} R_TIM1 : byte = $02; {Timer 1} {002h} R_TIM2 : byte = $03; {Timer 2} {003h} R_TIMC : byte = $04; {Timer Control} {004h} R_CSMK : byte = $08; {CSM Mode/Keyboard Split} {008h} R_AVR : byte = $BD; {AM VIB-Depth/Rhythm} {0BDh} {Second group : for each operator cell} R_AVEKM : byte = $20; {AM/VIB/EG/KSR/MULTIPLE} {020h-035h} R_KTL : byte = $40; {KSL/Total Level} {040h-055h} R_ARDR : byte = $60; {Attack Rate/Decay Rate} {060h-075h} R_SLRR : byte = $80; {Sustain Level/Release Rate} {080h-095h} R_WS : byte = $E0; {Wave Select} {0E0h-0F5h} {Third group : for each channel} R_FNUM : byte = $A0; {F-Number Low bits} {0A0h-0A8h} R_BLK : byte = $B0; {F-Number High bits} {0B0h-0B8h} R_FBC : byte = $C0; {Feedback/Connection} {0C0h-0C8h} var FMRegisters : array[0..$FF] of byte; MelRhythm : boolean; Install : boolean; TmpInsData : InsData; procedure OutCmd; assembler; {al = Address; ah = Data} asm {OutCmd} push ax push dx push bx xor bx,bx mov bl,al mov byte ptr FMRegisters[bx],ah {UpDate buffer area} pop bx cmp Install,true je @GoOn cmp AdlibInstalled,true jne @Exit @GoOn: mov dx,BaseReg out dx,al in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx inc dx mov al,ah out dx,al in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx in al, dx @Exit: pop dx pop ax end; {OutCmd} procedure SetAM(Ofs,Data : byte); assembler; asm {SetAM} mov al,Data and al,00000001b ror al,1 xor bx,bx mov bl,Ofs add bl,20h mov ah,byte ptr FMRegisters[bx] and ah,01111111b or ah,al mov al,bl call OutCmd end; {SetAM} procedure SetVib(Ofs,Data : byte); assembler; asm {SetVib} mov al,Data and al,00000001b ror al,1 ror al,1 xor bx,bx mov bl,Ofs add bx,20h mov ah,byte ptr FMRegisters[bx] and ah,10111111b or ah,al mov al,bl call OutCmd end; {SetVib} procedure SetEG(Ofs,Data : byte); assembler; asm {SetEG} mov al,Data and al,00000001b ror al,1 ror al,1 ror al,1 xor bx,bx mov bl,Ofs add bx,20h mov ah,byte ptr FMRegisters[bx] and ah,11011111b or ah,al mov al,bl call OutCmd end; {SetEG} procedure SetKSR(Ofs,Data : byte); assembler; asm {SetKSR} mov al,Data and al,00000001b ror al,1 ror al,1 ror al,1 ror al,1 xor bx,bx mov bl,Ofs add bx,20h mov ah,byte ptr FMRegisters[bx] and ah,11101111b or ah,al mov al,bl call OutCmd end; {SetKSR} procedure SetFreqMult(Ofs,Data : byte); assembler; asm {SetFreqMult} mov al,Data and al,00001111b xor bx,bx mov bl,Ofs add bx,20h mov ah,byte ptr FMRegisters[bx] and ah,11110000b or ah,al mov al,bl call OutCmd end; {SetFreqMult} procedure SetKSL(Ofs,Data : byte); assembler; asm {SetKSL} mov al,Data and al,00000011b ror al,1 ror al,1 xor bx,bx mov bl,Ofs add bx,40h mov ah,byte ptr FMRegisters[bx] and ah,00111111b or ah,al mov al,bl call OutCmd end; {SetKSL} procedure SetOutput(Ofs,Data : byte); assembler; asm {SetOutput} mov al,Data and al,00111111b xor bx,bx mov bl,Ofs add bx,40h mov ah,byte ptr FMRegisters[bx] and ah,11000000b or ah,al mov al,bl call OutCmd end; {SetOutput} procedure SetAttack(Ofs,Data : byte); assembler; asm {SetAttack} mov al,Data and al,00001111b ror al,1 ror al,1 ror al,1 ror al,1 xor bx,bx mov bl,Ofs add bx,60h mov ah,byte ptr FMRegisters[bx] and ah,00001111b or ah,al mov al,bl call OutCmd end; {SetAttack} procedure SetDecay(Ofs,Data : byte); assembler; asm {SetDecay} mov al,Data and al,00001111b xor bx,bx mov bl,Ofs add bx,60h mov ah,byte ptr FMRegisters[bx] and ah,11110000b or ah,al mov al,bl call OutCmd end; {SetDecay} procedure SetSustLevel(Ofs,Data : byte); assembler; asm {SetSustLevel} mov al,Data and al,00001111b ror al,1 ror al,1 ror al,1 ror al,1 xor bx,bx mov bl,Ofs add bx,80h mov ah,byte ptr FMRegisters[bx] and ah,00001111b or ah,al mov al,bl call OutCmd end; {SetSustLevel} procedure SetRelease(Ofs,Data : byte); assembler; asm {SetRelease} mov al,Data and al,00001111b xor bx,bx mov bl,Ofs add bx,80h mov ah,byte ptr FMRegisters[bx] and ah,11110000b or ah,al mov al,bl call OutCmd end; {SetRelease} procedure SetWaveSel(Ofs,Data : byte); assembler; asm {SetWaveSel} mov al,Data and al,00000011b xor bx,bx mov bl,Ofs add bx,0E0h mov ah,byte ptr FMRegisters[bx] and ah,11111100b or ah,al mov al,bl call OutCmd end; {SetWaveSel} procedure SetFeedback(Ofs,Data : byte); assembler; asm {SetFeedback} mov al,Data and al,00000111b shl al,1 xor bx,bx mov bl,Ofs add bx,0C0h mov ah,byte ptr FMRegisters[bx] and ah,11110001b or ah,al mov al,bl call OutCmd end; {SetFeedback} procedure SetFM(Ofs,Data : byte); assembler; asm {SetFM} mov al,Data and al,00000001b xor bx,bx mov bl,Ofs add bx,0C0h mov ah,byte ptr FMRegisters[bx] and ah,11111110b or ah,al mov al,bl call OutCmd end; {SetFM} procedure SetOpCellParameters(Offset : byte; Op : Operator; WaveSel : byte); begin {SetOpCellParameters} with Op do begin SetAM (Offset,AM); SetVib (Offset,Vib); SetEG (Offset,EG); SetKSR (Offset,KSR); SetFreqMult (Offset,FreqMult); SetKSL (Offset,KSL); SetOutput (Offset,Output); SetAttack (Offset,Attack); SetDecay (Offset,Decay); SetSustLevel(Offset,SustLevel); SetRelease (Offset,Release); SetWaveSel (Offset,WaveSel) end end; {SetOpCellParameters} procedure AssignVoice(Voice : byte; Ins : InsData); begin {AssignVoice} if Voice<=0 then begin FMError := 3; Exit end; if (CurrentFMMode=Melodic) then begin if Voice>9 then begin FMError := 3; Exit end; SetOpCellParameters(M_OpCell[Voice][0],Ins.OP0,Ins.Wave0); with Ins.OP0 do begin SetFeedBack(Voice-1,FeedBack); SetFM(Voice-1,FM); end; SetOpCellParameters(M_OpCell[Voice][1],Ins.OP1,Ins.Wave1); end else {Rhythmic} begin if Voice>11 then begin FMError := 3; Exit end; SetOpCellParameters(R_OpCell[Voice][0],Ins.OP0,Ins.Wave0); with Ins.OP0 do begin SetFeedBack(Voice-1,FeedBack); if Voice<=9 then SetFM(Voice-1,FM); end; if Voice<=7 then SetOpCellParameters(R_OpCell[Voice][1],Ins.OP1,Ins.Wave1); end end; {AssignVoice} procedure KeyOn(Voice, Note : byte); assembler; {Note is the MIDI value for the note to play: note in [0..$5F]} asm {KeyOn} xor bx,bx mov bl,Note cmp bl,5Fh jbe @NoteGood mov FMError,2 {Invalid note} jmp @Done @NoteGood: push bx mov bl,byte ptr Semitone[bx] {bl = Semitone} shl bx,1 mov bx,word ptr FNumbers[bx] xchg ax,bx {ax = FNumber} pop bx mov bl,byte ptr Octave[bx] {bl = Octave} and bl,07h; shl bl,1 shl bl,1 or ah,bl {ax = Octave|F-Number} mov dl,Voice cmp dl,11 ja @BadVoice cmp dl,0 jle @BadVoice cmp dl,6 {Exclude Bass Drum} jle @Melodic cmp CurrentFMMode,1 {is Rhythmic?} jne @Melodic {no, jump} {@Rhythmic:} cmp MelRhythm,1 {is Rhythmic section melodic-enabled?} jne @GoOn {no: skip frequency control} cmp dl,7 {is less than a Bass drum?} jl @GoOn cmp dl,11 {is more than Tom-Tom?} jg @GoOn xchg ax,bx mov al,dl dec al {al=offset} add al,0A0h {register} mov ah,bl {data : Lo(F-Number)} call OutCmd add al,010h {register} mov ah,bh {data : KeyOn|Block|Hi(F-Number)} call OutCmd @GoOn: mov cx,11 sub cl,Voice mov al,01h rol al,cl mov ah,byte ptr FMRegisters[0BDh] or ah,al mov al,0BDh call OutCmd jmp @Done @Melodic: cmp dl,9 jg @BadVoice or ah,20h {add KeyOn} xchg ax,bx mov al,dl dec al {al=offset} add al,0A0h {register} mov ah,bl {data : Lo(F-Number)} call OutCmd add al,010h {register} mov ah,bh {data : KeyOn|Block|Hi(F-Number)} call OutCmd jmp @Done @BadVoice: mov FMError,3 @Done: end; {KeyOn} procedure KeyOff(Voice : byte); assembler; asm {KeyOff} push cx mov al,Voice cmp al,6 jle @Melodic test CurrentFMMode,1 jz @Melodic mov cx,11 sub cl,al js @Error mov al,0FEh rol al,cl mov ah,byte ptr FMRegisters[0BDh] and ah,al mov al,0BDh call OutCmd jmp @Done @Melodic: cmp al,9 jg @Error dec al cmp al,0 jl @Error add al,0B0h xor bx,bx mov bl,al mov ah,byte ptr FMRegisters[bx] and ah,11011111b call OutCmd jmp @Done @Error: mov FMError,3 @Done: pop cx end; {KeyOff} procedure QuitVoice(Voice : byte); begin {QuitVoice} SetRelease(R_OpCell[Voice][0],15); SetRelease(R_OpCell[Voice][1],15); KeyOff(Voice); end; {QuitVoice} procedure QuitVoices; assembler; asm {QuitVoices} mov cx,3 mov ax,40h @NextN: push cx mov cx,3 @NextM: push cx mov ah,7Fh call OutCmd add al,40h mov ah,5Fh call OutCmd sub al,40h add al,3 mov ah,3Fh call OutCmd add al,40h mov ah,7Fh call OutCmd sub ax,40h sub ax,2 pop cx loop @NextM add ax,5 pop cx loop @NextN mov cx,9 @NextA: mov bx,cx dec bx add bx,0B0h mov ah,byte ptr FMRegisters[bx] and ah,11011111b mov al,bl call OutCmd loop @NextA mov ah,byte ptr FMRegisters[0BDh] and ah,11100000b mov al,0BDh call OutCmd end; {QuitVoices} procedure SetWaveForm(State : boolean); assembler; var i : byte; asm {SetWaveForm} mov ah,State and ah,1 mov WaveFormEnabled,ah ror ah,1 ror ah,1 ror ah,1 mov al,1 call OutCmd end; {SetWaveForm} procedure AllKeyOff; var i : byte; begin {AllKeyOff} if CurrentFMMode=Melodic then for i:=1 to 9 do KeyOff(i) else for i:=1 to 11 do KeyOff(i) end; {AllKeyOff} procedure SetCSMMode(State : boolean); assembler; asm {SetCSMMode} call AllKeyOff mov ah,State and ah,00000001b mov CSMModeEnabled,ah ror ah,1 mov al,byte ptr FMRegisters[8] and al,01111111b or ah,al mov al,8 call OutCmd end; {SetCSMMode} procedure SetKBDSplit(State : boolean); assembler; asm {SetKBDSplit} mov ah,State and ah,00000001b mov KBDSplitEnabled,ah ror ah,1 ror ah,1 mov al,byte ptr FMRegisters[8] and al,10111111b or ah,al mov al,8 call OutCmd end; {SetKBDSplit} procedure SetAMDepth(State : boolean); assembler; asm {SetAMDepth} mov ah,State and ah,00000001b mov AMDepthEnabled,ah ror ah,1 mov al,byte ptr FMRegisters[0BDh] and al,01111111b or ah,al mov al,0BDh call OutCmd end; {SetAMDepth} procedure SetVIBDepth(State : boolean); assembler; asm {SetVIBDepth} mov ah,State and ah,00000001b mov VIBDepthEnabled,ah ror ah,1 ror ah,1 mov al,byte ptr FMRegisters[0BDh] and al,10111111b or ah,al mov al,0BDh call OutCmd end; {SetVIBDepth} procedure SetFMMode(FMMode : byte); assembler; asm {SetFMMode} call QuitVoices mov al,FMMode and al,00000001b mov CurrentFMMode,al shl al,1 shl al,1 shl al,1 shl al,1 shl al,1 {Shift bit to D5} mov ah,byte ptr FMRegisters[0BDh] and ah,11000000b or ah,al mov al,0BDh call OutCmd end; {SetFMMode} procedure SetMelRhythm(State : boolean); begin {SetMelRhythm} MelRhythm := State end; {SetMelRhythm} {* compatibility with CMF modes *} procedure SetSC(Ofs, Data : byte); assembler; asm {SetSC} mov ah,Data mov al,Ofs add al,020h call OutCmd end; {SetSC} procedure SetSO(Ofs, Data : byte); assembler; asm {SetSO} mov ah,Data mov al,Ofs add al,040h call OutCmd end; {SetSO} procedure SetAD(Ofs, Data : byte); assembler; asm {SetAD} mov ah,Data mov al,Ofs add al,060h call OutCmd end; {SetAD} procedure SetSR(Ofs, Data : byte); assembler; asm {SetSR} mov ah,Data mov al,Ofs add al,080h call OutCmd end; {SetSR} procedure SetWS(Ofs, Data : byte); assembler; asm {SetWS} mov ah,Data mov al,Ofs add al,0E0h call OutCmd end; {SetWS} procedure SetFC(Ofs, Data : byte); assembler; asm {SetFC} mov ah,Data mov al,Ofs add al,0C0h call OutCmd end; {SetFC} function ModOfs(channel : byte) : byte; begin {ModOfs} case CurrentFMMode of Melodic : ModOfs := M_OpCell[channel+1,0]; Rhythmic: if channel<6 then ModOfs := R_OpCell[channel+1,0] else ModOfs := R_OpCell[channel-5,0] end end; {ModOfs} function CarOfs(channel : byte) : byte; begin {CarOfs} case CurrentFMMode of Melodic : CarOfs := M_OpCell[channel+1,1]; Rhythmic: if channel<6 then CarOfs := R_OpCell[channel+1,1] else CarOfs := R_OpCell[channel-5,1] end end; {CarOfs} {* end of compatibility with CMF modes *} procedure ResetTimers; assembler; asm {ResetTimers} mov ah,60h mov al,04h call OutCmd {Mask T1 & T2} mov ah,80h mov al,04h call OutCmd {Reset IRQ} end; {ResetTimers} procedure ResetRegisters; assembler; asm {ResetRegisters} mov cx,0F5h @NextReg: mov ax,cx call OutCmd loop @NextReg end; {ResetRegisters} procedure ResetVariables; begin {ResetVariables} SetWaveForm(ON); SetCSMMode(OFF); SetKBDSplit(ON); SetAMDepth(OFF); SetVIBDepth(OFF) end; {ResetVariables} procedure ResetPitch; assembler; asm {ResetPitch} mov al,CurrentFMMode cmp al,0 jne @Rhythm mov cx,9 mov bx,57A0h mov dx,01B0h @NextVoice: mov ax,bx call OutCmd inc bx mov ax,dx call OutCmd inc dx loop @NextVoice jmp @RPExit @Rhythm: mov ax,57A0h {Voice 1} call OutCmd mov ax,11B0h call OutCmd mov ax,57A1h {Voice 2} call OutCmd mov ax,01B1h call OutCmd mov ax,57A2h {Voice 3} call OutCmd mov ax,01B2h call OutCmd mov ax,57A3h {Voice 4} call OutCmd mov ax,01B3h call OutCmd mov ax,57A4h {Voice 5} call OutCmd mov ax,01B4h call OutCmd mov ax,57A5h {Voice 6} call OutCmd mov ax,01B5h call OutCmd mov ax,57A6h {Bass drum} call OutCmd mov ax,09B6h {Warning!!! was : 01B6} call OutCmd mov ax,03A7h {Snare drum & Hi-Hat} call OutCmd mov ax,0AB7h call OutCmd mov ax,57A8h {Tom & Cymbal} call OutCmd mov ax,09B8h call OutCmd @RPExit: end; {ResetPitch} procedure ResetVoice(Voice:byte); begin {ResetVoice} if (CurrentFMMode=Melodic) or (Voice<=6) then AssignVoice(Voice,InsData(Piano1)) else case Voice of 7 : AssignVoice(7,InsData(BDrum1)); 8 : AssignVoice(8,InsData(Snare1)); 9 : AssignVoice(9,InsData(Tom1)); 10: AssignVoice(10,InsData(Cymbal1)); 11: AssignVoice(11,InsData(HiHat1)) end; end; {ResetVoice} procedure ResetSynth; begin {ResetSynth} ResetVariables; AssignVoice(1,InsData(Piano1)); AssignVoice(2,InsData(Piano1)); AssignVoice(3,InsData(Piano1)); AssignVoice(4,InsData(Piano1)); AssignVoice(5,InsData(Piano1)); AssignVoice(6,InsData(Piano1)); if CurrentFMMode=Melodic then begin AssignVoice(7,InsData(Piano1)); AssignVoice(8,InsData(Piano1)); AssignVoice(9,InsData(Piano1)); end else begin AssignVoice(7,InsData(BDrum1)); AssignVoice(8,InsData(Snare1)); AssignVoice(9,InsData(Tom1)); AssignVoice(10,InsData(Cymbal1)); AssignVoice(11,InsData(HiHat1)) end; ResetPitch end; {ResetSynth} function FMStatus(voice : byte) : InsDataPtr; begin {FMStatus} with TmpInsData do begin Mode := 0; PercVoice := 0; if (Voice in [7..11]) and (CurrentFMMode=Rhythmic) then begin Mode := 1; PercVoice := Voice-1 end; with Op0 do begin FreqMult := (FMRegisters[$20+R_OpCell[Voice][0]] and $0F); KSR := (FMRegisters[$20+R_OpCell[Voice][0]] and $10) shr 4; EG := (FMRegisters[$20+R_OpCell[Voice][0]] and $20) shr 5; Vib := (FMRegisters[$20+R_OpCell[Voice][0]] and $40) shr 6; AM := (FMRegisters[$20+R_OpCell[Voice][0]] and $80) shr 7; Output := (FMRegisters[$40+R_OpCell[Voice][0]] and $3F); KSL := (FMRegisters[$40+R_OpCell[Voice][0]]) shr 6; Decay := (FMRegisters[$60+R_OpCell[Voice][0]] and $0F); Attack := (FMRegisters[$60+R_OpCell[Voice][0]]) shr 4; Release := (FMRegisters[$80+R_OpCell[Voice][0]] and $0F); SustLevel := (FMRegisters[$80+R_OpCell[Voice][0]]) shr 4; if (Mode=0) or (Voice<=7) then begin FM := (FMRegisters[$C0+Voice-1] and $01); FeedBack := (FMRegisters[$C0+Voice-1] and $0E) shr 1; end else begin FM := 0; Feedback := 0; end; end; Wave0 := (FMRegisters[$E0+R_OpCell[Voice][0]] and $03); if (Voice in [8..11]) and (CurrentFMMode=Rhythmic) then with Op1 do begin Attack := 15; SustLevel := 15; Decay := 15; Release := 15; KSL := 0; FreqMult := 0; FeedBack := 0; EG := 0; Output := 63; AM := 0; Vib := 0; KSR := 0; FM := 0; Wave1 := 0 end else with Op1 do begin FreqMult := (FMRegisters[$20+M_OpCell[Voice][1]] and $0F); KSR := (FMRegisters[$20+M_OpCell[Voice][1]] and $10) shr 4; EG := (FMRegisters[$20+M_OpCell[Voice][1]] and $20) shr 5; Vib := (FMRegisters[$20+M_OpCell[Voice][1]] and $40) shr 6; AM := (FMRegisters[$20+M_OpCell[Voice][1]] and $80) shr 7; Output := (FMRegisters[$40+M_OpCell[Voice][1]] and $3F); KSL := (FMRegisters[$40+M_OpCell[Voice][1]]) shr 6; Decay := (FMRegisters[$60+M_OpCell[Voice][1]] and $0F); Attack := (FMRegisters[$60+M_OpCell[Voice][1]]) shr 4; Release := (FMRegisters[$80+M_OpCell[Voice][1]] and $0F); SustLevel := (FMRegisters[$80+M_OpCell[Voice][1]]) shr 4; FM := 0; Feedback := 0; Wave1 := (FMRegisters[$E0+M_OpCell[Voice][1]] and $03) end end; FMStatus := @TmpInsData end; {FMStatus} procedure FMInit(Base : word); begin {FMInit} BaseReg := Base; Install := true; AdLibInstalled := IsAdLib; Install := false; if not(AdLibInstalled) then FMError := 1 else begin FMError := 0; ResetRegisters; ResetTimers; SetFMMode(Rhythmic); SetMelRhythm(OFF); ResetSynth end end; {FMInit} function IsAdLib : boolean; assembler; asm {IsAdLib} call ResetTimers mov dx,BaseReg in al,dx {Read T1} push ax {Save T1} mov ah,0FFh mov al,02h call OutCmd {Set Timer 1 latch} mov ah,21h mov al,04h call OutCmd {Unmask & start T1} mov dx,BaseReg mov cx,200 @Again: in al,dx loop @Again {100 uSec delay for timer-1 overflow} {al = T2} push ax call ResetTimers pop bx {T2 in bl} pop ax {T1 in al} and bl,0E0h cmp bl,0C0h jnz @AdLibNotFound and al,0E0h cmp al,0 jnz @AdLibNotFound mov ax,1 {return true} jmp @IsAdLibExit @AdLibNotFound: xor ax,ax {return false} @IsAdLibExit: end; {IsAdLib} function FindBasePort : boolean; const BasePort : array[1..9] of word = ($388,$318,$218,$228,$238,$248,$258,$268,$288); var i : byte; begin {FindBasePort} i := 1; repeat FMInit(BasePort[i]); inc(i) until (FMError=0) or (i>9); FindBasePort := FMError=0; end; {FindBasePort} function FindSBPBasePort : word; const BasePort : array[1..2] of word = ($248,$228); var i : byte; J,K : byte; begin {FindSBPBasePort} i := 1; repeat FMInit(BasePort[i]); if FMError=0 then begin Port[BaseReg-4] := $06; J := Port[BaseReg-3]; Port[BaseReg-4] := $06; Port[BaseReg-3] := $26; Port[BaseReg-4] := $06; K := Port[BaseReg-3]; if K<>$37 then FMError := 8 else Port[BaseReg-3] := J; end; inc(i) until (FMError=0) or (i>2); if FMError=0 then FindSBPBasePort := BaseReg else FindSBPBasePort := 0 end; {FindSBPBasePort} Procedure WhoKnows; begin {FM} FMError := 0; BaseReg := $0388; CurrentFMMode := Undefined end; end. {FM}
(***************************************************************************** * Pascal Solution to "Interesting Intersections" from the * * * * Seventh Annual UCF ACM UPE High School Programming Tournament * * May 15, 1993 * * * * This program determines whether a given line segment intersects a given * * circle. * *****************************************************************************) program Segment( input, output ); var infile : text; (* Input data file *) cx, cy, cr, (* Center and radius of the circle *) a, b, c, d : real; (* (a,b) and (c,d) define the line segment *) (****************************************************************************** * Exchanges the values of a and b. * ******************************************************************************) procedure Swap( var a, b : real ); var temp : real; begin temp := a; a := b; b := temp; end; (****************************************************************************** * Determines whether the line segment with endpoints (a,b) and (c,d) * * intersects the circle with center (0,0) and radius cr. * * * * Method: * * The equation of the circle is x^2 + y^2 = r^2. The equation of the * * line containing the line segment is y = mx + B, where m = (b-d)/(a-c) and * * B = a(b-d)/(a-c)+b. Substituting the equation of the line into the * * equation of the circle, we get * * x^2 + (mx+B)^2 = r^2, or * * x^2 + (mx)^2 + 2mxB + B^2 = r^2, or * * (1+m^2)x^2 + (2mB)x + (B^2 - r^2) = 0 * * which is a quadratic in x. Therefore, there are 0, 1, or 2 real solutions * * for x. If there are 0 solutions (i.e., 2 complex roots of the equation) * * then the line segment does not intersect the circle. If there is at least * * 1 solution, compute the corresponding y for each x using the equation for * * the line given above, and check whether that point is in between the * * endpoints of the line segment. We only need one point to be in between * * the two endpoints for the line segment to intersect the circle. * * * * Special case: If the line segment is vertical, the equation of the line * * becomes x = a. This is substituted into the equation for * * the circle, obtaining * * a^2 + y^2 = r^2, or * * y^2 = r^2 - a^2 * * As before, there are 0, 1, or 2 real solutions of this * * equation. Note that if there is a real solution for y, we * * already know the x coordinate (since x = a) and hence we * * only need to check that the point (a,y) is between the two * * endpoints of the line segment. * * * * Returns * * Boolean: Does the line segment intersect the circle? * ******************************************************************************) function Intersects : boolean; var m, (* Slope of the line segment *) k, (* Temp variable *) discr, (* Discriminant of quadratic formula *) x, y : real; (* Possible intersection point *) result : boolean; (* Whether the line segment intersects the circle *) begin result := false; if abs( a-c ) < 0.001 then begin (* The line segment is vertical *) if d < b then Swap( b, d ); discr := cr*cr-a*a; if discr >= 0 then begin k := sqrt(discr); result := ((b <= k) and (k <= d)) or ((b <= -k) and (-k <= d)); end; end else begin (* The line segment is not vertical *) m := (b-d)/(a-c); k := b-m*a; discr := m*m*k*k-(1+m*m)*(k*k-cr*cr); if c < a then Swap( a, c ); if d < b then Swap( b, d ); if discr >= 0 then begin x := (-m*k+sqrt(discr))/(1+m*m); y := m*x+k; result := (a<=x) and (x<=c) and (b<=y) and (y<=d); if not result then begin x := (-m*k-sqrt(discr))/(1+m*m); y := m*x+k; result := (a<=x) and (x<=c) and (b<=y) and (y<=d); end; end; end; Intersects := result; end; begin assign( infile, 'segment.in' ); reset( infile ); while not eof( infile ) do begin readln( infile, cx, cy, cr ); readln( infile, a, b, c, d ); (* Center the coordinate system at (cx,cy) for simplicity *) a := a - cx; b := b - cy; c := c - cx; d := d - cy; if Intersects then writeln( 'The line segment intersects the circle.' ) else writeln( 'The line segment does not intersect the circle.' ); end; close( infile ); end.
unit FC.StockChart.UnitTask.Calendar.Editor; interface {$I Compiler.inc} uses Types, SysUtils,Classes, BaseUtils, Serialization, StockChart.Definitions.Units,StockChart.Definitions, FC.Definitions, FC.Singletons, FC.StockChart.UnitTask.Base; implementation uses Graphics, StockChart.Definitions.Drawing, StockChart.Drawing, FC.StockChart.UnitTask.Calendar.EditorDialog; type //Специальный Unit Task для автоматического подбора размеров грани и длины периода. //Подюор оусщестьвляется прямым перебором. TStockUnitTaskCalendarEditor = class(TStockUnitTaskBase) public function CanApply(const aIndicator: ISCIndicator; out aOperationName: string): boolean; override; procedure Perform(const aIndicator: ISCIndicator; const aStockChart: IStockChart; const aCurrentPosition: TStockPosition); override; end; { TStockUnitTaskCalendarEditor } function TStockUnitTaskCalendarEditor.CanApply(const aIndicator: ISCIndicator; out aOperationName: string): boolean; begin result:=Supports(aIndicator,ISCIndicatorCalendar); if result then aOperationName:='Calendar: Edit Item'; end; procedure TStockUnitTaskCalendarEditor.Perform(const aIndicator: ISCIndicator; const aStockChart: IStockChart; const aCurrentPosition: TStockPosition); var aCalendar: ISCIndicatorCalendar; aHitTest: TSCHitTestData; begin if aCurrentPosition.X>0 then begin aCalendar:=aIndicator as ISCIndicatorCalendar; aHitTest.Bounds:=TSCGeometry.MakeBoundsRect( aCurrentPosition.X, aCurrentPosition.Y-aIndicator.GetInputData.PointToPrice(1), aCurrentPosition.X, aCurrentPosition.Y+aIndicator.GetInputData.PointToPrice(1)); aHitTest.Tag:=-1; if (aIndicator as ISCIndicatorDrawSupport).HitTest(aHitTest) and (aHitTest.Tag<>-1) then begin TfmCalendarEditorDialog.RunEdit(aCalendar.GetData.GetItem(aHitTest.Tag)); end; end; end; initialization //Регистрируем Unit Task StockUnitTaskRegistry.AddUnitTask(TStockUnitTaskCalendarEditor.Create); end.
// GLMultiProxy {: Implements a multi-proxy objects, useful for discreet LOD.<p> <b>History : </b><font size=-1><ul> <li>23/08/10 - Yar - Added OpenGLTokens to uses, replaced OpenGL1x functions to OpenGLAdapter <li>19/12/06 - DaS - Fixed a bug in TGLMultiProxy.Destroy <li>26/11/03 - EG - Added bounding, raycast and silhouette proxying <li>25/11/03 - EG - Added per-master visibility boolean <li>24/11/03 - EG - Creation </ul></font> } unit GLMultiProxy; interface uses System.Classes, System.SysUtils, OpenGLTokens, GLContext, GLScene, GLVectorGeometry, GLSilhouette, GLRenderContextInfo, GLBaseClasses, GLVectorTypes; type TGLMultiProxy = class; // TGLMultiProxyMaster // {: MasterObject description for a MultiProxy object. } TGLMultiProxyMaster = class (TCollectionItem) private { Private Declarations } FMasterObject : TGLBaseSceneObject; FDistanceMin, FDistanceMin2 : Single; FDistanceMax, FDistanceMax2 : Single; FVisible : Boolean; protected { Protected Declarations } function GetDisplayName : String; override; procedure SetMasterObject(const val : TGLBaseSceneObject); procedure SetDistanceMin(const val : Single); procedure SetDistanceMax(const val : Single); procedure SetVisible(const val : Boolean); public { Public Declarations } constructor Create(Collection : TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; function OwnerObject : TGLMultiProxy; procedure NotifyChange; published { Published Declarations } {: Specifies the Master object which will be proxy'ed. } property MasterObject : TGLBaseSceneObject read FMasterObject write SetMasterObject; {: Minimum visibility distance (inclusive). } property DistanceMin : Single read FDistanceMin write SetDistanceMin; {: Maximum visibility distance (exclusive). } property DistanceMax : Single read FDistanceMax write SetDistanceMax; {: Determines if the master object can be visible (proxy'ed).<p> Note: the master object's distance also has to be within DistanceMin and DistanceMax.} property Visible : Boolean read FVisible write SetVisible default True; end; // TGLMultiProxyMasters // {: Collection of TGLMultiProxyMaster. } TGLMultiProxyMasters = class (TOwnedCollection) private { Private Declarations } protected { Protected Declarations } procedure SetItems(index : Integer; const val : TGLMultiProxyMaster); function GetItems(index : Integer) : TGLMultiProxyMaster; procedure Update(Item: TCollectionItem); override; public { Public Declarations } constructor Create(AOwner : TPersistent); function Add : TGLMultiProxyMaster; overload; function Add(master : TGLBaseSceneObject; distanceMin, distanceMax : Single) : TGLMultiProxyMaster; overload; property Items[index : Integer] : TGLMultiProxyMaster read GetItems write SetItems; default; procedure Notification(AComponent: TComponent); procedure NotifyChange; procedure EndUpdate; override; end; // TGLMultiProxy // {: Multiple Proxy object.<p> This proxy has multiple master objects, which are individually made visible depending on a distance to the camera criterion. It can be used to implement discreet level of detail directly for static objects, or objects that go through cyclic animation.<p> For dimensionsn raycasting and silhouette purposes, the first master is used (item zero in the MasterObjects collection). } TGLMultiProxy = class (TGLSceneObject) private { Private Declarations } FMasterObjects : TGLMultiProxyMasters; FRendering : Boolean; // internal use (loop protection) protected { Protected Declarations } procedure SetMasterObjects(const val : TGLMultiProxyMasters); procedure Notification(AComponent: TComponent; Operation: TOperation); override; function PrimaryMaster : TGLBaseSceneObject; public { Public Declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure DoRender(var rci : TRenderContextInfo; renderSelf, renderChildren : Boolean); override; function AxisAlignedDimensionsUnscaled : TVector; override; function RayCastIntersect(const rayStart, rayVector : TVector; intersectPoint : PVector = nil; intersectNormal : PVector = nil) : Boolean; override; function GenerateSilhouette(const silhouetteParameters : TGLSilhouetteParameters) : TGLSilhouette; override; published { Published Declarations } property MasterObjects : TGLMultiProxyMasters read FMasterObjects write SetMasterObjects; property ObjectsSorting; property Direction; property PitchAngle; property Position; property RollAngle; property Scale; property ShowAxes; property TurnAngle; property Up; property Visible; property OnProgress; property Behaviours; end; //------------------------------------------------------------- //------------------------------------------------------------- //------------------------------------------------------------- implementation //------------------------------------------------------------- //------------------------------------------------------------- //------------------------------------------------------------- // ------------------ // ------------------ TGLMultiProxyMaster ------------------ // ------------------ // Create // constructor TGLMultiProxyMaster.Create(Collection : TCollection); begin inherited Create(Collection); FVisible:=True; end; // Destroy // destructor TGLMultiProxyMaster.Destroy; begin MasterObject:=nil; inherited Destroy; end; // Assign // procedure TGLMultiProxyMaster.Assign(Source: TPersistent); begin if Source is TGLMultiProxyMaster then begin MasterObject:=TGLMultiProxyMaster(Source).MasterObject; FDistanceMin:=TGLMultiProxyMaster(Source).FDistanceMin; FDistanceMin2:=TGLMultiProxyMaster(Source).FDistanceMin2; FDistanceMax:=TGLMultiProxyMaster(Source).FDistanceMax; FDistanceMax2:=TGLMultiProxyMaster(Source).FDistanceMax2; FVisible:=TGLMultiProxyMaster(Source).FVisible; NotifyChange; end else inherited; end; // OwnerObject // function TGLMultiProxyMaster.OwnerObject : TGLMultiProxy; begin Result:=TGLMultiProxy(TGLMultiProxyMasters(Collection).GetOwner); end; // NotifyChange // procedure TGLMultiProxyMaster.NotifyChange; begin TGLMultiProxyMasters(Collection).NotifyChange; end; // GetDisplayName // function TGLMultiProxyMaster.GetDisplayName : String; begin if MasterObject<>nil then Result:=MasterObject.Name else Result:='???'; Result:=Result+Format(' [%.2f; %.2f[', [DistanceMin, DistanceMax]); if not Visible then Result:=Result+' (hidden)'; end; // SetMasterObject // procedure TGLMultiProxyMaster.SetMasterObject(const val : TGLBaseSceneObject); begin if FMasterObject<>val then begin if Assigned(FMasterObject) then FMasterObject.RemoveFreeNotification(OwnerObject); FMasterObject:=val; if Assigned(FMasterObject) then FMasterObject.FreeNotification(OwnerObject); NotifyChange; end; end; // SetDistanceMin // procedure TGLMultiProxyMaster.SetDistanceMin(const val : Single); begin if FDistanceMin<>val then begin FDistanceMin:=val; FDistanceMin2:=Sqr(val); NotifyChange; end; end; // SetDistanceMax // procedure TGLMultiProxyMaster.SetDistanceMax(const val : Single); begin if FDistanceMax<>val then begin FDistanceMax:=val; FDistanceMax2:=Sqr(val); NotifyChange; end; end; // SetVisible // procedure TGLMultiProxyMaster.SetVisible(const val : Boolean); begin if FVisible<>val then begin FVisible:=val; NotifyChange; end; end; // ------------------ // ------------------ TGLMultiProxyMasters ------------------ // ------------------ // Create // constructor TGLMultiProxyMasters.Create(AOwner : TPersistent); begin inherited Create(AOwner, TGLMultiProxyMaster) end; // SetItems // procedure TGLMultiProxyMasters.SetItems(index : Integer; const val : TGLMultiProxyMaster); begin inherited Items[index]:=val; end; // GetItems // function TGLMultiProxyMasters.GetItems(index : Integer) : TGLMultiProxyMaster; begin Result:=TGLMultiProxyMaster(inherited Items[index]); end; // Update // procedure TGLMultiProxyMasters.Update(Item : TCollectionItem); begin inherited; NotifyChange; end; // Add (simple) // function TGLMultiProxyMasters.Add : TGLMultiProxyMaster; begin Result:=(inherited Add) as TGLMultiProxyMaster; end; // Add (classic params) // function TGLMultiProxyMasters.Add(master : TGLBaseSceneObject; distanceMin, distanceMax : Single) : TGLMultiProxyMaster; begin BeginUpdate; Result:=(inherited Add) as TGLMultiProxyMaster; Result.MasterObject:=master; Result.DistanceMin:=distanceMin; Result.DistanceMax:=distanceMax; EndUpdate; end; // Notification // procedure TGLMultiProxyMasters.Notification(AComponent: TComponent); var i : Integer; begin for i:=0 to Count-1 do with Items[i] do if FMasterObject=AComponent then FMasterObject:=nil; end; // NotifyChange // procedure TGLMultiProxyMasters.NotifyChange; begin if (UpdateCount=0) and (GetOwner<>nil) and (GetOwner is TGLUpdateAbleComponent) then TGLUpdateAbleComponent(GetOwner).NotifyChange(Self); end; // EndUpdate // procedure TGLMultiProxyMasters.EndUpdate; begin inherited EndUpdate; // Workaround for a bug in VCL's EndUpdate if UpdateCount=0 then NotifyChange; end; // ------------------ // ------------------ TGLMultiProxy ------------------ // ------------------ // Create // constructor TGLMultiProxy.Create(AOwner: TComponent); begin inherited Create(AOwner); ObjectStyle:=ObjectStyle+[osDirectDraw]; FMasterObjects:=TGLMultiProxyMasters.Create(Self); end; // Destroy // destructor TGLMultiProxy.Destroy; begin inherited Destroy; FMasterObjects.Free; end; // Notification // procedure TGLMultiProxy.Notification(AComponent: TComponent; Operation: TOperation); begin if Operation=opRemove then FMasterObjects.Notification(AComponent); inherited; end; // SetMasterObjects // procedure TGLMultiProxy.SetMasterObjects(const val : TGLMultiProxyMasters); begin FMasterObjects.Assign(val); StructureChanged; end; // Assign // procedure TGLMultiProxy.Assign(Source: TPersistent); begin if Source is TGLMultiProxy then begin MasterObjects:=TGLMultiProxy(Source).MasterObjects; end; inherited; end; // Render // procedure TGLMultiProxy.DoRender(var rci : TRenderContextInfo; renderSelf, renderChildren : Boolean); var i : Integer; oldProxySubObject : Boolean; mpMaster : TGLMultiProxyMaster; master : TGLBaseSceneObject; d2 : Single; begin if FRendering then Exit; FRendering:=True; try d2:=VectorDistance2(rci.cameraPosition, AbsolutePosition); for i:=0 to MasterObjects.Count-1 do begin mpMaster:=MasterObjects[i]; if mpMaster.Visible then begin master:=mpMaster.MasterObject; if (master<>nil) and (d2>=mpMaster.FDistanceMin2) and (d2<mpMaster.FDistanceMax2) then begin oldProxySubObject:=rci.proxySubObject; rci.proxySubObject:=True; GL.MultMatrixf(PGLFloat(master.MatrixAsAddress)); master.DoRender(rci, renderSelf, (master.Count>0)); rci.proxySubObject:=oldProxySubObject; end; end; end; // now render self stuff (our children, our effects, etc.) if renderChildren and (Count>0) then Self.RenderChildren(0, Count-1, rci); // if masterGotEffects then // FMasterObject.Effects.RenderPostEffects(Scene.CurrentBuffer, rci); finally FRendering:=False; end; ClearStructureChanged; end; // PrimaryMaster // function TGLMultiProxy.PrimaryMaster : TGLBaseSceneObject; begin if MasterObjects.Count>0 then Result:=MasterObjects[0].MasterObject else Result:=nil; end; // AxisAlignedDimensions // function TGLMultiProxy.AxisAlignedDimensionsUnscaled : TVector; var master : TGLBaseSceneObject; begin master:=PrimaryMaster; if Assigned(master) then begin Result:=master.AxisAlignedDimensionsUnscaled; end else Result:=inherited AxisAlignedDimensionsUnscaled; end; // RayCastIntersect // function TGLMultiProxy.RayCastIntersect(const rayStart, rayVector : TVector; intersectPoint : PVector = nil; intersectNormal : PVector = nil) : Boolean; var localRayStart, localRayVector : TVector; master : TGLBaseSceneObject; begin master:=PrimaryMaster; if Assigned(master) then begin SetVector(localRayStart, AbsoluteToLocal(rayStart)); SetVector(localRayStart, master.LocalToAbsolute(localRayStart)); SetVector(localRayVector, AbsoluteToLocal(rayVector)); SetVector(localRayVector, master.LocalToAbsolute(localRayVector)); NormalizeVector(localRayVector); Result:=master.RayCastIntersect(localRayStart, localRayVector, intersectPoint, intersectNormal); if Result then begin if Assigned(intersectPoint) then begin SetVector(intersectPoint^, master.AbsoluteToLocal(intersectPoint^)); SetVector(intersectPoint^, LocalToAbsolute(intersectPoint^)); end; if Assigned(intersectNormal) then begin SetVector(intersectNormal^, master.AbsoluteToLocal(intersectNormal^)); SetVector(intersectNormal^, LocalToAbsolute(intersectNormal^)); end; end; end else Result:=False; end; // GenerateSilhouette // function TGLMultiProxy.GenerateSilhouette(const silhouetteParameters : TGLSilhouetteParameters) : TGLSilhouette; var master : TGLBaseSceneObject; begin master:=PrimaryMaster; if Assigned(master) then Result:=master.GenerateSilhouette(silhouetteParameters) else Result:=nil; end; //------------------------------------------------------------- //------------------------------------------------------------- //------------------------------------------------------------- initialization //------------------------------------------------------------- //------------------------------------------------------------- //------------------------------------------------------------- RegisterClasses([TGLMultiProxy]); end.
unit main; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, LedNumber; type { TForm1 } TForm1 = class(TForm) Bevel1: TBevel; cbZeroToO: TCheckBox; cbSlanted: TCheckBox; edCaption: TEdit; lblSize: TLabel; lblCaption: TLabel; LEDNumber1: TLEDNumber; Panel1: TPanel; sbSize: TScrollBar; procedure cbSlantedChange(Sender: TObject); procedure cbZeroToOChange(Sender: TObject); procedure edCaptionChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure sbSizeChange(Sender: TObject); private procedure UpdateLED; public end; var Form1: TForm1; implementation {$R *.lfm} { TForm1 } procedure TForm1.cbSlantedChange(Sender: TObject); begin LEDNumber1.Slanted := cbSlanted.Checked; end; procedure TForm1.cbZeroToOChange(Sender: TObject); begin LEDNumber1.ZeroToO := cbZeroToO.Checked; end; procedure TForm1.edCaptionChange(Sender: TObject); begin UpdateLED; end; procedure TForm1.FormCreate(Sender: TObject); begin UpdateLED; end; procedure TForm1.sbSizeChange(Sender: TObject); begin LEDNumber1.Size := sbSize.Position; end; procedure TForm1.UpdateLED; var i, n: Integer; begin n := 0; for i := 1 to Length(edCaption.Text) do if not (edCaption.Text[i] in ['.', ',']) then inc(n); LEDNumber1.Columns := n; LEDNumber1.Caption := edCaption.Text; end; end.
unit WinBase; interface uses Windows, Messages; type TAppIdeEvent = procedure of object; TWinApp = class(TObject) public constructor Create; function MainWndProc(hWnd: HWND; uMsg: UINT; wParam: wPARAM; lParam: LPARAM): HRESULT; stdcall; private FInstance: THandle; FPlugin: THandle; FWnd: HWND; FMenu: HMENU; FOnIde: TAppIdeEvent; procedure SetWnd(Wnd: HWND); function GetExeName: string; procedure SetPlugin(const Value: THandle); procedure SetMenu(const Value: HMENU); procedure SetOnIde(const Value: TAppIdeEvent); procedure AppIdeEvent; public property HPlugin: THandle read FPlugin write SetPlugin; property MainWnd: HWND read FWnd write SetWnd; property ExeName: string read GetExeName; property MainMenu: HMENU read FMenu write SetMenu; property HInstance: THandle read FInstance; property OnIde: TAppIdeEvent read FOnIde write SetOnIde; end; TWnd = class(TObject) private FMenu: HMenu; procedure SetMenu(const Value: HMenu); public constructor Create(hParent: HWND); destructor Destroy; override; procedure DefaultHandler(var Message); override; function MainWndProc(hWnd: HWND; uMsg: UINT; wParam: wPARAM; lParam: LPARAM): HRESULT; stdcall; public Handle: HWND; protected procedure WndProc(var Message: TMessage); virtual; public property MainMenu: HMenu read FMenu write SetMenu; end; TWndFrame = class(TWnd) private protected public constructor Create(lpClassName: PChar; lpWndName: PChar; dwStyle: DWORD; x, y, Width, Height: integer; hParentWnd: HWND; hMenu: HMENU); published end; TDialog = class(TWnd) public procedure DefaultHandler(var Message); override; function DoModal(hWndParent: HWND): Integer; virtual; end; PWndProc = ^TWndProc; TWndProc = function(hWnd: HWND; uMsg: UINT; wParam: WPARAM; lParam: LPARAM): HRESULT; stdcall; function g_WndProc(hWnd: HWND; uMsg: Cardinal; wParam: WPARAM; lParam: LPARAM): HRESULT; stdcall; function g_DlgProc(hDlg: HWND; uMsg: Cardinal; wParam: WPARAM; lParam: LPARAM): BOOL; stdcall; function Application: TWinApp; implementation { TWinApp } constructor TWinApp.Create; begin FInstance := GetModuleHandle(nil); FOnIde := AppIdeEvent; end; procedure TWinApp.SetWnd(Wnd: HWND); begin FWnd := Wnd; end; function TWinApp.GetExeName: string; begin Result := ParamStr(0); end; procedure TWinApp.SetPlugin(const Value: THandle); begin FPlugin := Value; end; procedure TWinApp.SetMenu(const Value: HMENU); begin FMenu := Value; end; { Global Function } function g_DlgProc(hDlg: HWND; uMsg: Cardinal; wParam: WPARAM; lParam: LPARAM): BOOL; var Message: TMessage; Dlg: TWnd; begin Message.Msg := uMsg; Message.LParam := lParam; Message.WParam := wParam; Message.Result := 0; if uMsg = WM_INITDIALOG then begin Dlg := TWnd(GetWindowLong(hDlg, GWL_USERDATA)); if Dlg = nil then begin SetWindowLong(hDlg, GWL_USERDATA, Integer(lParam)); Dlg := TWnd(lParam); end; Dlg.Handle := hDlg; end; Dlg := TWnd(GetWindowLong(hDlg, GWL_USERDATA)); if Dlg <> nil then begin Dlg.Dispatch(Message); Result := BOOL(Message.Result); if Message.Msg = WM_CLOSE then Dlg.Free; Exit; end; Result := False; end; function g_WndProc(hWnd: HWND; uMsg: Cardinal; wParam: WPARAM; lParam: LPARAM): HRESULT; var lpcs: PCreateStruct; Wnd: TWnd; Message: TMessage; begin Message.Msg := uMsg; Message.WParam := wParam; Message.LParam := lParam; Message.Result := 0; if uMsg = WM_CREATE then begin lpcs := PCreateStruct(lParam); Wnd := TWnd(GetWindowLong(hWnd, GWL_USERDATA)); if Wnd = nil then begin SetWindowLong(hWnd, GWL_USERDATA, Integer(lpcs.lpCreateParams)); Wnd := TWnd(lpcs.lpCreateParams); Wnd.Handle := hWnd; end; end; Wnd := TWnd(GetWindowLong(hWnd, GWL_USERDATA)); if Wnd <> nil then begin Wnd.Dispatch(Message); if Message.Msg = WM_DESTROY then begin SetWindowLong(Wnd.Handle, GWL_USERDATA, 0); Wnd.Free; end; Result := Message.Result; Exit; end; Result := DefWindowProc(hWnd, uMsg, wParam, lParam); end; function TWinApp.MainWndProc(hWnd: HWND; uMsg: UINT; wParam: wPARAM; lParam: LPARAM): HRESULT; var lpcs: PCreateStruct; Wnd: TWnd; Message: TMessage; begin Message.Msg := uMsg; Message.WParam := wParam; Message.LParam := lParam; Message.Result := 0; if uMsg = WM_CREATE then begin lpcs := PCreateStruct(lParam); Wnd := TWnd(GetWindowLong(hWnd, GWL_USERDATA)); if Wnd = nil then begin SetWindowLong(hWnd, GWL_USERDATA, Integer(lpcs.lpCreateParams)); Wnd := TWnd(lpcs.lpCreateParams); Wnd.Handle := hWnd; end; end; Wnd := TWnd(GetWindowLong(hWnd, GWL_USERDATA)); if Wnd <> nil then begin Wnd.Dispatch(Message); if Message.Msg = WM_DESTROY then begin SetWindowLong(Wnd.Handle, GWL_USERDATA, 0); Wnd.Free; end; Result := Message.Result; Exit; end; Result := DefWindowProc(hWnd, uMsg, wParam, lParam); end; procedure TWinApp.SetOnIde(const Value: TAppIdeEvent); begin FOnIde := Value; end; procedure TWinApp.AppIdeEvent; begin end; { TWnd } constructor TWnd.Create(hParent: HWND); begin end; procedure TWnd.DefaultHandler(var Message); begin with TMessage(Message) do Result := DefWindowProc(Handle, Msg, WParam, LParam); end; destructor TWnd.Destroy; begin end; var WinApp: TWinApp; function Application: TWinApp; begin if WinApp = nil then begin WinApp := TWinApp.Create; end; Result := WinApp; end; function TWnd.MainWndProc(hWnd: HWND; uMsg: UINT; wParam: wPARAM; lParam: LPARAM): HRESULT; begin Result := 0; end; procedure TWnd.SetMenu(const Value: HMenu); begin FMenu := Value; if Handle <> 0 then Windows.SetMenu(Handle, FMenu); end; procedure TWnd.WndProc(var Message: TMessage); begin end; { TDialog } procedure TDialog.DefaultHandler(var Message); begin end; function TDialog.DoModal(hWndParent: HWND): Integer; begin end; { TWndFrame } constructor TWndFrame.Create(lpClassName, lpWndName: PChar; dwStyle: DWORD; x, y, Width, Height: integer; hParentWnd: HWND; hMenu: HMENU); var WndCls: TWndClassEx; begin if IsWindow(hParentWnd) then begin CreateWindowEx(WS_EX_OVERLAPPEDWINDOW, lpClassName, lpWndName, dwStyle, x, y, Width, Height, hParentWnd, hMenu, Application.HInstance, Self); Exit; end; end; initialization WinApp := nil; finalization if WinApp <> nil then WinApp.Free; end.
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ UltraMIX - AIMP3 plugin Version: 1.4.2 Copyright (c) Lyuter Mail : pro100lyuter@mail.ru ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~} unit UltraMixMain; interface uses Windows, SysUtils, Classes, StrUtils, AIMPCustomPlugin, apiWrappers, apiPlaylists, apiCore, apiMenu, apiActions, apiObjects, apiPlugin, apiMessages, apiFileManager; {$R MenuIcon.res} const UM_PLUGIN_NAME = 'UltraMIX v1.4.2'; UM_PLUGIN_AUTHOR = 'Author: Lyuter'; UM_PLUGIN_SHORT_DESCRIPTION = 'Provide improved algorithm of playlist mixing'; UM_PLUGIN_FULL_DESCRIPTION = 'This plugin allows you to evenly distribute ' + 'all the artists in the playlist.'; // UM_CAPTION = 'UltraMIX'; // UM_HOTKEY_ID = 'UltraMix.Hotkey'; UM_HOTKEY_GROUPNAME_KEYPATH = 'HotkeysGroups\PlaylistSorting'; UM_HOTKEY_DEFAULT_MOD = AIMP_ACTION_HOTKEY_MODIFIER_SHIFT; UM_HOTKEY_DEFAULT_KEY = 77; // 'M' key // UM_CONTEXTMENU_ID = 'UltraMix.Menu'; UM_CONTEXTMENU_ICON = 'MENU_ICON'; type TUMMessageHook = class(TInterfacedObject, IAIMPMessageHook) public procedure CoreMessage(Message: DWORD; Param1: Integer; Param2: Pointer; var Result: HRESULT); stdcall; end; TUMPlugin = class(TAIMPCustomPlugin) private function MakeLocalDefaultHotkey: Integer; procedure CreateActionAndMenu; function GetBuiltInMenu(ID: Integer): IAIMPMenuItem; function LoadMenuIcon(const ResName: string): IAIMPImage; protected UMMessageHook: TUMMessageHook; function InfoGet(Index: Integer): PWideChar; override; stdcall; function InfoGetCategories: Cardinal; override; stdcall; function Initialize(Core: IAIMPCore): HRESULT; override; stdcall; procedure Finalize; override; stdcall; end; TUMPlaylistListener = class(TInterfacedObject, IAIMPPlaylistListener) public procedure Activated; stdcall; procedure Changed(Flags: DWORD); stdcall; procedure Removed; stdcall; end; TUMPlaylistManagerListener = class(TInterfacedObject, IAIMPExtensionPlaylistManagerListener) protected UMPlaylistListener: IAIMPPlaylistListener; UMAttachedPlaylist: IAIMPPlaylist; public procedure PlaylistActivated(Playlist: IAIMPPlaylist); stdcall; procedure PlaylistAdded(Playlist: IAIMPPlaylist); stdcall; procedure PlaylistRemoved(Playlist: IAIMPPlaylist); stdcall; destructor Destroy; override; end; TUMExecuteHandler = class(TInterfacedObject, IAIMPActionEvent) public procedure OnExecute(Data: IInterface); stdcall; end; {--------------------------------------------------------------------} TExIndex = record Index : Integer; RealIndex : Real; end; TAuthorSong = record Name : String; Songs : array of TExIndex; end; TUltraMixer = class(TObject) protected procedure SortAuthors(var Arr: array of TAuthorSong; Low, High: Integer); procedure RandomizeList(var Arr: array of TAuthorSong); public procedure Execute(Playlist: IAIMPPlaylist); end; {--------------------------------------------------------------------} implementation {--------------------------------------------------------------------} procedure ShowErrorMessage(ErrorMessage: String); var DLLName: array[0..MAX_PATH - 1] of Char; FullMessage: String; begin FillChar(DLLName, MAX_PATH, #0); GetModuleFileName(HInstance, DLLName, MAX_PATH); FullMessage := 'Exception in module "' + DLLName + '".'#13#13 + ErrorMessage; MessageBox(0, PChar(FullMessage), UM_CAPTION, MB_ICONERROR); end; {--------------------------------------------------------------------} procedure UpdateActionStatusForActivePlaylist; var PLManager: IAIMPServicePlaylistManager; ActivePL: IAIMPPlaylist; PLProperties: IAIMPPropertyList; PLIsReadOnly: Integer; ActionManager: IAIMPServiceActionManager; Action: IAIMPAction; begin try // Get active playlist CheckResult(CoreIntf.QueryInterface(IID_IAIMPServicePlaylistManager, PLManager)); CheckResult(PLManager.GetActivePlaylist(ActivePL)); // Check "Read only" property CheckResult(ActivePL.QueryInterface(IID_IAIMPPropertyList, PLProperties)); CheckResult(PLProperties.GetValueAsInt32(AIMP_PLAYLIST_PROPID_READONLY, PLIsReadOnly)); PLIsReadOnly := Integer(not Bool(PLIsReadOnly)); // Update Action status for the Playlist CheckResult(CoreIntf.QueryInterface(IID_IAIMPServiceActionManager, ActionManager)); CheckResult(ActionManager.GetByID(MakeString(UM_HOTKEY_ID), Action)); CheckResult(Action.SetValueAsInt32(AIMP_ACTION_PROPID_ENABLED, PLIsReadOnly)); except ShowErrorMessage('"UpdateActionStatusForActivePlaylist" failure!'); end; end; {=========================================================================) TUMPlugin (=========================================================================} function TUMPlugin.InfoGet(Index: Integer): PWideChar; begin case Index of AIMP_PLUGIN_INFO_NAME : Result := UM_PLUGIN_NAME; AIMP_PLUGIN_INFO_AUTHOR : Result := UM_PLUGIN_AUTHOR; AIMP_PLUGIN_INFO_SHORT_DESCRIPTION : Result := UM_PLUGIN_SHORT_DESCRIPTION; AIMP_PLUGIN_INFO_FULL_DESCRIPTION : Result := UM_PLUGIN_FULL_DESCRIPTION; else Result := nil; end; end; function TUMPlugin.InfoGetCategories: Cardinal; begin Result := AIMP_PLUGIN_CATEGORY_ADDONS; end; {-------------------------------------------------------------------- Initialize} function TUMPlugin.Initialize(Core: IAIMPCore): HRESULT; var APlaylistManager: IAIMPServicePlaylistManager; UMServiceMessageDispatcher: IAIMPServiceMessageDispatcher; begin Result := Core.QueryInterface(IID_IAIMPServicePlaylistManager, APlaylistManager); if Succeeded(Result) then begin Result := inherited Initialize(Core); if Succeeded(Result) then try CreateActionAndMenu; // Creating the message hook CheckResult(CoreIntf.QueryInterface(IID_IAIMPServiceMessageDispatcher, UMServiceMessageDispatcher)); UMMessageHook := TUMMessageHook.Create; CheckResult(UMServiceMessageDispatcher.Hook(UMMessageHook)); except Result := E_UNEXPECTED; end; end; end; {-------------------------------------------------------------------- Finalize} procedure TUMPlugin.Finalize; var UMServiceMessageDispatcher: IAIMPServiceMessageDispatcher; begin try // Removing the message hook CheckResult(CoreIntf.QueryInterface(IID_IAIMPServiceMessageDispatcher, UMServiceMessageDispatcher)); CheckResult(UMServiceMessageDispatcher.Unhook(UMMessageHook)); except ShowErrorMessage('"Plugin.Finalize" failure!'); end; inherited; end; {--------------------------------------------------------------------} function TUMPlugin.MakeLocalDefaultHotkey: Integer; var ServiceActionManager: IAIMPServiceActionManager; begin CheckResult(CoreIntf.QueryInterface(IID_IAIMPServiceActionManager, ServiceActionManager)); Result := ServiceActionManager.MakeHotkey(UM_HOTKEY_DEFAULT_MOD, UM_HOTKEY_DEFAULT_KEY); end; function TUMPlugin.LoadMenuIcon(const ResName: string): IAIMPImage; var AContainer: IAIMPImageContainer; AResStream: TResourceStream; AVerInfo: IAIMPServiceVersionInfo; begin if CoreGetService(IID_IAIMPServiceVersionInfo, AVerInfo) then begin if AVerInfo.GetBuildNumber < 1683 then Exit(nil); //#AI - Older version of API has an incorrect definition of the IAIMPImageContainer.SetDataSize method end; CheckResult(CoreIntf.CreateObject(IID_IAIMPImageContainer, AContainer)); AResStream := TResourceStream.Create(HInstance, ResName, RT_RCDATA); try CheckResult(AContainer.SetDataSize(AResStream.Size)); AResStream.ReadBuffer(AContainer.GetData^, AContainer.GetDataSize); CheckResult(AContainer.CreateImage(Result)); finally AResStream.Free; end; end; function TUMPlugin.GetBuiltInMenu(ID: Integer): IAIMPMenuItem; var AMenuService: IAIMPServiceMenuManager; begin CheckResult(CoreIntf.QueryInterface(IAIMPServiceMenuManager, AMenuService)); CheckResult(AMenuService.GetBuiltIn(ID, Result)); end; {-------------------------------------------------------------------- CreateActionAndMenu} procedure TUMPlugin.CreateActionAndMenu; var UMHotkey: IAIMPAction; UMContextMenu: IAIMPMenuItem; begin try // Create hotkey action CheckResult(CoreIntf.CreateObject(IID_IAIMPAction, UMHotkey)); CheckResult(UMHotkey.SetValueAsObject(AIMP_ACTION_PROPID_ID, MakeString(UM_HOTKEY_ID))); CheckResult(UMHotkey.SetValueAsObject(AIMP_ACTION_PROPID_NAME, MakeString(UM_CAPTION))); CheckResult(UMHotkey.SetValueAsInt32(AIMP_ACTION_PROPID_DEFAULTLOCALHOTKEY, MakeLocalDefaultHotkey)); // Geting localized string for the HOTKEY_GROUPNAME CheckResult(UMHotkey.SetValueAsObject(AIMP_ACTION_PROPID_GROUPNAME, MakeString(LangLoadString(UM_HOTKEY_GROUPNAME_KEYPATH)))); CheckResult(UMHotkey.SetValueAsObject(AIMP_ACTION_PROPID_EVENT, TUMExecuteHandler.Create)); // Register the local hotkey in manager CheckResult(CoreIntf.RegisterExtension(IID_IAIMPServiceActionManager, UMHotkey)); // Create menu item CheckResult(CoreIntf.CreateObject(IID_IAIMPMenuItem, UMContextMenu)); CheckResult(UMContextMenu.SetValueAsObject(AIMP_MENUITEM_PROPID_ID, MakeString(UM_CONTEXTMENU_ID))); CheckResult(UMContextMenu.SetValueAsObject(AIMP_MENUITEM_PROPID_ACTION, UMHotkey)); CheckResult(UMContextMenu.SetValueAsInt32(AIMP_MENUITEM_PROPID_STYLE, AIMP_MENUITEM_STYLE_NORMAL)); CheckResult(UMContextMenu.SetValueAsObject(AIMP_MENUITEM_PROPID_PARENT, GetBuiltInMenu(AIMP_MENUID_PLAYER_PLAYLIST_SORTING))); CheckResult(UMContextMenu.SetValueAsObject(AIMP_MENUITEM_PROPID_GLYPH, LoadMenuIcon(UM_CONTEXTMENU_ICON))); // Register the menu item in manager CheckResult(CoreIntf.RegisterExtension(IID_IAIMPServiceMenuManager, UMContextMenu)); // Register PlaylistManagerListener CheckResult(CoreIntf.RegisterExtension(IID_IAIMPServicePlaylistManager, TUMPlaylistManagerListener.Create)); except ShowErrorMessage('"CreateActionAndMenu" failure!'); end; end; {=========================================================================) TUMMessageHook (=========================================================================} procedure TUMMessageHook.CoreMessage(Message: DWORD; Param1: Integer; Param2: Pointer; var Result: HRESULT); var UMServiceActionManager: IAIMPServiceActionManager; UMAction: IAIMPAction; begin case Message of AIMP_MSG_EVENT_LANGUAGE: try // Update the name of group in hotkey settings tab CheckResult(CoreIntf.QueryInterface(IID_IAIMPServiceActionManager, UMServiceActionManager)); CheckResult(UMServiceActionManager.GetByID(MakeString(UM_HOTKEY_ID), UMAction)); CheckResult(UMAction.SetValueAsObject(AIMP_ACTION_PROPID_GROUPNAME, MakeString(LangLoadString(UM_HOTKEY_GROUPNAME_KEYPATH)))); except ShowErrorMessage('"MessageHook.CoreMessage" failure!'); end; end; end; {=========================================================================) TUMPlaylistManagerListener (=========================================================================} destructor TUMPlaylistManagerListener.Destroy; begin try if UMPlaylistListener <> nil then CheckResult(UMAttachedPlaylist.ListenerRemove(UMPlaylistListener)); except ShowErrorMessage('"PlaylistManagerListener.Destroy" failure!'); end; inherited; end; procedure TUMPlaylistManagerListener.PlaylistActivated(Playlist: IAIMPPlaylist); begin try // Register PlaylistListener if UMPlaylistListener = nil then UMPlaylistListener := TUMPlaylistListener.Create else begin if UMAttachedPlaylist <> nil then CheckResult(UMAttachedPlaylist.ListenerRemove(UMPlaylistListener)); end; CheckResult(Playlist.ListenerAdd(UMPlaylistListener)); UMAttachedPlaylist := Playlist; except ShowErrorMessage('"PlaylistManagerListener.PlaylistActivated" failure!'); end; end; procedure TUMPlaylistManagerListener.PlaylistAdded(Playlist: IAIMPPlaylist); begin // end; procedure TUMPlaylistManagerListener.PlaylistRemoved(Playlist: IAIMPPlaylist); begin // end; {=========================================================================) TUMPlaylistListener (=========================================================================} procedure TUMPlaylistListener.Activated; begin UpdateActionStatusForActivePlaylist; end; procedure TUMPlaylistListener.Changed(Flags: DWORD); begin if (AIMP_PLAYLIST_NOTIFY_READONLY and Flags) <> 0 then UpdateActionStatusForActivePlaylist; end; procedure TUMPlaylistListener.Removed; begin // end; {=========================================================================) TUMExecuteHandler (=========================================================================} procedure TUMExecuteHandler.OnExecute(Data: IInterface); var PLManager: IAIMPServicePlaylistManager; ActivePL: IAIMPPlaylist; UMixer: TUltraMixer; begin try CheckResult(CoreIntf.QueryInterface(IID_IAIMPServicePlaylistManager, PLManager)); CheckResult(PLManager.GetActivePlaylist(ActivePL)); // Mixing the active playlist UMixer := TUltraMixer.Create; try UMixer.Execute(ActivePL); finally UMixer.Free; end; except ShowErrorMessage('"ExecuteHandler.OnExecute" failure!'); end; end; {=========================================================================) TUltraMixer (=========================================================================} procedure TUltraMixer.Execute(Playlist: IAIMPPlaylist); var PLPropertyList: IAIMPPropertyList; PLItem: IAIMPPlaylistItem; PLItemInfo: IAIMPFileInfo; PLItemAuthor: IAIMPString; PLItemAuthorStr: String; PLItemCount: Integer; i, j, k , SortedListLength: Integer; RealIndex : Real; AuthorsList : array of TAuthorSong; SortedList : array of TExIndex; begin // Checking the Playlist READONLY status CheckResult(Playlist.QueryInterface(IID_IAIMPPropertyList, PLPropertyList)); CheckResult(PLPropertyList.GetValueAsInt32(AIMP_PLAYLIST_PROPID_READONLY, i)); if i <> 0 then exit; try CheckResult(Playlist.BeginUpdate); // Initialization of variables PLItemCount := Playlist.GetItemCount; SetLength(SortedList, 0); SetLength(AuthorsList, 0); // Filling list of autors for i := 0 to PLItemCount - 1 do begin CheckResult(Playlist.GetItem(i, IID_IAIMPPlaylistItem, PLItem)); CheckResult(PLItem.GetValueAsObject(AIMP_PLAYLISTITEM_PROPID_FILEINFO, IID_IAIMPFileInfo, PLItemInfo)); CheckResult(PLItemInfo.GetValueAsObject(AIMP_FILEINFO_PROPID_ARTIST, IID_IAIMPString, PLItemAuthor)); PLItemAuthorStr := AnsiLowerCase(IAIMPStringToString(PLItemAuthor)); for j := 0 to Length(AuthorsList) - 1 do begin if PLItemAuthorStr = AuthorsList[j].Name then begin SetLength(AuthorsList[j].Songs, Length(AuthorsList[j].Songs)+1); AuthorsList[j].Songs[Length(AuthorsList[j].Songs)-1].Index := i; Break; end else Continue; end; if j > Length(AuthorsList) - 1 then begin k := Length(AuthorsList); SetLength(AuthorsList, k +1); AuthorsList[k].Name := PLItemAuthorStr; SetLength(AuthorsList[k].Songs, 1); AuthorsList[k].Songs[0].Index := i; end; end; // Sorting & rardomizing SortAuthors(AuthorsList, 0, Length(AuthorsList)-1); RandomizeList(AuthorsList); // Main cycle of mixing for i := 0 to Length(AuthorsList) - 1 do begin for j := 0 to Length(AuthorsList[i].Songs) - 1 do begin RealIndex := i + j * PLItemCount / Length(AuthorsList[i].Songs); SortedListLength := Length(SortedList); k := SortedListLength - 1; while (k > 0) and (RealIndex <= SortedList[k].RealIndex) do Dec(k); if k = SortedListLength - 1 then begin SetLength(SortedList, SortedListLength + 1); SortedList[SortedListLength].Index := AuthorsList[i].Songs[j].Index; SortedList[SortedListLength].RealIndex := RealIndex; end else begin SetLength(SortedList, SortedListLength + 1); Move(SortedList[k], SortedList[k + 1], (SortedListLength - k) * SizeOf(SortedList[k])); SortedList[k+1].Index := AuthorsList[i].Songs[j].Index; SortedList[k+1].RealIndex := RealIndex; end; end; end; // Moving playlist entries for i := 0 to PLItemCount - 1 do begin CheckResult(Playlist.GetItem(SortedList[i].Index, IID_IAIMPPlaylistItem, PLItem)); CheckResult(PLItem.SetValueAsInt32(AIMP_PLAYLISTITEM_PROPID_INDEX, PLItemCount - 1)); for j := i to PLItemCount - 1 do begin if (SortedList[j].Index > SortedList[i].Index) and (SortedList[j].Index <= PLItemCount - 1 - i) then SortedList[j].Index := SortedList[j].Index - 1; end; SortedList[i].Index := PLItemCount - 1; end; finally Playlist.EndUpdate; end; end; {--------------------------------------------------------------------} procedure TUltraMixer.RandomizeList(var Arr: array of TAuthorSong); procedure SwapSongs(Auth ,Index1, Index2: Integer); var Tmp: TExIndex; begin Tmp := Arr[Auth].Songs[Index1]; Arr[Auth].Songs[Index1] := Arr[Auth].Songs[Index2]; Arr[Auth].Songs[Index2] := Tmp; end; var i, j, k: Integer; Len: Integer; Randomized : array of Boolean; begin Randomize; for i := 0 to Length(Arr) - 1 do begin Len := Length(Arr[i].Songs); SetLength(Randomized, 0); SetLength(Randomized, Len); for j := 0 to Len - 1 do begin repeat k := Random(Len); until not Randomized[k]; SwapSongs(i, j, k); Randomized[k] := True; end; end; end; {--------------------------------------------------------------------} procedure TUltraMixer.SortAuthors(var Arr: array of TAuthorSong; Low, High: Integer); procedure Swap(Index1, Index2: Integer); var Tmp: TAuthorSong; begin Tmp := Arr[Index1]; Arr[Index1] := Arr[Index2]; Arr[Index2] := Tmp; end; var Mid: Integer; Item : TAuthorSong; ScanUp, ScanDown: Integer; begin if High - Low <= 0 then exit; if High - Low = 1 then begin if Length(Arr[High].Songs) > Length(Arr[Low].Songs) then Swap(Low, High); Exit; end; Mid := (High + Low) shr 1; Item := Arr[Mid]; Swap(Mid, Low); ScanUp := Low + 1; ScanDown := High; repeat while (ScanUp <= ScanDown) and (Length(Arr[ScanUp].Songs) >= Length(Item.Songs)) do Inc(ScanUp); while (Length(Arr[ScanDown].Songs) < Length(Item.Songs)) do Dec(ScanDown); if (ScanUp < ScanDown) then Swap(ScanUp, ScanDown); until (ScanUp >= ScanDown); Arr[Low] := Arr[ScanDown]; Arr[ScanDown] := Item; if (Low < ScanDown - 1) then SortAuthors(Arr, Low, ScanDown - 1); if (ScanDown + 1 < High) then SortAuthors(Arr, ScanDown + 1, High); end; {=========================================================================) THE END (=========================================================================} end.
unit uLembreteDAO; interface uses uLembrete, classes, DB, SysUtils, generics.defaults, generics.collections, Dialogs, uDM, uBaseDAO, FireDAC.Comp.Client; type TLembreteDAO = class(TBaseDAO) private FListaLembrete: TObjectList<TLembrete>; procedure PreencherColecao(Ds: TFDQuery); public constructor Create; destructor Destroy; override; function Inserir(pLembrete: TLembrete): Boolean; function Deletar(pLembrete: TLembrete): Boolean; function Alterar(pLembrete: TLembrete): Boolean; function ListarPorTitulo_Descricao(pConteudo: String): TObjectList<TLembrete>; end; implementation constructor TLembreteDAO.Create; begin inherited; FListaLembrete := TObjectList<TLembrete>.Create; end; destructor TLembreteDAO.Destroy; begin try inherited; if Assigned(FListaLembrete) then FreeAndNil(FListaLembrete); except on e: exception do raise Exception.Create(E.Message); end; end; function TLembreteDAO.Inserir(pLembrete: TLembrete): Boolean; var Sql: String; begin Sql := ' INSERT INTO Lembrete (Titulo, Descricao, DataHora) '+ ' VALUES ( '+ QuotedStr(pLembrete.Titulo) + ',' + QuotedStr(pLembrete.Descricao) + ',' + QuotedStr(FormatDateTime('yyyy-mm-dd hh:mm', pLembrete.DataHora)) + ')'; // Result := ExecutarComando(Sql) > 0; end; function TLembreteDAO.Alterar(pLembrete: TLembrete): Boolean; var Sql: String; begin Sql := ' UPDATE Lembrete ' + ' SET Titulo = ' + QuotedStr(pLembrete.Titulo) + ', ' + ' Descricao = ' + QuotedStr(pLembrete.Descricao) + ', '+ ' DataHora = ' + QuotedStr(FormatDateTime('yyyy-mm-dd hh:mm', pLembrete.DataHora)) + ' WHERE IDLembrete = ' + IntToStr(pLembrete.IDLembrete); // Result := ExecutarComando(Sql) > 0; end; function TLembreteDAO.Deletar(pLembrete: TLembrete): Boolean; var Sql: String; begin Sql := ' DELETE '+ ' FROM Lembrete '+ ' WHERE IDLembrete = ' + IntToStr(pLembrete.IDLembrete) ; // Result := ExecutarComando(Sql) > 0; end; function TLembreteDAO.ListarPorTitulo_Descricao(pConteudo: String): TObjectList<TLembrete>; var Sql: String; begin Result := Nil; Sql := ' SELECT C.IDLembrete, C.Titulo, '+ ' C.Descricao, C.DataHora '+ ' FROM Lembrete C '; if pConteudo = '' then begin Sql := Sql + ' WHERE C.DataHora >= ' + QuotedStr(FormatDateTime('yyyy-mm-dd', Now)); end else begin Sql := Sql + ' WHERE C.Titulo like ' + QuotedStr('%'+pConteudo+'%')+ ' OR C.Descricao like ' + QuotedStr('%'+pConteudo+'%'); end; Sql := Sql + ' ORDER BY C.DataHora '; FQry := RetornarDataSet(Sql); if not (FQry.IsEmpty) then begin PreencherColecao(FQry); Result := FListaLembrete; end; end; procedure TLembreteDAO.PreencherColecao(Ds: TFDQuery); var I: Integer; begin I := 0; FListaLembrete.Clear; while not Ds.eof do begin FListaLembrete.Add(TLembrete.Create); FListaLembrete[I].IDLembrete := Ds.FieldByName('IDLembrete').AsInteger; FListaLembrete[I].Titulo := Ds.FieldByName('Titulo' ).AsString; FListaLembrete[I].Descricao := Ds.FieldByName('Descricao' ).AsString; FListaLembrete[I].DataHora := Ds.FieldByName('DataHora' ).AsDateTime; Ds.Next; I := I + 1; end; end; end.
unit f09_tambahbaru; interface uses buku_handler; { DEKLARASI FUNGSI DAN PROSEDUR } procedure tambah_baru(var data_buku: tabel_buku); { IMPLEMENTASI FUNGSI DAN PROSEDUR } implementation procedure tambah_baru(var data_buku: tabel_buku); { DESKRIPSI : prosedur untuk menambahkan buku baru ke data buku } { PARAMETER : data buku } { KAMUS LOKAL } var temp: buku; { ALGORITMA } begin writeln('Masukkan Informasi buku yang ditambahkan:'); write('Masukkan id buku: '); readln(temp.id_buku); write('Masukkan judul buku: '); readln(temp.judul_buku); write('Masukkan pengarang buku: '); readln(temp.author); write('Masukkan jumlah buku: '); readln(temp.jumlah_buku); write('Masukkan tahun terbit buku: '); readln(temp.tahun_penerbit); write('Masukkan kategori buku: '); readln(temp.kategori); data_buku.sz := data_buku.sz+1; data_buku.t[data_buku.sz-1] := temp; writeln(); writeln('Buku berhasil ditambahkan ke dalam sistem!'); end; end.
{ "RTC Gate Receiver Link" - Copyright 2004-2017 (c) RealThinClient.com (http://www.realthinclient.com) @exclude } unit rtcXGateRecv; interface {$include rtcDefs.inc} uses Classes, SysUtils, rtcTypes, rtcSystem, rtcConn, rtcInfo, rtcGateConst, rtcGateCli, rtcXGateCIDs; type { @Abstract(RTC Gate Receiver Link) Link this component to a TRtcHttpGateClient to handle Group Receive events. } {$IFDEF IDE_XE2up} [ComponentPlatformsAttribute(pidAll)] {$ENDIF} TRtcGateReceiverLink=class(TRtcAbsGateClientLink) private FOnHostConnect: TNotifyEvent; FOnHostDisconnect: TNotifyEvent; FOnHostOffLine: TNotifyEvent; FOnHostClosed: TNotifyEvent; FOnControlEnabled: TNotifyEvent; FOnControlDisabled: TNotifyEvent; FOnLogOut: TNotifyEvent; FOnDisconnect: TNotifyEvent; protected LastConfirmID:word; FHostUserID, FHostGroupID:TGateUID; FHostKey:RtcByteArray; FControlAllowed:boolean; StreamWasReset:boolean; procedure DoDataFilter(Client:TRtcHttpGateClient; Data:TRtcGateClientData; var Wanted:boolean); procedure DoDataReceivedGUI(Client:TRtcHttpGateClient; Data:TRtcGateClientData); procedure DoInfoFilter(Client:TRtcHttpGateClient; Data:TRtcGateClientData; var Wanted:boolean); procedure DoInfoReceivedGUI(Client:TRtcHttpGateClient; Data:TRtcGateClientData); // @exclude procedure Call_AfterLogOut(Sender:TRtcConnection); override; // @exclude procedure Call_OnDataReceived(Sender:TRtcConnection); override; // @exclude procedure Call_OnInfoReceived(Sender:TRtcConnection); override; // @exclude procedure Call_OnReadyToSend(Sender:TRtcConnection); override; // @exclude procedure Call_OnStreamReset(Sender:TRtcConnection); override; // @exclude procedure SetClient(const Value: TRtcHttpGateClient); override; function CompareKeys(const OrigKey,RecvKey:RtcByteArray):boolean; procedure SetControlAllowed(const Value: boolean); virtual; procedure ConfirmLastReceived; function IsMyPackage(Data:TRtcGateClientData):boolean; protected procedure DoOnHostConnect; virtual; procedure DoOnHostDisconnect; virtual; procedure DoOnHostOffLine; virtual; procedure DoOnHostClosed; virtual; procedure DoOnControlEnabled; virtual; procedure DoOnControlDisabled; virtual; procedure DoOnLogOut; virtual; procedure DoOnDisconnect; virtual; protected cid_GroupInvite:word; // needs to be assigned the Group Invitation ID !!! procedure DoInputReset; virtual; procedure DoReceiveStart; virtual; procedure DoReceiveStop; virtual; public constructor Create(AOwner:TComponent); override; destructor Destroy; override; procedure HostInviteAccept(UserID,GroupID:TGateUID; const Key:RtcString); property ControlAllowed:boolean read FControlAllowed write SetControlAllowed; property HostUserID:TGateUID read FHostUserID; property HostGroupID:TGateUID read FHostGroupID; property InviteCallID:word read cid_GroupInvite write cid_GroupInvite; published property OnLogOut:TNotifyEvent read FOnLogOut write FOnLogOut; property OnDisconnect:TNotifyEvent read FOnDisconnect write FOnDisconnect; property OnHostOffLine:TNotifyEvent read FOnHostOffLine write FOnHostOffLine; property OnHostConnect:TNotifyEvent read FOnHostConnect write FOnHostConnect; property OnHostDisconnect:TNotifyEvent read FOnHostDisconnect write FOnHostDisconnect; property OnHostClosed:TNotifyEvent read FOnHostClosed write FOnHostClosed; property OnControlEnabled:TNotifyEvent read FOnControlEnabled write FOnControlEnabled; property OnControlDisabled:TNotifyEvent read FOnControlDisabled write FOnControlDisabled; end; implementation { TRtcGateReceiverLink } constructor TRtcGateReceiverLink.Create(AOwner: TComponent); begin inherited; FControlAllowed:=False; end; destructor TRtcGateReceiverLink.Destroy; begin Client:=nil; inherited; end; function TRtcGateReceiverLink.CompareKeys(const OrigKey,RecvKey:RtcByteArray):boolean; var a:integer; begin if length(OrigKey)>length(RecvKey) then Result:=False else begin Result:=True; for a:=0 to length(OrigKey)-1 do if OrigKey[a]<>RecvKey[a] then begin Result:=False; Break; end; end; end; procedure TRtcGateReceiverLink.DoOnControlDisabled; begin if assigned(FOnControlDisabled) then FOnControlDisabled(self); end; procedure TRtcGateReceiverLink.DoOnControlEnabled; begin if assigned(FOnControlEnabled) then FOnControlEnabled(self); end; procedure TRtcGateReceiverLink.DoOnDisconnect; begin if assigned(FOnDisconnect) then FOnDisconnect(self); end; procedure TRtcGateReceiverLink.DoOnHostClosed; begin if assigned(FOnHostClosed) then FOnHostClosed(self); end; procedure TRtcGateReceiverLink.DoOnHostConnect; begin if assigned(FOnHostConnect) then FOnHostConnect(self); end; procedure TRtcGateReceiverLink.DoOnHostDisconnect; begin if assigned(FOnHostDisconnect) then FOnHostDisconnect(self); end; procedure TRtcGateReceiverLink.DoOnHostOffLine; begin if assigned(FOnHostOffLine) then FOnHostOffLine(self); end; procedure TRtcGateReceiverLink.DoOnLogOut; begin if assigned(FOnLogOut) then FOnLogOut(self); end; procedure TRtcGateReceiverLink.ConfirmLastReceived; var toID:word; begin toID:=LastConfirmID; if toID>0 then begin Client.SendBytes(FHostUserID,FHostGroupID,cid_GroupConfirmRecv,Word2Bytes(toID)); LastConfirmID:=0; end; end; procedure TRtcGateReceiverLink.SetClient(const Value: TRtcHttpGateClient); begin if Value=Client then Exit; if assigned(Client) then begin DoReceiveStop; if assigned(Client) then if Client.Ready then if Groups.GetStatus(FHostUserID,FHostGroupID)>=10 then Client.RemUserFromGroup(FHostUserID,FHostGroupID,Client.MyUID); end; StreamWasReset:=False; inherited; end; procedure TRtcGateReceiverLink.HostInviteAccept(UserID,GroupID:TGateUID; const Key:RtcString); begin if (UserID>0) and (GroupID>0) and (length(Key)>0) then if assigned(Client) and Client.Ready then begin if (FHostUserID>0) and (FHostGroupID>0) then begin DoReceiveStop; if assigned(Client) then if Client.Ready then if Groups.GetStatus(FHostUserID,FHostGroupID)>=10 then Client.RemUserFromGroup(FHostUserID,HostGroupID,Client.MyUID); Groups.ClearStatus(FHostUserID,FHostGroupID); end; FHostUserID:=UserID; FHostGroupID:=GroupID; FHostKey:=RtcStringToBytes(Key); DoReceiveStart; Groups.SetStatus(FHostUserID,FHostGroupID,5); Client.AddFriend(FHostUserID); Client.SendBytes(FHostUserID,FHostGroupID,cid_GroupAccept,FHostKey); end; end; procedure TRtcGateReceiverLink.Call_AfterLogOut(Sender: TRtcConnection); begin if Client=nil then Exit; if assigned(Sender) then if not Sender.inMainThread then begin Sender.Sync(Call_AfterLogOut); Exit; end; Groups.ClearAllStates; DoOnLogOut; inherited; end; procedure TRtcGateReceiverLink.DoDataFilter(Client: TRtcHttpGateClient; Data: TRtcGateClientData; var Wanted: boolean); begin if (Client=nil) or (FHostUserID=0) or (FHostGroupID=0) or (Data.UserID<>FHostUserID) then Exit; if Data.CallID=cid_GroupInvite then begin if Data.Footer then Wanted:=Groups.GetMinStatus(Data.UserID)>0 else if Data.Header then Data.ToBuffer:=Groups.GetMinStatus(Data.UserID)>0; end else begin case Data.CallID of cid_GroupClosed: if Data.Footer then Wanted:=(Groups.GetStatus(Data.UserID,Data.GroupID)>0) else if Data.Header then Data.ToBuffer:=(Groups.GetStatus(Data.UserID,Data.GroupID)>0); cid_GroupAllowControl: if Data.Footer then Wanted:=(Groups.GetStatus(Data.UserID,Data.ToGroupID)=10) else if Data.Header then Data.ToBuffer:=(Groups.GetStatus(Data.UserID,Data.ToGroupID)=10); cid_GroupDisallowControl: if Data.Footer then Wanted:=(Groups.GetStatus(Data.UserID,Data.ToGroupID)=20) else if Data.Header then Data.ToBuffer:=(Groups.GetStatus(Data.UserID,Data.ToGroupID)=20); end; end; end; procedure TRtcGateReceiverLink.DoDataReceivedGUI(Client: TRtcHttpGateClient; Data: TRtcGateClientData); procedure ProcessInvite; begin if CompareKeys(FHostKey, Data.Content) then begin if Groups.GetStatus(Data.UserID, Data.ToGroupID)<10 then begin Groups.ClearStatus(FHostUserID,FHostGroupID); FHostUserID:=Data.UserID; FHostGroupID:=Data.ToGroupID; Groups.SetStatus(Data.UserID,FHostGroupID,5); ControlAllowed:=False; AddFriend(FHostUserID); SendBytes(FHostUserID,FHostGroupID,cid_GroupAccept,Data.Content); end; end; end; procedure ProcessClosed; begin DoInputReset; Groups.SetStatus(Data.UserID, Data.GroupID, 1); LeaveUsersGroup(Data.UserID, Data.GroupID); ControlAllowed:=False; DoOnHostClosed; end; procedure ProcessAllowControl; begin Groups.SetStatus(Data.UserID, Data.ToGroupID, 20); ControlAllowed:=True; DoOnControlEnabled; end; procedure ProcessDisallowControl; begin Groups.SetStatus(Data.UserID, Data.ToGroupID, 10); ControlAllowed:=False; DoOnControlDisabled; end; begin if (Client=nil) or (FHostUserID=0) or (FHostGroupID=0) or (Data.UserID<>FHostUserID) then Exit; if Data.CallID=cid_GroupInvite then ProcessInvite else case Data.CallID of cid_GroupClosed: ProcessClosed; cid_GroupAllowControl: ProcessAllowControl; cid_GroupDisallowControl: ProcessDisallowControl; end; end; procedure TRtcGateReceiverLink.Call_OnDataReceived(Sender: TRtcConnection); begin if Filter(DoDataFilter,Sender) then CallGUI(DoDataReceivedGUI,Sender); inherited; end; procedure TRtcGateReceiverLink.DoInfoFilter(Client: TRtcHttpGateClient; Data: TRtcGateClientData; var Wanted: boolean); begin if (Client=nil) or (FHostUserID=0) or (FHostGroupID=0) or (Data.UserID<>FHostUserID) then Exit; case Data.Command of gc_UserOffline: Wanted:=Groups.GetMinStatus(Data.UserID)>0; gc_JoinedUser: Wanted:=Groups.GetStatus(Data.UserID, Data.GroupID) in [5..9]; gc_LeftUser: Wanted:=Groups.GetStatus(Data.UserID, Data.GroupID)>0; end; end; procedure TRtcGateReceiverLink.DoInfoReceivedGUI(Client: TRtcHttpGateClient; Data: TRtcGateClientData); begin if (Client=nil) or (FHostUserID=0) or (FHostGroupID=0) or (Data.UserID<>FHostUserID) then Exit; case Data.Command of gc_UserOffline: begin DoInputReset; ControlAllowed:=False; Groups.SetStatus(Data.UserID,FHostGroupID,1); DoOnHostOffLine; end; gc_JoinedUser: begin DoInputReset; Groups.SetStatus(Data.UserID,Data.GroupID,10); ControlAllowed:=False; DoOnHostConnect; end; gc_LeftUser: begin DoInputReset; Groups.SetStatus(Data.UserID,Data.GroupID,1); ControlAllowed:=False; DoOnHostDisconnect; end; end; end; procedure TRtcGateReceiverLink.Call_OnInfoReceived(Sender: TRtcConnection); begin if Filter(DoInfoFilter,Sender) then CallGUI(DoInfoReceivedGUI,Sender); inherited; end; procedure TRtcGateReceiverLink.Call_OnStreamReset(Sender: TRtcConnection); begin if (Client=nil) or (FHostUserID=0) or (FHostGroupID=0) then Exit; if not Sender.inMainThread then begin Sender.Sync(Call_OnStreamReset); Exit; end; if Groups.GetStatus(FHostUserID,FHostGroupID)>0 then begin DoInputReset; StreamWasReset:=True; Groups.SetStatus(FHostUserID,FHostGroupID,1); ControlAllowed:=False; DoOnDisconnect; end; inherited; end; procedure TRtcGateReceiverLink.Call_OnReadyToSend(Sender: TRtcConnection); begin if (Client=nil) or (FHostUserID=0) or (FHostGroupID=0) then Exit; if StreamWasReset then if Client.Ready then begin StreamWasReset:=False; Groups.SetStatus(FHostUserID,FHostGroupID,5); ControlAllowed:=False; Client.AddFriend(FHostUserID); Client.SendBytes(FHostUserID,FHostGroupID,cid_GroupAccept,FHostKey); end; inherited; end; procedure TRtcGateReceiverLink.SetControlAllowed(const Value: boolean); begin FControlAllowed:=Value; end; function TRtcGateReceiverLink.IsMyPackage(Data:TRtcGateClientData): boolean; begin Result := Groups.GetStatus(Data.UserID,Data.GroupID)>=10; end; procedure TRtcGateReceiverLink.DoInputReset; begin // Input Stream was reset, initialize input stream data end; procedure TRtcGateReceiverLink.DoReceiveStart; begin // prepare stream for receiving end; procedure TRtcGateReceiverLink.DoReceiveStop; begin // stop and release receiving stream end; end.
unit mdf_AddRestrFieldToInv_BalanceOption; interface uses IBDatabase, gdModify; procedure AddRestrFieldToInv_BalanceOption(IBDB: TIBDatabase; Log: TModifyLog); implementation uses IBSQL, SysUtils, mdf_MetaData_unit; procedure AddRestrFieldToInv_BalanceOption(IBDB: TIBDatabase; Log: TModifyLog); var FTr: TIBTransaction; q: TIBSQL; begin FTr := TIBTransaction.Create(nil); try FTr.DefaultDatabase := IBDB; FTr.StartTransaction; q := TIBSQL.Create(nil); try q.Transaction := FTr; try AddField2('INV_BALANCEOPTION', 'RESTRICTREMAINSBY', 'DTEXT32', FTr); q.SQL.Text := 'UPDATE OR INSERT INTO fin_versioninfo ' + ' VALUES (262, ''0000.0001.0000.0293'', ''31.03.2017'', ''Added restrict remains field to INV_BALANCEOPTION'') ' + ' MATCHING (id)'; q.ExecQuery; FTr.Commit; except on E: Exception do begin Log('Произошла ошибка: ' + E.Message); if FTr.InTransaction then FTr.Rollback; raise; end; end; finally q.Free; end; finally FTr.Free; end; end; end.
{*******************************************************} { } { Delphi Visual Component Library } { Copyright(c) 2012-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit ExpertsUIIniOptions; interface uses IniFiles, WizardAPI, Classes, Variants; type TWizardIniOptions = class; TOptionChangeEvent = procedure(AIniFile: TIniFile; const SectionName, OptionName: string; const Value: Variant) of object; TWizardIniOptions = class(TPersistent) private FIniFile: TIniFile; FSectionName: string; FOptions: TStringList; FOnOptionChange: TOptionChangeEvent; function GetOptionData(const Name: string): TObject; procedure SetOptionData(const Name: string; const Value: TObject); class procedure OptionChanged(AIniFile: TIniFile; const SectionName, OptionName: string; const Value: Variant); protected procedure SetOption(const Name: string; const Value: Variant); property SectionName: string read FSectionName; procedure AssignTo(Dest: TPersistent); override; procedure DoOptionChange(const OptionName: string; const Value: Variant); public constructor Create(const SectionName: string; AIniFile: TIniFile; OnChangeEvent: TOptionChangeEvent = nil); destructor Destroy; override; class procedure InitOptions(const AIniFileName: string; out AUIOptions: TWizardIniOptions); static; procedure EnsureOption(const OptionStr: string); function GetOptionValue(const Name: string): Variant; function GetOption(const Name: string; const Default: Variant): Variant; procedure InitializeOptions(const Values: array of string); overload; procedure InitializeOptions(const Values: TStrings); overload; function IsTrue(const Name: string): Boolean; property Options[const Name: string]: Variant read GetOptionValue write SetOption; default; property OptionData[const Name: string]: TObject read GetOptionData write SetOptionData; procedure Assign(Source: TPersistent); override; procedure Clear; property OnOptionChange: TOptionChangeEvent read FOnOptionChange write FOnOptionChange; end; implementation uses Graphics, Math, SysUtils, ToolsAPI, Forms, Dialogs, Controls; const fnOptionsFile = 'DSSampleWizard.ini'; STrue = 'True'; { Ini File Sections } SWizardUI = 'Wizard State'; class procedure TWizardIniOptions.InitOptions(const AIniFileName: string; out AUIOptions: TWizardIniOptions); var LIniFile: TIniFile; procedure LoadOptions(const Section: string; Options: TWizardIniOptions); var IniValues: TStrings; begin IniValues := TStringList.Create; try LIniFile.ReadSectionValues(Section, IniValues); if IniValues.Count = 0 then Exit; Options.InitializeOptions(IniValues); finally IniValues.Free; end; end; function GetIniDirectory: string; var OTAServices: IOTAServices; begin if (BorlandIDEServices <> nil) and Supports(BorlandIDEServices, IOTAServices, OTAServices) then Result := OTAServices.GetApplicationDataDirectory else Result := ExtractFilePath(ParamStr(0)); Result := IncludeTrailingPathDelimiter(Result); end; begin LIniFile := TIniFile.Create(GetIniDirectory+AIniFileName); AUIOptions := TWizardIniOptions.Create(SWizardUI, LIniFile, OptionChanged); LoadOptions(SWizardUI, AUIOptions); end; class procedure TWizardIniOptions.OptionChanged(AIniFile: TIniFile; const SectionName, OptionName: string; const Value: Variant); begin if OptionName <> '' then AIniFile.WriteString(SectionName, OptionName, Value) else AIniFile.EraseSection(SectionName); end; { TWizardIniOptions } constructor TWizardIniOptions.Create(const SectionName: string; AIniFile: TIniFile; OnChangeEvent: TOptionChangeEvent = nil); begin //FWebWizardContext := TWebWizardContext.Create; FOptions := TStringList.Create; FIniFile := AIniFile; FSectionName := SectionName; if Assigned(OnChangeEvent) then FOnOptionChange := OnChangeEvent; inherited Create; end; destructor TWizardIniOptions.Destroy; var I: Integer; begin //FWebWizardContext.Free; { We are assumed to be the owner of any objects placed into the OptionData properties } for I := 0 to FOptions.Count - 1 do FOptions.Objects[I].Free; FOptions.Free; FIniFile.Free; inherited; end; procedure TWizardIniOptions.Assign(Source: TPersistent); var I, ValPos: Integer; S: string; Strings: TStrings; begin if Source is TStrings then begin Strings := TStrings(Source); for I := 0 to Strings.Count - 1 do begin S := Strings[I]; ValPos := Pos('=', S); if ValPos > 0 then SetOption(Copy(S, 1, ValPos-1), Copy(S, ValPos+1, MAXINT)); end; end else inherited; end; procedure TWizardIniOptions.AssignTo(Dest: TPersistent); begin if Dest is TStrings then begin TStrings(Dest).Assign(FOptions) end else inherited; end; procedure TWizardIniOptions.DoOptionChange(const OptionName: string; const Value: Variant); begin if Assigned(OnOptionChange) then OnOptionChange(FIniFile, SectionName, OptionName, Value); end; procedure TWizardIniOptions.EnsureOption(const OptionStr: string); var ValPos: Integer; Name, Value: string; begin ValPos := Pos('=', OptionStr); Name := Copy(OptionStr, 1, ValPos-1); Value := Copy(OptionStr, ValPos+1, MAXINT); { Force option to exist in the list } if FOptions.Values[Name] <> Value then SetOption(Name, Value); end; function TWizardIniOptions.GetOption(const Name: string; const Default: Variant): Variant; begin Result := FOptions.Values[Name]; if (Result = '') and (VarToStr(Default) <> '') then Result := Default; end; function TWizardIniOptions.GetOptionValue(const Name: string): Variant; begin Result := GetOption(Name, ''); end; procedure TWizardIniOptions.SetOption(const Name: string; const Value: Variant); var Index: Integer; StrValue: string; begin StrValue := VarToStr(Value); if FOptions.Values[Name] = StrValue then Exit; if StrValue = '' then begin Index := FOptions.IndexOfName(Name); FOptions[Index] := Name+'='; end else FOptions.Values[Name] := StrValue; DoOptionChange(Name, Value); end; function TWizardIniOptions.GetOptionData(const Name: string): TObject; var Index: Integer; begin Index := FOptions.IndexOfName(Name); if Index <> -1 then Result := FOptions.Objects[Index] else Result := nil; end; procedure TWizardIniOptions.SetOptionData(const Name: string; const Value: TObject); var Index: Integer; begin Index := FOptions.IndexOfName(Name); if Index <> -1 then FOptions.Objects[Index] := Value; end; procedure TWizardIniOptions.InitializeOptions(const Values: array of string); var I: Integer; begin for I := 0 to High(Values) do EnsureOption(Values[I]); end; procedure TWizardIniOptions.InitializeOptions(const Values: TStrings); var I: Integer; begin for I := 0 to Values.Count - 1 do EnsureOption(Values[I]); end; procedure TWizardIniOptions.Clear; begin FOptions.Clear; DoOptionChange('', VarNull); end; function TWizardIniOptions.IsTrue(const Name: string): Boolean; var Value: Variant; begin Value := GetOption(Name, ''); Result := Value; end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { } { Copyright(c) 2010-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} // // Delphi-Objective-C Bridge // Interfaces for Cocoa framework SystemConfiguration // unit Macapi.SystemConfiguration; interface const kSCBondStatusLinkInvalid = 1; kSCBondStatusNoPartner = 2; kSCBondStatusNotInActiveGroup = 3; kSCBondStatusOK = 0; kSCBondStatusUnknown = 999; kSCNetworkConnectionConnected = 2; kSCNetworkConnectionConnecting = 1; kSCNetworkConnectionDisconnected = 0; kSCNetworkConnectionDisconnecting = 3; kSCNetworkConnectionInvalid = -1; kSCNetworkConnectionPPPAuthenticating = 5; kSCNetworkConnectionPPPConnected = 8; kSCNetworkConnectionPPPConnectingLink = 2; kSCNetworkConnectionPPPDialOnTraffic = 3; kSCNetworkConnectionPPPDisconnected = 0; kSCNetworkConnectionPPPDisconnectingLink = 10; kSCNetworkConnectionPPPHoldingLinkOff = 11; kSCNetworkConnectionPPPInitializing = 1; kSCNetworkConnectionPPPNegotiatingLink = 4; kSCNetworkConnectionPPPNegotiatingNetwork = 7; kSCNetworkConnectionPPPSuspended = 12; kSCNetworkConnectionPPPTerminating = 9; kSCNetworkConnectionPPPWaitingForCallBack = 6; kSCNetworkConnectionPPPWaitingForRedial = 13; kSCNetworkFlagsConnectionAutomatic = 8; kSCNetworkFlagsConnectionRequired = 4; kSCNetworkFlagsInterventionRequired = 16; kSCNetworkFlagsIsDirect = 131072; kSCNetworkFlagsIsLocalAddress = 65536; kSCNetworkFlagsReachable = 2; kSCNetworkFlagsTransientConnection = 1; kSCNetworkReachabilityFlagsConnectionAutomatic = 8; kSCNetworkReachabilityFlagsConnectionOnDemand = 32; kSCNetworkReachabilityFlagsConnectionOnTraffic = 8; kSCNetworkReachabilityFlagsConnectionRequired = 4; kSCNetworkReachabilityFlagsInterventionRequired = 16; kSCNetworkReachabilityFlagsIsDirect = 131072; kSCNetworkReachabilityFlagsIsLocalAddress = 65536; kSCNetworkReachabilityFlagsReachable = 2; kSCNetworkReachabilityFlagsTransientConnection = 1; kSCPreferencesNotificationApply = 2; kSCPreferencesNotificationCommit = 1; kSCStatusAccessError = 1003; kSCStatusConnectionNoService = 5001; kSCStatusFailed = 1001; kSCStatusInvalidArgument = 1002; kSCStatusKeyExists = 1005; kSCStatusLocked = 1006; kSCStatusMaxLink = 3006; kSCStatusNeedLock = 1007; kSCStatusNoConfigFile = 3003; kSCStatusNoKey = 1004; kSCStatusNoLink = 3004; kSCStatusNoPrefsSession = 3001; kSCStatusNoStoreServer = 2002; kSCStatusNoStoreSession = 2001; kSCStatusNotifierActive = 2003; kSCStatusOK = 0; kSCStatusPrefsBusy = 3002; kSCStatusReachabilityUnknown = 4001; kSCStatusStale = 3005; implementation end.
{****************************************************} { } { Delphi Functional Library } { } { Copyright (C) 2015 Colin Johnsun } { } { https:/github.com/colinj } { } {****************************************************} { } { 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/ } { } {****************************************************} unit Functional.Value; interface uses SysUtils, Classes; type TValueState = (vsStart, vsSomething, vsNothing, vsFinish); TValue<T> = record private FValue: T; FState: TValueState; public class operator Implicit(const aValue: T): TValue<T>; class function Nothing: TValue<T>; static; class function Start: TValue<T>; static; class function Finish: TValue<T>; static; function HasValue: Boolean; procedure SetState(const aState: TValueState); property Value: T read FValue; property State: TValueState read FState; end; implementation { TValue<T> } class operator TValue<T>.Implicit(const aValue: T): TValue<T>; begin Result.FValue := aValue; Result.FState := vsSomething; end; function TValue<T>.HasValue: Boolean; begin Result := FState = vsSomething; end; class function TValue<T>.Nothing: TValue<T>; begin Result.FState := vsNothing; end; procedure TValue<T>.SetState(const aState: TValueState); begin FState := aState; end; class function TValue<T>.Start: TValue<T>; begin Result.FState := vsStart; end; class function TValue<T>.Finish: TValue<T>; begin Result.FState := vsFinish; end; end.
{*******************************************************} { } { Delphi REST Client Framework } { } { Copyright(c) 2014-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$HPPEMIT LINKUNIT} unit REST.Backend.KinveyProvider; interface uses System.Classes, System.Generics.Collections, REST.Backend.Providers, REST.Backend.KinveyAPI, REST.Client, REST.Backend.ServiceTypes, REST.Backend.MetaTypes; type TCustomKinveyConnectionInfo = class(TComponent) public type TNotifyList = class private FList: TList<TNotifyEvent>; procedure Notify(Sender: TObject); public constructor Create; destructor Destroy; override; procedure Add(const ANotify: TNotifyEvent); procedure Remove(const ANotify: TNotifyEvent); end; TAndroidPush = class(TPersistent) private FOwner: TCustomKinveyConnectionInfo; FGCMAppID: string; procedure SetGCMAppID(const Value: string); protected procedure AssignTo(AValue: TPersistent); override; published property GCMAppID: string read FGCMAppID write SetGCMAppID; end; private FConnectionInfo: TKinveyApi.TConnectionInfo; FNotifyOnChange: TNotifyList; FAndroidPush: TAndroidPush; FPushEndpoint: string; procedure SetApiVersion(const Value: string); procedure SetAppSecret(const Value: string); procedure SetAppKey(const Value: string); procedure SetMasterSecret(const Value: string); function GetApiVersion: string; function GetAppKey: string; function GetAppSecret: string; function GetMasterSecret: string; procedure SetAndroidPush(const Value: TAndroidPush); function GetPassword: string; function GetUserName: string; procedure SetPassword(const Value: string); procedure SetUserName(const Value: string); procedure SetPushEndpoint(const Value: string); function GetProxyPassword: string; function GetProxyPort: integer; function GetProxyServer: string; function GetProxyUsername: string; procedure SetProxyPassword(const Value: string); procedure SetProxyPort(const Value: integer); procedure SetProxyServer(const Value: string); procedure SetProxyUsername(const Value: string); protected procedure DoChanged; virtual; property NotifyOnChange: TNotifyList read FNotifyOnChange; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure UpdateApi(const AApi: TKinveyApi); property ApiVersion: string read GetApiVersion write SetApiVersion; property AppSecret: string read GetAppSecret write SetAppSecret; property AppKey: string read GetAppKey write SetAppKey; property MasterSecret: string read GetMasterSecret write SetMasterSecret; property UserName: string read GetUserName write SetUserName; property Password: string read GetPassword write SetPassword; property AndroidPush: TAndroidPush read FAndroidPush write SetAndroidPush; property PushEndpoint: string read FPushEndpoint write SetPushEndpoint; property ProxyPassword: string read GetProxyPassword write SetProxyPassword; property ProxyPort: integer read GetProxyPort write SetProxyPort default 0; property ProxyServer: string read GetProxyServer write SetProxyServer; property ProxyUsername: string read GetProxyUsername write SetProxyUsername; end; TCustomKinveyProvider = class(TCustomKinveyConnectionInfo, IBackendProvider) public const ProviderID = 'Kinvey'; protected { IBackendProvider } function GetProviderID: string; end; TKinveyProvider = class(TCustomKinveyProvider) published property ApiVersion; property AppKey; property AppSecret; property MasterSecret; property UserName; property Password; property AndroidPush; property PushEndpoint; property ProxyPassword; property ProxyPort; property ProxyServer; property ProxyUsername; end; TKinveyBackendService = class(TInterfacedObject) // , IBackendService) private FConnectionInfo: TCustomKinveyConnectionInfo; procedure SetConnectionInfo(const Value: TCustomKinveyConnectionInfo); procedure OnConnectionChanged(Sender: TObject); protected procedure DoAfterConnectionChanged; virtual; property ConnectionInfo: TCustomKinveyConnectionInfo read FConnectionInfo write SetConnectionInfo; public constructor Create(const AProvider: IBackendProvider); virtual; destructor Destroy; override; end; IGetKinveyAPI = interface ['{ACEF8B21-82B8-4B61-B796-DB09CDCE962C}'] function GetKinveyAPI: TKinveyAPI; property KinveyAPI: TKinveyAPI read GetKinveyAPI; end; TKinveyServiceAPI = class(TInterfacedObject, IBackendAPI, IGetKinveyAPI) private FKinveyAPI: TKinveyAPI; { IGetKinveyAPI } function GetKinveyAPI: TKinveyAPI; protected property KinveyAPI: TKinveyAPI read FKinveyAPI; public constructor Create; destructor Destroy; override; end; TKinveyServiceAPIAuth = class(TKinveyServiceAPI, IBackendAuthenticationApi) protected { IBackendAuthenticationApi } procedure Login(const ALogin: TBackendEntityValue); procedure Logout; procedure SetDefaultAuthentication(ADefaultAuthentication: TBackendDefaultAuthentication); function GetDefaultAuthentication: TBackendDefaultAuthentication; procedure SetAuthentication(AAuthentication: TBackendAuthentication); function GetAuthentication: TBackendAuthentication; end; TKinveyBackendService<TAPI: TKinveyServiceAPI, constructor> = class(TKinveyBackendService, IGetKinveyAPI) private FBackendAPI: TAPI; FBackendAPIIntf: IInterface; procedure ReleaseBackendApi; { IGetKinveyAPI } function GetKinveyAPI: TKinveyAPI; protected function CreateBackendApi: TAPI; virtual; procedure EnsureBackendApi; procedure DoAfterConnectionChanged; override; property BackendAPI: TAPI read FBackendAPI; end; implementation uses System.SysUtils, REST.Backend.KinveyMetaTypes, REST.Backend.Consts; { TCustomKinveyConnectionInfo } constructor TCustomKinveyConnectionInfo.Create(AOwner: TComponent); begin inherited; FConnectionInfo := TKinveyApi.TConnectionInfo.Create(TKinveyApi.cDefaultApiVersion, ''); FAndroidPush := TAndroidPush.Create; FAndroidPush.FOwner := Self; FNotifyOnChange := TNotifyList.Create; end; destructor TCustomKinveyConnectionInfo.Destroy; begin FAndroidPush.Free; inherited; FNotifyOnChange.Free; end; procedure TCustomKinveyConnectionInfo.DoChanged; begin FNotifyOnChange.Notify(Self); end; function TCustomKinveyConnectionInfo.GetApiVersion: string; begin Result := FConnectionInfo.ApiVersion; end; function TCustomKinveyConnectionInfo.GetAppSecret: string; begin Result := FConnectionInfo.AppSecret; end; function TCustomKinveyConnectionInfo.GetMasterSecret: string; begin Result := FConnectionInfo.MasterSecret; end; function TCustomKinveyConnectionInfo.GetPassword: string; begin Result := FConnectionInfo.Password; end; function TCustomKinveyConnectionInfo.GetProxyPassword: string; begin Result := FConnectionInfo.ProxyPassword; end; function TCustomKinveyConnectionInfo.GetProxyPort: integer; begin Result := FConnectionInfo.ProxyPort; end; function TCustomKinveyConnectionInfo.GetProxyServer: string; begin Result := FConnectionInfo.ProxyServer; end; function TCustomKinveyConnectionInfo.GetProxyUsername: string; begin Result := FConnectionInfo.ProxyUsername; end; function TCustomKinveyConnectionInfo.GetUserName: string; begin Result := FConnectionInfo.UserName; end; function TCustomKinveyConnectionInfo.GetAppKey: string; begin Result := FConnectionInfo.AppKey; end; procedure TCustomKinveyConnectionInfo.SetAndroidPush( const Value: TAndroidPush); begin FAndroidPush.Assign(Value); end; procedure TCustomKinveyConnectionInfo.SetApiVersion(const Value: string); begin if Value <> ApiVersion then begin FConnectionInfo.ApiVersion := Value; DoChanged; end; end; procedure TCustomKinveyConnectionInfo.SetAppSecret(const Value: string); begin if Value <> AppSecret then begin FConnectionInfo.AppSecret := Value; DoChanged; end; end; procedure TCustomKinveyConnectionInfo.SetMasterSecret(const Value: string); begin if Value <> MasterSecret then begin FConnectionInfo.MasterSecret := Value; DoChanged; end; end; procedure TCustomKinveyConnectionInfo.SetPassword(const Value: string); begin if Value <> Password then begin FConnectionInfo.Password := Value; DoChanged; end; end; procedure TCustomKinveyConnectionInfo.SetProxyPassword(const Value: string); begin if Value <> ProxyPassword then begin FConnectionInfo.ProxyPassword := Value; DoChanged; end; end; procedure TCustomKinveyConnectionInfo.SetProxyPort(const Value: integer); begin if Value <> ProxyPort then begin FConnectionInfo.ProxyPort := Value; DoChanged; end; end; procedure TCustomKinveyConnectionInfo.SetProxyServer(const Value: string); begin if Value <> ProxyServer then begin FConnectionInfo.ProxyServer := Value; DoChanged; end; end; procedure TCustomKinveyConnectionInfo.SetProxyUsername(const Value: string); begin if Value <> ProxyUsername then begin FConnectionInfo.ProxyUsername := Value; DoChanged; end; end; procedure TCustomKinveyConnectionInfo.SetPushEndpoint(const Value: string); begin if Value <> PushEndpoint then begin FPushEndpoint := Value; DoChanged; end; end; procedure TCustomKinveyConnectionInfo.SetUserName(const Value: string); begin if Value <> UserName then begin FConnectionInfo.UserName := Value; DoChanged; end; end; procedure TCustomKinveyConnectionInfo.SetAppKey(const Value: string); begin if Value <> AppKey then begin FConnectionInfo.AppKey := Value; DoChanged; end; end; procedure TCustomKinveyConnectionInfo.UpdateApi(const AApi: TKinveyApi); begin AApi.ConnectionInfo := FConnectionInfo; end; { TCustomKinveyConnectionInfo.TNotifyList } procedure TCustomKinveyConnectionInfo.TNotifyList.Add(const ANotify: TNotifyEvent); begin Assert(not FList.Contains(ANotify)); if not FList.Contains(ANotify) then FList.Add(ANotify); end; constructor TCustomKinveyConnectionInfo.TNotifyList.Create; begin FList := TList<TNotifyEvent>.Create; end; destructor TCustomKinveyConnectionInfo.TNotifyList.Destroy; begin FList.Free; inherited; end; procedure TCustomKinveyConnectionInfo.TNotifyList.Notify(Sender: TObject); var LProc: TNotifyEvent; begin for LProc in FList do LProc(Sender); end; procedure TCustomKinveyConnectionInfo.TNotifyList.Remove( const ANotify: TNotifyEvent); begin Assert(FList.Contains(ANotify)); FList.Remove(ANotify); end; { TCustomKinveyConnectionInfo.TAndroidProps } procedure TCustomKinveyConnectionInfo.TAndroidPush.AssignTo( AValue: TPersistent); begin if AValue is TAndroidPush then begin Self.FGCMAppID := TAndroidPush(AValue).FGCMAppID end else inherited; end; procedure TCustomKinveyConnectionInfo.TAndroidPush.SetGCMAppID( const Value: string); begin if FGCMAppID <> Value then begin FGCMAppID := Value; FOwner.DoChanged; end; end; { TCustomKinveyProvider } function TCustomKinveyProvider.GetProviderID: string; begin Result := ProviderID; end; { TKinveyBackendService } constructor TKinveyBackendService.Create(const AProvider: IBackendProvider); begin if AProvider is TCustomKinveyConnectionInfo then ConnectionInfo := TCustomKinveyConnectionInfo(AProvider) else raise EArgumentException.Create('AProvider'); // Do not localize end; destructor TKinveyBackendService.Destroy; begin if Assigned(FConnectionInfo) then FConnectionInfo.NotifyOnChange.Remove(OnConnectionChanged); inherited; end; procedure TKinveyBackendService.DoAfterConnectionChanged; begin // end; procedure TKinveyBackendService.OnConnectionChanged(Sender: TObject); begin DoAfterConnectionChanged; end; procedure TKinveyBackendService.SetConnectionInfo( const Value: TCustomKinveyConnectionInfo); begin if FConnectionInfo <> nil then FConnectionInfo.NotifyOnChange.Remove(OnConnectionChanged); FConnectionInfo := Value; if FConnectionInfo <> nil then FConnectionInfo.NotifyOnChange.Add(OnConnectionChanged); OnConnectionChanged(Self); end; { TKinveyServiceAPI } constructor TKinveyServiceAPI.Create; begin FKinveyAPI := TKinveyAPI.Create(nil); end; destructor TKinveyServiceAPI.Destroy; begin FKinveyAPI.Free; inherited; end; function TKinveyServiceAPI.GetKinveyAPI: TKinveyAPI; begin Result := FKinveyAPI; end; { TKinveyBackendService<TAPI> } function TKinveyBackendService<TAPI>.CreateBackendApi: TAPI; begin Result := TAPI.Create; if ConnectionInfo <> nil then ConnectionInfo.UpdateAPI(Result.FKinveyAPI) else Result.FKinveyAPI.ConnectionInfo := TKinveyAPI.EmptyConnectionInfo; end; procedure TKinveyBackendService<TAPI>.EnsureBackendApi; begin if FBackendAPI = nil then begin FBackendAPI := CreateBackendApi; FBackendAPIIntf := FBackendAPI; // Reference end; end; function TKinveyBackendService<TAPI>.GetKinveyAPI: TKinveyAPI; begin EnsureBackendApi; if FBackendAPI <> nil then Result := FBackendAPI.FKinveyAPI; end; procedure TKinveyBackendService<TAPI>.ReleaseBackendApi; begin FBackendAPI := nil; FBackendAPIIntf := nil; end; procedure TKinveyBackendService<TAPI>.DoAfterConnectionChanged; begin ReleaseBackendApi; end; { TKinveyServiceAPIAuth } function TKinveyServiceAPIAuth.GetAuthentication: TBackendAuthentication; begin case KinveyApi.Authentication of TKinveyApi.TAuthentication.Default: Result := TBackendAuthentication.Default; TKinveyApi.TAuthentication.MasterSecret: Result := TBackendAuthentication.Root; TKinveyApi.TAuthentication.UserName: Result := TBackendAuthentication.User; TKinveyApi.TAuthentication.Session: Result := TBackendAuthentication.Session; else Assert(False); Result := TBackendAuthentication.Default; end; end; function TKinveyServiceAPIAuth.GetDefaultAuthentication: TBackendDefaultAuthentication; begin case KinveyApi.DefaultAuthentication of TKinveyApi.TDefaultAuthentication.MasterSecret: Result := TBackendDefaultAuthentication.Root; TKinveyApi.TDefaultAuthentication.UserName: Result := TBackendDefaultAuthentication.User; TKinveyApi.TDefaultAuthentication.Session: Result := TBackendDefaultAuthentication.Session; else Assert(False); Result := TBackendDefaultAuthentication.Root; end; end; procedure TKinveyServiceAPIAuth.Login(const ALogin: TBackendEntityValue); var LMetaLogin: TMetaLogin; begin if ALogin.Data is TMetaLogin then begin LMetaLogin := TMetaLogin(ALogin.Data); KinveyAPI.Login(LMetaLogin.Login); end else raise EArgumentException.Create(sParameterNotLogin); end; procedure TKinveyServiceAPIAuth.Logout; begin KinveyAPI.Logout; end; procedure TKinveyServiceAPIAuth.SetAuthentication( AAuthentication: TBackendAuthentication); begin case AAuthentication of TBackendAuthentication.Default: FKinveyAPI.Authentication := TKinveyApi.TAuthentication.Default; TBackendAuthentication.Root: FKinveyAPI.Authentication := TKinveyApi.TAuthentication.MasterSecret; TBackendAuthentication.Application: FKinveyAPI.Authentication := TKinveyApi.TAuthentication.AppSecret; TBackendAuthentication.User: FKinveyAPI.Authentication := TKinveyApi.TAuthentication.UserName; TBackendAuthentication.Session: FKinveyAPI.Authentication := TKinveyApi.TAuthentication.Session; TBackendAuthentication.None: FKinveyAPI.Authentication := TKinveyApi.TAuthentication.None; else Assert(False); end; end; procedure TKinveyServiceAPIAuth.SetDefaultAuthentication( ADefaultAuthentication: TBackendDefaultAuthentication); begin case ADefaultAuthentication of TBackendDefaultAuthentication.Root: FKinveyAPI.DefaultAuthentication := TKinveyApi.TDefaultAuthentication.MasterSecret; TBackendDefaultAuthentication.Application: FKinveyAPI.DefaultAuthentication := TKinveyApi.TDefaultAuthentication.AppSecret; TBackendDefaultAuthentication.User: FKinveyAPI.DefaultAuthentication := TKinveyApi.TDefaultAuthentication.UserName; TBackendDefaultAuthentication.Session: FKinveyAPI.DefaultAuthentication := TKinveyApi.TDefaultAuthentication.Session; TBackendDefaultAuthentication.None: FKinveyAPI.DefaultAuthentication := TKinveyApi.TDefaultAuthentication.None; else Assert(False); end; end; const sDisplayName = 'Kinvey'; initialization TBackendProviders.Instance.Register(TCustomKinveyProvider.ProviderID, sDisplayName); finalization TBackendProviders.Instance.UnRegister(TCustomKinveyProvider.ProviderID); end.
unit Utw_cap; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Dll96v1, StdCtrls; type TTwainCaps = class(TForm) Button1: TButton; ListBox1: TListBox; Label1: TLabel; Edit1: TEdit; Label2: TLabel; Edit2: TEdit; Label3: TLabel; eMinValue: TEdit; eMaxValue: TEdit; eStepSize: TEdit; eDefaultValue: TEdit; eCurrentValue: TEdit; lMinValue: TLabel; LMaxValue: TLabel; LStepSize: TLabel; LDefaultValue: TLabel; LCurrentValue: TLabel; Label4: TLabel; eSmallInt: TEdit; lSmallInt: TLabel; eLongint: TEdit; LLongint: TLabel; eDouble: TEdit; lDouble: TLabel; eBoolean: TEdit; LBoolean: TLabel; LPchar: TLabel; EPchar: TEdit; EMeaning: TEdit; LMeaning: TLabel; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure ListBox1Click(Sender: TObject); private { Private declarations } CapList : TList; public { Public declarations } procedure FreeCapList; Function GetStrValueOfCap(Capabil : SmallInt; Value : SmallInt) : String; function Caps(CapChar : PChar; CapShort : SmallInt; CapLong : LongInt; CapFloat : Double; TWON : SmallInt; TWTYPE : SmallInt; RgMinValue : LongInt; RgMaxValue : LongInt; RgStepSize : LongInt; RgDefaultValue : LongInt; RgCurrentValue : LongInt; Capabil : SmallInt) : SmallInt; end; var TwainCaps: TTwainCaps; implementation {$R *.DFM} function CapsCallBackfunction (CapChar : PChar; CapShort : SmallInt; CapLong : LongInt; CapFloat : Double; TWON : SmallInt; TWTYPE : SmallInt; RgMinValue : LongInt; RgMaxValue : LongInt; RgStepSize : LongInt; RgDefaultValue : LongInt; RgCurrentValue : LongInt; Capabil : SmallInt; d_object : longint) : SmallInt; CDECL; export; begin result:=0; if d_object <> 0 then result:=TTwainCaps(d_object).Caps(CapChar, CapShort, CapLong, CapFloat, TWON, TWTYPE, RgMinValue, RgMaxValue, RgStepSize, RgDefaultValue, RgCurrentValue, Capabil); end; function TTwainCaps.Caps(CapChar : PChar; CapShort : SmallInt; CapLong : LongInt; CapFloat : Double; TWON : SmallInt; TWTYPE : SmallInt; RgMinValue : LongInt; RgMaxValue : LongInt; RgStepSize : LongInt; RgDefaultValue : LongInt; RgCurrentValue : LongInt; Capabil : SmallInt) : SmallInt; var MyCap : PCapRecord; begin New(MyCap); with MyCap^ do begin _CapChar :=String(CapChar); _CapShort :=CapShort; _CapLong :=CapLong; _CapFloat :=CapFloat; _TWON :=TWON; _TWTYPE :=TWTYPE; _RgMinValue :=RgMinValue; _RgMaxValue :=RgMaxValue; _RgStepSize :=RgStepSize; _RgDefaultValue:=RgDefaultValue; _RgCurrentValue:=RgCurrentValue; _Capabil :=Capabil; end; CapList.Add(MyCap); ListBox1.Items.Add(GetTwainCapName(Capabil)); result:=1; end; procedure TTwainCaps.Button1Click(Sender: TObject); var Capp : Array[0..255] of SmallInt; begin Capp[0]:=CAP_XFERCOUNT; Capp[1]:=ICAP_COMPRESSION; Capp[2]:=ICAP_PIXELTYPE; Capp[3]:=ICAP_UNITS; Capp[4]:=ICAP_XFERMECH; Capp[5]:=CAP_AUTHOR; Capp[6]:=CAP_CAPTION; Capp[7]:=CAP_FEEDERENABLED; Capp[8]:=CAP_FEEDERLOADED; Capp[9]:=CAP_TIMEDATE; Capp[10]:=CAP_EXTENDEDCAPS; Capp[11]:=CAP_AUTOFEED; Capp[12]:=CAP_CLEARPAGE; Capp[13]:=CAP_FEEDPAGE; Capp[14]:=CAP_REWINDPAGE; Capp[15]:=CAP_INDICATORS; Capp[16]:=CAP_SUPPORTEDCAPSEXT; Capp[17]:=CAP_PAPERDETECTABLE; Capp[18]:=CAP_UICONTROLLABLE; Capp[19]:=CAP_DEVICEONLINE; Capp[20]:=CAP_AUTOSCAN; Capp[21]:=CAP_THUMBNAILSENABLED; Capp[22]:=CAP_DUPLEX; Capp[23]:=CAP_DUPLEXENABLED; Capp[24]:=CAP_ENABLEDSUIONLY; Capp[25]:=CAP_CUSTOMDSDATA; Capp[26]:=CAP_ENDORSER; Capp[27]:=CAP_JOBCONTROL; Capp[28]:=ICAP_AUTOBRIGHT; Capp[29]:=ICAP_BRIGHTNESS; Capp[30]:=ICAP_CONTRAST; Capp[31]:=ICAP_CUSTHALFTONE; Capp[32]:=ICAP_EXPOSURETIME; Capp[33]:=ICAP_FILTER; Capp[34]:=ICAP_FLASHUSED; Capp[35]:=ICAP_GAMMA; Capp[36]:=ICAP_HALFTONES; Capp[37]:=ICAP_HIGHLIGHT; Capp[38]:=ICAP_IMAGEFILEFORMAT; Capp[39]:=ICAP_LAMPSTATE; Capp[40]:=ICAP_LIGHTSOURCE; Capp[41]:=ICAP_ORIENTATION; Capp[42]:=ICAP_PHYSICALWIDTH; Capp[43]:=ICAP_PHYSICALHEIGHT; Capp[44]:=ICAP_SHADOW; Capp[45]:=ICAP_FRAMES; Capp[46]:=ICAP_XNATIVERESOLUTION; Capp[47]:=ICAP_YNATIVERESOLUTION; Capp[48]:=ICAP_XRESOLUTION; Capp[49]:=ICAP_YRESOLUTION; Capp[50]:=ICAP_MAXFRAMES; Capp[51]:=ICAP_TILES; Capp[52]:=ICAP_BITORDER; Capp[53]:=ICAP_CCITTKFACTOR; Capp[54]:=ICAP_LIGHTPATH; Capp[55]:=ICAP_PIXELFLAVOR; Capp[56]:=ICAP_PLANARCHUNKY; Capp[57]:=ICAP_ROTATION; Capp[58]:=ICAP_SUPPORTEDSIZES; Capp[59]:=ICAP_THRESHOLD; Capp[60]:=ICAP_XSCALING; Capp[61]:=ICAP_YSCALING; Capp[62]:=ICAP_BITORDERCODES; Capp[63]:=ICAP_PIXELFLAVORCODES; Capp[64]:=ICAP_JPEGPIXELTYPE; Capp[65]:=ICAP_TIMEFILL; Capp[66]:=ICAP_BITDEPTH; Capp[67]:=ICAP_BITDEPTHREDUCTION; Capp[68]:=ICAP_UNDEFINEDIMAGESIZE; Capp[69]:=ICAP_IMAGEDATASET; Capp[70]:=ICAP_EXTIMAGEINFO; Capp[71]:=ICAP_MINIMUMHEIGHT; Capp[72]:=ICAP_MINIMUMWIDTH; FreeCapList; ListBox1.Clear; Screen.Cursor:=crHourGlass; GetTwainCapabilities(@Capp, 73, LongInt(Self), CapsCallBackfunction); Screen.Cursor:=crDefault; end; procedure TTwainCaps.FormCreate(Sender: TObject); begin CapList :=TList.Create; end; procedure TTwainCaps.FreeCapList; Var I : Integer; begin for i:=CapList.Count-1 downto 0 do begin Dispose(PCapRecord(CapList.Items[i])); CapList.Items[i]:=nil; end; CapList.Pack; end; procedure TTwainCaps.FormDestroy(Sender: TObject); begin FreeCapList; CapList.Free; end; procedure TTwainCaps.ListBox1Click(Sender: TObject); var MyCap : PCapRecord; begin //get pointer Caprecord from list MyCap:= CapList.Items[ListBox1.ItemIndex]; //Reset Values eMinValue.Visible:=False; eMaxValue.Visible:=False; eStepSize.Visible:=False; eDefaultValue.Visible:=False; eCurrentValue.Visible:=False; lMinValue.Visible:=False; lMaxValue.Visible:=False; lStepSize.Visible:=False; lDefaultValue.Visible:=False; lCurrentValue.Visible:=False; Label4.Visible:=False; eSmallInt.Visible:=False; lSmallInt.Visible:=False; eLongint.Visible:=False; LLongint.Visible:=False; eDouble.Visible:=False; lDouble.Visible:=False; eBoolean.Visible:=False; LBoolean.Visible:=False; LPchar.Visible:=False; EPchar.Visible:=False; EMeaning.Visible:=False; LMeaning.Visible:=False; //Set Data Type case MyCap^._TWTYPE of TWTY_INT32 : Begin Edit1.Text:='TWTY_IN32'; eLongint.Visible:=True; LLongint.Visible:=True; eLongint.Text:=IntToStr(MyCap^._CapLong); EMeaning.Text:=GetStrValueOfCap(MyCap^._Capabil, MyCap^._CapLong); If EMeaning.Text <>'' then begin EMeaning.Visible:=True; LMeaning.Visible:=True; end; end; TWTY_UINT32 : Begin Edit1.Text:='TWTY_UINT32'; eLongint.Visible:=True; LLongint.Visible:=True; eLongint.Text:=IntToStr(MyCap^._CapLong); EMeaning.Text:=GetStrValueOfCap(MyCap^._Capabil, MyCap^._CapLong); If EMeaning.Text <>'' then begin EMeaning.Visible:=True; LMeaning.Visible:=True; end; end; TWTY_INT8 : Begin Edit1.Text:='TWTY_INT8'; eSmallInt.Visible:=True; lSmallInt.Visible:=True; eSmallInt.Text:=IntToStr(MyCap^._CapShort); EMeaning.Text:=GetStrValueOfCap(MyCap^._Capabil, MyCap^._CapShort); If EMeaning.Text <>'' then begin EMeaning.Visible:=True; LMeaning.Visible:=True; end; end; TWTY_INT16 : Begin Edit1.Text:='TWTY_INT16'; eSmallInt.Visible:=True; lSmallInt.Visible:=True; eSmallInt.Text:=IntToStr(MyCap^._CapShort); EMeaning.Text:=GetStrValueOfCap(MyCap^._Capabil, MyCap^._CapShort); If EMeaning.Text <>'' then begin EMeaning.Visible:=True; LMeaning.Visible:=True; end; end; TWTY_UINT8 : Begin Edit1.Text:='TWTY_UINT8'; eSmallInt.Visible:=True; lSmallInt.Visible:=True; eSmallInt.Text:=IntToStr(MyCap^._CapShort); EMeaning.Text:=GetStrValueOfCap(MyCap^._Capabil, MyCap^._CapShort); If EMeaning.Text <>'' then begin EMeaning.Visible:=True; LMeaning.Visible:=True; end; end; TWTY_UINT16 : Begin Edit1.Text:='TWTY_UINT16'; eSmallInt.Visible:=True; lSmallInt.Visible:=True; eSmallInt.Text:=IntToStr(MyCap^._CapShort); EMeaning.Text:=GetStrValueOfCap(MyCap^._Capabil, MyCap^._CapShort); If EMeaning.Text <>'' then begin EMeaning.Visible:=True; LMeaning.Visible:=True; end; end; TWTY_BOOL : Begin Edit1.Text:='TWTY_BOOL'; eBoolean.Visible:=True; LBoolean.Visible:=True; if MyCap^._CapShort = 0 then eBoolean.Text:='FALSE' else eBoolean.Text:='TRUE' end; TWTY_FIX32 : Begin Edit1.Text:='TWTY_FIX32'; eDouble.Visible:=True; lDouble.Visible:=True; eDouble.Text:=FloatToStr(MyCap^._CapFloat); end; TWTY_FRAME : Begin Edit1.Text:='TWTY_FRAME'; end; TWTY_STR32 : Begin Edit1.Text:='TWTY_STR32'; LPchar.Visible:=True; EPchar.Visible:=True; EPchar.Text:=MyCap^._CapChar; end; TWTY_STR64 : Begin Edit1.Text:='TWTY_STR64'; LPchar.Visible:=True; EPchar.Visible:=True; EPchar.Text:=MyCap^._CapChar; end; TWTY_STR128 : Begin Edit1.Text:='TWTY_STR128'; LPchar.Visible:=True; EPchar.Visible:=True; EPchar.Text:=MyCap^._CapChar; end; TWTY_STR255 : Begin Edit1.Text:='TWTY_STR255'; LPchar.Visible:=True; EPchar.Visible:=True; EPchar.Text:=MyCap^._CapChar; end; end; //Set Container type case MyCap^._TWON of TWON_ARRAY: begin Edit2.Text:='TWON_ARRAY'; end; TWON_ENUMERATION: begin Edit2.Text:='TWON_ENUMERATION'; end; TWON_ONEVALUE: begin Edit2.Text:='TWON_ONEVALUE'; end; TWON_RANGE: begin eDouble.Visible:=False; lDouble.Visible:=False; eLongint.Visible:=False; LLongint.Visible:=False; Edit2.Text:='TWON_RANGE'; eMinValue.Text:=IntToStr(MyCap^._RgMinValue); eMaxValue.Text:=IntToStr(MyCap^._RgMaxValue); eStepSize.Text:=IntToStr(MyCap^._RgStepSize); eDefaultValue.Text:=IntToStr(MyCap^._RgDefaultValue); eCurrentValue.Text:=IntToStr(MyCap^._RgCurrentValue); eMinValue.Visible:=True; eMaxValue.Visible:=True; eStepSize.Visible:=True; eDefaultValue.Visible:=True; eCurrentValue.Visible:=True; lMinValue.Visible:=True; lMaxValue.Visible:=True; lStepSize.Visible:=True; lDefaultValue.Visible:=True; lCurrentValue.Visible:=True; Label4.Visible:=True; end; end; end; Function TTwainCaps.GetStrValueOfCap(Capabil : SmallInt; Value : SmallInt) : String; begin Result:=''; Case Capabil of ICAP_BITDEPTHREDUCTION: Case Value of 0: Result:='TWBR_THRESHOLD'; 1: Result:='TWBR_HALFTONE'; 2: Result:='TWBR_CUSTHALFTONE'; 3: Result:='TWBR_DIFFUSION'; end; ICAP_BITDEPTH: Result:='Possible Bits per Pixels of ICAP_PIXELTYPE'; ICAP_BITORDER: Case Value of 0: Result:='LSB_FIRST (Least Significant Byte first'; 1: Result:='MSB_FIRST (Most Significant Byte first'; end; ICAP_BITORDERCODES: Case Value of 0: Result:='LSB_FIRST (CCITT Only. Least Significant Byte first'; 1: Result:='MSB_FIRST (CCITT Only. Most Significant Byte first'; end; ICAP_COMPRESSION: Case Value of 0: Result:='Device can Hardware Compress to NONE'; 1: Result:='Device can Hardware Compress to PACKBITS'; 2: Result:='Device can Hardware Compress to GROUP31D'; 3: Result:='Device can Hardware Compress to GROUP31DEOL'; 4: Result:='Device can Hardware Compress to GROUP32D'; 5: Result:='Device can Hardware Compress to GROUP4'; 6: Result:='Device can Hardware Compress to JPEG'; 7: Result:='Device can Hardware Compress to LZW'; end; ICAP_FILTER: Case Value of 0: Result:='Can Subtract RED'; 1: Result:='Can Subtract GREEN'; 2: Result:='Can Subtract BLUE'; 3: Result:='Can Subtract NONE'; 4: Result:='Can Subtract WHITE'; 5: Result:='Can Subtract CYAN'; 6: Result:='Can Subtract MAGENTA'; 7: Result:='Can Subtract YELLOW'; 8: Result:='Can Subtract BLACK'; end; ICAP_IMAGEFILEFORMAT: Case Value of 0: Result:='Device can Hardware Compress to TIFF Tagged Image File Format'; 1: Result:='Device can Hardware Compress to PICT Macintosh PICT'; 2: Result:='Device can Hardware Compress to BMP Windows Bitmap'; 3: Result:='Device can Hardware Compress to XBM X-Windows Bitmap'; 4: Result:='Device can Hardware Compress to JFIF JPEG File Interchange Format'; end; ICAP_JPEGPIXELTYPE: Case Value of 0: Result:='Support Jpeg Color Descriptor of BW'; 1: Result:='Support Jpeg Color Descriptor of GRAY'; 2: Result:='Support Jpeg Color Descriptor of RGB'; 3: Result:='Support Jpeg Color Descriptor of PALETTE'; 4: Result:='Support Jpeg Color Descriptor of CMY'; 5: Result:='Support Jpeg Color Descriptor of CMYK'; 6: Result:='Support Jpeg Color Descriptor of YUV'; 7: Result:='Support Jpeg Color Descriptor of YUVK'; 8: Result:='Support Jpeg Color Descriptor of CIEXYZ'; end; ICAP_LIGHTPATH: Case Value of 0: Result:='Can Capture Image REFLECTIVE'; 1: Result:='Can Capture Image TRANSMISSIVE'; end; ICAP_LIGHTSOURCE: Case Value of 0: Result:='Can Apply Light Source of RED'; 1: Result:='Can Apply Light Source of GREEN'; 2: Result:='Can Apply Light Source of BLUE'; 3: Result:='Can Apply Light Source of NONE'; 4: Result:='Can Apply Light Source of WHITE'; 5: Result:='Can Apply Light Source of UV'; 6: Result:='Can Apply Light Source of IR'; end; ICAP_ORIENTATION: Case Value of 0: Result:='Device Can Rotate 0 Degrees (Portait)'; 1: Result:='Device Can Rotate 90 Degrees'; 2: Result:='Device Can Rotate 180 Degrees'; 3: Result:='Device Can Rotate 270 Degrees (LandScape)'; end; ICAP_PIXELFLAVOR: Case Value of 0: Result:='Make darkest pixel CHOCOLATE'; 1: Result:='Make lightest pixel VANILLA'; end; ICAP_PIXELFLAVORCODES: Case Value of 0: Result:='CCITT Only. Make darkest pixel CHOCOLATE'; 1: Result:='CCITT Only. Make lightest pixel VANILLA'; end; ICAP_PIXELTYPE: Case Value of 0: Result:='Device Supports BW Compression'; 1: Result:='Device Supports GRAY Compression'; 2: Result:='Device Supports RGB Compression'; 3: Result:='Device Supports PALETTE Compression'; 4: Result:='Device Supports CMY Compression'; 5: Result:='Device Supports CMYK Compression'; 6: Result:='Device Supports YUV Compression'; 7: Result:='Device Supports YUVK Compression'; 8: Result:='Device Supports CIEXYZ Compression'; end; ICAP_PLANARCHUNKY: Case Value of 0: Result:='Color Identify is CHUNKY'; 1: Result:='Color Identify is PLANAR'; end; ICAP_SUPPORTEDSIZES: Case Value of 0: Result:='Device Supports Size NONE'; 1: Result:='Device Supports Size A4LETTER'; 2: Result:='Device Supports Size B5LETTER'; 3: Result:='Device Supports Size USLETTER'; 4: Result:='Device Supports Size USLEGAL'; 5: Result:='Device Supports Size A5'; 6: Result:='Device Supports Size B4'; 7: Result:='Device Supports Size B6'; 8: Result:='Device Supports Size B'; 9: Result:='Device Supports Size USLEDGER'; 10: Result:='Device Supports Size USEXECUTIVE'; 11: Result:='Device Supports Size A3'; 12: Result:='Device Supports Size B3'; 13: Result:='Device Supports Size A6'; 14: Result:='Device Supports Size C4'; 15: Result:='Device Supports Size C5'; 16: Result:='Device Supports Size C6'; end; ICAP_UNITS: Case Value of 0: Result:='Device Supports Measure Units of INCHES'; 1: Result:='Device Supports Measure Units of CENTIMETERS'; 2: Result:='Device Supports Measure Units of PICAS'; 3: Result:='Device Supports Measure Units of POINTS'; 4: Result:='Device Supports Measure Units of TWIPS'; 5: Result:='Device Supports Measure Units of PIXELS'; end; ICAP_XFERMECH: Case Value of 0: Result:='Device Supports the image transfer Natively (DIB)'; 1: Result:='Device Supports the image transfer To File (TIF , JPG, Etc.)'; 2: Result:='Device Supports the image transfer To Memory (TIF , JPG, Etc.)'; end; CAP_JOBCONTROL: Case Value of 0: Result:='No job control'; 1: Result:='Detect and include job separator and continue scanning'; 2: Result:='Detect and include job separator and stop scanning'; 3: Result:='Detect and exclude job separator and continue scanning'; 4: Result:='Detect and exclude job separator and stop scanning'; end; end; end; end.
unit NodeOutline; interface uses Classes, Outline, Nodes; type TNodeOutLine = class(TOutLine) public procedure SelectNode(ANode: TNode); procedure Show(ANode: TNode); end; implementation //=============================================================== uses Repr; { TNodeOutline } procedure TNodeOutline.SelectNode(ANode: TNode); var I: Integer; begin // N.B. range is 1 .. ItemCount; Help says it is 0 .. ItemCount-1 . for I := 1{0} to ItemCount {- 1} do if Items[I].Data = ANode then SelectedItem := I; end; procedure TNodeOutLine.Show(ANode: TNode); begin Lines := NodesToStringList(ANode); FullExpand; end; end.
unit UHttp; interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, IdBaseComponent, IdComponent, IdCustomTCPServer, IdCustomHTTPServer, IdHTTPServer, StdCtrls, ComCtrls, IdServerIOHandler, IdSSL, IdSSLOpenSSL, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdTCPConnection, IdTCPClient, IdHTTP,UHash,IdMultipartFormData; type { hrError - ошибка пр загрузке (возможно нет коннекта) hrNoValidJSON - загруженный json не валдный hrErrorCreateHash - не удается создать hash по загруженному json } THttpResult = (hrOk,hrError,hrNoValidJSON,hrErrorCreateHash); THttp = class(TObject) private fEncode: Boolean; fhttp: TidHTTP; fread_block_name: string; fScript: string; fSSL: TIdIOHandler; fUrl: THash; function getProxyPassword: string; function getProxyPort: Integer; function getProxyServer: string; function getProxyUserName: string; procedure setProxyPassword(const Value: string); procedure setProxyPort(const Value: Integer); procedure setProxyServer(const Value: string); procedure setProxyUserName(const Value: string); procedure setScript(const Value: string); public constructor Create; destructor Destroy; override; //1 Простой GET запрос function get(NameValueParams: array of variant; var Response: string): THttpResult; overload; //1 Простой GET запрос с последующим распарсиванием ответа (aResponse) function get(NameValueParams: array of variant; aResponse: THash): THttpResult; overload; //1 Простой GET запрос function get(aParams: THash; var aResponse: string): THttpResult; overload; //1 Простой GET запрос с последующим распарсиванием ответа (aResponse) function get(aParams, aResponse: THash): THttpResult; overload; //1 Чтение данных в поток function read(aParams:THash;aData:TStream): THttpResult; //1 Запись строки на сервер (POST) function write(aParams: THash; var aResponse: string): THttpResult; overload; function write(aParams, aResponse: THash): THttpResult; overload; function write(aParams: THash; data: TStream; var aResponse: string): THttpResult; overload; function write(aParams: THash; data: TStream; aResponse: THash): THttpResult; overload; function write(data: TStream; var aResponse: string): THttpResult; overload; property Encode: Boolean read fEncode write fEncode; property http: TidHTTP read fhttp write fhttp; property ProxyPassword: string read getProxyPassword write setProxyPassword; property ProxyPort: Integer read getProxyPort write setProxyPort; property ProxyServer: string read getProxyServer write setProxyServer; property ProxyUserName: string read getProxyUserName write setProxyUserName; property read_block_name: string read fread_block_name write fread_block_name; property Script: string read fScript write setScript; end; implementation uses UUrl, UUtils; { ************************************ THttp ************************************* } constructor THttp.Create; begin inherited Create; fEncode:=false; fHttp:=TIdHttp.Create(nil); fSSL:=TIdSSLIOHandlerSocketOpenSSL.Create(nil); fHttp.IOHandler:=fSSL; fUrl:=Hash(); Script:='http://windeco/exweb/server/'; fread_block_name:='b'; end; destructor THttp.Destroy; begin FreeHash(fUrl); fHttp.IOHandler:=nil; fSSL.Free; fHttp.Free; inherited Destroy; end; function THttp.get(NameValueParams: array of variant; var Response: string): THttpResult; var cUrl: string; begin result:=hrError; try try cUrl:=UUrl.Url.build(fUrl,NameValueParams,false,Encode); Response:=Http.Get(cUrl); result:=hrOk; except on e:Exception do begin end; end; finally end; end; function THttp.get(NameValueParams: array of variant; aResponse: THash): THttpResult; var cHashParsingResult: THashJsonResult; cResponse: string; begin result:=get(NameValueParams,cResponse); if (result = hrOk) then begin cHashParsingResult:=aResponse.fromJSON(cResponse); if (cHashParsingResult = hjprErrorParsing) then result:=hrNoValidJSON; if (cHashParsingResult = hjprErrorCreate) then result:=hrErrorCreateHash; end; end; function THttp.get(aParams: THash; var aResponse: string): THttpResult; var cUrl: string; begin result:=hrError; try try cUrl:=UUrl.Url.build(fUrl,aParams,false,Encode); aResponse:=Http.Get(cUrl); result:=hrOk; except on e:Exception do begin end; end; finally end; end; function THttp.get(aParams, aResponse: THash): THttpResult; var cHashParsingResult: THashJsonResult; cResponse: string; begin result:=get(aParams,cResponse); if (result = hrOk) then begin cHashParsingResult:=aResponse.fromJSON(cResponse); if (cHashParsingResult = hjprErrorParsing) then result:=hrNoValidJSON; if (cHashParsingResult = hjprErrorCreate) then result:=hrErrorCreateHash; end; end; function THttp.getProxyPassword: string; begin result:=http.ProxyParams.ProxyPassword; end; function THttp.getProxyPort: Integer; begin result:=http.ProxyParams.ProxyPort; end; function THttp.getProxyServer: string; begin result:=http.ProxyParams.ProxyServer; end; function THttp.getProxyUserName: string; begin result:=http.ProxyParams.ProxyUserName; end; function THttp.read(aParams:THash;aData:TStream): THttpResult; var cChar: AnsiChar; cPostStream: TIdMultiPartFormDataStream; cPostStrings: TStringList; cResponse: AnsiString; cUrl: string; i: Integer; const cFuncName = 'read'; begin cPostStream:=TIdMultiPartFormDataStream.Create(); cPostStrings:=TStringList.Create(); result:=hrError; try try aData.Size:=0; if (aParams<>nil) then cUrl:=UUrl.Url.build(fUrl,aParams,false,Encode) else cUrl:=Script; http.Get(cUrl,aData); aData.Position:=0; result:=hrOK; except on e:Exception do begin {$ifdef _log_}ULog.Error('',e,ClassName,cFuncName);{$endif} end; end; finally cPostStrings.Free; cPostStream.Free; end; end; procedure THttp.setProxyPassword(const Value: string); begin http.ProxyParams.ProxyPassword:=Value; end; procedure THttp.setProxyPort(const Value: Integer); begin http.ProxyParams.ProxyPort:=Value; end; procedure THttp.setProxyServer(const Value: string); begin http.ProxyParams.ProxyServer:=Value; end; procedure THttp.setProxyUserName(const Value: string); begin http.ProxyParams.ProxyUserName:=Value; end; procedure THttp.setScript(const Value: string); begin if (Value<>fScript) then UUrl.Url.parse(Value,fUrl,Encode); fScript := Value; end; function THttp.write(aParams: THash; var aResponse: string): THttpResult; var cPostStream: TIdMultiPartFormDataStream; cUrl: string; data: TMemoryStream; begin result:=hrError; cPostStream:=TIdMultiPartFormDataStream.Create(); data:=TMemoryStream.Create; try try if (aParams<>nil) then cUrl:=UUrl.Url.build(fUrl,aParams,false,Encode) else cUrl:=Script; cPostStream.AddFormField('empty','','',data,'file100tmp_'); aResponse:=http.Post(cUrl,cPostStream); result:=hrOk; except on e:Exception do begin {$ifdef _log_}ULog.Error(aResponse,e,ClassName,cFuncName);{$endif} end; end; finally data.Free; cPostStream.Free; end; end; function THttp.write(aParams, aResponse: THash): THttpResult; var cHashParsingResult: THashJsonResult; cResponse: string; begin result:=write(aParams,cResponse); if (result = hrOk) then begin cHashParsingResult:=aResponse.fromJSON(cResponse); if (cHashParsingResult = hjprErrorParsing) then result:=hrNoValidJSON; if (cHashParsingResult = hjprErrorCreate) then result:=hrErrorCreateHash; end; end; function THttp.write(aParams: THash; data: TStream; var aResponse: string): THttpResult; var cPostStream: TIdMultiPartFormDataStream; idField: TIdFormDataField; cUrl: string; begin result:=hrError; cPostStream:=TIdMultiPartFormDataStream.Create(); try try data.Position:=0; if (aParams<>nil) then cUrl:=UUrl.Url.build(fUrl,aParams,false,Encode) else cUrl:=Script; idField:=cPostStream.AddFormField(read_block_name,'','',data,'file100tmp_'); aResponse:=http.Post(cUrl,cPostStream); result:=hrOk; except on e:Exception do begin end; end; finally cPostStream.Free(); end; end; function THttp.write(aParams: THash; data: TStream; aResponse: THash): THttpResult; var cHashParsingResult: THashJsonResult; cResponse: string; begin result:=write(aParams,data,cResponse); if (result = hrOk) then begin cHashParsingResult:=aResponse.fromJSON(cResponse); if (cHashParsingResult = hjprErrorParsing) then result:=hrNoValidJSON; if (cHashParsingResult = hjprErrorCreate) then result:=hrErrorCreateHash; end; end; function THttp.write(data: TStream; var aResponse: string): THttpResult; begin result:=write(nil,data,aResponse); end; end.
unit uDbObject; interface uses Data.DB, System.SysUtils, System.Classes, Datasnap.DBClient, System.Variants, Vcl.Forms, uDbCustomObject; const cMsgDeleteEmpty : string = ''; const cMsgErrorDelete : String = ''; const cMsgErrorRowsAffectedDelete : String = ''; type TOperacaoBd = (dbInsert, dbUpdate, dbDelete); TDbObject = class; TDbField = class private FIsNull: Boolean; FRequired: Boolean; FKey: Boolean; FReadOnly: Boolean; FAsFloat: Double; FAsInteger: Integer; FIndex: Integer; FColumName: String; FAsString: String; FAsDateTime: TDateTime; FDataType: TFieldType; FValue: Variant; FOwner: TDbObject; FNullIfZero: Boolean; FDisplayName: String; FOldValue: Variant; FSaveDateTimeFormat: Boolean; FFloatPrecision: Integer; FIncludeOnInsert: Boolean; FMasterTableName: String; FMastercolumnname: String; FSequence: Boolean; function GetAsDateTime: TDateTime; function GetAsFloat: Double; function GetAsInteger: Integer; function GetIsNull: Boolean; function GetsString: String; function GetValue: Variant; procedure SetAsDateTime(const Value: TDateTime); procedure SetAsFloat(const Value: Double); procedure SetAsInteger(const Value: Integer); procedure SetAsString(const Value: String); procedure SetColumName(const Value: String); procedure SetDataType(const Value: TFieldType); procedure SetDisplayName(const Value: String); procedure SetFloatPrecision(const Value: Integer); procedure SetIncludeOnInsert(const Value: Boolean); procedure SetIndex(const Value: Integer); procedure SetKey(const Value: Boolean); procedure SetMastercolumnname(const Value: String); procedure SetMasterTableName(const Value: String); procedure SetNullIfZero(const Value: Boolean); procedure SetOldValue(const Value: Variant); procedure SetReadOnly(const Value: Boolean); procedure SetRequired(const Value: Boolean); procedure SetSaveDateTimeFormat(const Value: Boolean); procedure SetValue(const Value: Variant); procedure SetSequence(const Value: Boolean); protected public Constructor Create(aOwner : TDbObject); Destructor Destroy; Override; procedure Clear; {Descrição "amigável" da coluna a ser exibida em mensagens de erro} property DisplayName: String read FDisplayName write SetDisplayName; {Referencia o DbObject owner da coluna} //property Owner :TDbObject read FOwner; {Indica se o valor será preenchido com null caso seja zero ou ''} property NullIfZero :Boolean read FNullIfZero write SetNullIfZero; {Nome da coluna no banco de dados} property ColumName :String read FColumName write SetColumName; {Indica se a coluna é chave da tabela} property Key :Boolean read FKey write SetKey; property Sequence: Boolean read FSequence write SetSequence; property IncludeOnInsert: Boolean read FIncludeOnInsert write SetIncludeOnInsert; {Indica o tipo da coluna no banco de dados} property DataType :TFieldType read FDataType write SetDataType; {Indica se a coluna é not null} property Required :Boolean read FRequired write SetRequired; {Indica se a coluna é somente para leitura} property ReadOnly :Boolean read FReadOnly write SetReadOnly; {Indica da coluna} property Index :Integer read FIndex write SetIndex; {indica se a coluna esta vazia para strings, 0 para numero ou null para data e variant} property IsNull: Boolean read GetIsNull; {manipula o valor da coluna como uma string} property AsString: String read GetsString write SetAsString; {manipula o valor da coluna como um float} property AsFloat :Double read GetAsFloat write SetAsFloat; {manipula o valor da coluna como um inteiro} property AsInteger :Integer read GetAsInteger write SetAsInteger; {manipula o valor da coluna como um DateTime} property AsDateTime :TDateTime read GetAsDateTime write SetAsDateTime; {manipula o valor da coluna como um Variant} property Value :Variant read GetValue write SetValue; {manipula o valor da coluna como um Variant} property OldValue: Variant read FOldValue write SetOldValue; {Nº de casas decimais utilizadas para formatação de valores do tipo float} property FloatPrecision: Integer read FFloatPrecision write SetFloatPrecision; {indica se a data será gravada com formatação de hora} property SaveDateTimeFormat: Boolean read FSaveDateTimeFormat write SetSaveDateTimeFormat; property MasterTableName: String read FMasterTableName write SetMasterTableName; property Mastercolumnname: String read FMastercolumnname write SetMastercolumnname; end; //////////////////////////////////////////////////////////////////////////////// /// Classe para Persistência //////////////////////////////////////////////////////////////////////////////// TDbObject = class(TCustomDbObject) private FDataBaseName: String; FErrorIfNoRowsAffected: Boolean; FTableName: String; fOwner: TCustomDbObject; FUseSequenceOnInsert: Boolean; FExecuteCommand: Boolean; procedure SetErrorIfNoRowsAffected(const Value: Boolean); procedure SetTableName(const Value: String); function GetFields(x: Integer): TDbField; {Monta o array de valores e nomes das colunas para montagem dos SQL's de INSERT, DELETE, UPDATE} //Procedure BuildArray(Var CampoValores :Array of Const; Var CampoNome :Array of String; Var CampoNullIfZero :Array of Boolean); Procedure BuildArray(Var CampoValores :Variant; Var CampoNome :Array of String; Var CampoNullIfZero :Array of Boolean; Var aFloatPrecision :Array of Integer; Var aSaveDateTimeFormat: Array of Boolean; Var aIncludeOnInsert: Array of Boolean); {Libera o array de valores e nomes das colunas para montagem dos SQL's de INSERT, DELETE, UPDATE} //Procedure FreeArray(Var CampoValores :Array of Const); Procedure SetDbFields; {Método para gravação de colunas do tipo "Blob" ou LONGRAW no Oracle} procedure SetUseSequenceOnInsert(const Value: Boolean); procedure SetExecuteCommand(const Value: Boolean); protected _CdsSelect: TClientDataSet; fSqlInsert: String; fSqlUpdate: String; fSqlDelete: String; _UpdateKeyFields: Boolean; _DbOperacao: TOperacaoBd; _ListDbField :TList; {Query ultilizada para execução dos comandos} procedure SetDbSessionName; function GetSequence(Table, field :string) :Integer; Override; {Monta Where para frases de update e delete Tal procedimento é interno da aplicação e considera os parâmetros de criação do TDbField} function MontaWhere(OldValue: Boolean = False): String; {Executa frase SQL validando preenchimento, erro de execução, erro se não afetar registros retornado a string do erro para o MessageInfo Tal procedimento é interno da aplicação e considera os parâmetros de criação do TDbField} function ExecuteSql (Const sSql:string; bErrorIfNoRowsAffected :boolean = false; MsgErrorRowsAffected :String = '') :Boolean; {Cria as instâncias das propriedades de persistência com as colunas da tabelas} function CreateDbField(ColumName: String; DataType: TFieldType; Required: Boolean = false; Key: Boolean = false; ReadOnly: Boolean = false; NullIfZero: Boolean = True; sDisplayName: String = ''; iFloatPrecision: Integer = -1; bSaveDateTimeFormat: Boolean = false; bIncludeOnInsert: Boolean = True; bSequence: Boolean = True; MasterTableName: String = ''; Mastercolumnname: String = '') : TDbField; {Verifica antes de um Insert ou Update se os campos ditos com required estão preenchidos} function ValidateNullFields :Boolean; {Retorna o nome dos fields do dbobject separados por vírgulas} function GetFieldsForSelect: String; procedure SetDataBaseName(const Value: String); Override; {Monta a consulta a ser executada nos métodos LOADFROMDB e BEFOREOPEN do clientDataSet associado a classe de persistência. Esse método deve ser sobrescrito quando quisermos utilizar uma consulta diferente da consulta padrão do Objeto} function GetSqlSelect: String; Virtual; {Evento before open da query associada ao CLientDataSet da classe} { function ExecSql(sSql: String): Boolean; } public Constructor Create(Aowner: TCustomdbObject); Reintroduce; Virtual; Destructor Destroy; Override; {"Limpa" todas os DBFields da Classe} procedure Clear; Virtual; {Executa o SQL de Insert com os parâmetros passados nas propriedades} function Insert :Boolean; virtual; {Executa o SQL de Delete com os parâmetros passados nas propriedades} function Delete :Boolean; virtual; {Executa o SQL de Update com os parâmetros passados nas propriedades} function Update :Boolean; virtual; {Atribui para as propriedades os valores do registro no banco de dados de acordo como os campos chave} function LoadFromDb :Boolean; virtual; {Atribui as Colunas do Client DataSet para o DbObject} procedure LoadFromCds(Cds: TClientDataSet); {Retorna o Número de DbField's do DbObject} Function FieldCount : Integer; {Acessa os DbField's do DbObject pelo nome} function FieldByName(const Name: string): TDbField; {Procura i FieldName da DbObject} function FindField(const Name: String): Boolean; {Verifica se o conteúdo dos Db Fields são idênticos a um registro do DbObject passado como parâmetro} function IsEqual(DbFieldCompare: TDbObject): Boolean; {Métodos utilizados para posicionamento do classe de persistência quando a query principal da mesma retorna mais de um registro. Isso ocorre quando sobrescrevemos o método GetSQLSelect} procedure First; Procedure Prior; Procedure Next; Procedure Last; function Eof: Boolean; function Bof: Boolean; function RecordCount: Integer; procedure setKeys(AKeys: array of TDbField); {Comando SQL de Select com parâmetro de filtro pelo ID e/ou Foreign Key no caso de Master Detail} property SSqlSelect :String read GetSqlSelect; {Comando SQL de Insert} property SSqlInsert :String read fSqlInsert; {Comando SQL de Update} property SSqlUpdate :String read fSqlUpdate; {Comando SQL de Delete} property SSqlDelete :String read fSqlDelete; {Habilita a geração de exceção qdo os comando de Delete e Update não afetar nenhum registro} property ErrorIfNoRowsAffected :Boolean read FErrorIfNoRowsAffected write SetErrorIfNoRowsAffected; {Nome da tabela a ser persistida} property TableName :String read FTableName write SetTableName; {Acessa os DbField's do DbObject pelo índice} property Fields[x:Integer]: TDbField Read GetFields; property Owner:TCustomdbObject read fOwner; property UseSequenceOnInsert: Boolean read FUseSequenceOnInsert write SetUseSequenceOnInsert; property ExecuteCommand: Boolean read FExecuteCommand write SetExecuteCommand; end; implementation { TDbObject } uses uMontaSql; function TDbObject.Bof: Boolean; begin Result := _CdsSelect.Bof; end; procedure TDbObject.BuildArray( var CampoValores: Variant; var CampoNome: array of String; var CampoNullIfZero: array of Boolean; var aFloatPrecision: array of Integer; var aSaveDateTimeFormat, aIncludeOnInsert: array of Boolean); Var x : Integer; sValor : String; rValor : Extended; begin For x := 0 To Pred(FieldCount) Do Begin aFloatPrecision[x] := TDbField(_ListDbField.Items[x]).FloatPrecision; aSaveDateTimeFormat[x] := TDbField(_ListDbField.Items[x]).SaveDateTimeFormat; aIncludeOnInsert[x] := TDbField(_ListDbField.Items[x]).IncludeOnInsert; If TDbField(_ListDbField.Items[x]).DataType <> ftBlob Then Begin If (TDbField(_ListDbField.Items[x]).Key) And (_DbOperacao = dbUpdate) And (Not _UpdateKeyFields) Then Begin (*CampoNome[x] := CMInvalidField; CampoNullIfZero[x] := False; sValor := CMInvalidField; *) //CampoValores[x].VType := vtString; //GetMem(CampoValores[x].vString,Length(sValor) + 1); //CampoValores[x].vString^ := sValor; CampoValores[x] := sValor; End Else Begin {Alimenta o array com os nomes das colunas} CampoNome[x] := TDbField(_ListDbField.Items[x]).ColumName; CampoNullIfZero[x] := TDbField(_ListDbField.Items[x]).NullIfZero; {limenta o array com os valores das colunas. De acordo com o tipo de dado do field é alimentado o CONST da função de Update/Insert. É ultilizado um Array of TVarRec pq este equivale ao Array of Const. O GetMem aloca o espaço para o ponteiro de acordo com o tamanho do dado a ser endereçado para ele. É nescessário desalocar o array com o FreeMem. Esse procedimento só é utilizado para os Dados do tipo String, Extended e Variant.} Case TDbField(_ListDbField.Items[x]).DataType Of ftString :Begin sValor := TDbField(_ListDbField.Items[x]).AsString; (*CampoValores[x].VType := vtString; GetMem(CampoValores[x].vString,Length(sValor) + 1); CampoValores[x].vString^ := sValor;*) CampoValores[x] := sValor; End; ftSmallint, ftInteger, ftWord :Begin //CampoValores[x].VType := vtInteger; //CampoValores[x].VInteger := TCmDbField(_ListDbField.Items[x]).AsInteger; CampoValores[x] := TDbField(_ListDbField.Items[x]).AsInteger; End; ftFloat, ftCurrency, ftBCD :Begin rValor := TDbField(_ListDbField.Items[x]).AsFloat; (*CampoValores[x].VType := vtExtended; GetMem(CampoValores[x].VExtended,SizeOf(rValor)); CampoValores[x].VExtended^ := rValor;*) CampoValores[x] := rValor; End; Else CampoValores[x] := TDbField(_ListDbField.Items[x]).AsDateTime; End; End; End; (* Else Begin CampoNome[x] := CMFieldBlob; CampoNullIfZero[x] := False; sValor := CMFieldBlob; CampoValores[x] := sValor; (*CampoValores[x].VType := vtString; GetMem(CampoValores[x].vString,Length(sValor) + 1); CampoValores[x].vString^ := sValor; End;*) End; end; procedure TDbObject.Clear; Var X: Integer; begin For X := (_ListDbField.Count - 1) DownTo 0 Do TDbField(_ListDbField.Items[x]).clear; end; constructor TDbObject.Create(Aowner: TCustomdbObject); begin Inherited Create; FExecuteCommand := True; fOwner := Aowner; _CdsSelect := TClientDataSet.Create(nil); fSqlInsert := ''; fSqlUpdate := ''; fSqlDelete := ''; fErrorIfNoRowsAffected := False; FConexaoPadrao := AOwner.Conexao; _ListDbField := TList.Create; _UpdateKeyFields := False; FUseSequenceOnInsert := True; end; function TDbObject.CreateDbField(ColumName: String; DataType: TFieldType; Required, Key, ReadOnly, NullIfZero: Boolean; sDisplayName: String; iFloatPrecision: Integer; bSaveDateTimeFormat, bIncludeOnInsert: Boolean; bSequence: Boolean; MasterTableName, Mastercolumnname: String): TDbField; Var Indice :Integer; begin Result := TDbField.Create(self); Result.Required := Required; Result.Key := Key; Result.ReadOnly := ReadOnly; Result.ColumName := ColumName; Result.DataType := DataType; Result.NullIfZero := NullIfZero; Result.DisplayName := sDisplayName; Result.SaveDateTimeFormat := bSaveDateTimeFormat; Result.FloatPrecision := iFloatPrecision; Result.IncludeOnInsert := bIncludeOnInsert; Result.MasterTableName := MasterTableName; Result.Mastercolumnname := Mastercolumnname; Result.Sequence := bSequence; Indice := _ListDbField.Add(Result); Result.Index := Indice; //If DataType = ftBlob Then Inc(_iNumBlobFields); end; function TDbObject.Delete: Boolean; begin _DbOperacao := dbDelete; fSqlDelete := 'DELETE FROM ' + TableName + ' WHERE ' + MontaWhere; if FExecuteCommand then Result := ExecuteSql(fSqlDelete, FErrorIfNoRowsAffected, cMsgErrorRowsAffectedDelete) else Result := True; end; destructor TDbObject.Destroy; Var X :Integer; begin For X := (_ListDbField.Count - 1) DownTo 0 Do TDbField(_ListDbField.Items[x]).Free; _ListDbField.Clear; _ListDbField.Free; _CdsSelect.Free; inherited Destroy; end; function TDbObject.Eof: Boolean; begin Result := _CdsSelect.Eof; end; function TDbObject.ExecuteSql(const sSql: string; bErrorIfNoRowsAffected: boolean; MsgErrorRowsAffected: String): Boolean; begin Try MessageInfo := ''; If Trim(sSql) = '' Then Raise EDbObjectError.Create('Instrução SQL Vazia'); result := FConexaoPadrao.ExecSQL(sSQL); if (not result) And bErrorIfNoRowsAffected then raise EDbObjectError.Create(MsgErrorRowsAffected); Except On E :Exception Do Begin Result := False; MessageInfo := e.Message; End; End; end; function TDbObject.FieldByName(const Name: string): TDbField; Var X: Integer; bAchou: Boolean; begin bAchou := False; For X:= 0 To FieldCount - 1 Do If UpperCase(TDbField(_ListDbField[x]).ColumName) = UpperCase(Name) Then Begin bAchou := True; Break; End; If bAchou Then Result := TDbField(_ListDbField[x]) Else Raise Exception.Create('CMsgFieldNameNotFound'); end; function TDbObject.FieldCount: Integer; begin Result := _ListDbField.Count; end; function TDbObject.FindField(const Name: String): Boolean; begin try FieldByName(Name); Result := True; except on e : Exception do Result := false; end; end; procedure TDbObject.First; begin _CdsSelect.First; SetDbFields; end; function TDbObject.GetFields(x: Integer): TDbField; begin Result := TDbField(_ListDbField[x]); end; function TDbObject.GetFieldsForSelect: String; Var X: Integer; sAux: String; Begin sAux := ''; For X := 0 To pred(_ListDbField.Count) Do If Saux = '' Then sAux := TDbField(_ListDbField.Items[x]).ColumName Else sAux := sAux + ', ' + TDbField(_ListDbField.Items[x]).ColumName; Result := sAux; End; function TDbObject.GetSequence(Table, field: string): Integer; var codigo: Integer; begin codigo := FConexaoPadrao.LeUltimoRegistro(Table, Field) + 1; //FConexaoPadrao.insereUltimoRegistro(Table, codigo); Result := codigo; end; function TDbObject.GetSqlSelect: String; var where: string; begin where := MontaWhere; Result := 'SELECT ' + GetFieldsForSelect + ' FROM ' + fTableName; if Trim(where) <> '' then result := result + ' WHERE ' + MontaWhere; end; function TDbObject.Insert: Boolean; Var CampoNome : Array Of String; //CampoValores : Array Of TVarRec; CampoValores : variant; CampoNullIfZero : array of boolean; aFloatPrecision: Array of Integer; aSaveDateTimeFormat: Array of boolean; aIncludeOnInsert: Array of boolean; i : Integer; begin SetDbSessionName; for i := 0 to FieldCount - 1 do if (Fields[i].Key) and (Fields[i].Sequence) then Fields[i].AsInteger := GetSequence(TableName, Fields[i].ColumName); _DbOperacao := dbInsert; SetLength(CampoNome,FieldCount); //SetLength(CampoValores,FieldCount); CampoValores := VarArrayCreate([0,pred(FieldCount)],varVariant); SetLength(CampoNullIfZero,FieldCount); SetLength(aFloatPrecision,FieldCount); SetLength(aIncludeOnInsert,FieldCount); SetLength(aSaveDateTimeFormat,FieldCount); BuildArray(CampoValores, CampoNome, CampoNullIfZero, aFloatPrecision, aSaveDateTimeFormat, aIncludeOnInsert); fSqlInsert := TMontaSQL.SqlInsert(FTableName, CampoValores, CampoNome, CampoNullIfZero, aSaveDateTimeFormat, aIncludeOnInsert, aFloatPrecision, Self); if FExecuteCommand then begin Result := ValidateNullFields; with TStringList.Create do begin Add(fSqlInsert); SaveToFile('sql.sql'); Free; end; if result then result := ExecuteSql(fSqlInsert); end else Result := True; //FreeArray(Campovalores); SetLength(CampoNome,0); //SetLength(CampoValores,0); CampoValores := null; SetLength(CampoNullIfZero,0); SetLength(aFloatPrecision,0); SetLength(aIncludeOnInsert,0); SetLength(aSaveDateTimeFormat,0); end; function TDbObject.IsEqual(DbFieldCompare: TDbObject): Boolean; Var x : Integer; begin Result := False; for x := 0 To Pred( Self.FieldCount ) Do begin If Self.FieldByName(Self.Fields[x].ColumName).DataType = FtDateTime Then Result := ( Self.FieldByName(Self.Fields[x].ColumName).AsDateTime = DbFieldCompare.FieldByName(Self.Fields[x].ColumName).AsDateTime ) Else Result := ( Self.FieldByName(Self.Fields[x].ColumName).Value = DbFieldCompare.FieldByName(Self.Fields[x].ColumName).Value ); if Not Result Then Break; end; end; procedure TDbObject.Last; begin _CdsSelect.Last; SetDbFields; end; procedure TDbObject.LoadFromCds(Cds: TClientDataSet); Var x : Integer; begin Clear; for x := 0 To Pred( FieldCount ) Do If Cds.Fields.FindField(Fields[x].ColumName) <> nil Then Begin If FieldByName(Fields[x].ColumName).DataType = FtDateTime Then FieldByName(Fields[x].ColumName).AsDateTime := Cds.Fields.FieldByName(Fields[x].ColumName).AsDateTime Else FieldByName(Fields[x].ColumName).Value := Cds.Fields.FieldByName(Fields[x].ColumName).Value; If (Cds.Fields.FieldByName(Fields[x].ColumName).OldValue = null) And (FieldByName(Fields[x].ColumName).DataType = FtDateTime) Then FieldByName(Fields[x].ColumName).OldValue := 0 ELse FieldByName(Fields[x].ColumName).OldValue := Cds.Fields.FieldByName(Fields[x].ColumName).OldValue; End; end; function TDbObject.LoadFromDb: Boolean; begin SetDbSessionName; _CdsSelect.Data := FConexaoPadrao.GetDataPacket(GetSqlSelect); SetDbFields; Result := Not _CdsSelect.IsEmpty; end; function TDbObject.MontaWhere(OldValue: Boolean): String; Var sAuxDec: Char; sWhere: String; X: Integer; dData: TDateTime; sData: string; begin sWhere := ''; For x := 0 To Pred(FieldCount) Do Begin Case TDbField(_ListDbField.Items[x]).DataType Of ftString: If TDbField(_ListDbField.Items[x]).Key Then Begin If OldValue Then sWhere := sWhere + ' (' + TDbField(_ListDbField.Items[x]).ColumName + ' = ' + QuotedStr(TDbField(_ListDbField.Items[x]).OldValue) + ') AND' Else sWhere := sWhere + ' (' + TDbField(_ListDbField.Items[x]).ColumName + ' = ' + QuotedStr(TDbField(_ListDbField.Items[x]).AsString) + ') AND'; End; ftSmallint, ftInteger, ftWord: If (TDbField(_ListDbField.Items[x]).Key) Then Begin if (TDbField(_ListDbField.Items[x]).AsInteger = -1) or (TDbField(_ListDbField.Items[x]).AsInteger >0) then begin If OldValue Then sWhere := sWhere + ' (' + TDbField(_ListDbField.Items[x]).ColumName + ' = ' + FloatToStr(TDbField(_ListDbField.Items[x]).OldValue) + ') AND' Else sWhere := sWhere + ' (' + TDbField(_ListDbField.Items[x]).ColumName + ' = ' + IntToStr(TDbField(_ListDbField.Items[x]).AsInteger) + ') AND'; end else sWhere := ' (' + TDbField(_ListDbField.Items[x]).ColumName + ' <> -9999) AND'; End; ftFloat, ftCurrency, ftBCD: Begin //sAuxDec := DecimalSeparator; Try //DecimalSeparator := '.'; If TDbField(_ListDbField.Items[x]).Key Then Begin if (TDbField(_ListDbField.Items[x]).AsFloat > 0) then begin If OldValue Then sWhere := sWhere + ' (' + TDbField(_ListDbField.Items[x]).ColumName + ' = ' + FloatToStr(TDbField(_ListDbField.Items[x]).OldValue) + ') AND' Else sWhere := sWhere + ' (' + TDbField(_ListDbField.Items[x]).ColumName + ' = ' + IntToStr(TDbField(_ListDbField.Items[x]).AsInteger) + ') AND'; end else sWhere := ' (' + TDbField(_ListDbField.Items[x]).ColumName + ' <> -9999) AND'; End; finally //DecimalSeparator := sAuxDec; End; End; ftDate, ftDateTime: If TDbField(_ListDbField.Items[x]).Key Then Begin if OldValue then dData := TDbField(_ListDbField.Items[x]).OldValue else dData := TDbField(_ListDbField.Items[x]).AsDateTime; sData := QuotedStr(FormatDateTime('dd/mm/yyyy',dData)); sWhere := sWhere + ' (' + TDbField(_ListDbField.Items[x]).ColumName + ' = TO_DATE(' + sData + ',''DD/MM/YYYY'')) AND'; //If OldValue Then //sWhere := sWhere + ' (' + TDbField(_ListDbField.Items[x]).ColumName + ' = TO_DATE(' + QuotedStr(TDbField(_ListDbField.Items[x]).OldValue) + ',''DD/MM/YYYY'')) AND' //Else //sWhere := sWhere + ' (' + TDbField(_ListDbField.Items[x]).ColumName + ' = TO_DATE(' + QuotedStr(TDbField(_ListDbField.Items[x]).AsString) + ',''DD/MM/YYYY'')) AND'; End; End; End; Result := Copy(sWhere,1,Length(sWhere) - 4); end; procedure TDbObject.Next; begin _CdsSelect.Next; SetDbFields; end; procedure TDbObject.Prior; begin _CdsSelect.Prior; SetDbFields; end; function TDbObject.RecordCount: Integer; begin Result := _CdsSelect.RecordCount; end; procedure TDbObject.SetDataBaseName(const Value: String); begin inherited; FDataBaseName := Value; end; procedure TDbObject.SetDbFields; Var x : Integer; Begin If _CdsSelect.IsEmpty Then Clear Else for x := 0 To Pred(_ListDbField.Count) Do try If TDbField(_ListDbField.Items[x]).DataType = FtDateTime Then TDbField(_ListDbField.Items[x]).AsDateTime := _CdsSelect.Fields.FieldByName(TDbField(_ListDbField.Items[x]).ColumName).AsDateTime Else TDbField(_ListDbField.Items[x]).Value := _CdsSelect.Fields.FieldByName(TDbField(_ListDbField.Items[x]).ColumName).Value; If (TDbField(_ListDbField.Items[x]).DataType = FtDateTime) And (_CdsSelect.Fields.FieldByName(TDbField(_ListDbField.Items[x]).ColumName).IsNull) Then TDbField(_ListDbField.Items[x]).OldValue := 0 ELse TDbField(_ListDbField.Items[x]).OldValue := _CdsSelect.Fields.FieldByName(TDbField(_ListDbField.Items[x]).ColumName).Value; Except //Trata a Excessão para casos onde o field não existe no ClinetDataset End; End; procedure TDbObject.SetDbSessionName; begin FConexaoPadrao := fOwner.Conexao; end; procedure TDbObject.SetErrorIfNoRowsAffected(const Value: Boolean); begin FErrorIfNoRowsAffected := Value; end; procedure TDbObject.SetExecuteCommand(const Value: Boolean); begin FExecuteCommand := Value; end; procedure TDbObject.setKeys(AKeys: array of TDbField); var i : Integer; begin for i := 0 to FieldCount - 1 do Fields[i].Key := False; for i := Low(AKeys) to High(AKeys) do TDbField(AKeys[i]).Key := True; end; procedure TDbObject.SetTableName(const Value: String); begin FTableName := Value; end; procedure TDbObject.SetUseSequenceOnInsert(const Value: Boolean); begin FUseSequenceOnInsert := Value; end; function TDbObject.Update: Boolean; Var CampoNome : Array Of String; CampoValores : Variant; CampoNullIfZero : Array Of Boolean; aFloatPrecision: Array of Integer; aIncludeOnInsert: Array of boolean; aSaveDateTimeFormat: Array of boolean; begin SetDbSessionName; _DbOperacao := dbUpdate; SetLength(CampoNome,FieldCount); //SetLength(CampoValores,FieldCount); CampoValores := VarArrayCreate([0,pred(FieldCount)],varVariant); SetLength(CampoNullIfZero,FieldCount); SetLength(aFloatPrecision,FieldCount); SetLength(aIncludeOnInsert,FieldCount); SetLength(aSaveDateTimeFormat,FieldCount); BuildArray(CampoValores, CampoNome, CampoNullIfZero, aFloatPrecision, aSaveDateTimeFormat, aIncludeOnInsert); fSqlUpdate := TMontaSQL.SqlUpdate( TableName, MontaWhere(True), CampoValores, CampoNome, CampoNullIfZero, aSaveDateTimeFormat, aFloatPrecision, Self); if FExecuteCommand then begin Result := ValidateNullFields; if result then result := ExecuteSql(fSqlUpdate,FErrorIfNoRowsAffected); end else Result := true; //FreeArray(Campovalores); SetLength(CampoNome,0); //SetLength(CampoValores,0); CampoValores := null; SetLength(CampoNullIfZero,0); SetLength(aFloatPrecision,0); SetLength(aSaveDateTimeFormat,0); SetLength(aIncludeOnInsert,0); end; function TDbObject.ValidateNullFields: Boolean; Var X :Integer; begin Result := True; For X:=0 To _ListDbField.Count - 1 Do Begin If TDbField(_ListDbField.Items[x]).Required And TDbField(_ListDbField.Items[x]).IsNull Then Begin MessageInfo := Format('O campo "%s" não foi informado.', [TDbField(_ListDbField.Items[x]).DisplayName]); Result := False; Break; End; End; end; { TDbField } procedure TDbField.Clear; begin fAsString := ''; Case fDataType Of ftSmallint, ftInteger, ftWord, ftFloat, ftCurrency, ftBCD: Begin fAsFloat := 0; fAsInteger := 0; End; ftDate, ftDateTime: fAsDateTime := 0; Else fValue := null; End; fOldValue := null; end; constructor TDbField.Create(aOwner: TDbObject); begin FOwner := aOwner; FIsNull := True; FRequired := False; FKey := False; FReadOnly := False; FIndex := 0; FColumName := ''; FDataType := ftString; FAsFloat :=0; FAsInteger := 0; FAsString := ''; FAsDateTime := 0; FValue := null; fOldValue := null; fNullIfZero := True; FDisplayName := ''; end; destructor TDbField.Destroy; begin inherited; end; function TDbField.GetAsDateTime: TDateTime; begin If fDataType = ftDateTime Then Result := fAsDateTime Else Result := StrToDate(fAsString); end; function TDbField.GetAsFloat: Double; begin Case fDataType Of ftSmallint, ftInteger, ftWord, ftFloat, ftCurrency: Result := fAsFloat Else Result := StrToFloat(fAsString); End; end; function TDbField.GetAsInteger: Integer; begin Case fDataType Of ftSmallint, ftInteger, ftWord: Result := fAsInteger Else Result := StrToIntDef(fAsString,0); End; end; function TDbField.GetIsNull: Boolean; begin Case fDataType Of ftString: Result := (Trim(fAsString) = ''); ftSmallint, ftInteger, ftWord: Result := (fAsInteger = 0) And NullIfZero; ftFloat, ftCurrency, ftBCD: Result := (fAsFloat = 0) And NullIfZero; ftDate, ftDateTime: Result := (fAsDateTime = 0); Else Result := (fValue = null) Or (Trim(fAsString) = ''); End; end; function TDbField.GetsString: String; begin Result := fAsString; end; function TDbField.GetValue: Variant; begin Case fDataType Of ftString: Result := fAsString; ftSmallint, ftInteger, ftWord: Result := fAsInteger; ftFloat, ftCurrency, ftBCD: Result := fAsFloat; ftDate, ftDateTime: Result := fAsDateTime; Else Result := fValue; End; end; procedure TDbField.SetAsDateTime(const Value: TDateTime); begin FAsDateTime := Value; fAsString := DateTimeToStr(FAsDateTime); If FOldValue = null Then FOldValue := Value; end; procedure TDbField.SetAsFloat(const Value: Double); begin FAsFloat := Value; FAsInteger := Trunc(Value); fAsString := FloatToStr(FAsFloat); If FOldValue = null Then FOldValue := Value; end; procedure TDbField.SetAsInteger(const Value: Integer); begin FAsInteger := Value; fAsString := FloatToStr(FAsInteger); fAsFloat := Value; If FOldValue = null Then FOldValue := Value; end; procedure TDbField.SetAsString(const Value: String); begin FAsString := Value; Case fDataType Of ftSmallint, ftInteger, ftWord: fAsInteger := StrToIntDef(FAsString,0); ftFloat, ftCurrency, ftBCD: Begin if Trim(Value) = '' Then fAsFloat := 0 Else fAsFloat := StrToFloat(FAsString); End; ftDate, ftDateTime: Begin if Trim(Value) = '' Then fAsDateTime := 0 Else fAsDateTime := StrToDate(FAsString); End Else fValue := fAsString; End; If FOldValue = null Then FOldValue := Value; end; procedure TDbField.SetColumName(const Value: String); begin FColumName := Value; end; procedure TDbField.SetDataType(const Value: TFieldType); begin FDataType := Value; end; procedure TDbField.SetDisplayName(const Value: String); begin FDisplayName := Value; end; procedure TDbField.SetFloatPrecision(const Value: Integer); begin FFloatPrecision := Value; end; procedure TDbField.SetIncludeOnInsert(const Value: Boolean); begin FIncludeOnInsert := Value; end; procedure TDbField.SetIndex(const Value: Integer); begin FIndex := Value; end; procedure TDbField.SetKey(const Value: Boolean); begin FKey := Value; end; procedure TDbField.SetMastercolumnname(const Value: String); begin FMastercolumnname := Value; end; procedure TDbField.SetMasterTableName(const Value: String); begin FMasterTableName := Value; end; procedure TDbField.SetNullIfZero(const Value: Boolean); begin FNullIfZero := Value; end; procedure TDbField.SetOldValue(const Value: Variant); begin FOldValue := Value; end; procedure TDbField.SetReadOnly(const Value: Boolean); begin FReadOnly := Value; end; procedure TDbField.SetRequired(const Value: Boolean); begin FRequired := Value; end; procedure TDbField.SetSaveDateTimeFormat(const Value: Boolean); begin FSaveDateTimeFormat := Value; end; procedure TDbField.SetSequence(const Value: Boolean); begin FSequence := Value; end; procedure TDbField.SetValue(const Value: Variant); begin FValue := Value; If Value = Null Then SetAsString('') Else SetAsString(Value); end; end. (*type TDbObject = class(TComponent) private _fdCursor : TFDGUIxWaitCursor; _fdDriverFB : TFDPhysFBDriverLink; _FdDriverMySql : TFDPhysMySQLDriverLink; _fdQuery : TFDQuery; _dsProvider : TDataSetProvider; FTableName: string; FMessageInfo: string; procedure SetTableName(const Value: string); function trataException(AException: Exception): Boolean; protected function CreateDBField(AName : string; ARequired : Boolean; AKey : Boolean; AAutoInc : Boolean; AFieldType : TFieldType; ANullIfZero: Boolean = False; ACaption : String = ''): TDbField; function GetSequence(ASequenceName: String = ''): Integer; public property TableName: string read FTableName write SetTableName; property MessageInfo: string read FMessageInfo; procedure clear; procedure StartTransaction; procedure Commit; procedure RollBack; function GetDataPacket(ASql: string): OleVariant; function ExecSql(ASql: String): Boolean; function ExecSqlAndCommit(ASql: String): Boolean; function FieldByName(AName: String): TDbField; //////////////////////////////////////////////////////////////////////////// /// CRUD //////////////////////////////////////////////////////////////////////////// function Insert(bCommit: Boolean = True): Boolean; function Update(bCommit: Boolean = True): Boolean; function Delete(bCommit: Boolean = True): Boolean; function LoadFromDb(originalKey: array of TDbField; temporalKeys: array of TDbField; values: array of variant): Boolean; function SSqlSelect : string; function SSqlInsert : string; function SSqlUpdate : string; function SSqlDelete : string; constructor create; destructor destroy; end; implementation { TDbObject } procedure TDbObject.clear; var i : Integer; begin for i := 0 to ComponentCount -1 do begin if Components[i] is TDbField then TDbField(Components[i]).Clear; end; end; procedure TDbObject.Commit; begin DM.fdConn.Commit; end; constructor TDbObject.create; begin _fdCursor := TFDGUIxWaitCursor.Create(nil); _fdDriverFB := TFDPhysFBDriverLink.Create(nil); _FdDriverMySql := TFDPhysMySQLDriverLink.Create(nil); _fdQuery := TFDQuery.Create(nil); _fdQuery.Connection := DM.fdConn; _dsProvider := TDataSetProvider.Create(nil); _dsProvider.DataSet := _fdQuery; _FdDriverMySql.VendorLib := ExtractFilePath(Application.ExeName) + '\libmysql.dll'; end; destructor TDbObject.destroy; begin if _fdQuery.Active then _fdQuery.Close; FreeAndNil(_dsProvider); FreeAndNil(_fdQuery); FreeAndNil(_fdDriverFB); FreeAndNil(_fdCursor); end; function TDbObject.ExecSql(ASql: String): Boolean; begin result := False; try _fdQuery.SQL.Clear; _fdQuery.SQL.Text := ASql; _fdQuery.ExecSQL; Result := True; except on e : Exception do result := trataException(e); end; end; function TDbObject.ExecSqlAndCommit(ASql: String): Boolean; begin Result := False; StartTransaction; Result := ExecSql(ASql); if Result then Commit else RollBack; end; function TDbObject.FieldByName(AName: String): TDbField; var i : Integer; field : TDbField; begin result := nil; for i := 0 to ComponentCount - 1 do begin if Components[i] is TDbField then begin field := TDbField(Components[i]); if field.Name.ToUpper = AName.ToUpper then result := field; end; end; end; function TDbObject.GetDataPacket(ASql: string): OleVariant; begin try _fdQuery.Close; _fdQuery.SQL.Text := ASql; _fdQuery.Open; result := _dsProvider.Data; except on e : Exception do raise Exception.Create('Erro ao executar a instrução SQL: ' + Chr(13) + ASql + Chr(13) + e.Message); end; end; function TDbObject.GetSequence(ASequenceName: String): Integer; var cds : TClientDataSet; sequence: string; begin result := 0; sequence := ASequenceName; if sequence = '' then sequence := 'SEQ' + TableName; //ExecSqlAndCommit() try cds := TClientDataSet.Create(nil); cds.Data := GetDataPacket('SELECT GEN_ID(' + sequence + ', 1) from rdb$database'); Result := cds.FieldByName('GEN_ID').AsInteger; except on e: Exception do raise Exception.Create(e.Message); end; cds.Free; end; function TDbObject.Insert(bCommit: Boolean): Boolean; begin if bCommit then Result := ExecSqlAndCommit(SSqlInsert) else result := ExecSql(SSqlInsert); end; function TDbObject.Update(bCommit: Boolean): Boolean; begin if bCommit then Result := ExecSqlAndCommit(SSqlUpdate) else result := ExecSql(SSqlUpdate); end; function TDbObject.Delete(bCommit: Boolean): Boolean; begin if bCommit then Result := ExecSqlAndCommit(SSqlDelete) else result := ExecSql(SSqlDelete); end; function TDbObject.LoadFromDb(originalKey: array of TDbField; temporalKeys: array of TDbField; values: array of variant): Boolean; var cds : TClientDataSet; i : Integer; begin if Length(originalKey) > 0 then begin for i := Low(originalKey) to High(originalKey) do TDbField(originalKey[i]).Key := False; end; if Length(temporalKeys) > 0 then begin for i := Low(temporalKeys) to High(temporalKeys) do begin TDbField(temporalKeys[i]).Key := True; TDbField(temporalKeys[i]).Value := values[i]; end; end; cds := TClientDataSet.Create(Self); cds.Data := GetDataPacket(SSqlSelect); result := cds.RecordCount > 0; if result then begin for i := 0 to ComponentCount - 1 do begin if Components[i] is TDbField then TDbField(Components[i]).Value := cds.FieldByName(TDbField(Components[i]).Name).Value; end; end; if Length(temporalKeys) > 0 then begin for i := Low(temporalKeys) to High(temporalKeys) do TDbField(temporalKeys[i]).Key := False; end; if Length(originalKey) > 0 then begin for i := Low(originalKey) to High(originalKey) do TDbField(originalKey[i]).Key := True; end; cds.Free; end; procedure TDbObject.RollBack; begin DM.fdConn.Rollback; end; procedure TDbObject.SetTableName(const Value: string); begin FTableName := Value; end; function TDbObject.SSqlDelete: string; var i : Integer; campo : string; delete : string; where : string; campos : Integer; field : TDbField; valor : string; begin delete := 'DELETE FROM ' + TableName + ' '; where := ' WHERE 1 = 1 '; campos := 0; for i := 0 to ComponentCount - 1 do begin if Components[i] is TDbField then begin field := TDbField(Components[i]); campo := field.Name; if field.FieldType in [ftInteger, ftSmallint, ftShortint] then valor := field.AsString else if field.FieldType = ftString then valor := QuotedStr( field.AsString ); if field.Key then where := where + ' AND ' + campo + ' = ' + valor; end; end; Result := delete + where; end; function TDbObject.SSqlInsert: string; var i : Integer; campo : string; insert : string; values : string; campos : Integer; field : TDbField; valor : string; begin insert := ' INSERT INTO ' + TableName + ' ('; values := ' VALUES ('; campos := 0; for i := 0 to ComponentCount - 1 do begin if Components[i] is TDbField then begin field := TDbField(Components[i]); campo := field.Name; if not field.AutoInc then begin if field.AutoInc then valor := GetSequence.ToString else if field.FieldType in [ftInteger, ftSmallint, ftShortint] then valor := field.AsString else if field.FieldType = ftString then valor := QuotedStr( field.AsString ); if campos = 0 then begin insert := insert + field.Name; values := values + valor; end else begin insert := insert + ', ' + field.Name; values := values + ', ' + valor; end; campos := campos + 1; end; end; end; insert := insert + ')'; values := values + ')'; Result := insert + values; end; function TDbObject.SSqlSelect: string; var i : Integer; sql : string; where : string; campo : string; begin where := ' WHERE 1 = 1 '; sql := 'SELECT '; for i := 0 to ComponentCount - 1 do begin if Components[i] is TDbField then begin campo := TableName + '.' + TDbField(Components[i]).Name; if i = 0 then sql := sql + campo else sql := sql + ', ' + campo; end; end; sql := sql + ' FROM ' + TableName; for i := 0 to ComponentCount - 1 do begin if Components[i] is TDbField then begin with TDbField(Components[i]) do begin if (Key) and ( not VarIsNull(Value)) then begin where := where + ' AND ' + TableName + '.' + Name + ' = '; if FieldType in [ftInteger, ftSmallint, ftShortint] then where := where + AsInteger.ToString else if FieldType = ftString then where := where + QuotedStr(AsString); end; end; end; end; result := sql + where; end; function TDbObject.SSqlUpdate: string; var i : Integer; campo : string; update : string; where : string; campos : Integer; field : TDbField; valor : string; begin update := 'UPDATE ' + TableName + ' SET '; where := ' WHERE 1 = 1 '; campos := 0; for i := 0 to ComponentCount - 1 do begin if Components[i] is TDbField then begin field := TDbField(Components[i]); campo := field.Name; if field.FieldType in [ftInteger, ftSmallint, ftShortint] then valor := field.AsString else if field.FieldType = ftString then valor := QuotedStr( field.AsString ); if campos = 0 then update := update + campo + ' = ' + valor else update := update + ', ' + campo + ' = ' + valor; campos := campos + 1; if field.Key then where := where + ' AND ' + campo + ' = ' + valor; end; end; Result := update + where; end; procedure TDbObject.StartTransaction; begin DM.fdConn.StartTransaction; end; function TDbObject.trataException(AException: Exception): Boolean; begin FMessageInfo := AException.ClassName + ': ' + AException.Message; Result := False; end; function TDbObject.CreateDBField(AName : string; ARequired : Boolean; AKey : Boolean; AAutoInc : Boolean; AFieldType : TFieldType; ANullIfZero: Boolean = False; ACaption : String = ''): TDbField; begin result := TDbField.create(Self, AName, AKey, AAutoInc, ARequired, AFieldType, ANullIfZero, ACaption); end; *)
{*************************************************************** * * Project : Traceroute * Unit Name: fmTraceRouteMainU * Purpose : Demonstrates a TraceRoute using ICMP * Version : 1.0 * Date : Wed 25 Apr 2001 - 01:38:35 * Author : <unknown> * History : * Tested : Wed 25 Apr 2001 // Allen O'Neill <allen_oneill@hotmail.com> * ****************************************************************} unit fmTraceRouteMainU; interface uses {$IFDEF Linux} QGraphics, QControls, QForms, QDialogs, QStdCtrls, QComCtrls, QExtCtrls, QActnList, {$ELSE} windows, messages, graphics, controls, forms, dialogs, comctrls, actnlist, stdctrls, spin, extctrls, {$ENDIF} SysUtils, Classes, IdBaseComponent, IdComponent, IdRawBase, IdRawClient, IdIcmpClient, IdAntiFreezeBase, IdAntiFreeze; type TfmTracertMain = class(TForm) Panel1: TPanel; Panel2: TPanel; Panel3: TPanel; Panel4: TPanel; lbLog: TListBox; Label1: TLabel; Label2: TLabel; ActionList1: TActionList; edTarget: TEdit; seMaxHops: TSpinEdit; Button1: TButton; acGo: TAction; acResolve: TAction; acPing: TAction; acTrace: TAction; lvTrace: TListView; IdIcmpClient: TIdIcmpClient; IdAntiFreeze1: TIdAntiFreeze; Splitter1: TSplitter; Button2: TButton; acStop: TAction; procedure edTargetChange(Sender: TObject); procedure acResolveExecute(Sender: TObject); procedure acGoExecute(Sender: TObject); procedure acPingExecute(Sender: TObject); procedure acTraceExecute(Sender: TObject); procedure lvTraceCompare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); procedure acStopExecute(Sender: TObject); private { Private declarations } bResolved: Boolean; ResolvedHost: String; Stopped: Boolean; function PingHost(Host: string; TTL: Integer): boolean; function FindItem(TTL: Integer; Add: boolean): TListItem; public { Public declarations } end; var fmTracertMain: TfmTracertMain; implementation uses IdStack, IdException; {$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF} procedure TfmTracertMain.edTargetChange(Sender: TObject); begin bResolved := false; end; procedure TfmTracertMain.acResolveExecute(Sender: TObject); begin bResolved := false; lbLog.Items.Append(Format('resolving %s',[edTarget.text])); try Application.ProcessMessages; ResolvedHost := gStack.WSGetHostByName(edTarget.text); bResolved := true; lbLog.Items.Append(format('%s resolved to %s',[edTarget.text, ResolvedHost])); except on e: EIdSocketError do lbLog.Items.text := lbLog.Items.text + e.message; end; end; procedure TfmTracertMain.acGoExecute(Sender: TObject); var saveCursor: TCursor; begin saveCursor := Screen.Cursor; Screen.Cursor := crHourGlass; try Stopped := false; acGo.Enabled := false; acStop.enabled := true; acResolve.execute; if bResolved and not stopped then begin acPing.execute; if not stopped then acTrace.Execute; end; acGo.Enabled := true; acStop.enabled := false; finally Screen.Cursor := saveCursor; end; { try/finally } end; function TfmTracertMain.PingHost(Host: string; TTL: Integer): Boolean; begin result := false; IdIcmpClient.Host := Host; IdIcmpClient.TTL := TTL; IdIcmpClient.ReceiveTimeout := 5000; IdIcmpClient.Ping; case IdIcmpClient.ReplyStatus.ReplyStatusType of rsEcho: begin lbLog.Items.Append(format('response from host %s in %d millisec.', [ IdIcmpClient.ReplyStatus.FromIpAddress, IdIcmpClient.ReplyStatus.MsRoundTripTime ])); result := true; end; rsError: lbLog.Items.Append('Unknown error.'); rsTimeOut: lbLog.Items.Append('Timed out.'); rsErrorUnreachable: lbLog.Items.Append(format('Host %s reports destination network unreachable.', [ IdIcmpClient.ReplyStatus.FromIpAddress ])); rsErrorTTLExceeded: lbLog.Items.Append(format('Hope %d %s: TTL expired.', [ IdIcmpClient.TTL, IdIcmpClient.ReplyStatus.FromIpAddress ])); end; // case end; procedure TfmTracertMain.acPingExecute(Sender: TObject); begin PingHost(ResolvedHost, seMaxHops.value); Application.ProcessMessages; end; function TfmTracertMain.FindItem(TTL: Integer; Add: boolean): TListItem; var i: Integer; begin result := nil; // Find the TTL item if lvTrace.Items.Count < TTL Then begin for i := 0 to lvTrace.Items.Count - 1 do begin if StrToIntDef(lvTrace.Items[i].Caption, -1) = TTL then begin result := lvTrace.Items[i]; Break; end; end; end; if not assigned( result ) then begin // Not found, add it result := lvTrace.Items.Add; result.Caption := IntToStr(TTL); end; end; procedure TfmTracertMain.acTraceExecute(Sender: TObject); var TTL: Integer; Reached: boolean; aItem: TListItem; begin TTL := 0; reached := false; lvTrace.Items.Clear; repeat inc(TTL); IdIcmpClient.Host := ResolvedHost; IdIcmpClient.TTL := TTL; IdIcmpClient.ReceiveTimeout := 5000; IdIcmpClient.Ping; aItem := FindItem(TTL, True); aItem.SubItems.Clear; case IdIcmpClient.ReplyStatus.ReplyStatusType of rsEcho: begin aItem.SubItems.Append(IdIcmpClient.ReplyStatus.FromIpAddress); aItem.SubItems.Append(format('Reached in : %d ms', [IdIcmpClient.ReplyStatus.MsRoundTripTime])); reached := true; end; rsError: begin aItem.SubItems.Append(IdIcmpClient.ReplyStatus.FromIpAddress); aItem.SubItems.Append('Unknown error.'); end; rsTimeOut: begin aItem.SubItems.Append('?.?.?.?'); aItem.SubItems.Append('Timed out.'); end; rsErrorUnreachable: begin aItem.SubItems.Append(IdIcmpClient.ReplyStatus.FromIpAddress); aItem.SubItems.Append(format('Destination network unreachable', [IdIcmpClient.ReplyStatus.MsRoundTripTime])); break; end; rsErrorTTLExceeded: begin aItem.SubItems.Append(IdIcmpClient.ReplyStatus.FromIpAddress); aItem.SubItems.Append(format('TTL=%d', [IdIcmpClient.ReplyStatus.TimeToLive])); end; end; // case Application.ProcessMessages; until reached or (TTL > seMaxHops.value) or Stopped; end; procedure TfmTracertMain.lvTraceCompare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer); begin Compare := StrToIntDef(Item1.Caption, -1) - StrToIntDef(Item2.Caption, -1); end; procedure TfmTracertMain.acStopExecute(Sender: TObject); begin Stopped := true; acStop.enabled := false; end; end.
unit Unit1; interface uses System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, //GLS GLNGDManager, GLScene, GLObjects, GLCoordinates, GLCadencer, GLWin32Viewer, GLCrossPlatform, GLBaseClasses, GLVectorGeometry; type TForm1 = class(TForm) GLScene1: TGLScene; GLSceneViewer1: TGLSceneViewer; GLCadencer1: TGLCadencer; GLCamera1: TGLCamera; GLLightSource1: TGLLightSource; Floor: TGLCube; GLCube1: TGLCube; GLNGDManager1: TGLNGDManager; GLSphere1: TGLSphere; GLCube2: TGLCube; GLCube3: TGLCube; GLCube4: TGLCube; GLLines1: TGLLines; procedure GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure GLSceneViewer1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FormCreate(Sender: TObject); private { Private declarations } point3d, FPaneNormal: TVector; public { Public declarations } pickjoint: TNGDJoint; end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); begin pickjoint := TNGDJoint(GLNGDManager1.NewtonJoint.Items[0]); end; procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: Double); begin GLNGDManager1.Step(deltaTime); end; procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var PickedSceneObject: TGLBaseSceneObject; begin if Button = TMouseButton(mbLeft) then begin PickedSceneObject := GLSceneViewer1.Buffer.GetPickedObject(X, Y); if Assigned(PickedSceneObject) and Assigned (GetNGDDynamic(PickedSceneObject)) then pickjoint.ParentObject := PickedSceneObject else exit; point3d := VectorMake(GLSceneViewer1.Buffer.PixelRayToWorld(X, Y)); // Attach the body pickjoint.KinematicControllerPick(point3d, paAttach); if Assigned(GLSceneViewer1.Camera.TargetObject) then FPaneNormal := GLSceneViewer1.Camera.AbsoluteVectorToTarget else FPaneNormal := GLSceneViewer1.Camera.AbsoluteDirection; end; end; procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var point2d, GotoPoint3d: TVector; begin if ssLeft in Shift then begin // Get the screenPoint with opengl correction [Height - Y] for the next function point2d := VectorMake(X, GLSceneViewer1.Height - Y, 0, 0); // Get the intersect point between the plane [parallel to camera] and mouse position if GLSceneViewer1.Buffer.ScreenVectorIntersectWithPlane(point2d, point3d, FPaneNormal, GotoPoint3d) then // Move the body to the new position pickjoint.KinematicControllerPick(GotoPoint3d, paMove); end else pickjoint.KinematicControllerPick(GotoPoint3d, paDetach); end; procedure TForm1.GLSceneViewer1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin // Detach the body if Button = TMouseButton(mbLeft) then pickjoint.KinematicControllerPick(NullHmgVector, paDetach); end; end.
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+} {$M 1024,0,0} { by Behdad Esfahbod Algorithmic Problems Book April '2000 Problem 139 O(E) Bfs Method } program RailsNetwork; const MaxN = 100; MaxE = 3 * MaxN; var N, S, T : Integer; G : array [1 .. MaxN, 0 .. MaxN + 1] of Integer; D : array [1 .. MaxN] of Integer; Mark, P : array [1 .. MaxN, 1 .. MaxN] of Integer; Q : array [1 .. MaxE + 2, 1 .. 2] of Integer; QL, QR : Integer; I, J, K, U, V : Integer; procedure ReadInput; begin Assign(Input, 'input.txt'); Reset(Input); Readln(N, T, S); for I := 1 to N do begin while not SeekEoln do begin Read(J); Inc(D[I]); G[I, D[I]] := J; end; G[I, 0] := G[I, D[I]]; G[I, D[I] + 1] := G[I, 1]; Readln; end; end; procedure WriteOutput; begin Assign(Output, 'output.txt'); Rewrite(Output); K := U; J := T; Writeln(Mark[K, J] + 1); Write(J); while J <> S do begin Write(' ', K); I := K; K := P[K, J]; J := I; end; Writeln; Close(Output); end; procedure Bfs; begin for I := 1 to D[S] do begin Inc(QR); Q[QR, 1] := S; Q[QR, 2] := G[S, I]; Mark[S, I] := 1; end; while QL < QR do begin Inc(QL); U := Q[QL, 1]; V := Q[QL, 2]; if V = T then Break; for I := 1 to D[V] do if G[V, I] = U then Break; for J := -1 to 1 do if J <> 0 then if Mark[V, G[V, I + J]] = 0 then begin Mark[V, G[V, I + J]] := Mark[U, V] + 1; P[V, G[V, I + J]] := U; Inc(QR); Q[QR, 1] := V; Q[QR, 2] := G[V, I + J]; end; end; end; begin ReadInput; Bfs; WriteOutput; end.
unit MiscTypes; interface type TClientSummary = class HClient : String; HHours : Double; HRevenue: Double; published property Client : String read HClient write HClient; property Hours : Double read HHours write HHours; property Revenue: Double read HRevenue write HRevenue; function ToString : String; constructor Create(NewClient : String; NewHours : Double; NewRevenue : Double); end; type TDaySummary = class private HClients : array of TClientSummary; HHours : Double; HRevenue : Double; HDate : TDateTime; published property Date : TDateTime read HDate write HDate; property Hours : Double read HHours; property Revenue : Double read HRevenue; procedure Add(ClientSummary : TClientSummary); function ToString : String; function ClientsToString : String; constructor Create(NewDate : TDateTime); end; type TWeek = class private HDays : array of TDaySummary; HDate : TDateTime; published property Date : TDateTime read HDate write HDate; procedure Add(ClientSummary : TClientSummary; Day : Integer); function GetDay(Day : Integer) : TDaySummary; constructor Create(BeginDate : TDateTime); end; implementation uses SysUtils; function TClientSummary.ToString : String; begin Result := 'Client: ' + Client + ' | Hours: ' + Hours.ToString + ' | Revenue: $' + Revenue.ToString; end; constructor TClientSummary.Create(NewClient : String; NewHours : Double; NewRevenue : Double); begin Client := NewClient; Hours := NewHours; Revenue := NewRevenue; end; procedure TDaySummary.Add(ClientSummary : TClientSummary); var I: Integer; Success : Boolean; begin Success := False; // If Client already exists, add hours and revenue if Length(HClients) > 0 then begin for I := 0 to Length(HClients) -1 do begin if ClientSummary.Client = HClients[I].HClient then begin HClients[I].Hours := HClients[I].Hours + ClientSummary.Hours; HClients[I].Revenue := HClients[I].Revenue + ClientSummary.Revenue; Success := True; Break; end; end; end; // Else, add new Client if not Success then begin; SetLength(HClients, Length(HClients) + 1); HClients[High(HClients)] := ClientSummary; end; // Update overall Hours and Revenue HHours := HHours + ClientSummary.Hours; HRevenue := HRevenue + ClientSummary.Revenue; end; function TDaySummary.ToString : String; begin Result := 'Hours: ' + HHours.ToString + sLineBreak + 'Revenue: $' + HRevenue.ToString; end; function TDaySummary.ClientsToString : String; var I : Integer; begin if Length(HClients) <= 0 then begin Result := 'No Results Found.'; end else begin Result := ''; for I := 0 to Length(HClients) - 1 do begin Result := Result + HClients[I].HClient + ':' + sLineBreak + 'Hours: ' + HClients[I].HHours.ToString + sLineBreak + 'Revenue: $' + HClients[I].HRevenue.ToString; if I <> Length(HClients)-1 then Result := Result + sLineBreak + sLineBreak; end; end; end; constructor TDaySummary.Create(NewDate : TDateTime); begin HHours := 0; HRevenue := 0; SetLength(HClients,0); Date := NewDate; end; constructor TWeek.Create(BeginDate : TDateTime); var I : Integer; begin SetLength(HDays, 7); for I := 0 to 6 do HDays[I] := TDaySummary.Create(BeginDate + I); end; procedure TWeek.Add(ClientSummary: TClientSummary; Day: Integer); begin HDays[Day].Add(ClientSummary); end; function TWeek.GetDay(Day : Integer) : TDaySummary; begin Result := HDays[Day]; end; end.
{==============================================================================| | Project : Ararat Synapse | 001.004.000 | | Project : Internet Tools | 001.004.000 | |==============================================================================| | Content: SSL support by OpenSSL | |==============================================================================| | Copyright (c)1999-2017, Lukas Gebauer | | 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 Lukas Gebauer nor the names of its contributors may | | be used to endorse or promote products derived from this software without | | specific prior written permission. | | | | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE | | ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR | | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT | | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY | | OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH | | DAMAGE. | |==============================================================================| | The Initial Developer of the Original Code is Lukas Gebauer (Czech Republic).| | Portions created by Lukas Gebauer are Copyright (c)2005-2017. | | Portions created by Petr Fejfar are Copyright (c)2011-2012. | | Portions created by Pepak are Copyright (c)2018. | | All Rights Reserved. | |==============================================================================| | Contributor(s): | |==============================================================================| | History: see HISTORY.HTM from distribution package | | (Found at URL: http://www.ararat.cz/synapse/) | |==============================================================================} //requires OpenSSL libraries! {:@abstract(SSL plugin for OpenSSL) Compatibility with OpenSSL versions: 0.9.6 should work, known mysterious crashing on FreePascal and Linux platform. 0.9.7 - 1.0.0 working fine. 1.1.0 should work, under testing. OpenSSL libraries are loaded dynamicly - you not need OpenSSL librares even you compile your application with this unit. SSL just not working when you not have OpenSSL libraries. This plugin have limited support for .NET too! Because is not possible to use callbacks with CDECL calling convention under .NET, is not supported key/certificate passwords and multithread locking. :-( For handling keys and certificates you can use this properties: @link(TCustomSSL.CertificateFile) for PEM or ASN1 DER (cer) format. @br @link(TCustomSSL.Certificate) for ASN1 DER format only. @br @link(TCustomSSL.PrivateKeyFile) for PEM or ASN1 DER (key) format. @br @link(TCustomSSL.PrivateKey) for ASN1 DER format only. @br @link(TCustomSSL.CertCAFile) for PEM CA certificate bundle. @br @link(TCustomSSL.PFXFile) for PFX format. @br @link(TCustomSSL.PFX) for PFX format from binary string. @br This plugin is capable to create Ad-Hoc certificates. When you start SSL/TLS server without explicitly assigned key and certificate, then this plugin create Ad-Hoc key and certificate for each incomming connection by self. It slowdown accepting of new connections! } //{$INCLUDE 'jedi.inc'} {$IFDEF FPC} {$MODE DELPHI} {$ENDIF} {$H+} {$IFDEF UNICODE} {$WARN IMPLICIT_STRING_CAST OFF} {$WARN IMPLICIT_STRING_CAST_LOSS OFF} {$ENDIF} unit synapse_ssl_openssl_override; interface uses SysUtils, Classes, blcksock, synsock, synautil, {$IFDEF CIL} System.Text, {$ENDIF} {$IFDEF DELPHI23_UP} AnsiStrings, {$ENDIF} ssl_openssl_lib; type {:@abstract(class implementing OpenSSL SSL plugin.) Instance of this class will be created for each @link(TTCPBlockSocket). You not need to create instance of this class, all is done by Synapse itself!} TSSLOpenSSLOverride = class(TCustomSSL) private FServer: boolean; protected FOldSSLType: TSSLType; FOldVerifyCert: boolean; function customCertificateHandling: boolean; virtual; function customQuickClientPrepare: boolean; virtual; procedure customNormalizeSNIHost; procedure setCustomError(msg: string; id: integer = -3); public CAFile, CAPath, outErrorMessage: string; outErrorCode: integer; class procedure LoadOpenSSL; virtual; protected FSsl: PSSL; Fctx: PSSL_CTX; function NeedSigningCertificate: boolean; virtual; function SSLCheck: Boolean; function SetSslKeys: boolean; virtual; function Init: Boolean; function DeInit: Boolean; function Prepare: Boolean; overload; function Prepare(aserver: Boolean): Boolean; overload; function LoadPFX(pfxdata: ansistring): Boolean; function CreateSelfSignedCert(Host: string): Boolean; override; property Server: boolean read FServer; public {:See @inherited} constructor Create(const Value: TTCPBlockSocket); override; destructor Destroy; override; {:See @inherited} function LibVersion: String; override; {:See @inherited} function LibName: String; override; {:See @inherited and @link(ssl_cryptlib) for more details.} function Connect: boolean; override; {:See @inherited and @link(ssl_cryptlib) for more details.} function Accept: boolean; override; {:See @inherited} function Shutdown: boolean; override; {:See @inherited} function BiShutdown: boolean; override; {:See @inherited} function SendBuffer(Buffer: TMemory; Len: Integer): Integer; override; {:See @inherited} function RecvBuffer(Buffer: TMemory; Len: Integer): Integer; override; {:See @inherited} function WaitingData: Integer; override; {:See @inherited} function GetSSLVersion: string; override; {:See @inherited} function GetPeerSubject: string; override; {:See @inherited} function GetPeerSerialNo: integer; override; {pf} {:See @inherited} function GetPeerIssuer: string; override; {:See @inherited} function GetPeerName: string; override; {:See @inherited} function GetPeerNameHash: cardinal; override; {pf} {:See @inherited} function GetPeerFingerprint: string; override; {:See @inherited} function GetCertInfo: string; override; {:See @inherited} function GetCipherName: string; override; {:See @inherited} function GetCipherBits: integer; override; {:See @inherited} function GetCipherAlgBits: integer; override; {:See @inherited} function GetVerifyCert: integer; override; end; implementation uses dynlibs; {==============================================================================} {$IFNDEF CIL} function PasswordCallback(buf:PAnsiChar; size:Integer; rwflag:Integer; userdata: Pointer):Integer; cdecl; var Password: AnsiString; begin Password := ''; if TCustomSSL(userdata) is TCustomSSL then Password := TCustomSSL(userdata).KeyPassword; if Length(Password) > (Size - 1) then SetLength(Password, Size - 1); Result := Length(Password); {$IFDEF DELPHI23_UP}AnsiStrings.{$ENDIF}StrLCopy(buf, PAnsiChar(Password + #0), Result + 1); end; {$ENDIF} {==============================================================================} constructor TSSLOpenSSLOverride.Create(const Value: TTCPBlockSocket); begin inherited Create(Value); FCiphers := 'DEFAULT'; FSsl := nil; Fctx := nil; end; destructor TSSLOpenSSLOverride.Destroy; begin DeInit; inherited Destroy; end; function TSSLOpenSSLOverride.LibName: String; begin Result := 'ssl_openssl'; end; function TSSLOpenSSLOverride.SSLCheck: Boolean; var {$IFDEF CIL} sb: StringBuilder; {$ENDIF} s : AnsiString; begin Result := true; FLastErrorDesc := ''; FLastError := ErrGetError; ErrClearError; if FLastError <> 0 then begin Result := False; {$IFDEF CIL} sb := StringBuilder.Create(256); ErrErrorString(FLastError, sb, 256); FLastErrorDesc := Trim(sb.ToString); {$ELSE} s := StringOfChar(#0, 256); ErrErrorString(FLastError, s, Length(s)); FLastErrorDesc := s; {$ENDIF} end; end; function TSSLOpenSSLOverride.CreateSelfSignedCert(Host: string): Boolean; var pk: EVP_PKEY; x: PX509; rsa: PRSA; t: PASN1_UTCTIME; name: PX509_NAME; b: PBIO; xn, y: integer; s: AnsiString; {$IFDEF CIL} sb: StringBuilder; {$ENDIF} begin Result := True; pk := EvpPkeynew; x := X509New; try rsa := RsaGenerateKey(2048, $10001, nil, nil); EvpPkeyAssign(pk, EVP_PKEY_RSA, rsa); X509SetVersion(x, 2); Asn1IntegerSet(X509getSerialNumber(x), 0); t := Asn1UtctimeNew; try X509GmtimeAdj(t, -60 * 60 *24); X509SetNotBefore(x, t); X509GmtimeAdj(t, 60 * 60 * 60 *24); X509SetNotAfter(x, t); finally Asn1UtctimeFree(t); end; X509SetPubkey(x, pk); Name := X509GetSubjectName(x); X509NameAddEntryByTxt(Name, 'C', $1001, 'CZ', -1, -1, 0); X509NameAddEntryByTxt(Name, 'CN', $1001, host, -1, -1, 0); x509SetIssuerName(x, Name); x509Sign(x, pk, EvpGetDigestByName('SHA1')); b := BioNew(BioSMem); try i2dX509Bio(b, x); xn := bioctrlpending(b); {$IFDEF CIL} sb := StringBuilder.Create(xn); y := bioread(b, sb, xn); if y > 0 then begin sb.Length := y; s := sb.ToString; end; {$ELSE} setlength(s, xn); y := bioread(b, s, xn); if y > 0 then setlength(s, y); {$ENDIF} finally BioFreeAll(b); end; FCertificate := s; b := BioNew(BioSMem); try i2dPrivatekeyBio(b, pk); xn := bioctrlpending(b); {$IFDEF CIL} sb := StringBuilder.Create(xn); y := bioread(b, sb, xn); if y > 0 then begin sb.Length := y; s := sb.ToString; end; {$ELSE} setlength(s, xn); y := bioread(b, s, xn); if y > 0 then setlength(s, y); {$ENDIF} finally BioFreeAll(b); end; FPrivatekey := s; finally X509free(x); EvpPkeyFree(pk); end; end; function TSSLOpenSSLOverride.LoadPFX(pfxdata: ansistring): Boolean; var cert, pkey, ca: SslPtr; b: PBIO; p12: SslPtr; begin Result := False; b := BioNew(BioSMem); try BioWrite(b, pfxdata, Length(PfxData)); p12 := d2iPKCS12bio(b, nil); if not Assigned(p12) then Exit; try cert := nil; pkey := nil; ca := nil; try {pf} if PKCS12parse(p12, FKeyPassword, pkey, cert, ca) > 0 then if SSLCTXusecertificate(Fctx, cert) > 0 then if SSLCTXusePrivateKey(Fctx, pkey) > 0 then Result := True; {pf} finally EvpPkeyFree(pkey); X509free(cert); SkX509PopFree(ca,_X509Free); // for ca=nil a new STACK was allocated... end; {/pf} finally PKCS12free(p12); end; finally BioFreeAll(b); end; end; function TSSLOpenSSLOverride.SetSslKeys: boolean; var st: TFileStream; s: string; begin Result := False; if not assigned(FCtx) then Exit; try if FCertificateFile <> '' then if SslCtxUseCertificateChainFile(FCtx, FCertificateFile) <> 1 then if SslCtxUseCertificateFile(FCtx, FCertificateFile, SSL_FILETYPE_PEM) <> 1 then if SslCtxUseCertificateFile(FCtx, FCertificateFile, SSL_FILETYPE_ASN1) <> 1 then Exit; if FCertificate <> '' then if SslCtxUseCertificateASN1(FCtx, length(FCertificate), FCertificate) <> 1 then Exit; SSLCheck; if FPrivateKeyFile <> '' then if SslCtxUsePrivateKeyFile(FCtx, FPrivateKeyFile, SSL_FILETYPE_PEM) <> 1 then if SslCtxUsePrivateKeyFile(FCtx, FPrivateKeyFile, SSL_FILETYPE_ASN1) <> 1 then Exit; if FPrivateKey <> '' then if SslCtxUsePrivateKeyASN1(EVP_PKEY_RSA, FCtx, FPrivateKey, length(FPrivateKey)) <> 1 then Exit; SSLCheck; if FCertCAFile <> '' then if SslCtxLoadVerifyLocations(FCtx, FCertCAFile, '') <> 1 then Exit; if FPFXfile <> '' then begin try st := TFileStream.Create(FPFXfile, fmOpenRead or fmShareDenyNone); try s := ReadStrFromStream(st, st.Size); finally st.Free; end; if not LoadPFX(s) then Exit; except on Exception do Exit; end; end; if FPFX <> '' then if not LoadPFX(FPfx) then Exit; SSLCheck; Result := True; finally SSLCheck; end; end; function TSSLOpenSSLOverride.NeedSigningCertificate: boolean; begin Result := (FCertificateFile = '') and (FCertificate = '') and (FPFXfile = '') and (FPFX = ''); end; function TSSLOpenSSLOverride.DeInit: Boolean; begin Result := True; if assigned (Fssl) then sslfree(Fssl); Fssl := nil; if assigned (Fctx) then begin SslCtxFree(Fctx); Fctx := nil; ErrRemoveState(0); end; FSSLEnabled := False; end; function TSSLOpenSSLOverride.Prepare: Boolean; begin Result := false; DeInit; if Init then Result := true else DeInit; end; function TSSLOpenSSLOverride.Prepare(aserver: Boolean): Boolean; begin fserver := aserver; result := Prepare(); end; function TSSLOpenSSLOverride.Accept: boolean; var x: integer; begin Result := False; if FSocket.Socket = INVALID_SOCKET then Exit; FServer := True; if Prepare then begin {$IFDEF CIL} if sslsetfd(FSsl, FSocket.Socket.Handle.ToInt32) < 1 then {$ELSE} if sslsetfd(FSsl, FSocket.Socket) < 1 then {$ENDIF} begin SSLCheck; Exit; end; x := sslAccept(FSsl); if x < 1 then begin SSLcheck; Exit; end; FSSLEnabled := True; Result := True; end; end; function TSSLOpenSSLOverride.Shutdown: boolean; begin if not IsSSLloaded then begin //prevent crash if OpenSSL has been unloaded. //this would only happen if the program is closed, so the main thread has run the ssl_openssl_lib finalization section, //but this functino is called from a secondary thread. //then sslShutdown cannot be called because it would try to enter a critsection which already has been destroyed FSSLEnabled := false; Fssl := nil; Fctx := nil; exit(false); end; if assigned(FSsl) then sslshutdown(FSsl); DeInit; Result := True; end; function TSSLOpenSSLOverride.BiShutdown: boolean; var x: integer; begin if assigned(FSsl) then begin x := sslshutdown(FSsl); if x = 0 then begin Synsock.Shutdown(FSocket.Socket, 1); sslshutdown(FSsl); end; end; DeInit; Result := True; end; function TSSLOpenSSLOverride.SendBuffer(Buffer: TMemory; Len: Integer): Integer; var err: integer; {$IFDEF CIL} s: ansistring; {$ENDIF} begin FLastError := 0; FLastErrorDesc := ''; repeat {$IFDEF CIL} s := StringOf(Buffer); Result := SslWrite(FSsl, s, Len); {$ELSE} Result := SslWrite(FSsl, Buffer , Len); {$ENDIF} err := SslGetError(FSsl, Result); until (err <> SSL_ERROR_WANT_READ) and (err <> SSL_ERROR_WANT_WRITE); if err = SSL_ERROR_ZERO_RETURN then Result := 0 else if (err <> 0) then FLastError := err; end; function TSSLOpenSSLOverride.RecvBuffer(Buffer: TMemory; Len: Integer): Integer; var err: integer; {$IFDEF CIL} sb: stringbuilder; s: ansistring; {$ENDIF} begin FLastError := 0; FLastErrorDesc := ''; repeat {$IFDEF CIL} sb := StringBuilder.Create(Len); Result := SslRead(FSsl, sb, Len); if Result > 0 then begin sb.Length := Result; s := sb.ToString; System.Array.Copy(BytesOf(s), Buffer, length(s)); end; {$ELSE} Result := SslRead(FSsl, Buffer , Len); {$ENDIF} err := SslGetError(FSsl, Result); until (err <> SSL_ERROR_WANT_READ) and (err <> SSL_ERROR_WANT_WRITE); if err = SSL_ERROR_ZERO_RETURN then Result := 0 {pf}// Verze 1.1.0 byla s else tak jak to ted mam, // ve verzi 1.1.1 bylo ELSE zruseno, ale pak je SSL_ERROR_ZERO_RETURN // propagovano jako Chyba. {pf} else {/pf} if (err <> 0) then FLastError := err; end; function TSSLOpenSSLOverride.WaitingData: Integer; begin Result := sslpending(Fssl); end; function TSSLOpenSSLOverride.GetSSLVersion: string; begin if not assigned(FSsl) then Result := '' else Result := SSlGetVersion(FSsl); end; function TSSLOpenSSLOverride.GetPeerSubject: string; var cert: PX509; s: ansistring; {$IFDEF CIL} sb: StringBuilder; {$ENDIF} begin if not assigned(FSsl) then begin Result := ''; Exit; end; cert := SSLGetPeerCertificate(Fssl); if not assigned(cert) then begin Result := ''; Exit; end; {$IFDEF CIL} sb := StringBuilder.Create(4096); Result := X509NameOneline(X509GetSubjectName(cert), sb, 4096); {$ELSE} setlength(s, 4096); Result := X509NameOneline(X509GetSubjectName(cert), s, Length(s)); {$ENDIF} X509Free(cert); end; function TSSLOpenSSLOverride.GetPeerSerialNo: integer; {pf} var cert: PX509; SN: PASN1_INTEGER; begin if not assigned(FSsl) then begin Result := -1; Exit; end; cert := SSLGetPeerCertificate(Fssl); try if not assigned(cert) then begin Result := -1; Exit; end; SN := X509GetSerialNumber(cert); Result := Asn1IntegerGet(SN); finally X509Free(cert); end; end; function TSSLOpenSSLOverride.GetPeerName: string; var s: ansistring; begin s := GetPeerSubject; s := SeparateRight(s, '/CN='); Result := Trim(SeparateLeft(s, '/')); end; function TSSLOpenSSLOverride.GetPeerNameHash: cardinal; {pf} var cert: PX509; begin if not assigned(FSsl) then begin Result := 0; Exit; end; cert := SSLGetPeerCertificate(Fssl); try if not assigned(cert) then begin Result := 0; Exit; end; Result := X509NameHash(X509GetSubjectName(cert)); finally X509Free(cert); end; end; function TSSLOpenSSLOverride.GetPeerIssuer: string; var cert: PX509; s: ansistring; {$IFDEF CIL} sb: StringBuilder; {$ENDIF} begin if not assigned(FSsl) then begin Result := ''; Exit; end; cert := SSLGetPeerCertificate(Fssl); if not assigned(cert) then begin Result := ''; Exit; end; {$IFDEF CIL} sb := StringBuilder.Create(4096); Result := X509NameOneline(X509GetIssuerName(cert), sb, 4096); {$ELSE} setlength(s, 4096); Result := X509NameOneline(X509GetIssuerName(cert), s, Length(s)); {$ENDIF} X509Free(cert); end; function TSSLOpenSSLOverride.GetPeerFingerprint: string; var cert: PX509; x: integer; {$IFDEF CIL} sb: StringBuilder; {$ENDIF} begin if not assigned(FSsl) then begin Result := ''; Exit; end; cert := SSLGetPeerCertificate(Fssl); if not assigned(cert) then begin Result := ''; Exit; end; {$IFDEF CIL} sb := StringBuilder.Create(EVP_MAX_MD_SIZE); X509Digest(cert, EvpGetDigestByName('MD5'), sb, x); sb.Length := x; Result := sb.ToString; {$ELSE} setlength(Result, EVP_MAX_MD_SIZE); X509Digest(cert, EvpGetDigestByName('MD5'), Result, x); SetLength(Result, x); {$ENDIF} X509Free(cert); end; function TSSLOpenSSLOverride.GetCertInfo: string; var cert: PX509; x, y: integer; b: PBIO; s: AnsiString; {$IFDEF CIL} sb: stringbuilder; {$ENDIF} begin if not assigned(FSsl) then begin Result := ''; Exit; end; cert := SSLGetPeerCertificate(Fssl); if not assigned(cert) then begin Result := ''; Exit; end; try {pf} b := BioNew(BioSMem); try X509Print(b, cert); x := bioctrlpending(b); {$IFDEF CIL} sb := StringBuilder.Create(x); y := bioread(b, sb, x); if y > 0 then begin sb.Length := y; s := sb.ToString; end; {$ELSE} setlength(s,x); y := bioread(b,s,x); if y > 0 then setlength(s, y); {$ENDIF} Result := ReplaceString(s, LF, CRLF); finally BioFreeAll(b); end; {pf} finally X509Free(cert); end; {/pf} end; function TSSLOpenSSLOverride.GetCipherName: string; begin if not assigned(FSsl) then Result := '' else Result := SslCipherGetName(SslGetCurrentCipher(FSsl)); end; function TSSLOpenSSLOverride.GetCipherBits: integer; var x: integer; begin if not assigned(FSsl) then Result := 0 else Result := SSLCipherGetBits(SslGetCurrentCipher(FSsl), x); end; function TSSLOpenSSLOverride.GetCipherAlgBits: integer; begin if not assigned(FSsl) then Result := 0 else SSLCipherGetBits(SslGetCurrentCipher(FSsl), Result); end; function TSSLOpenSSLOverride.GetVerifyCert: integer; begin if not assigned(FSsl) then Result := 1 else Result := SslGetVerifyResult(FSsl); end; {==============================================================================} resourcestring rsSSLErrorOpenSSLTooOld = 'OpenSSL version is too old for certificate checking. Required is OpenSSL 1.0.2+'; rsSSLErrorOpenSSLTooOldForTLS13 = 'OpenSSL version is too old for TLS1.3 (functions SSL_set_min/max_proto_version not found)'; rsSSLErrorCAFileLoadingFailed = 'Failed to load CA files.'; rsSSLErrorSettingHostname = 'Failed to set hostname for certificate validation.'; rsSSLErrorConnectionFailed = 'HTTPS connection failed after connecting to server. Some possible causes: handshake failure, mismatched HTTPS version/ciphers, invalid certificate'; rsSSLErrorVerificationFailed = 'HTTPS certificate validation failed'; type PX509_VERIFY_PARAM = pointer; TOpenSSL_version = function(t: integer): pchar; cdecl; TSSL_get0_param = function(ctx: PSSL_CTX): PX509_VERIFY_PARAM; cdecl; TX509_VERIFY_PARAM_set_hostflags = procedure(param: PX509_VERIFY_PARAM; flags: cardinal); cdecl; TX509_VERIFY_PARAM_set1_host = function(param: PX509_VERIFY_PARAM; name: pchar; nameLen: SizeUInt): integer; cdecl; TSslCtxSetMinProtoVersion = function(ctx: PSSL_CTX; version: integer): integer; cdecl; TSslCtxSetMaxProtoVersion = function(ctx: PSSL_CTX; version: integer): integer; cdecl; TSslMethodTLS = function:PSSL_METHOD; cdecl; TSSLSetTlsextHostName = function(ctx: PSSL_CTX; name: pchar): integer; cdecl; const X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS = 4; var _SSL_get0_param: TSSL_get0_param = nil; _X509_VERIFY_PARAM_set_hostflags: TX509_VERIFY_PARAM_set_hostflags = nil; _X509_VERIFY_PARAM_set1_host: TX509_VERIFY_PARAM_set1_host = nil; _OpenSSL_version: TOpenSSL_version = nil; _SslCtxSetMinProtoVersion: TSslCtxSetMinProtoVersion = nil; _SslCtxSetMaxProtoVersion: TSslCtxSetMaxProtoVersion = nil; _SSLsetTLSextHostName: TSSLSetTlsextHostName = nil; SslMethodTLSV11: TSslMethodTLS = nil; SslMethodTLSV12: TSslMethodTLS = nil; SslMethodTLS: TSslMethodTLS = nil; class procedure TSSLOpenSSLOverride.LoadOpenSSL; begin if not ssl_openssl_lib.InitSSLInterface then exit; if (SSLLibHandle <> 0) and (SSLUtilHandle <> 0) then begin _SSL_get0_param := TSSL_get0_param(GetProcedureAddress(SSLLibHandle, 'SSL_get0_param')); _X509_VERIFY_PARAM_set_hostflags := TX509_VERIFY_PARAM_set_hostflags(GetProcedureAddress(SSLUtilHandle, 'X509_VERIFY_PARAM_set_hostflags')); _X509_VERIFY_PARAM_set1_host := TX509_VERIFY_PARAM_set1_host(GetProcedureAddress(SSLUtilHandle, 'X509_VERIFY_PARAM_set1_host')); _OpenSSL_version := TOpenSSL_version(GetProcedureAddress(SSLLibHandle, 'OpenSSL_version')); _SslCtxSetMinProtoVersion := TSslCtxSetMinProtoVersion(GetProcedureAddress(SSLLibHandle, 'SSL_CTX_set_min_proto_version')); if not assigned(_SslCtxSetMinProtoVersion) then _SslCtxSetMinProtoVersion := TSslCtxSetMinProtoVersion(GetProcedureAddress(SSLLibHandle, 'SSL_set_min_proto_version')); _SslCtxSetMaxProtoVersion := TSslCtxSetMaxProtoVersion(GetProcedureAddress(SSLLibHandle, 'SSL_CTX_set_max_proto_version')); if not assigned(_SslCtxSetMaxProtoVersion) then _SslCtxSetMaxProtoVersion := TSslCtxSetMinProtoVersion(GetProcedureAddress(SSLLibHandle, 'SSL_set_max_proto_version')); if not assigned(_SSLsetTLSextHostName) then _SSLsetTLSextHostName := TSSLSetTlsextHostName(GetProcedureAddress(SSLLibHandle, 'SSL_set_tlsext_host_name')); SslMethodTLSV11 := TSslMethodTLS(GetProcedureAddress(SSLLibHandle, 'TLSv1_1_method')); SslMethodTLSV12 := TSslMethodTLS(GetProcedureAddress(SSLLibHandle, 'TLSv1_2_method')); SslMethodTLS := TSslMethodTLS(GetProcedureAddress(SSLLibHandle, 'TLS_method')); end; end; function TSSLOpenSSLOverride.LibVersion: String; begin Result := SSLeayversion(0); if assigned(_OpenSSL_version) then result += _OpenSSL_version(0); end; function TSSLOpenSSLOverride.customCertificateHandling: boolean; var param: PX509_VERIFY_PARAM; label onError; begin result := false; if VerifyCert then begin //see https://wiki.openssl.org/index.php/Hostname_validation if not assigned(_SSL_get0_param) or not assigned(_X509_VERIFY_PARAM_set_hostflags) or not assigned(_X509_VERIFY_PARAM_set1_host) then begin setCustomError(rsSSLErrorOpenSSLTooOld, -2); exit; end; param := _SSL_get0_param(Fssl); if param = nil then goto onError; _X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); if _X509_VERIFY_PARAM_set1_host(param, pchar(SNIHost), length(SNIHost)) = 0 then goto onError; end; result := true; exit; onError: setCustomError(rsSSLErrorSettingHostname, -2); result := false; end; function TSSLOpenSSLOverride.customQuickClientPrepare: boolean; begin if not assigned(FSsl) or not assigned(Fctx) or (FOldSSLType <> FSSLType) or (VerifyCert <> FOldVerifyCert) then begin result := Prepare(false); if result and VerifyCert then if SslCtxLoadVerifyLocations(FCtx, CAFile, CAPath) <> 1 then begin SSLCheck; setCustomError(rsSSLErrorCAFileLoadingFailed); result := false; end; end else begin sslfree(Fssl); Fssl := SslNew(Fctx); result := FSsl <> nil; if not result then SSLCheck; end; if result then begin FOldSSLType := FSSLType; FOldVerifyCert := VerifyCert; end; end; procedure TSSLOpenSSLOverride.customNormalizeSNIHost; begin while FSNIHost.EndsWith('.') do delete(FSNIHost, FSNIHost.Length, 1); FSNIHost := LowerCase(FSNIHost); end; procedure TSSLOpenSSLOverride.setCustomError(msg: string; id: integer); begin outErrorCode := id; outErrorMessage := LineEnding + msg; outErrorMessage += LineEnding+'OpenSSL-Error: '+LastErrorDesc; // str(FSSLType, temp); outErrorMessage += LineEnding+'OpenSSL information: CA file: '+CAFile+' , CA dir: '+CAPath+' , '+ {temp+', '+}GetSSLVersion+', '+LibVersion; end; function TSSLOpenSSLOverride.Init: Boolean; const TLS1_VERSION = $0301; TLS1_1_VERSION = $0302; TLS1_2_VERSION = $0303; TLS1_3_VERSION = $0304; var fallbackMethod: PSSL_METHOD = nil; minVersion, maxVersion: integer; var s: AnsiString; isTLSv1_3, isTLSv1_2: Boolean; begin Result := False; FLastErrorDesc := ''; FLastError := 0; Fctx := nil; isTLSv1_2 := (ord(FSSLType) = ord(LT_TLSv1_1) + 1) and (FSSLType < LT_SSHv2); //LT_TLSv1_2 or LT_TLSv1_3, but older synapse version do not have that isTLSv1_3 := (ord(FSSLType) = ord(LT_TLSv1_1) + 2) and (FSSLType < LT_SSHv2); //LT_TLSv1_3, but older synapse version do not have that //writeln(isTLSv1_3, ' ',assigned(_SslCtxSetMinProtoVersion), ' ',assigned(_SslCtxSetMaxProtoVersion)); if isTLSv1_3 and not (assigned(_SslCtxSetMinProtoVersion) and assigned(_SslCtxSetMaxProtoVersion)) then begin // setCustomError(rsSSLErrorOpenSSLTooOldForTLS13); exit; end; case FSSLType of LT_SSLv2: begin fallbackMethod := SslMethodV2; minVersion := 0; maxVersion := minVersion; end; LT_SSLv3: begin fallbackMethod := SslMethodV3; minVersion := 0; maxVersion := minVersion; end; LT_TLSv1: begin fallbackMethod := SslMethodTLSV1; minVersion := TLS1_VERSION; maxVersion := minVersion; end; LT_TLSv1_1: begin fallbackMethod := SslMethodTLSV11; minVersion := TLS1_1_VERSION; maxVersion := minVersion; end; //LT_TLSv1_2: begin fallbackMethod := SslMethodTLSV12; minVersion := TLS1_2_VERSION; maxVersion := minVersion; end; LT_all: begin fallbackMethod := SslMethodV23; minVersion := TLS1_VERSION; maxVersion := TLS1_3_VERSION; end; else if isTLSv1_2 then begin fallbackMethod := SslMethodTLSV12; minVersion := TLS1_2_VERSION; maxVersion := minVersion; end else if isTLSv1_3 then begin minVersion := TLS1_3_VERSION; maxVersion := TLS1_3_VERSION; end else exit; end; if assigned(SslMethodTLS) and ( (FSSLType = LT_all) or (assigned(_SslCtxSetMinProtoVersion) and assigned(_SslCtxSetMaxProtoVersion)) ) then begin Fctx := SslCtxNew(SslMethodTLS); if Fctx <> nil then begin if assigned(_SslCtxSetMinProtoVersion) and assigned(_SslCtxSetMaxProtoVersion) then begin _SslCtxSetMinProtoVersion(Fctx, minVersion); _SslCtxSetMaxProtoVersion(Fctx, maxVersion); //todo: check result? end; end; end; if (Fctx = nil) and assigned(fallbackMethod) then Fctx := SslCtxNew(fallbackMethod); if Fctx = nil then begin SSLCheck; Exit; end else begin s := FCiphers; SslCtxSetCipherList(Fctx, s); if FVerifyCert then SslCtxSetVerify(FCtx, SSL_VERIFY_PEER, nil) else SslCtxSetVerify(FCtx, SSL_VERIFY_NONE, nil); {$IFNDEF CIL} SslCtxSetDefaultPasswdCb(FCtx, @PasswordCallback); SslCtxSetDefaultPasswdCbUserdata(FCtx, self); {$ENDIF} if server and NeedSigningCertificate then begin CreateSelfSignedcert(FSocket.ResolveIPToName(FSocket.GetRemoteSinIP)); end; if not SetSSLKeys then Exit else begin Fssl := nil; Fssl := SslNew(Fctx); if Fssl = nil then begin SSLCheck; exit; end; end; end; Result := true; end; function TSSLOpenSSLOverride.Connect: boolean; var x: integer; b: boolean; err: integer; begin Result := False; if FSocket.Socket = INVALID_SOCKET then Exit; FServer := False; customNormalizeSNIHost; if customQuickClientPrepare() {!!override!!} then begin if not customCertificateHandling {!!override!!} then exit; {$IFDEF CIL} if sslsetfd(FSsl, FSocket.Socket.Handle.ToInt32) < 1 then {$ELSE} if sslsetfd(FSsl, FSocket.Socket) < 1 then {$ENDIF} begin SSLCheck; Exit; end; if SNIHost<>'' then if assigned(_SSLsetTLSextHostName) then _SSLsetTLSextHostName(Fssl, PAnsiChar(AnsiString(SNIHost))) else SSLCtrl(Fssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name, PAnsiChar(AnsiString(SNIHost))); //if (FSocket.ConnectionTimeout <= 0) then //do blocking call of SSL_Connect {!!override!!} begin x := sslconnect(FSsl); if x < 1 then begin SSLcheck; setCustomError(rsSSLErrorConnectionFailed, -3); {!!override!!} Exit; end; end //this must be commented out, because ConnectionTimeout is missing in Synapse SVN r40 {else //do non-blocking call of SSL_Connect begin b := Fsocket.NonBlockMode; Fsocket.NonBlockMode := true; repeat x := sslconnect(FSsl); err := SslGetError(FSsl, x); if err = SSL_ERROR_WANT_READ then if not FSocket.CanRead(FSocket.ConnectionTimeout) then break; if err = SSL_ERROR_WANT_WRITE then if not FSocket.CanWrite(FSocket.ConnectionTimeout) then break; until (err <> SSL_ERROR_WANT_READ) and (err <> SSL_ERROR_WANT_WRITE); Fsocket.NonBlockMode := b; if err <> SSL_ERROR_NONE then begin SSLcheck; Exit; end; end}; if FverifyCert then //seems like this is not needed, since sslconnect already fails on an invalid certificate {!!override!!} if (GetVerifyCert <> 0) or (not DoVerifyCert) then begin setCustomError(rsSSLErrorVerificationFailed, -3); Exit; end; FSSLEnabled := True; Result := True; end; end; initialization SSLImplementation := TSSLOpenSSLOverride; end.
unit uDrawingSupport; interface uses uBase, GdiPlus, Graphics, Windows; const DefColor = clRed; PGDefColor = TGPColor.Red; type ICoordConverter = interface function LogToScreen( aValue : Extended ) : integer; overload; function ScreenToLog( aValue : integer ) : Extended; overload; procedure LogToScreen( aLogVal1, aLogVal2 : Extended; var aScrVal1, aScrVal2 : integer ); overload; procedure ScreenToLog( aScrVal1, aScrVal2 : integer; aLogVal1, aLogVal2 : Extended ); overload; end; IDrawingPage = interface procedure DrawWhat; end; IFigure = interface procedure SetBackgroundColor( aValue : TColor ); function GetBackgroundColor : TColor; procedure SetBorderColor( aValue : TColor ); function GetBorderColor : TColor; procedure SetBorderWidth( aValue : byte ); function GetBorderWidth : byte; procedure SetIndexColor( aValue : TColor ); function GetIndexColor : TColor; function GetNextFigure : IFigure; procedure SetNextFigure ( aValue : IFigure ); function GetPrevFigure : IFigure; procedure SetPrevFigure ( aValue : IFigure ); function GetParentFigure : IFigure; procedure SetParentFigure ( aValue : IFigure ); procedure SetFirstChildFigure( aValue : IFigure ); function GetFirstChildFigure : IFigure; procedure Draw( const aPage : IDrawingPage ); procedure DrawIndex( const aPage : IDrawingPage ); property BackgroundColor : TColor read GetBackgroundColor write SetBackgroundColor; property BorderColor : TColor read GetBorderColor write SetBorderColor; property BorderWidth : byte read GetBorderWidth write SetBorderWidth; property IndexColor : TColor read GetIndexColor write SetIndexColor; procedure AddChildFigure( const aFigure : IFigure ); procedure RemoveChildFigure( const aFigure : IFigure ); procedure ClearChildrensFigure; property ParentFigure : IFigure read GetParentFigure write SetParentFigure; property NextFigure : IFigure read GetNextFigure write SetNextFigure; property PrevFigure : IFigure read GetPrevFigure write SetPrevFigure; property FirstChildFigure : IFigure read GetFirstChildFigure write SetFirstChildFigure; end; TPoints = class( TObject ) strict private FPoints : array of TPoint; FCount : integer; function GetPount( aIndex : integer ): TPoint; procedure SetPoint(aIndex: integer; const Value: TPoint); public constructor Create; destructor Destroy; override; procedure Add( const aX, aY : integer ); overload; procedure Add( const aPoint : TPoint ); overload; procedure Clear; property Count : integer read FCount; property Point[ aIndex : integer ] : TPoint read GetPount write SetPoint; end; TDrawingBox = class( TObject ) strict private FSolidBrush : IGPSolidBrush; FPen : IGPPen; FBackGroundColor : TColor; FBorderColor : TColor; FBorderWidth : byte; function GetPen: IGPPen; function GetSolidBrush: IGPSolidBrush; public constructor Create; procedure SetColor( const aColor : TColor ); property SolidBrush : IGPSolidBrush read GetSolidBrush; property Pen : IGPPen read GetPen; property BackgroundColor : TColor read FBackgroundColor write FBackgroundColor; property BorderColor : TColor read FBorderColor write FBorderColor; property BorderWidth : byte read FBorderWidth write FBorderWidth; end; function GPColor( const aColor : TColor ) : TGPColor; function GetNextIndexColor : TColor; procedure GetXYHW( const aFirstPoint, aSecondPoint : TPoint; const aCorrectZeroValue : boolean; var aX, aY, aH, aW : integer ); implementation procedure GetXYHW( const aFirstPoint, aSecondPoint : TPoint; const aCorrectZeroValue : boolean; var aX, aY, aH, aW : integer ); begin if aSecondPoint.X < aFirstPoint.X then begin aX := aSecondPoint.X; aW := aFirstPoint.X - aSecondPoint.X; end else begin aX := aFirstPoint.X; aW := aSecondPoint.X - aFirstPoint.X; end; if aSecondPoint.Y < aFirstPoint.Y then begin aY := aSecondPoint.Y; aH := aFirstPoint.Y - aSecondPoint.Y; end else begin aY := aFirstPoint.Y; aH := aSecondPoint.Y - aFirstPoint.Y; end; if aCorrectZeroValue then begin if aH = 0 then aH := 1; if aW = 0 then aW := 1; end; end; function GPColor( const aColor : TColor ) : TGPColor; begin Result := TGPColor.Create( Byte( aColor), Byte( aColor shr 8 ), Byte( aColor shr 16) ); end; var GlobalIndexColor : TColor; function GetNextIndexColor : TColor; var r, g, b : Byte; begin r := GetRValue( GlobalIndexColor ); g := GetGValue( GlobalIndexColor ); b := GetBValue( GlobalIndexColor ); if r >= 254 then begin r := 1; if g >= 254 then begin g := 1; if b >= 254 then begin b := 1; end else begin b := b + 1; end; end else begin g := g + 1; end; end else begin r := r + 1; end; GlobalIndexColor := RGB( r, g, b ); Result := GlobalIndexColor; end; { TPoints } procedure TPoints.Add(const aX, aY: integer); begin Add( TPoint.Create( aX, aY ) ); end; procedure TPoints.Add(const aPoint: TPoint); const AddCount = 5; begin if FCount >= length( FPoints ) then begin SetLength( FPoints, FCount + AddCount ); end; FPoints[ FCount ] := aPoint; inc( FCount ); end; procedure TPoints.Clear; begin SetLength( FPoints, 0 ); FPoints := nil; FCount := 0; end; constructor TPoints.Create; begin inherited Create; Clear; end; destructor TPoints.Destroy; begin Clear; inherited; end; function TPoints.GetPount(aIndex: integer): TPoint; begin if ( aIndex >= 0 ) and ( aIndex < Count ) then begin Result := FPoints[ aIndex ]; end else begin Result := TPoint.Create( 0, 0 ); end; end; procedure TPoints.SetPoint(aIndex: integer; const Value: TPoint); begin if ( aIndex >= 0 ) and ( aIndex < Count ) then begin FPoints[ aIndex ] := Value; end else begin // end; end; { TDrawingBox } constructor TDrawingBox.Create; begin inherited Create; FPen := nil; FSolidBrush := nil; BackGroundColor := DefColor; BorderColor := DefColor; BorderWidth := 1; end; function TDrawingBox.GetPen: IGPPen; begin if FPen = nil then FPen := TGPPen.Create( PGDefColor ); Result := FPen; end; function TDrawingBox.GetSolidBrush: IGPSolidBrush; begin if FSolidBrush = nil then FSolidBrush := TGPSolidBrush.Create( PGDefColor ); Result := FSolidBrush; end; procedure TDrawingBox.SetColor(const aColor: TColor); begin BackgroundColor := aColor; BorderColor := aColor; end; initialization GlobalIndexColor := 1; end.
unit HKConnection; {$mode objfpc}{$H+} interface uses Classes, SysUtils, fpjson, LResources, Forms, Controls, Graphics, Dialogs, Requester, HKCompPacksTypes, HKLogFile; type { THKConnection } THKConnection = class(TComponent) private FBaseUrl: String; FLogComponent: THKLogFile; FonDebugMsg: TOnDebugMessage; FonPrepareData: TNotifyEvent; FonProcessRequestFinished: TNotifyEvent; FonProcessRequestStart: TNotifyEvent; FOnTokenInvalid: TNotifyEvent; FToken: String; FTokenName: String; procedure doDebug(Sender: TObject; aMessage: String; aDebugType: TDebugType ); procedure SetBaseUrl(AValue: String); procedure SetLogComponent(AValue: THKLogFile); procedure SetonDebugMsg(AValue: TOnDebugMessage); procedure SetonPrepareData(AValue: TNotifyEvent); procedure SetonProcessRequestFinished(AValue: TNotifyEvent); procedure SetonProcessRequestStart(AValue: TNotifyEvent); procedure SetOnTokenInvalid(AValue: TNotifyEvent); procedure SetToken(AValue: String); procedure SetTokenName(AValue: String); protected //procedure doDebug(); public Function CreateConnection:TJsonRequester; Function CreateAsyncConnection():TAsyncJsonRequester; Procedure TestConnection(aUrl:String); published property LogComponent:THKLogFile read FLogComponent write SetLogComponent; property BaseUrl:String read FBaseUrl write SetBaseUrl; property Token:String read FToken write SetToken; property TokenName:String read FTokenName write SetTokenName; property onDebugMsg:TOnDebugMessage read FonDebugMsg write SetonDebugMsg; property onProcessRequestStart:TNotifyEvent read FonProcessRequestStart write SetonProcessRequestStart; property onProcessRequestFinished:TNotifyEvent read FonProcessRequestFinished write SetonProcessRequestFinished; property onPrepareData:TNotifyEvent read FonPrepareData write SetonPrepareData; property OnTokenInvalid:TNotifyEvent read FOnTokenInvalid write SetOnTokenInvalid; end; procedure Register; implementation procedure Register; begin {$I hkconnection_icon.lrs} RegisterComponents('HKCompPacks',[THKConnection]); end; { THKConnection } procedure THKConnection.SetBaseUrl(AValue: String); begin if FBaseUrl=AValue then Exit; FBaseUrl:=AValue; end; procedure THKConnection.doDebug(Sender: TObject; aMessage: String; aDebugType: TDebugType); begin if Assigned(FonDebugMsg)then FonDebugMsg(Sender, aMessage, aDebugType); if Assigned(FLogComponent)then FLogComponent.WriteLog(aMessage, aDebugType); end; procedure THKConnection.SetLogComponent(AValue: THKLogFile); begin if FLogComponent=AValue then Exit; FLogComponent:=AValue; end; procedure THKConnection.SetonDebugMsg(AValue: TOnDebugMessage); begin if FonDebugMsg=AValue then Exit; FonDebugMsg:=AValue; end; procedure THKConnection.SetonPrepareData(AValue: TNotifyEvent); begin if FonPrepareData=AValue then Exit; FonPrepareData:=AValue; end; procedure THKConnection.SetonProcessRequestFinished(AValue: TNotifyEvent); begin if FonProcessRequestFinished=AValue then Exit; FonProcessRequestFinished:=AValue; end; procedure THKConnection.SetonProcessRequestStart(AValue: TNotifyEvent); begin if FonProcessRequestStart=AValue then Exit; FonProcessRequestStart:=AValue; end; procedure THKConnection.SetOnTokenInvalid(AValue: TNotifyEvent); begin if FOnTokenInvalid=AValue then Exit; FOnTokenInvalid:=AValue; end; procedure THKConnection.SetToken(AValue: String); begin if FToken=AValue then Exit; FToken:=AValue; end; procedure THKConnection.SetTokenName(AValue: String); begin if FTokenName=AValue then Exit; FTokenName:=AValue; end; function THKConnection.CreateConnection: TJsonRequester; begin Result:=TJsonRequester.Create(Self); Result.BaseUrl:=BaseUrl; Result.Token:=Token; Result.TokenName:=TokenName; Result.onDebugMsg:=@doDebug; Result.onResponseTokenInvalid:=OnTokenInvalid; Result.OnPrepareData:=onPrepareData; Result.OnProcessRequestFinished:=onProcessRequestFinished; Result.OnProcessRequestStart:=onProcessRequestStart; end; function THKConnection.CreateAsyncConnection(): TAsyncJsonRequester; begin Result:=TAsyncJsonRequester.Create(Self); Result.BaseUrl:=BaseUrl; Result.Token:=Token; Result.TokenName:=TokenName; Result.onDebugMsg:=@doDebug; Result.onResponseTokenInvalid:=OnTokenInvalid; Result.OnPrepareData:=onPrepareData; Result.OnProcessRequestFinished:=onProcessRequestFinished; Result.OnProcessRequestStart:=onProcessRequestStart; end; procedure THKConnection.TestConnection(aUrl: String); var con: TJsonRequester; resp: TJSONData; begin con:=CreateConnection; try con.BaseUrl:=aUrl; resp:=con.JsonGet(''); if resp<>nil then ShowMessage('Connection Success'); finally con.Free; end; end; end.
{ Copyright (C) 1998-2011, written by Mike Shkolnik, Scalabium Software E-Mail: mshkolnik@scalabium WEB: http://www.scalabium.com Const strings for localization freeware SMComponent library } unit SMCnst; interface {English strings} const strMessage = 'Skriv ut...'; strSaveChanges = 'Vill du verkligen spara ändringarna på databasservern?'; strErrSaveChanges = 'Kan inte spara uppgifter! Kontrollera förbindelsen med servern eller validera uppgifterna.'; strDeleteWarning = 'Vill du verkligen ta bort tabellen %s?'; strEmptyWarning = 'Vill du verkligen tömma tabellen %s?'; const PopUpCaption: array [0..24] of string = ('Lägg till post', 'Infoga post', 'Ändra post', 'Radera post', '-', 'Skriv ut ...', 'Exportera ...', 'Filtrera ...', 'Sök ...', '-', 'Spara ändringar', 'Annulera ändringarna', 'Uppdatera', '-', 'Markera/Avmarkera poster', 'Markera post', 'Markera alla poster', '-', 'Avmarkera post', 'Avmarkera alla poster', '-', 'Spara kolumnlayout', 'Återställ kolumnlayout', '-', 'Inställningar...'); const //for TSMSetDBGridDialog SgbTitle = ' Rubrik '; SgbData = ' Uppgifter '; STitleCaption = 'Rubrik:'; STitleAlignment = 'Justering:'; STitleColor = 'Bakgrund:'; STitleFont = 'Teckensnitt:'; SWidth = 'Bredd:'; SWidthFix = 'tecken'; SAlignLeft = 'vänster'; SAlignRight = 'höger'; SAlignCenter = 'mitten'; const //for TSMDBFilterDialog strEqual = 'lika med'; strNonEqual = 'inte lika med'; strNonMore = 'inte större'; strNonLess = 'inte mindre'; strLessThan = 'mindre än'; strLargeThan = 'större än'; strExist = 'tom'; strNonExist = 'inte tom'; strIn = 'i listan'; strBetween = 'mellan'; strLike = 'liknande'; strOR = 'ELLER'; strAND = 'OCH'; strField = 'Fält'; strCondition = 'Villkor'; strValue = 'Värde'; strAddCondition = ' Definiera ytterligare villkor:'; strSelection = ' Markera posterna med nästa villkor:'; strAddToList = 'Lägg till listan'; strEditInList = 'Redigera i listan'; strDeleteFromList = 'Ta bort från listan'; strTemplate = 'Filtermall-dialog'; strFLoadFrom = 'Läs in från...'; strFSaveAs = 'Spara som..'; strFDescription = 'Beskrivning'; strFFileName = 'Filnamn'; strFCreate = 'Skapad: %s'; strFModify = 'Ändrad: %s'; strFProtect = 'Skydda mot överskrift'; strFProtectErr = 'Filen är skyddad!'; const //for SMDBNavigator SFirstRecord = 'Första posten'; SPriorRecord = 'Föregående post'; SNextRecord = 'Nästa post'; SLastRecord = 'Sista posten'; SInsertRecord = 'Infoga post'; SCopyRecord = 'Kopiera posten'; SDeleteRecord = 'Radera posten'; SEditRecord = 'Ändra posten'; SFilterRecord = 'Filtervillkor'; SFindRecord = 'Sök efter post'; SPrintRecord = 'Skriv ut posterna'; SExportRecord = 'Exportera posterna'; SImportRecord = 'Importera poster'; SPostEdit = 'Spara ändringarna'; SCancelEdit = 'Avbryt ändringarna'; SRefreshRecord = 'Uppdatera uppgifter'; SChoice = 'Välj en post'; SClear = 'Töm vald post'; SDeleteRecordQuestion = 'Radera posten?'; SDeleteMultipleRecordsQuestion = 'Vill du verkligen ta bort valda poster?'; SRecordNotFound = 'Posten kan inte hittas'; SFirstName = 'Första'; SPriorName = 'Föregående'; SNextName = 'Nästa'; SLastName = 'Sista'; SInsertName = 'Infoga'; SCopyName = 'Kopiera'; SDeleteName = 'Radera'; SEditName = 'Ändra'; SFilterName = 'Filtrera'; SFindName = 'Sök'; SPrintName = 'Skriv ut'; SExportName = 'Exportera'; SImportName = 'Importera'; SPostName = 'Spara'; SCancelName = 'Avbryt'; SRefreshName = 'Uppdatera'; SChoiceName = 'Välj'; SClearName = 'Töm'; SBtnOk = '&OK'; SBtnCancel = '&Avbryt'; SBtnLoad = 'Läs in'; SBtnSave = 'Spara'; SBtnCopy = 'Kopiera'; SBtnPaste = 'Klistra in'; SBtnClear = 'Töm'; SRecNo = 'post.'; SRecOf = ' av '; const //for EditTyped etValidNumber = 'giltigt nummer'; etValidInteger = 'giltigt heltal'; etValidDateTime = 'giltigt datum/tid'; etValidDate = 'giltigt datum'; etValidTime = 'giltig tid'; etValid = 'giltigt'; etIsNot = 'är inte ett'; etOutOfRange = 'Värde %s utanför intervallet %s..%s'; SApplyAll = 'Tillämpa på alla'; SNoDataToDisplay = '<Inga uppgifter att visa>'; SPrevYear = 'föregående år'; SPrevMonth = 'föregående månad'; SNextMonth = 'nästa månad'; SNextYear = 'nästa år'; implementation end.
unit FC.StockData.InputDataCollectionLimitor; {$I Compiler.inc} interface uses BaseUtils,SysUtils, Classes, Controls, Serialization, StockChart.Definitions,FC.Definitions, StockChart.Obj; type //---------------------------------------------------------------------------- IStockInputDataCollectionLimitor = interface ['{543055E5-5432-4D12-A6D0-173D9B863118}'] procedure SetDataSource(aDS: ISCInputDataCollection); function GetDataSource: ISCInputDataCollection; //Ограничивает правый край указанным индексом, как будто дальше данных нет procedure Limit(const aEnd: integer); end; TStockInputDataCollectionLimitor = class (TSCInputDataCollection_B,IStockInputDataCollectionLimitor) private FDS : ISCInputDataCollection; FLimit: integer; public constructor Create(aDS:ISCInputDataCollection; AOwner: ISCChangeNotifier); destructor Destroy; override; function ISCInputDataCollection_GetItem(Index: Integer): ISCInputData; override; function DirectGetItem_DataDateTime(index: integer):TDateTime; override; function DirectGetItem_DataClose(index: integer): TStockRealNumber; override; function DirectGetItem_DataHigh(index: integer): TStockRealNumber; override; function DirectGetItem_DataLow(index: integer): TStockRealNumber; override; function DirectGetItem_DataOpen(index: integer): TStockRealNumber; override; function DirectGetItem_DataVolume(index: integer): integer; override; function Count: integer; override; //Ограничивает правый край указанным индексом, как будто дальше данных нет procedure Limit(const aEnd: integer); procedure SetDataSource(aDS: ISCInputDataCollection); function GetDataSource: ISCInputDataCollection; end; implementation uses Math; { TStockInputDataCollectionLimitor } constructor TStockInputDataCollectionLimitor.Create(aDS: ISCInputDataCollection; AOwner: ISCChangeNotifier); begin FLimit:=-1; inherited Create(AOwner,0.0); SetDataSource(aDS); end; destructor TStockInputDataCollectionLimitor.Destroy; begin inherited; end; function TStockInputDataCollectionLimitor.Count: integer; begin if FDS=nil then result:=0 else result:=FDS.Count; if (FLimit<>-1) and (result>FLimit) then result:=FLimit; end; function TStockInputDataCollectionLimitor.ISCInputDataCollection_GetItem(Index: Integer): ISCInputData; begin result:=FDS[index]; end; procedure TStockInputDataCollectionLimitor.Limit( const aEnd: integer); begin if FLimit=aEnd then exit; FLimit:=aEnd; OnItemsChanged; end; procedure TStockInputDataCollectionLimitor.SetDataSource(aDS: ISCInputDataCollection); begin if FDS<>aDS then begin FDS:=aDS; if FDS<>nil then begin SetGradation(aDS.GetGradation); SetPricePrecision(aDS.GetPricePrecision); SetPricesInPoint(aDS.GetPricesInPoint); end; OnItemsChanged; end; end; function TStockInputDataCollectionLimitor.GetDataSource: ISCInputDataCollection; begin result:=FDS; end; function TStockInputDataCollectionLimitor.DirectGetItem_DataOpen(index: integer): TStockRealNumber; begin result:=FDS.DirectGetItem_DataOpen(index); end; function TStockInputDataCollectionLimitor.DirectGetItem_DataHigh(index: integer): TStockRealNumber; begin result:=FDS.DirectGetItem_DataHigh(index); end; function TStockInputDataCollectionLimitor.DirectGetItem_DataDateTime(index: integer): TDateTime; begin result:=FDS.DirectGetItem_DataDateTime(index); end; function TStockInputDataCollectionLimitor.DirectGetItem_DataVolume(index: integer): integer; begin result:=FDS.DirectGetItem_DataVolume(index); end; function TStockInputDataCollectionLimitor.DirectGetItem_DataClose(index: integer): TStockRealNumber; begin result:=FDS.DirectGetItem_DataClose(index); end; function TStockInputDataCollectionLimitor.DirectGetItem_DataLow(index: integer): TStockRealNumber; begin result:=FDS.DirectGetItem_DataLow(index); end; end.
unit PropertyStyle; interface type TPropertyStyle = (psInteger, psString, psBoolean, psFloat, psDouble, psStringList); const PROPERTY_STYLE_COUNT = 6; implementation end.
{***************************************************************************} { Copyright 2021 Google LLC } { } { 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 } { } { https://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 BitStr; interface const MaxBufferSize = 256; type ByteBuffer = array[0..MaxBufferSize - 1] of Byte; ByteBufferPtr = ^ByteBuffer; BitStream = object Buffer: ByteBuffer; BitPtr: Integer; BufferLength: Integer; constructor Init; destructor Done; virtual; procedure AddBits(data: Word; bits: Byte); procedure PadToByte; procedure Dump; function BitLength: Integer; function ByteLength: Integer; function GetByte(idx: Integer): Byte; end; implementation constructor BitStream.Init; var i: Integer; begin BufferLength := 256; { reasonable default } for i := 0 to BufferLength - 1 do Buffer[i] := 0; BitPtr := 0; end; destructor BitStream.Done; begin end; procedure BitStream.AddBits(data: Word; bits: Byte); var i, newByteLength: Integer; bit, shift: Integer; begin newByteLength := (BitPtr + bits) div 8; if (bitPtr + bits) mod 8 <> 0 then newByteLength := newByteLength + 1; if newByteLength > BufferLength then Exit; for i := bits - 1 downto 0 do begin bit := (data shr i) and 1; bit := bit shl (7 - (bitPtr mod 8)); Buffer[bitPtr div 8] := Buffer[bitPtr div 8] or bit; bitPtr := bitPtr + 1; end; end; procedure BitStream.PadToByte; begin if BitPtr mod 8 <> 0 then BitPtr := BitPtr - (BitPtr mod 8) + 8; end; function BitStream.BitLength: Integer; begin BitLength := BitPtr; end; function BitStream.ByteLength: Integer; var l: Integer; begin l := BitPtr div 8; if BitPtr mod 8 <> 0 then l := l + 1; ByteLength := l; end; function BitStream.GetByte(idx: Integer): Byte; begin GetByte := Buffer[idx]; end; procedure BitStream.Dump; var i, bytes: Integer; begin bytes := BitPtr div 8; if BitPtr mod 8 <> 0 then bytes := bytes + 1; Write('Bitstream is '); Write(BitPtr, ' bit(s):'); for i := 0 to bytes - 1 do Write(Buffer[i], ' '); WriteLn; end; begin end.
// // Copyright (c) 2009-2010 Mikko Mononen memon@inside.org // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors 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. // unit RN_RecastFilter; interface uses Math, SysUtils, RN_Helper, RN_Recast; /// Marks non-walkable spans as walkable if their maximum is within @p walkableClimp of a walkable neihbor. /// @ingroup recast /// @param[in,out] ctx The build context to use during the operation. /// @param[in] walkableClimb Maximum ledge height that is considered to still be traversable. /// [Limit: >=0] [Units: vx] /// @param[in,out] solid A fully built heightfield. (All spans have been added.) procedure rcFilterLowHangingWalkableObstacles(ctx: TrcContext; const walkableClimb: Integer; const solid: TrcHeightfield); /// Marks spans that are ledges as not-walkable. /// @ingroup recast /// @param[in,out] ctx The build context to use during the operation. /// @param[in] walkableHeight Minimum floor to 'ceiling' height that will still allow the floor area to /// be considered walkable. [Limit: >= 3] [Units: vx] /// @param[in] walkableClimb Maximum ledge height that is considered to still be traversable. /// [Limit: >=0] [Units: vx] /// @param[in,out] solid A fully built heightfield. (All spans have been added.) procedure rcFilterLedgeSpans(ctx: TrcContext; const walkableHeight: Integer; const walkableClimb: Integer; const solid: TrcHeightfield); /// Marks walkable spans as not walkable if the clearence above the span is less than the specified height. /// @ingroup recast /// @param[in,out] ctx The build context to use during the operation. /// @param[in] walkableHeight Minimum floor to 'ceiling' height that will still allow the floor area to /// be considered walkable. [Limit: >= 3] [Units: vx] /// @param[in,out] solid A fully built heightfield. (All spans have been added.) procedure rcFilterWalkableLowHeightSpans(ctx: TrcContext; walkableHeight: Integer; const solid: TrcHeightfield); implementation uses RN_RecastHelper; /// @par /// /// Allows the formation of walkable regions that will flow over low lying /// objects such as curbs, and up structures such as stairways. /// /// Two neighboring spans are walkable if: <tt>rcAbs(currentSpan.smax - neighborSpan.smax) < waklableClimb</tt> /// /// @warning Will override the effect of #rcFilterLedgeSpans. So if both filters are used, call /// #rcFilterLedgeSpans after calling this filter. /// /// @see rcHeightfield, rcConfig procedure rcFilterLowHangingWalkableObstacles(ctx: TrcContext; const walkableClimb: Integer; const solid: TrcHeightfield); var w,h,x,y: Integer; ps,s: PrcSpan; previousWalkable,walkable: Boolean; previousArea: Byte; begin //rcAssert(ctx); ctx.startTimer(RC_TIMER_FILTER_LOW_OBSTACLES); w := solid.width; h := solid.height; for y := 0 to h - 1 do begin for x := 0 to w - 1 do begin ps := nil; previousWalkable := false; previousArea := RC_NULL_AREA; //for (rcSpan* s := solid.spans[x + y*w]; s; ps := s, s := s.next) s := solid.spans[x + y*w]; while (s <> nil) do begin walkable := s.area <> RC_NULL_AREA; // If current span is not walkable, but there is walkable // span just below it, mark the span above it walkable too. if (not walkable and previousWalkable) then begin if (Abs(s.smax - ps.smax) <= walkableClimb) then s.area := previousArea; end; // Copy walkable flag so that it cannot propagate // past multiple non-walkable objects. previousWalkable := walkable; previousArea := s.area; ps := s; s := s.next; end; end; end; ctx.stopTimer(RC_TIMER_FILTER_LOW_OBSTACLES); end; /// @par /// /// A ledge is a span with one or more neighbors whose maximum is further away than @p walkableClimb /// from the current span's maximum. /// This method removes the impact of the overestimation of conservative voxelization /// so the resulting mesh will not have regions hanging in the air over ledges. /// /// A span is a ledge if: <tt>rcAbs(currentSpan.smax - neighborSpan.smax) > walkableClimb</tt> /// /// @see rcHeightfield, rcConfig procedure rcFilterLedgeSpans(ctx: TrcContext; const walkableHeight: Integer; const walkableClimb: Integer; const solid: TrcHeightfield); const MAX_HEIGHT = $ffff; var w,h,x,y: Integer; s,ns: PrcSpan; bot,top,minh,asmin,asmax,dir,dx,dy,nbot,ntop: Integer; begin //rcAssert(ctx); ctx.startTimer(RC_TIMER_FILTER_BORDER); w := solid.width; h := solid.height; // Mark border spans. for y := 0 to h - 1 do begin for x := 0 to w - 1 do begin //for (rcSpan* s := solid.spans[x + y*w]; s; s := s.next) s := solid.spans[x + y*w]; while (s <> nil) do begin // Skip non walkable spans. if (s.area = RC_NULL_AREA) then begin //C++ seems to be doing loop increase, so do we s := s.next; continue; end; bot := (s.smax); if s.next <> nil then top := (s.next.smin) else top := MAX_HEIGHT; // Find neighbours minimum height. minh := MAX_HEIGHT; // Min and max height of accessible neighbours. asmin := s.smax; asmax := s.smax; for dir := 0 to 3 do begin dx := x + rcGetDirOffsetX(dir); dy := y + rcGetDirOffsetY(dir); // Skip neighbours which are out of bounds. if (dx < 0) or (dy < 0) or (dx >= w) or (dy >= h) then begin minh := rcMin(minh, -walkableClimb - bot); continue; end; // From minus infinity to the first span. ns := solid.spans[dx + dy*w]; nbot := -walkableClimb; if ns <> nil then ntop := ns.smin else ntop := MAX_HEIGHT; // Skip neightbour if the gap between the spans is too small. if (rcMin(top,ntop) - rcMax(bot,nbot) > walkableHeight) then minh := rcMin(minh, nbot - bot); // Rest of the spans. //for (ns := solid.spans[dx + dy*w]; ns; ns := ns.next) ns := solid.spans[dx + dy*w]; while (ns <> nil) do begin nbot := ns.smax; if ns.next <> nil then ntop := ns.next.smin else ntop := MAX_HEIGHT; // Skip neightbour if the gap between the spans is too small. if (rcMin(top,ntop) - rcMax(bot,nbot) > walkableHeight) then begin minh := rcMin(minh, nbot - bot); // Find min/max accessible neighbour height. if (Abs(nbot - bot) <= walkableClimb) then begin if (nbot < asmin) then asmin := nbot; if (nbot > asmax) then asmax := nbot; end; end; ns := ns.next; end; end; // The current span is close to a ledge if the drop to any // neighbour span is less than the walkableClimb. if (minh < -walkableClimb) then s.area := RC_NULL_AREA; // If the difference between all neighbours is too large, // we are at steep slope, mark the span as ledge. if ((asmax - asmin) > walkableClimb) then begin s.area := RC_NULL_AREA; end; s := s.next; end; end; end; ctx.stopTimer(RC_TIMER_FILTER_BORDER); end; /// @par /// /// For this filter, the clearance above the span is the distance from the span's /// maximum to the next higher span's minimum. (Same grid column.) /// /// @see rcHeightfield, rcConfig procedure rcFilterWalkableLowHeightSpans(ctx: TrcContext; walkableHeight: Integer; const solid: TrcHeightfield); const MAX_HEIGHT = $ffff; var w,h,x,y: Integer; s: PrcSpan; bot,top: Integer; begin Assert(ctx <> nil); ctx.startTimer(RC_TIMER_FILTER_WALKABLE); w := solid.width; h := solid.height; // Remove walkable flag from spans which do not have enough // space above them for the agent to stand there. for y := 0 to h - 1 do begin for x := 0 to w - 1 do begin s := solid.spans[x + y*w]; while (s <> nil) do begin bot := (s.smax); if s.next <> nil then top := (s.next.smin) else top := MAX_HEIGHT; if ((top - bot) <= walkableHeight) then s.area := RC_NULL_AREA; s := s.next; end; end; end; ctx.stopTimer(RC_TIMER_FILTER_WALKABLE); end; end.
unit Tests_OriStrings; {$mode objfpc}{$H+} interface uses FpcUnit, TestRegistry; type TTest_OriStrings = class(TTestCase) published procedure SplitStr; end; implementation uses OriStrings; procedure TTest_OriStrings.SplitStr; var S: String; R: TStringArray; begin S := 'C1 λ_min,рус; ЉϢȠЂӔӜ ڝڶڥڰڇکگ'; R := OriStrings.SplitStr(S, ';, '); AssertEquals(5, Length(R)); AssertEquals('C1', R[0]); AssertEquals('λ_min', R[1]); AssertEquals('рус', R[2]); AssertEquals('ЉϢȠЂӔӜ', R[3]); AssertEquals('ڝڶڥڰڇکگ', R[4]); end; initialization RegisterTest(TTest_OriStrings); end.
//////////////////////////////////////////////////////////////////////////////// // // // FileName : SUIProgressBar.pas // Creator : Shen Min // Date : 2002-05-27 // Comment : // // Copyright (c) 2002-2003 Sunisoft // http://www.sunisoft.com // Email: support@sunisoft.com // //////////////////////////////////////////////////////////////////////////////// unit SUIProgressBar; interface {$I SUIPack.inc} uses Windows, Messages, SysUtils, Classes, Controls, ExtCtrls, ComCtrls, Graphics, Forms, Math, SUIPublic, SUIThemes, SUIMgr; type TsuiProgressBarOrientation = (suiHorizontal, suiVertical); TsuiProgressBar = class(TCustomPanel) private m_Max : Integer; m_Min : Integer; m_Position : Integer; m_UIStyle : TsuiUIStyle; m_FileTheme : TsuiFileTheme; m_Orientation : TsuiProgressBarOrientation; m_BorderColor : TColor; m_Color : TColor; m_Picture : TPicture; m_ShowCaption : Boolean; m_CaptionColor : TColor; m_SmartShowCaption : Boolean; procedure SetMax(const Value: Integer); procedure SetMin(const Value: Integer); procedure SetPosition(const Value: Integer); procedure SetUIStyle(const Value: TsuiUIStyle); procedure SetOrientation(const Value: TsuiProgressBarOrientation); procedure SetColor(const Value: TColor); procedure SetBorderColor(const Value: TColor); procedure SetPicture(const Value: TPicture); procedure SetShowCaption(const Value: Boolean); procedure SetCaptionColor(const Value: TColor); procedure SetSmartShowCaption(const Value: Boolean); procedure SetFileTheme(const Value: TsuiFileTheme); procedure UpdateProgress(); procedure UpdatePicture(); function GetWidthFromPosition(nWidth : Integer) : Integer; function GetPercentFromPosition() : Integer; procedure WMERASEBKGND(var Msg : TMessage); message WM_ERASEBKGND; protected procedure Paint(); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner : TComponent); override; destructor Destroy(); override; procedure StepBy(Delta : Integer); procedure StepIt(); published property Anchors; property BiDiMode; property FileTheme : TsuiFileTheme read m_FileTheme write SetFileTheme; property UIStyle : TsuiUIStyle read m_UIStyle write SetUIStyle; property CaptionColor : TColor read m_CaptionColor write SetCaptionColor; property ShowCaption : Boolean read m_ShowCaption write SetShowCaption; property SmartShowCaption : Boolean read m_SmartShowCaption write SetSmartShowCaption; property Max : Integer read m_Max write SetMax; property Min : Integer read m_Min write SetMin; property Position : Integer read m_Position write SetPosition; property Orientation : TsuiProgressBarOrientation read m_Orientation write SetOrientation; property BorderColor : TColor read m_BorderColor write SetBorderColor; property Color : TColor read m_Color write SetColor; property Picture : TPicture read m_Picture write SetPicture; property Visible; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnClick; end; implementation uses SUIForm; { TsuiProgressBar } constructor TsuiProgressBar.Create(AOwner: TComponent); begin inherited; ControlStyle := ControlStyle - [csAcceptsControls]; m_Picture := TPicture.Create(); m_Min := 0; m_Max := 100; m_Position := 50; m_Orientation := suiHorizontal; m_BorderColor := clBlack; m_Color := clBtnFace; m_CaptionColor := clBlack; Height := 12; Width := 150; Caption := '50%'; m_ShowCaption := true; Color := clBtnFace; UIStyle := GetSUIFormStyle(AOwner); UpdateProgress(); end; destructor TsuiProgressBar.Destroy; begin m_Picture.Free(); m_Picture := nil; inherited; end; function TsuiProgressBar.GetPercentFromPosition: Integer; begin if m_Max <> m_Min then Result := 100 * (m_Position - m_Min) div (m_Max - m_Min) else Result := 0; end; function TsuiProgressBar.GetWidthFromPosition(nWidth : Integer): Integer; begin Result := 0; if ( (m_Max <= m_Min) or (m_Position <= m_Min) ) then Exit; Result := nWidth; if m_Position > m_Max then Exit; Result := (m_Position - m_Min) * nWidth div (m_Max - m_Min); end; procedure TsuiProgressBar.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if ( (Operation = opRemove) and (AComponent = m_FileTheme) )then begin m_FileTheme := nil; SetUIStyle(SUI_THEME_DEFAULT); end; end; procedure TsuiProgressBar.Paint; var nProgressWidth : Integer; Buf : TBitmap; R : TRect; begin Buf := TBitmap.Create(); Buf.Width := ClientWidth; Buf.Height := ClientHeight; if m_Orientation = suiHorizontal then begin nProgressWidth := GetWidthFromPosition(Buf.Width - 1); if nProgressWidth = 0 then Inc(nProgressWidth); if m_Picture.Graphic <> nil then begin R := Rect(1, 1, nProgressWidth, Buf.Height - 1); Buf.Canvas.StretchDraw(R, m_Picture.Graphic); end; Buf.Canvas.Brush.Color := m_Color; R := Rect(nProgressWidth, 1, Buf.Width - 1, Buf.Height - 1); Buf.Canvas.FillRect(R); end else begin nProgressWidth := Buf.Height - 1 - GetWidthFromPosition(Buf.Height - 1); if nProgressWidth = 0 then Inc(nProgressWidth); if m_Picture.Graphic <> nil then begin R := Rect(1, Buf.Height - 2, Buf.Width - 1, nProgressWidth - 1); Buf.Canvas.StretchDraw(R, m_Picture.Graphic); end; Buf.Canvas.Brush.Color := m_Color; R := Rect(1, nProgressWidth, Buf.Width - 1, 1); Buf.Canvas.FillRect(R); m_ShowCaption := false; end; if m_ShowCaption then begin Buf.Canvas.Font.Color := m_CaptionColor; Buf.Canvas.Brush.Style := bsClear; if m_SmartShowCaption and (m_Position = m_Min) then else Buf.Canvas.TextOut(((Buf.Width - Buf.Canvas.TextWidth(Caption)) div 2), (Buf.Height - Buf.Canvas.TextHeight(Caption)) div 2, Caption); end; Buf.Canvas.Brush.Color := m_BorderColor; Buf.Canvas.FrameRect(ClientRect); BitBlt(Canvas.Handle, 0, 0, Buf.Width, Buf.Height, Buf.Canvas.Handle, 0, 0, SRCCOPY); Buf.Free(); end; procedure TsuiProgressBar.SetBorderColor(const Value: TColor); begin m_BorderColor := Value; Repaint(); end; procedure TsuiProgressBar.SetCaptionColor(const Value: TColor); begin m_CaptionColor := Value; Repaint(); end; procedure TsuiProgressBar.SetColor(const Value: TColor); begin m_Color := Value; Repaint(); end; procedure TsuiProgressBar.SetFileTheme(const Value: TsuiFileTheme); begin m_FileTheme := Value; SetUIStyle(m_UIStyle); end; procedure TsuiProgressBar.SetMax(const Value: Integer); begin m_Max := Value; UpdateProgress(); end; procedure TsuiProgressBar.SetMin(const Value: Integer); begin m_Min := Value; UpdateProgress(); end; procedure TsuiProgressBar.SetOrientation( const Value: TsuiProgressBarOrientation); begin m_Orientation := Value; UpdatePicture(); end; procedure TsuiProgressBar.SetPicture(const Value: TPicture); begin m_Picture.Assign(Value); Repaint(); end; procedure TsuiProgressBar.SetPosition(const Value: Integer); begin m_Position := Value; UpdateProgress(); end; procedure TsuiProgressBar.SetShowCaption(const Value: Boolean); begin m_ShowCaption := Value; Repaint(); end; procedure TsuiProgressBar.SetSmartShowCaption(const Value: Boolean); begin m_SmartShowCaption := Value; Repaint(); end; procedure TsuiProgressBar.SetUIStyle(const Value: TsuiUIStyle); begin m_UIStyle := Value; UpdatePicture(); end; procedure TsuiProgressBar.StepBy(Delta: Integer); begin Position := Position + Delta; end; procedure TsuiProgressBar.StepIt; begin Position := Position + 1; end; procedure TsuiProgressBar.UpdatePicture; var OutUIStyle : TsuiUIStyle; TempBuf : TBitmap; begin if UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle) then begin m_FileTheme.GetBitmap(SUI_THEME_PROGRESSBAR_IMAGE, m_Picture.Bitmap); Color := m_FileTheme.GetColor(SUI_THEME_CONTROL_BACKGROUND_COLOR); BorderColor := m_FileTheme.GetColor(SUI_THEME_CONTROL_BORDER_COLOR); end else begin GetInsideThemeBitmap(OutUIStyle, SUI_THEME_PROGRESSBAR_IMAGE, m_Picture.Bitmap); Color := GetInsideThemeColor(OutUIStyle, SUI_THEME_CONTROL_BACKGROUND_COLOR); BorderColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_CONTROL_BORDER_COLOR); end; if m_Orientation = suiVertical then begin TempBuf := TBitmap.Create(); TempBuf.Assign(m_Picture.Bitmap); RoundPicture(TempBuf); m_Picture.Bitmap.Assign(TempBuf); TempBuf.Free(); end; Repaint(); end; procedure TsuiProgressBar.UpdateProgress; begin Caption := IntToStr(GetPercentFromPosition()) + '%'; Repaint(); end; procedure TsuiProgressBar.WMERASEBKGND(var Msg: TMessage); begin // Do nothing end; end.
PROGRAM Sort(INPUT, OUTPUT); VAR F1: TEXT; Ch: CHAR; PROCEDURE CopyText(VAR FromFile, ToFile: TEXT); VAR Ch: CHAR; BEGIN RESET(FromFile); REWRITE(ToFile); WHILE NOT EOLN(FromFile) DO BEGIN READ(FromFile, Ch); WRITE(ToFile, Ch); END; END; BEGIN {Проверка успешности копирования текста из одного файла в другой} CopyText(INPUT, F1); RESET(F1); WHILE NOT EOLN(F1) DO BEGIN READ(F1, Ch); WRITE(Ch); END; END.
unit ejb_sidl_java_sql_i; {This file was generated on 28 Feb 2001 10:06:55 GMT by version 03.03.03.C1.06} {of the Inprise VisiBroker idl2pas CORBA IDL compiler. } {Please do not edit the contents of this file. You should instead edit and } {recompile the original IDL which was located in the file sidl.idl. } {Delphi Pascal unit : ejb_sidl_java_sql_i } {derived from IDL module : sql } interface uses CORBA; type Date = interface; Time = interface; Timestamp = interface; Date = interface ['{53B882A9-254B-D3A0-24D9-CB4366F297C9}'] function _get_time : Int64; procedure _set_time (const time : Int64); property time : Int64 read _get_time write _set_time; end; Time = interface ['{4A689788-18FF-E321-505B-E04A1709A35D}'] function _get_time1 : Int64; procedure _set_time1 (const time1 : Int64); property time1 : Int64 read _get_time1 write _set_time1; end; Timestamp = interface ['{8CFA614B-6EFD-2A09-1098-B5E900C94E41}'] function _get_time : Int64; procedure _set_time (const time : Int64); property time : Int64 read _get_time write _set_time; end; implementation initialization end.
unit xHttpServer; interface uses System.SysUtils, System.Types, System.Classes, IdBaseComponent, IdComponent, IdCustomTCPServer, IdCustomHTTPServer, IdHTTPServer, IdContext; type THttpServer = class private FHttpServer: TIdHTTPServer; FRootDir: string; FFileText : TStringList; FDefaultMainPage: string; FDefaultPort: Integer; function GetActive: Boolean; procedure SetActive(const Value: Boolean); procedure CommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); public constructor Create; destructor Destroy; override; /// <summary> /// 服务器根目录 (默认 程序根目录下的www文件夹) /// </summary> property RootDir : string read FRootDir write FRootDir; /// <summary> /// 服务器端口 (默认80) /// </summary> property DefaultPort : Integer read FDefaultPort write FDefaultPort; /// <summary> /// 是否启动 /// </summary> property Active : Boolean read GetActive write SetActive; /// <summary> /// 默认主页 (相对目录) /// </summary> property DefaultMainPage : string read FDefaultMainPage write FDefaultMainPage; end; implementation { THttpServer } procedure THttpServer.CommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var LFilename: string; LPathname: string; sFileExt : string; begin //浏览器请求http://127.0.0.1:8008/index.html?a=1&b=2 //ARequestInfo.Document 返回 /index.html //ARequestInfo.QueryParams 返回 a=1b=2 //ARequestInfo.Params.Values['name'] 接收get,post过来的数据 ////webserver发文件 LFilename := ARequestInfo.Document; if LFilename = '/' then LFilename := '/'+DefaultMainPage; LPathname := RootDir + LFilename; if FileExists(LPathname) then begin sFileExt := UpperCase(ExtractFileExt(LPathname)); if (sFileExt = '.HTML') or (sFileExt = '.HTM')then begin FFileText.LoadFromFile(LPathname); AResponseInfo.ContentType :='text/html;Charset=UTF-8'; // 中文不乱码 AResponseInfo.ContentText:=FFileText.Text; end else if sFileExt = '.XML'then begin FFileText.LoadFromFile(LPathname); AResponseInfo.ContentType :='text/xml;Charset=UTF-8'; AResponseInfo.ContentText:=FFileText.Text; end else begin AResponseInfo.ContentStream := TFileStream.Create(LPathname, fmOpenRead + fmShareDenyWrite);//发文件 if (sFileExt = '.RAR') or (sFileExt = '.ZIP')or (sFileExt = '.EXE') then begin //下载文件时,直接从网页打开而没有弹出保存对话框的问题解决 AResponseInfo.CustomHeaders.Values['Content-Disposition'] :='attachment; filename="'+extractfilename(LPathname)+'"'; end; end; end else begin AResponseInfo.ContentType :='text/html;Charset=UTF-8'; AResponseInfo.ResponseNo := 404; AResponseInfo.ContentText := '找不到' + ARequestInfo.Document; end; //替换 IIS {AResponseInfo.Server:='IIS/6.0'; AResponseInfo.CacheControl:='no-cache'; AResponseInfo.Pragma:='no-cache'; AResponseInfo.Date:=Now;} end; constructor THttpServer.Create; begin FHttpServer:= TIdHTTPServer.Create; FFileText := TStringList.Create; FHttpServer.OnCommandGet := CommandGet; FRootDir := ExtractFilePath(ParamStr(0)) + 'www'; FDefaultMainPage := 'Index.html'; FDefaultPort := 80; end; destructor THttpServer.Destroy; begin FHttpServer.Free; FFileText.Free; inherited; end; function THttpServer.GetActive: Boolean; begin Result := FHttpServer.Active; end; procedure THttpServer.SetActive(const Value: Boolean); begin if FHttpServer.Active <> Value then begin if Value then begin FHttpServer.Bindings.Clear; FHttpServer.DefaultPort:= FDefaultPort; end; FHttpServer.Active := Value; end; end; end.
{----------------------------------------------------------------------------- Unit Name : Bugger.pas Author : n0mad Version : (B) 2004.11.12.02 Creation : 04.04.2003 Purpose : Debuging functions Program : Universal unit History : -----------------------------------------------------------------------------} unit Bugger; // **************************************************************************** interface uses SysUtils; {$DEFINE DEBUG_Module_Start_Finish} {$DEFINE DEBUG_Module_Default_Set} {$DEFINE DEBUG_Module_Catch_ExitProc} {$DEFINE DEBUG_Module_AddTerminateProc} // if finalization section exists DLL compiled with unit fail at calling FreeLibrary() // Undefine it in Bugger.inc {$DEFINE DEBUG_Module_Final_Section} {$I Bugger.inc} {$IFDEF NO_DEBUG} {$UNDEF DEBUG_Module_Start_Finish} {$ENDIF} {$IFDEF NO_DEBUG} {$UNDEF DEBUG_Module_Default_Set} {$ENDIF} // **************************************************************************** {$IFDEF DEBUG_Module_Default_Set} const DEBUGWorkDir: string = ''; DEBUGProjectName: string = 'ProjectName'; DEBUGFileNameDateTimeAddon: string = '_(yyyy_mm_dd^hh_nn_ss_ddd)'; DEBUGSavFileDateTimeAddon: string = '(yyyy-mm-dd^hh-nn-ss)'; DEBUGFileNameExt: string = 'log'; DEBUGToFile: boolean = true; DEBUGSaveToFile: boolean = true; DEBUGShowScr: boolean = false; DEBUGShowWarnings: boolean = true; DEBUGShowPrn: boolean = false; DEBUGNewLogFile: boolean = true; DEBUGShowAddr: boolean = true; DEBUGLogSeparatorWidth: integer = 77; DEBUGFreeSpaceLimitPercent: integer = 4; DEBUGFreeSpaceLimitBytes: int64 = 8 * 1024 * 1024; {$ENDIF} // **************************************************************************** {$IFDEF DEBUG_Module_Start_Finish} function DEBUGMess(const Shift: integer; const Mess: string): boolean; {$ENDIF} function DEBUGMessEnh(const Shift: integer; const UnitName, ProcName, Mess: string): boolean; function DEBUGMessBrk(const Shift: integer; const Mess: string): boolean; //function DEBUGMessLine(const Breaker: char; const Count: byte): boolean; function DEBUGMessExt(const Shift: integer; const Mess: string; const DateStamp, BreakerFromStart: boolean): boolean; function DEBUGSave(const FName, Data: string; const DateStamp: boolean): boolean; // **************************************************************************** implementation uses {$IFNDEF DEBUG_Module_Default_Set} Bugres, {$ENDIF} Windows; const UnitName: string = 'Bugger(B)'; UnitVer: string = '(B)2004.11.12.02'; const DEBUG_FileName: string = '.\prog_run.log'; DEBUG_Shift: integer = 0; DEBUG_Shift_Delta: byte = 2; DEBUG_Shift_Deep: byte = 20; DEBUG_Shift_Stop: byte = 3; DEBUG_Shift_Save: integer = 0; CRLF: string = #13#10; DEBUG_Log_Started: boolean = false; DEBUG_Log_Stop: boolean = true; // **************************************************************************** function DEBUGMess(const Shift: integer; const Mess: string): boolean; begin Result := DEBUGMessExt(Shift, Mess, true, false); end; function DEBUGMessEnh(const Shift: integer; const UnitName, ProcName, Mess: string): boolean; var ProcAddr: LongWord; begin if ((Length(UnitName) > 0) or (Length(ProcName) > 0) or (Length(Mess) > 0)) then begin if DEBUGShowAddr and (Shift <> 0) then begin // New style with address ProcAddr := LongWord(Pointer(@ProcName)^) + LongWord(Length(ProcName)); ProcAddr := ProcAddr + (4 - ProcAddr mod 4); Result := DEBUGMessExt(Shift, '[' + UnitName + '::' + ProcName + ':@=(0x' + IntToHex(ProcAddr, 8) + ')]: ' + Mess, true, false); end else // Old style Result := DEBUGMessExt(Shift, '[' + UnitName + '::' + ProcName + ']: ' + Mess, true, false); end else // Send void string just to shift Result := DEBUGMessExt(Shift, CRLF, false, false); end; function DEBUGMessBrk(const Shift: integer; const Mess: string): boolean; begin Result := DEBUGMessExt(Shift, StringOfChar('-', 20) + '=< ' + Mess + ' >=' + StringOfChar('-', 20), true, false); end; function DEBUGMessLine(const Breaker: char; const Count: byte): boolean; var tmpBreaker: char; tmpCount: byte; begin if Breaker = #0 then tmpBreaker := '-' else tmpBreaker := Breaker; if Count > 0 then tmpCount := Count else tmpCount := DEBUGLogSeparatorWidth; Result := DEBUGMessExt(0, CRLF + StringOfChar(tmpBreaker, tmpCount), false, true); end; function FreeSpaceCheckPassed(Directory: string; FreePercent: integer; FreeBytes: int64): boolean; var FreeAvailable, TotalSpace, TotalFree: Int64; begin Result := false; if not GetDiskFreeSpaceEx(PChar(Directory), FreeAvailable, TotalSpace, @TotalFree) then Result := true else if (FreeBytes < FreeAvailable) or (FreePercent < FreeAvailable / TotalSpace) then Result := true; end; function DEBUGMessExt(const Shift: integer; const Mess: string; const DateStamp, BreakerFromStart: boolean): boolean; var fh, i, j, last: integer; tmp_Mess, tmp_DateStamp: AnsiString; tmp_Shift: string; begin Result := false; if (DEBUG_Shift > DEBUG_Shift_Deep) then begin if (DEBUG_Shift mod DEBUG_Shift_Deep = 1) and (DEBUG_Shift <> DEBUG_Shift_Save) then begin try DEBUGSave('warning_stack_exhaust_detected.log', '', false); if DEBUGShowWarnings then begin // An exclamation-point icon appears in the message box MessageBox(0, PChar('Stack overflow is possible. Current shift = ' + IntToStr(DEBUG_Shift) + ' > ' + IntToStr(DEBUG_Shift_Deep) + '.' + CRLF + 'Обнаружено превышение глубины вызова. Возможно переполнение стека.'), PChar(DEBUGProjectName), MB_OK + MB_ICONSTOP {+ MB_RIGHT} {+ MB_RTLREADING}); end; finally DEBUG_Shift_Save := DEBUG_Shift; end; if (DEBUG_Shift_Save div DEBUG_Shift_Deep >= DEBUG_Shift_Stop) then begin try DEBUG_Shift := DEBUG_Shift_Deep div 2; DEBUGMessExt(0, Mess, true, false); DEBUGMessExt(0, 'Program goes to deep in cycle. Aborted.', true, false); if DEBUGShowWarnings then begin MessageBox(0, PChar('I warned you. Program goes to deep in cycle.' + CRLF + 'Вообщем я предупреждал, пора заканчивать вечные циклы.'), PChar(DEBUGProjectName), MB_OK + MB_ICONSTOP {+ MB_RIGHT} {+ MB_RTLREADING}); end; finally Abort; end; end; end; end; if DEBUGToFile or (not DEBUG_Log_Stop) then begin if (not DEBUG_Log_Stop) then if not FreeSpaceCheckPassed(ExtractFileDir(ExpandFileName(DEBUG_FileName)), DEBUGFreeSpaceLimitPercent, DEBUGFreeSpaceLimitBytes) then begin DEBUG_Log_Stop := true; try DEBUGSave('warning_free_space_not_available.log', '', false); if DEBUG_Log_Started then // log to file if already created DEBUGMessExt(0, 'Program exhausted space for logfile. Logging stopped.', true, false) else // create file if not created DEBUGSave(DEBUG_FileName, '', false); if DEBUGShowWarnings then begin MessageBox(0, PChar('Free space for log file not available. Logging will be disabled.' + CRLF + 'Свободного места для журнального файла не осталось. Журналирование будет отключено.'), PChar(DEBUGProjectName), MB_OK + MB_ICONSTOP {+ MB_RIGHT} {+ MB_RTLREADING}); end; finally DEBUGToFile := false; end; Exit; end; try tmp_Mess := Mess; except exit; end; fh := 0; try if FileExists(DEBUG_FileName) then begin fh := FileOpen(DEBUG_FileName, fmOpenReadWrite or fmShareDenyWrite); FileSeek(fh, 0, 2); end else fh := FileCreate(DEBUG_FileName); if fh > 0 then begin {--------------------------------} if Shift < 0 then dec(DEBUG_Shift); {--------------------------------} tmp_Shift := ''; if not BreakerFromStart then begin last := -1; tmp_Shift := StringOfChar(' ', DEBUG_Shift * DEBUG_Shift_Delta); for i := 0 to DEBUG_Shift div 2 do begin j := (2 * i) * DEBUG_Shift_Delta + 1; if (j > 0) and (j <= length(tmp_Shift)) then begin tmp_Shift[j] := '|'; last := j; end; end; j := last; if (j > 0) and (j <= length(tmp_Shift)) then if (Shift > 0) then tmp_Shift[j] := '>' else if (Shift < 0) then tmp_Shift[j] := '<' else tmp_Shift[j] := ' '; end; tmp_DateStamp := ''; if DateStamp then tmp_DateStamp := FormatDateTime('[yyyy.mm.dd]-(hh:nn:ss)-', Now); tmp_Mess := tmp_DateStamp + tmp_Shift + Mess + CRLF; if Length(Mess) = Length(CRLF) then tmp_Mess := ''; {--------------------------------} if Shift > 0 then inc(DEBUG_Shift); {--------------------------------} try if Length(tmp_Mess) > 0 then FileWrite(fh, tmp_Mess[1], Length(tmp_Mess)); Result := true; except // Possibly media is full or something else. end; end; finally FileClose(fh); DEBUG_Log_Started := true; end; end else begin // touch file to change modification timestamp if DEBUG_Log_Started then begin // log to file if already created fh := 0; try if FileExists(DEBUG_FileName) then begin fh := FileOpen(DEBUG_FileName, fmOpenReadWrite or fmShareDenyWrite); end else fh := FileCreate(DEBUG_FileName); if (fh > 0) then try tmp_Mess := ''; FileSeek(fh, 0, 2); FileWrite(fh, tmp_Mess[1], Length(tmp_Mess)); Result := false; except // Possibly media is full or something else. end; finally FileClose(fh); DEBUG_Log_Started := true; end; end else // create file if not created DEBUGSave(DEBUG_FileName, '', false); end; if DEBUGShowScr then MessageBox(0, PChar(Mess), PChar(DEBUGProjectName), MB_OK + MB_ICONINFORMATION {+ MB_RIGHT} {+ MB_RTLREADING}); end; function DEBUGSave(const FName, Data: string; const DateStamp: boolean): boolean; var fh: integer; tmp_FName, tmp_WorkDir, tmp_Data: AnsiString; tmp_DateTime: string; begin Result := false; if DEBUGSaveToFile then begin try tmp_FName := ExtractFileName(FName); tmp_WorkDir := ExtractFilePath(FName); if Length(tmp_WorkDir) = 0 then tmp_WorkDir := DEBUGWorkDir; tmp_Data := Data; except exit; end; fh := 0; if DateStamp then begin // DateSeparator := '-'; // TimeSeparator := '-'; try tmp_DateTime := FormatDateTime(DEBUGSavFileDateTimeAddon, Now); except tmp_DateTime := FormatDateTime('(yyyy-mm-dd`hh-nn-ss)', Now); end; end else tmp_DateTime := ''; try tmp_FName := tmp_WorkDir + tmp_DateTime + tmp_FName; fh := FileCreate(tmp_FName); if fh > 0 then try FileWrite(fh, tmp_Data[1], Length(tmp_Data)); Result := true; except // Possibly media is full or something else. end; finally FileClose(fh); end; end; end; // **************************************************************************** procedure BuggerInit; const ProcName: string = 'BuggerInit'; begin DEBUG_Log_Started := false; DEBUG_Log_Stop := false; if (DEBUGFreeSpaceLimitPercent < 0) then DEBUGFreeSpaceLimitPercent := 0; if (DEBUGFreeSpaceLimitPercent > 100) then DEBUGFreeSpaceLimitPercent := 100; if (DEBUGFreeSpaceLimitBytes < 0) then DEBUGFreeSpaceLimitBytes := 32 * 1024 * 1024; if Length(DEBUGProjectName) = 0 then DEBUGProjectName := ChangeFileExt(ExtractFileName(ParamStr(0)), ''); if Length(DEBUGWorkDir) = 0 then DEBUGWorkDir := GetCurrentDir + '\' else if (DEBUGWorkDir[Length(DEBUGWorkDir)] = '/') then DEBUGWorkDir[Length(DEBUGWorkDir)] := '/' else if (DEBUGWorkDir[Length(DEBUGWorkDir)] <> '\') then DEBUGWorkDir := DEBUGWorkDir + '\'; if DEBUGNewLogFile then begin // DEBUGFileName := DEBUGProjectName + FormatDateTime('_(yyyy.mm.dd_hh-nn-ss_ddd)', Now) + '.log'; DEBUG_FileName := DEBUGWorkDir + DEBUGProjectName + FormatDateTime(DEBUGFileNameDateTimeAddon, Now) + '.' + DEBUGFileNameExt; end else begin DEBUG_FileName := DEBUGWorkDir + DEBUGProjectName + '.' + DEBUGFileNameExt; end; { DEBUGMess(0, StringOfChar('-', 10) + StringOfChar('=', 10) + '[Start]' + StringOfChar('=', 10) + StringOfChar('-', 10)); } end; // **************************************************************************** procedure BuggerInfo; const ProcName: string = 'BuggerInfo'; begin DEBUGMessEnh(1, UnitName, ProcName, '...Init... ->'); DEBUGMess(0, 'Unit version is - ' + UnitVer); DEBUGMess(0, 'DateTime is = ' + FormatDateTime('yyyy, mmmm dd, dddd, hh:nn:ss)', Now)); DEBUGMess(0, 'DEBUGFileName = "' + DEBUG_FileName + '"'); DEBUGMess(0, 'CurrentDir = "' + GetCurrentDir + '"'); DEBUGMessEnh(-1, UnitName, ProcName, '...Init... <-'); end; // **************************************************************************** {$IFDEF DEBUG_Module_Catch_ExitProc} const ptr_SavExit: Pointer = nil; procedure BuggerFinal; const ProcName: string = 'BuggerFinal'; begin DEBUGMess(0, StringOfChar('.', 7)); DEBUGMessEnh(1, UnitName, ProcName, '...Final... ->'); DEBUGMessEnh(0, UnitName, ProcName, 'ExitProcF = 0x' + IntToHex(LongInt(@ExitProc), 8)); DEBUGMessEnh(0, UnitName, ProcName, 'SaveExitAddress = 0x' + IntToHex(LongInt(ptr_SavExit), 8)); DEBUGMessEnh(0, UnitName, ProcName, 'Restoring ExitProc pointer... '); ExitProc := ptr_SavExit; // restore exit procedure chain DEBUGMessEnh(0, UnitName, ProcName, 'ExitProcR = 0x' + IntToHex(LongInt(@ExitProc), 8)); DEBUGMessEnh(-1, UnitName, ProcName, '...Final... <-'); DEBUGMess(0, StringOfChar('.', 7)); { DEBUGMess(0, StringOfChar('-', 10) + StringOfChar('=', 10) + '[Finish]' + StringOfChar('=', 10) + StringOfChar('-', 10)); } end; {$ENDIF} // **************************************************************************** {$IFDEF DEBUG_Module_AddTerminateProc} function BuggerTerminate: boolean; const ProcName: string = 'BuggerTerminate'; begin Result := True; DEBUGMess(0, StringOfChar('.', 7)); DEBUGMessEnh(1, UnitName, ProcName, '...Terminate... ->'); DEBUGMessEnh(-1, UnitName, ProcName, '...Terminate... <-'); DEBUGMess(0, StringOfChar('.', 7)); { DEBUGMess(0, StringOfChar('-', 10) + StringOfChar('=', 10) + '[Finish]' + StringOfChar('=', 10) + StringOfChar('-', 10)); } end; {$ENDIF} // **************************************************************************** initialization asm jmp @@loc db $90, $90, $90, $90, $90, $90, $90, $90 db $0D, $0A, '#-Sign4U-#', $0D, $0A, 0 db 'initialization section', 0 db 'Begin here', $0D, $0A, 0 db $90, $90, $90, $90, $90, $90, $90, $90 @@loc: end; BuggerInit; DEBUGMess(0, StringOfChar('-', 10) + StringOfChar('=', 10) + '[Start]' + StringOfChar('=', 10) + StringOfChar('-', 10)); {$IFDEF DEBUG_Module_Catch_ExitProc} DEBUGMessEnh(0, UnitName, 'SInit', 'ExitProcB = 0x' + IntToHex(LongInt(@ExitProc), 8)); ptr_SavExit := ExitProc; // save exit procedure chain DEBUGMessEnh(0, UnitName, 'SInit', 'Installing ExitProc pointer... '); ExitProc := @BuggerFinal; // install LibExit exit procedure DEBUGMessEnh(0, UnitName, 'SInit', 'ExitProcA = 0x' + IntToHex(LongInt(@ExitProc), 8)); DEBUGMessEnh(0, UnitName, 'SInit', 'SaveExitAddress = 0x' + IntToHex(LongInt(ptr_SavExit), 8)); {$ENDIF} {$IFDEF DEBUG_Module_AddTerminateProc} DEBUGMessEnh(0, UnitName, 'SInit', 'Adding TerminateProc = 0x' + IntToHex(LongInt(@BuggerTerminate), 8)); AddTerminateProc(BuggerTerminate); {$ENDIF} BuggerInfo; DEBUGMessBrk(0, '...'); asm jmp @@loc db $90, $90, $90, $90, $90, $90, $90, $90 db $0D, $0A, '#-Sign4U-#', $0D, $0A, 0 db 'initialization section', 0 db 'End here', $0D, $0A, 0 db $90, $90, $90, $90, $90, $90, $90, $90 @@loc: end; // **************************************************************************** {$IFDEF DEBUG_Module_Final_Section} finalization // if finalization section exists DLL compiled with unit fail at calling FreeLibrary() // library finalization code asm jmp @@loc db $90, $90, $90, $90, $90, $90, $90, $90 db $0D, $0A, '#-Sign4U-#', $0D, $0A, 0 db 'finalization section', 0 db 'Begin here', $0D, $0A, 0 db $90, $90, $90, $90, $90, $90, $90, $90 @@loc: end; DEBUGMessBrk(0, 'Finalization'); DEBUGMessEnh(0, UnitName, 'SFinal', 'ExitProcC = 0x' + IntToHex(LongInt(@ExitProc), 8)); DEBUGMessEnh(0, UnitName, 'SFinal', 'SaveExitAddress = 0x' + IntToHex(LongInt(ptr_SavExit), 8)); // DEBUGMessBrk(0, '...'); DEBUGMess(0, StringOfChar('-', 10) + StringOfChar('=', 10) + '[Finish]' + StringOfChar('=', 10) + StringOfChar('-', 10)); asm jmp @@loc db $90, $90, $90, $90, $90, $90, $90, $90 db $0D, $0A, '#-Sign4U-#', $0D, $0A, 0 db 'finalization section', 0 db 'End here', $0D, $0A, 0 db $90, $90, $90, $90, $90, $90, $90, $90 @@loc: end; {$ENDIF} end.
// // Created by the DataSnap proxy generator. // 2017-03-02 ¿ÀÈÄ 5:27:11 // unit unit1; interface uses System.JSON, Data.DBXCommon, Data.DBXClient, Data.DBXDataSnap, Data.DBXJSON, Datasnap.DSProxy, System.Classes, System.SysUtils, Data.DB, Data.SqlExpr, Data.DBXDBReaders, Data.DBXCDSReaders, Data.DBXJSONReflect; type TServerMethods1Client = class(TDSAdminClient) private FEchoStringCommand: TDBXCommand; FReverseStringCommand: TDBXCommand; FTableNumCommand: TDBXCommand; FMenuKindCommand: TDBXCommand; FSumPeopleCommand: TDBXCommand; FDeleteKitchenCommand: TDBXCommand; FTotalPriceCommand: TDBXCommand; FDeleteDataCommand: TDBXCommand; FInsertDetailCommand: TDBXCommand; FKeychangeCommand: TDBXCommand; FOpenDetailCommand: TDBXCommand; FKeyUpdateCommand: TDBXCommand; FDatePickCommand: TDBXCommand; public constructor Create(ADBXConnection: TDBXConnection); overload; constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload; destructor Destroy; override; function EchoString(Value: string): string; function ReverseString(Value: string): string; function TableNum(tableno: Integer): Integer; function MenuKind(Kind: string): string; function SumPeople(TableNo: Integer; Peopleno: Integer; price: Integer; Menu: string): string; procedure DeleteKitchen(seq: Integer); function TotalPrice(tableno: Integer): Integer; procedure DeleteData(tableno: Integer); procedure InsertDetail(tableno: Integer); procedure Keychange(Keyno: Integer); function OpenDetail(Keyno: Integer): Integer; procedure KeyUpdate(keyno: Integer; tableno: Integer); function DatePick(DatePick: string): string; end; implementation function TServerMethods1Client.EchoString(Value: string): string; begin if FEchoStringCommand = nil then begin FEchoStringCommand := FDBXConnection.CreateCommand; FEchoStringCommand.CommandType := TDBXCommandTypes.DSServerMethod; FEchoStringCommand.Text := 'TServerMethods1.EchoString'; FEchoStringCommand.Prepare; end; FEchoStringCommand.Parameters[0].Value.SetWideString(Value); FEchoStringCommand.ExecuteUpdate; Result := FEchoStringCommand.Parameters[1].Value.GetWideString; end; function TServerMethods1Client.ReverseString(Value: string): string; begin if FReverseStringCommand = nil then begin FReverseStringCommand := FDBXConnection.CreateCommand; FReverseStringCommand.CommandType := TDBXCommandTypes.DSServerMethod; FReverseStringCommand.Text := 'TServerMethods1.ReverseString'; FReverseStringCommand.Prepare; end; FReverseStringCommand.Parameters[0].Value.SetWideString(Value); FReverseStringCommand.ExecuteUpdate; Result := FReverseStringCommand.Parameters[1].Value.GetWideString; end; function TServerMethods1Client.TableNum(tableno: Integer): Integer; begin if FTableNumCommand = nil then begin FTableNumCommand := FDBXConnection.CreateCommand; FTableNumCommand.CommandType := TDBXCommandTypes.DSServerMethod; FTableNumCommand.Text := 'TServerMethods1.TableNum'; FTableNumCommand.Prepare; end; FTableNumCommand.Parameters[0].Value.SetInt32(tableno); FTableNumCommand.ExecuteUpdate; Result := FTableNumCommand.Parameters[1].Value.GetInt32; end; function TServerMethods1Client.MenuKind(Kind: string): string; begin if FMenuKindCommand = nil then begin FMenuKindCommand := FDBXConnection.CreateCommand; FMenuKindCommand.CommandType := TDBXCommandTypes.DSServerMethod; FMenuKindCommand.Text := 'TServerMethods1.MenuKind'; FMenuKindCommand.Prepare; end; FMenuKindCommand.Parameters[0].Value.SetWideString(Kind); FMenuKindCommand.ExecuteUpdate; Result := FMenuKindCommand.Parameters[1].Value.GetWideString; end; function TServerMethods1Client.SumPeople(TableNo: Integer; Peopleno: Integer; price: Integer; Menu: string): string; begin if FSumPeopleCommand = nil then begin FSumPeopleCommand := FDBXConnection.CreateCommand; FSumPeopleCommand.CommandType := TDBXCommandTypes.DSServerMethod; FSumPeopleCommand.Text := 'TServerMethods1.SumPeople'; FSumPeopleCommand.Prepare; end; FSumPeopleCommand.Parameters[0].Value.SetInt32(TableNo); FSumPeopleCommand.Parameters[1].Value.SetInt32(Peopleno); FSumPeopleCommand.Parameters[2].Value.SetInt32(price); FSumPeopleCommand.Parameters[3].Value.SetWideString(Menu); FSumPeopleCommand.ExecuteUpdate; Result := FSumPeopleCommand.Parameters[4].Value.GetWideString; end; procedure TServerMethods1Client.DeleteKitchen(seq: Integer); begin if FDeleteKitchenCommand = nil then begin FDeleteKitchenCommand := FDBXConnection.CreateCommand; FDeleteKitchenCommand.CommandType := TDBXCommandTypes.DSServerMethod; FDeleteKitchenCommand.Text := 'TServerMethods1.DeleteKitchen'; FDeleteKitchenCommand.Prepare; end; FDeleteKitchenCommand.Parameters[0].Value.SetInt32(seq); FDeleteKitchenCommand.ExecuteUpdate; end; function TServerMethods1Client.TotalPrice(tableno: Integer): Integer; begin if FTotalPriceCommand = nil then begin FTotalPriceCommand := FDBXConnection.CreateCommand; FTotalPriceCommand.CommandType := TDBXCommandTypes.DSServerMethod; FTotalPriceCommand.Text := 'TServerMethods1.TotalPrice'; FTotalPriceCommand.Prepare; end; FTotalPriceCommand.Parameters[0].Value.SetInt32(tableno); FTotalPriceCommand.ExecuteUpdate; Result := FTotalPriceCommand.Parameters[1].Value.GetInt32; end; procedure TServerMethods1Client.DeleteData(tableno: Integer); begin if FDeleteDataCommand = nil then begin FDeleteDataCommand := FDBXConnection.CreateCommand; FDeleteDataCommand.CommandType := TDBXCommandTypes.DSServerMethod; FDeleteDataCommand.Text := 'TServerMethods1.DeleteData'; FDeleteDataCommand.Prepare; end; FDeleteDataCommand.Parameters[0].Value.SetInt32(tableno); FDeleteDataCommand.ExecuteUpdate; end; procedure TServerMethods1Client.InsertDetail(tableno: Integer); begin if FInsertDetailCommand = nil then begin FInsertDetailCommand := FDBXConnection.CreateCommand; FInsertDetailCommand.CommandType := TDBXCommandTypes.DSServerMethod; FInsertDetailCommand.Text := 'TServerMethods1.InsertDetail'; FInsertDetailCommand.Prepare; end; FInsertDetailCommand.Parameters[0].Value.SetInt32(tableno); FInsertDetailCommand.ExecuteUpdate; end; procedure TServerMethods1Client.Keychange(Keyno: Integer); begin if FKeychangeCommand = nil then begin FKeychangeCommand := FDBXConnection.CreateCommand; FKeychangeCommand.CommandType := TDBXCommandTypes.DSServerMethod; FKeychangeCommand.Text := 'TServerMethods1.Keychange'; FKeychangeCommand.Prepare; end; FKeychangeCommand.Parameters[0].Value.SetInt32(Keyno); FKeychangeCommand.ExecuteUpdate; end; function TServerMethods1Client.OpenDetail(Keyno: Integer): Integer; begin if FOpenDetailCommand = nil then begin FOpenDetailCommand := FDBXConnection.CreateCommand; FOpenDetailCommand.CommandType := TDBXCommandTypes.DSServerMethod; FOpenDetailCommand.Text := 'TServerMethods1.OpenDetail'; FOpenDetailCommand.Prepare; end; FOpenDetailCommand.Parameters[0].Value.SetInt32(Keyno); FOpenDetailCommand.ExecuteUpdate; Result := FOpenDetailCommand.Parameters[1].Value.GetInt32; end; procedure TServerMethods1Client.KeyUpdate(keyno: Integer; tableno: Integer); begin if FKeyUpdateCommand = nil then begin FKeyUpdateCommand := FDBXConnection.CreateCommand; FKeyUpdateCommand.CommandType := TDBXCommandTypes.DSServerMethod; FKeyUpdateCommand.Text := 'TServerMethods1.KeyUpdate'; FKeyUpdateCommand.Prepare; end; FKeyUpdateCommand.Parameters[0].Value.SetInt32(keyno); FKeyUpdateCommand.Parameters[1].Value.SetInt32(tableno); FKeyUpdateCommand.ExecuteUpdate; end; function TServerMethods1Client.DatePick(DatePick: string): string; begin if FDatePickCommand = nil then begin FDatePickCommand := FDBXConnection.CreateCommand; FDatePickCommand.CommandType := TDBXCommandTypes.DSServerMethod; FDatePickCommand.Text := 'TServerMethods1.DatePick'; FDatePickCommand.Prepare; end; FDatePickCommand.Parameters[0].Value.SetWideString(DatePick); FDatePickCommand.ExecuteUpdate; Result := FDatePickCommand.Parameters[1].Value.GetWideString; end; constructor TServerMethods1Client.Create(ADBXConnection: TDBXConnection); begin inherited Create(ADBXConnection); end; constructor TServerMethods1Client.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); begin inherited Create(ADBXConnection, AInstanceOwner); end; destructor TServerMethods1Client.Destroy; begin FEchoStringCommand.DisposeOf; FReverseStringCommand.DisposeOf; FTableNumCommand.DisposeOf; FMenuKindCommand.DisposeOf; FSumPeopleCommand.DisposeOf; FDeleteKitchenCommand.DisposeOf; FTotalPriceCommand.DisposeOf; FDeleteDataCommand.DisposeOf; FInsertDetailCommand.DisposeOf; FKeychangeCommand.DisposeOf; FOpenDetailCommand.DisposeOf; FKeyUpdateCommand.DisposeOf; FDatePickCommand.DisposeOf; inherited; end; end.
unit ExportToMSSQLCmd; interface procedure ExportToMSSQL(tableName, databaseName : String; userId, password : String; hostName : String; hostPort : Integer); implementation uses SysUtils, StrUtils, edbcomps, SessionManager; procedure ExportToMSSQL(tableName, databaseName : String; userId, password : String; hostName : String; hostPort : Integer); var db : TEDBDatabase; sessionMgr : TSessionManager; ds, dsConstraints : TEDBQuery; sSQL : String; outStr : String; fieldName, fieldType : String; defaultExpr, defaultStr, nullableStr : String; function MakeIndexes(tableName : String) : String; var sSQL : String; dsIndexes : TEDBQuery; lastIndex : String; indexName : String; iIndex : Integer; iCol : Integer; begin Result := ''; sSQL := 'Select t.Name IndexName, c.ColumnName, c.Descending ' + 'from Information.Indexes t ' + 'inner join Information.IndexColumns c on t.TableName = c.TableName and t.Name = c.IndexName ' + 'Where t.Type Not In (''Primary Key'', ''Text Index'') and t.TableName = ''' + tableName + ''' ' + 'Order By t.TableName, t.Name, c.OrdinalPos '; dsIndexes := TEDBQuery.Create(nil); try dsIndexes.SessionName := sessionMgr.session.SessionName; dsIndexes.DatabaseName := db.Database; dsIndexes.SQL.Add(sSQL); dsIndexes.ExecSQL; lastIndex := ''; iIndex := 0; iCol := 0; while not dsIndexes.EOF do begin if lastIndex <> dsIndexes.FieldByName('IndexName').AsString then begin if lastIndex <> '' then Result := Result + ');' + CRLF; indexName := 'idx' + tableName + IntToStr(iIndex); Result := Result + 'CREATE NONCLUSTERED INDEX [' + indexName + '] ON [dbo].[' + tableName + '] (' + CRLF; lastIndex := dsIndexes.FieldByName('IndexName').AsString; iCol := 0; iIndex := iIndex + 1; end; if iCol <> 0 then Result := Result + ','; Result := Result + '[' + dsIndexes.FieldByName('ColumnName').AsString + ']'; if dsIndexes.FieldByName('Descending').AsBoolean then Result := Result + ' DESC'; Result := Result + CRLF; iCol := iCol + 1; dsIndexes.Next; end; if lastIndex <> '' then Result := Result + ');' + CRLF; finally FreeAndNil(dsIndexes); end; end; procedure LoadContraints(var dsContraints : TEDBQuery); begin if Assigned(dsContraints) then FreeAndNil(dsContraints); sSQL := 'Select t.Name IndexName, t.TableName, t.Type, c.ColumnName, c.Descending ' + 'from Information.Indexes t ' + 'inner join Information.IndexColumns c on t.TableName = c.TableName and t.Name = c.IndexName ' + 'Where t.Type = ''Primary Key'' and t.TableName = ''' + tableName + ''' ' + 'Order By t.TableName, t.Name, c.OrdinalPos '; dsContraints := TEDBQuery.Create(nil); dsContraints.SessionName := sessionMgr.session.SessionName; dsContraints.DatabaseName := db.Database; dsContraints.SQL.Add(sSQL); dsContraints.ExecSQL; end; function MakeConstraints(dsContraints : TEDBQuery; tableName : String) : String; var sFields : String; begin Result := ''; dsConstraints.First; if not dsContraints.eof then begin sFields := ''; while not dsContraints.Eof do begin if sFields <> '' then sFields := sFields + ',' + crlf; sFields := sFields + dsContraints.FieldByName('ColumnName').AsString; if dsContraints.FieldByName('Descending').AsBoolean then sFields := sFields + ' DESC'; dsContraints.Next; end; Result := Format(', CONSTRAINT [PK_%s] PRIMARY KEY CLUSTERED (%s) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]', [tableName, sFields]); end; end; function FieldInConstraint(dsConstraints : TEDBQuery; tableName, fieldName : String) : Boolean; begin Result := false; dsConstraints.First; while not dsConstraints.Eof do begin if fieldName = dsConstraints.FieldByName('ColumnName').AsString then begin Result := True; break; end; dsConstraints.Next; end; end; begin sessionMgr := TSessionManager.Create(userId, password, hostName, hostPort); db := TEDBDatabase.Create(nil); db.OnStatusMessage := sessionMgr.Status; db.OnLogMessage := sessionMgr.Status; db.SessionName := sessionMgr.session.Name; db.Database := databaseName; db.LoginPrompt := true; db.DatabaseName := databaseName + DateTimeToStr(now); ds := TEDBQuery.Create(nil); ds.SessionName := sessionMgr.session.SessionName; ds.DatabaseName := db.Database; sSQL := 'Select Tables.Name TableName, ' + 'c.Name FieldName, c.Description, c.Type, ' + 'c.Length, c.Precision, c.Scale, ' + 'c.Nullable, ' + 'c.Generated, ' + 'c.GeneratedWhen, ' + 'c.GenerateExpr, ' + 'c.Identity, ' + 'c.IdentityIncrement, ' + 'c.IdentitySeed, ' + 'c.DefaultExpr ' + ' From Information.Tables t inner join Information.TableColumns c on t.Name = c.TableName '; if tableName <> '*' then sSQL := sSQL + 'Where t.Name = ''' + tableName + ''' '; sSQL := sSQL + 'Order by t.Name, c.OrdinalPos'; ds.SQL.Add(sSQL); ds.ExecSQL; // Field Names while not ds.Eof do begin tableName := ds.FieldByName('TableName').AsString; LoadContraints(dsConstraints); outStr := ''; repeat if outStr <> '' then outStr := outStr + ',' + CRLF; defaultStr := ''; defaultExpr := Trim(ds.FieldByName('DefaultExpr').AsString); fieldName := ds.FieldByName('FieldName').AsString; fieldType := LowerCase(ds.FieldByName('Type').AsString); nullableStr := 'NULL'; if Not ds.FieldByName('Nullable').AsBoolean then nullableStr := 'NOT NULL' else begin if FieldInConstraint(dsConstraints, tableName, fieldName) then nullableStr := 'NOT NULL'; end; if fieldType = 'integer' then begin fieldType := 'int'; if ds.FieldByName('Identity').AsBoolean then begin fieldType := fieldType + Format(' Identity (%d, %d)', [ds.FieldByName('IdentitySeed').AsInteger, ds.FieldByName('IdentityIncrement').AsInteger]); nullableStr := 'NOT NULL'; // override the nullable'ness. end; end else if fieldType = 'timestamp' then begin fieldType := 'datetime'; if ds.FieldByName('Generated').AsBoolean then // really should be default begin if StartsText('CURRENT_TIMESTAMP', UpperCase(ds.FieldByName('GenerateExpr').AsString)) then defaultExpr := 'getdate()'; end else if StartsText('CURRENT_TIMESTAMP', UpperCase(defaultExpr)) then begin defaultExpr := 'getdate()'; end; end else if fieldType = 'boolean' then begin fieldType := 'bit'; if defaultExpr <> '' then begin if LowerCase(defaultExpr) = 'false' then defaultExpr := '0' else if LowerCase(defaultExpr) = 'true' then defaultExpr := '1'; end; end else if fieldType = 'clob' then begin fieldType := 'text'; end else if fieldType = 'varchar' then fieldType := 'varchar(' + ds.FieldByName('Length').AsString + ')' else if fieldType = 'char' then fieldType := 'char(' + ds.FieldByName('Length').AsString + ')' else if fieldType = 'decimal' then fieldType := 'decimal(' + ds.FieldByName('Precision').AsString + ',' + ds.FieldByName('Scale').AsString + ')' ; if defaultExpr <> '' then defaultStr := Format('DEFAULT (%s)', [defaultExpr]); outStr := outStr + Format('[%s] %s %s %s', [fieldName, fieldType, nullableStr, defaultStr]); ds.Next; until ds.Eof or (tableName <> ds.FieldByName('TableName').AsString); outStr := 'IF OBJECT_ID (N''' + tableName + ''', N''U'') IS NOT NULL ' + CRLF + ' Drop Table [' + tableName + '];' + CRLF + 'Create Table [' + tableName + '] (' + CRLF + outStr + MakeConstraints(dsConstraints, tableName) + ');'; Writeln(outStr); Writeln(MakeIndexes(tableName)); Writeln; Writeln; end; FreeAndNil(ds); FreeAndNil(db); end; end.
unit uMensagem; interface uses Vcl.Dialogs, System.SysUtils, Vcl.Forms, Vcl.Controls, Vcl.Consts; procedure infoMessage (AMensagem: string); procedure warningMessage(AMensagem: string); procedure errorMessage (AMensagem: string); function questionMessage(AMensagem: String): Boolean; implementation function questionMessage(AMensagem: String): Boolean; begin result := TaskMessageDlg('Confirma', AMensagem, mtConfirmation, [mbYes, mbNo], 0, mbNo) = mrYes; end; procedure errorMessage(AMensagem: string); begin MessageDlg(AMensagem, mtError, [mbOK], 0); end; procedure infoMessage(AMensagem: string); begin MessageDlg(AMensagem, mtInformation, [mbOK], 0); end; procedure warningMessage(AMensagem: string); begin MessageDlg(AMensagem, mtWarning, [mbOK], 0); end; end.
{ ******************************************************************************************************************* SpiderCGI: Contains TSpiderCGI component which generate a CGI application. Any Free Spider CGI application should containe only one TSpiderCGI component Author: Motaz Abdel Azeem email: motaz@code.sd Home page: http://code.sd License: LGPL Last modified: 27.July.2012 Jul/2010 - Modified by Luiz Américo * Remove LCL dependency * Microoptimizations: add const to parameters, remove unnecessary typecast ******************************************************************************************************************* } unit SpiderCGI; {$mode objfpc}{$H+} interface uses Classes, SysUtils, SpiderUtils, FileUtil, CGIUtils; type TDataModuleClass = class of TDataModule; { TSpiderCGI } TSpiderCGI = class(TComponent) private fOnRequest: TSpiderEvent; fRequest: TSpiderRequest; fResponse: TSpiderResponse; fPath: string; fModules: array of String; fPathList: array of TStringList; fEnabled: Boolean; function SearchActionInModule(const APath: string; AModule: TDataModule): Boolean; { Private declarations } protected { Protected declarations } public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; procedure Execute; property Request: TSpiderRequest read fRequest; property Response: TSpiderResponse read fResponse; procedure AddDataModule(const ADataModuleClassName: string; APaths: array of string); { Public declarations } published { Published declarations } property OnRequest: TSpiderEvent read FOnRequest write FOnRequest; property Enabled: Boolean read fEnabled write fEnabled; property Path: string read fPath; end; implementation uses SpiderAction; { TSpiderCGI } procedure TSpiderCGI.Execute; var i: Integer; Found: Boolean; APath: string; dmc: TDataModuleClass; DataMod: TDataModule; httpVer: string; begin try if (not fEnabled) or ((GetEnvironmentVariable('REMOTE_ADDR') = '') and // Make sure it is launched from web server (GetEnvironmentVariable('REQUEST_METHOD') = '') and (LowerCase(ParamStr(1)) <> '-con')) then // enable run from console using -d option begin Exit; end; APath:= Trim(LowerCase(GetEnvironmentVariable('PATH_INFO'))); if (APath <> '') and (APath[Length(APath)] = '/') then APath:= Copy(APath, 1, Length(APath) - 1); Found:= False; // Search path in main module actions if APath <> '' then Found:= SearchActionInModule(APath, TDataModule(Owner)); // Search path in other additional modules if (not Found) then for i:= 0 to High(fModules) do if fPathList[i].IndexOf(APath) <> -1 then begin dmc:= TDataModuleClass(FindClass(fModules[i])); if dmc <> nil then begin DataMod:= dmc.Create(nil); Found:= SearchActionInModule(APath, DataMod); end; if Found then Break; end; // triger SpiderCGI action when no path action found if (Not Found) and (Assigned(fOnRequest)) then fOnRequest(Self, fRequest, fResponse); //Response code httpVer := 'STATUS: ' + IntToStr(Response.ResponseCode) + ' ' + Response.ResponseString; Writeln(httpVer); // Put cookies for i:= 0 to Response.CookieList.Count - 1 do Writeln(Trim(Response.CookieList[i])); // Put custom header for i:= 0 to Response.CustomHeader.Count - 1 do Writeln(Response.CustomHeader[i]); // Send page response to the browser Writeln('CONTENT-TYPE: ' + Response.ContentType); Writeln; Writeln(Response.Content.Text); except on e: exception do begin Writeln('CONTENT-TYPE: TEXT/HTML'); Writeln; Writeln('<font color=red>' + e.message + '<font>'); end; end; end; procedure TSpiderCGI.AddDataModule(const ADataModuleClassName: string; APaths: array of string); var i: Integer; begin SetLength(fModules, Length(fModules) + 1); fModules[High(fModules)]:= ADataModuleClassName; SetLength(fPathList, Length(fPathList) + 1); fPathList[High(fPathList)]:= TStringList.Create; for i:= 0 to High(APaths) do fPathList[High(fPathList)].Add(LowerCase(APaths[i])); end; function TSpiderCGI.SearchActionInModule(const APath: string; AModule: TDataModule): Boolean; var i: Integer; begin Result:= False; for i:= 0 to AModule.ComponentCount - 1 do if AModule.Components[i] is TSpiderAction then if LowerCase(TSpiderAction(AModule.Components[i]).Path) = APath then begin TSpiderAction(AModule.Components[i]).DoRequest(Request, Response); Result:= True; Break; end; end; constructor TSpiderCGI.Create(TheOwner: TComponent); begin inherited Create(TheOwner); fRequest:= TCGIRequest.Create; fResponse:= TSpiderResponse.Create; fPath:= '/'; fEnabled:= True; end; destructor TSpiderCGI.Destroy; var i: Integer; begin fRequest.Free; fResponse.Free; for i:= 0 to High(fPathList) do fPathList[i].Free; SetLength(fPathList, 0); inherited Destroy; end; end.
unit DescriptionsQuery; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, DescriptionsInterface, RecordCheck, DSWrap, BaseEventsQuery; type TDescrW = class(TDSWrap) private FComponentName: TFieldWrap; FDescription: TFieldWrap; FIDComponentType: TFieldWrap; FIDProducer: TFieldWrap; FID: TFieldWrap; public constructor Create(AOwner: TComponent); override; property ComponentName: TFieldWrap read FComponentName; property Description: TFieldWrap read FDescription; property IDComponentType: TFieldWrap read FIDComponentType; property IDProducer: TFieldWrap read FIDProducer; property ID: TFieldWrap read FID; end; TQueryDescriptions = class(TQueryBaseEvents, IDescriptions) FDQueryID: TFDAutoIncField; FDQueryComponentName: TWideStringField; FDQueryDescription: TWideMemoField; FDQueryIDComponentType: TIntegerField; FDQueryIDProducer: TIntegerField; strict private function Check(const AComponentName, ADescription: String; AProducerID: Integer): TRecordCheck; stdcall; private FCheckClone: TFDMemTable; FFilterText: string; FShowDuplicate: Boolean; FW: TDescrW; procedure ApplyFilter(AShowDuplicate: Boolean; const AFilterText: string); function GetCheckClone: TFDMemTable; { Private declarations } protected function CreateDSWrap: TDSWrap; override; property CheckClone: TFDMemTable read GetCheckClone; public constructor Create(AOwner: TComponent); override; function TryApplyFilter(AShowDuplicate: Boolean; const AFilterText: string): Boolean; property FilterText: string read FFilterText; property ShowDuplicate: Boolean read FShowDuplicate; property W: TDescrW read FW; { Public declarations } end; implementation {$R *.dfm} uses RepositoryDataModule, NotifyEvents, StrHelper, ErrorType; constructor TQueryDescriptions.Create(AOwner: TComponent); begin inherited; FW := FDSWrap as TDescrW; AutoTransaction := False; end; procedure TQueryDescriptions.ApplyFilter(AShowDuplicate: Boolean; const AFilterText: string); var ASQL: String; begin // Получаем первоначальный запрос ASQL := SQL; // Если нужно показать дубликаты if AShowDuplicate then begin ASQL := ASQL.Replace('/* ShowDuplicate', '', [rfReplaceAll]); ASQL := ASQL.Replace('ShowDuplicate */', '', [rfReplaceAll]); end; // Если нужно показать отфильтровать по названию компонента if not AFilterText.IsEmpty then begin ASQL := ASQL.Replace('/* Filter', '', [rfReplaceAll]); ASQL := ASQL.Replace('Filter */', '', [rfReplaceAll]); end; FDQuery.Close; FDQuery.SQL.Text := ASQL; if not AFilterText.IsEmpty then begin SetParamType(W.ComponentName.FieldName, ptInput, ftWideString); SetParameters([W.ComponentName.FieldName], [AFilterText + '%']); end; FDQuery.Open; end; function TQueryDescriptions.Check(const AComponentName, ADescription: String; AProducerID: Integer): TRecordCheck; begin Result.ErrorType := etNone; // Ищем компонент if not CheckClone.LocateEx(W.ComponentName.FieldName, AComponentName, [lxoCaseInsensitive]) then Exit; // Сравниваем описания if W.Description.F.AsString = ADescription then begin Result.ErrorType := etError; Result.Description := 'Такое описание уже есть в справочнике'; end else begin Result.ErrorType := etWarring; Result.Description := 'Компонент с таким наименованием имеет другое описание в справочнике'; end; end; function TQueryDescriptions.CreateDSWrap: TDSWrap; begin Result := TDescrW.Create(FDQuery); end; function TQueryDescriptions.GetCheckClone: TFDMemTable; begin if FCheckClone = nil then FCheckClone := W.AddClone(''); Result := FCheckClone; end; function TQueryDescriptions.TryApplyFilter(AShowDuplicate: Boolean; const AFilterText: string): Boolean; begin Result := FDQuery.RecordCount > 0; if (AShowDuplicate = FShowDuplicate) and (AFilterText = FFilterText) then Exit; ApplyFilter(AShowDuplicate, AFilterText); Result := FDQuery.RecordCount > 0; if Result then begin FShowDuplicate := AShowDuplicate; FFilterText := AFilterText; end else // Возвращаем старые значения ApplyFilter(FShowDuplicate, FFilterText); end; constructor TDescrW.Create(AOwner: TComponent); begin inherited; FID := TFieldWrap.Create(Self, 'ID', '', True); FComponentName := TFieldWrap.Create(Self, 'ComponentName'); FDescription := TFieldWrap.Create(Self, 'Description'); FIDComponentType := TFieldWrap.Create(Self, 'IDComponentType'); FIDProducer := TFieldWrap.Create(Self, 'IDProducer'); end; end.
unit uUsuario; interface uses uPaiControle, uCidade, uAtributosCustomizados; type TUsuario = class(TControle) private FIdUsuario: Integer; FSenha: string; FEmail: string; FNome: string; FIdCidade: integer; FCidade: TCidade; function GetCidade: TCidade; public destructor Destroy; override; property IdUsuario: Integer read FIdUsuario write FIdUsuario; property Senha: string read FSenha write FSenha; property Email: string read FEmail write FEmail; property Nome: string read FNome write FNome; property IdCidade: integer read FIdCidade write FIdCidade; [TCampoTabelaExterna('NOME')] [TCampoTabelaExterna('IDESTADO')] property Cidade: TCidade read GetCidade; end; implementation uses SysUtils; { TUsuario } destructor TUsuario.Destroy; begin if FCidade <> nil then FreeAndNil(FCidade); inherited; end; function TUsuario.GetCidade: TCidade; begin if FCidade = nil then FCidade := TCidade.Create(FIdCidade) else FCidade.PesquisarPorCodigo(FCidade.IdCidade, FIdCidade); Result := FCidade; end; end.
{ Device driver for USBCAN devices. } module can_usbcan; define can_addlist_usbcan; define can_open_usbcan; %include 'can2.ins.pas'; %include 'usbcan.ins.pas'; type dev_p_t = ^dev_t; dev_t = record {private device data for this driver} uc: usbcan_t; {USBCAN library use state} end; procedure can_usbcan_send ( {driver routine to send CAN frame} in out cl: can_t; {CAN library use state} in out dev: dev_t; {private driver data} in frame: can_frame_t; {the CAN frame to send} out stat: sys_err_t); val_param; forward; function can_usbcan_recv ( {driver routine to get next CAN frame} in out cl: can_t; {CAN library use state} in out dev: dev_t; {private driver data} in tout: real; {max seconds to wait} out frame: can_frame_t; {returned CAN frame} out stat: sys_err_t) :boolean; {TRUE with frame, FALSE with timeout or error} val_param; forward; procedure can_usbcan_close ( {driver routine to close the device} in out cl: can_t; {CAN library use state} in out dev: dev_t; {private driver data} out stat: sys_err_t); val_param; forward; { ******************************************************************************** * * Subroutine CAN_ADDLIST_USBCAN (DEVS) * * Add all the devices connected to the system that are known to this driver to * the list DEVS. } procedure can_addlist_usbcan ( {add USBCAN devices to list} in out devs: can_devs_t); {list to add known devices to} val_param; var ddv: usbcan_devs_t; {list of devices known to this driver} dent_p: usbcan_dev_p_t; {pointer to current devices list entry} dev_p: can_dev_p_t; {pnt to contents of one returned list entry} begin usbcan_devs_get (util_top_mem_context, ddv); {get list of devices} dent_p := ddv.list_p; {init to first list entry} while dent_p <> nil do begin {scan the private devices list} can_devlist_add (devs, dev_p); {make new master list entry} string_copy (dent_p^.name, dev_p^.name); {set device name} string_copy (dent_p^.path, dev_p^.path); {set system device pathname} dent_p := dent_p^.next_p; {advance to next entry in local list} end; usbcan_devs_dealloc (ddv); {done with local devices list} end; { ******************************************************************************** * * Subroutine CAN_OPEN_USBCAN (CL, STAT) * * Open a device managed by this driver for the CAN library use state CL. } procedure can_open_usbcan ( {open USBCAN device} in out cl: can_t; {state for this use of the library} out stat: sys_err_t); {completion status} val_param; var dev_p: dev_p_t; {pointer to private device state} label abort; begin util_mem_grab ( {allocate private driver data for this device} sizeof(dev_p^), cl.mem_p^, true, dev_p); usbcan_init (dev_p^.uc); {init USBCAN library state} string_copy (cl.dev.name, dev_p^.uc.name); {set name of device to open} usbcan_open (dev_p^.uc, stat); {try to open the device} if sys_error(stat) then goto abort; { * The device was successfully opened. } string_copy (dev_p^.uc.name, cl.dev.name); {indicate name of device actually opened} cl.dat_p := dev_p; {save pointer to driver state} cl.send_p := univ_ptr(addr(can_usbcan_send)); {install pointer to driver routines} cl.recv_p := univ_ptr(addr(can_usbcan_recv)); cl.close_p := univ_ptr(addr(can_usbcan_close)); return; {device opened successfully} { * Unable to open the device. STAT is indicating the error. } abort: util_mem_ungrab (dev_p, cl.mem_p^); {deallocate the driver data} end; { ******************************************************************************** * * Subroutine CAN_USBCAN_SEND (CL, DEV, FRAME, STAT) * * Send the CAN frame in FRAME. CL is the CAN library use state and DEV is the * private driver state for this connection. } procedure can_usbcan_send ( {driver routine to send CAN frame} in out cl: can_t; {CAN library use state} in out dev: dev_t; {private driver data} in frame: can_frame_t; {the CAN frame to send} out stat: sys_err_t); val_param; begin usbcan_frame_send (dev.uc, frame, stat); {send the frame} end; { ******************************************************************************** * * Function CAN_USBCAN_RECV (CL, DEV, TOUT, FRAME, STAT) * * Get the next CAN frame into FRAME. CL is the CAN library use state and DEV * is the private driver state for this connection. TOUT is the maximum time * to wait in seconds for a CAN frame to be available. TOUT may have the * special value of SYS_TIMEOUT_NONE_K, which causes this routine to wait * indefinitely until a CAN frame is available. * * The function return value will be TRUE when returninig with a CAN frame, and * FALSE if returning because no frame was available or a hard error occurred. * STAT will be set to indicate the error in the latter case. STAT will always * indicate no error when the function returns TRUE. } function can_usbcan_recv ( {driver routine to get next CAN frame} in out cl: can_t; {CAN library use state} in out dev: dev_t; {private driver data} in tout: real; {max seconds to wait} out frame: can_frame_t; {returned CAN frame} out stat: sys_err_t) :boolean; {TRUE with frame, FALSE with timeout or error} val_param; begin can_usbcan_recv := usbcan_frame_recv (dev.uc, tout, frame, stat); end; { ******************************************************************************** * * Subroutine CAN_USBCAN_CLOSE (CL, DEV, STAT) * * Close the CAN library connection to the USBCAN device. CL is the CAN * library state. DEV is the private state for this use of this device. Any * dynamic memory subordinate to the CAN library memory context in CL will be * automatically deallocated by the CAN library after this routine returns. } procedure can_usbcan_close ( {driver routine to close the device} in out cl: can_t; {CAN library use state} in out dev: dev_t; {private driver data} out stat: sys_err_t); val_param; begin usbcan_close (dev.uc, stat); {close this use of the USBCAN library} end;
unit InternetHTTP; interface uses Windows; type TDownloadStatus = record SizeOfFile: LongWord; DownloadSpeed: single; ReceivedBytes: LongWord; RemainingTime: single; // Указатель на файл в памяти (если выбрана загрузка в память) FilePtr: pointer; // За 1 такт: CurrentReceivedBytes: LongWord; CurrentElapsedTime: single; end; procedure HTTPDownload(URL, Destination: string; SaveInMemory: boolean; MainHandle: Cardinal; Msg: LongWord); { Загружает файл по ссылке в URL в локальный каталог в Destination. Выполняется в отдельном потоке, передаёт информацию о загрузке в структуру TDownloadStatus. Параметры: URL - адрес файла в сети Destination - Путь к файлу, в который надо сохранить данные SaveInMemory - если TRUE, то загрузка производится в оперативную память, Destination не используется MainHandle - хэндл, которому будут посылаться сообщения о статусе загрузки Msg - номер, под которым хэндлу будут посылаться сообщения TDownloadStatus: SizeOfFile - размер загружаемого файла DownloadSpeed - скорость загрузки ReceivedBytes - загружено байт RemainingTime - осталось времени до окончания загрузки FilePointer - указатель на начало памяти, куда загружен файл (опционально) После каждой загруженного пакета данных процедура посылает сообщение с номером Msg хэндлу в MainHandle, в wParam содержится указатель на структуру TDownloadThread. По окончании загрузки хэндлу посылается сообщение с номером, указанным в Msg, в котором в wParam = $FFFF } function HTTPGet(ScriptAddress: string): string; { Выполняет GET-запрос к скрипту в ScriptAddress. Ответ возвращает в строке. } function HTTPPost(ScriptAddress: string; Data: pointer; Size: LongWord): string; procedure AddPOSTField(var Data: pointer; var Size: LongWord; Param, Value: string); procedure AddPOSTFile(var Data: pointer; var Size: LongWord; Param, Value, FilePath, ContentType: string); { HTTPPost выполняет POST-запрос к скрипту, указанному в ScriptAddress. Data - указатель на область памяти с параметрами запроса. Size - размер этой области памяти. Ответ возвращает в строке. AddPOSTField - добавляет поле запроса: Data - переменная, в которую будет записан указатель на область памяти с параметрами. Size - переменная, в которую будет записан размер передаваемых данных !!!ВНИМАНИЕ!!! Перед добавлением параметров сделать Size = 0. Param - название поля. Value - значение поля. AddPOSTFile - добавляет в запрос файл: То же самое, что и в AddPOSTField FilePath - путь к файлу. ContentType - тип файла: например, 'image/png' ПРИМЕР: var Size: LongWord; Data: pointer; Response: string; begin Size := 0; // Делать ОБЯЗАТЕЛЬНО! // Добавляем данные для запроса AddPOSTField(Data, Size, 'user', 'Stepashka'); AddPOSTField(Data, Size, 'password', '12345'); AddPOSTFile(Data, Size, 'file', 'NewImage', 'C:\Photo-Stepashka.png', 'image/png'); // Отправляем запрос: Response := HTTPPost('http://site.ru/folder/script.php', Data, Size); // Выводим ответ от запроса: MessageBoxA(0, PAnsiChar(Response), 'Ответ от запроса', MB_ICONASTERISK); end; } procedure CreatePath(EndDir: string); { Создаёт иерархию каталогов до конечного каталога включительно. Допускаются разделители: "\" и "/" } function ExtractFileDir(Path: string): string; { Извлекает путь к файлу. Допускаются разделители: "\" и "/" } function ExtractFileName(Path: string): string; { Извлекает имя файла. Допускаются разделители: "\" и "/" } function ExtractHost(Path: string): string; { Извлекает имя хоста из сетевого адреса. http://site.ru/folder/script.php --> site.ru } function ExtractObject(Path: string): string; { Извлекает имя объекта из сетевого адреса: http://site.ru/folder/script.php --> folder/script.php } implementation //HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH // Windows.pas //HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH type PLPSTR = ^PAnsiChar; POverlapped = ^TOverlapped; _OVERLAPPED = record Internal: LongWord; InternalHigh: LongWord; Offset: LongWord; OffsetHigh: LongWord; hEvent: THandle; end; TOverlapped = _OVERLAPPED; PSecurityAttributes = ^TSecurityAttributes; _SECURITY_ATTRIBUTES = record nLength: LongWord; lpSecurityDescriptor: Pointer; bInheritHandle: LongBool; end; TSecurityAttributes = _SECURITY_ATTRIBUTES; const advapi32 = 'advapi32.dll'; kernel32 = 'kernel32.dll'; user32 = 'user32.dll'; GENERIC_READ = LongWord($80000000); GENERIC_WRITE = $40000000; CREATE_ALWAYS = 2; FILE_ATTRIBUTE_NORMAL = $00000080; MB_ICONERROR = $00000010; OPEN_EXISTING = 3; function CreateDirectory(lpPathName: PChar; lpSecurityAttributes: PSecurityAttributes): LongBool; stdcall; external kernel32 name 'CreateDirectoryA'; function CreateFile(lpFileName: PChar; dwDesiredAccess, dwShareMode: LongWord; lpSecurityAttributes: PSecurityAttributes; dwCreationDisposition, dwFlagsAndAttributes: LongWord; hTemplateFile: THandle): THandle; stdcall; external kernel32 name 'CreateFileA'; function QueryPerformanceFrequency(var lpFrequency: Int64): LongBool; stdcall; external kernel32 name 'QueryPerformanceFrequency'; function QueryPerformanceCounter(var lpPerformanceCount: Int64): LongBool; stdcall; external kernel32 name 'QueryPerformanceCounter'; function MessageBoxA(Handle: THandle; lpText, lpCaption: PAnsiChar; uType: LongWord): Integer; stdcall; external user32 name 'MessageBoxA'; function SendMessage(Handle: THandle; Msg: LongWord; wParam: LongInt; lParam: LongInt): LongInt; stdcall; external user32 name 'SendMessageA'; function PostMessage(Handle: THandle; Msg: LongWord; wParam: LongInt; lParam: LongInt): LongInt; stdcall; external user32 name 'PostMessageA'; function CloseHandle(hObject: THandle): LongBool; stdcall; external kernel32 name 'CloseHandle'; procedure Sleep(dwMilliseconds: LongWord); stdcall; external kernel32 name 'Sleep'; function WriteFile(hFile: THandle; const Buffer; nNumberOfBytesToWrite: LongWord; var lpNumberOfBytesWritten: LongWord; lpOverlapped: POverlapped): LongBool; stdcall; external kernel32 name 'WriteFile'; function ReadFile(hFile: THandle; var Buffer; nNumberOfBytesToRead: LongWord; var lpNumberOfBytesRead: LongWord; lpOverlapped: POverlapped): LongBool; stdcall; external kernel32 name 'ReadFile'; function GetFileSize(hFile: THandle; lpFileSizeHigh: Pointer): LongWord; stdcall; external kernel32 name 'GetFileSize'; //HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH // WinInet.pas //HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH type hInternet = pointer; INTERNET_PORT = Word; const HTTP_QUERY_CONTENT_LENGTH: LongWord = 5; HTTP_QUERY_FLAG_NUMBER: LongWord = $20000000; WinInetDLL = 'wininet.dll'; function InternetOpen(lpszAgent: PChar; dwAccessType: LongWord; lpszProxy, lpszProxyBypass: PChar; dwFlags: LongWord): HINTERNET; stdcall; external WinInetDLL name 'InternetOpenA'; function InternetOpenUrl(hInet: HINTERNET; lpszUrl: PChar; lpszHeaders: PChar; dwHeadersLength: LongWord; dwFlags: LongWord; dwContext: LongWord): HINTERNET; stdcall; external WinInetDLL name 'InternetOpenUrlA'; function InternetReadFile(hFile: HINTERNET; lpBuffer: Pointer; dwNumberOfBytesToRead: LongWord; var lpdwNumberOfBytesRead: LongWord): LongBool; stdcall; external WinInetDLL name 'InternetReadFile'; function InternetConnect(hInet: HINTERNET; lpszServerName: PChar; nServerPort: INTERNET_PORT; lpszUsername: PChar; lpszPassword: PChar; dwService: LongWord; dwFlags: LongWord; dwContext: LongWord): HINTERNET; stdcall; external WinInetDLL name 'InternetConnectA'; function HttpOpenRequest(hConnect: HINTERNET; lpszVerb: PChar; lpszObjectName: PChar; lpszVersion: PChar; lpszReferrer: PChar; lplpszAcceptTypes: PLPSTR; dwFlags: LongWord; dwContext: LongWord): HINTERNET; stdcall; external WinInetDLL name 'HttpOpenRequestA'; function InternetCloseHandle(hInet: HINTERNET): LongBool; stdcall; external WinInetDLL name 'InternetCloseHandle'; function HttpSendRequest(hRequest: HINTERNET; lpszHeaders: PChar; dwHeadersLength: LongWord; lpOptional: Pointer; dwOptionalLength: LongWord): LongBool; stdcall; external WinInetDLL name 'HttpSendRequestA'; function HttpQueryInfo(hRequest: HINTERNET; dwInfoLevel: LongWord; lpvBuffer: Pointer; var lpdwBufferLength: LongWord; var lpdwReserved: LongWord): LongBool; stdcall; external WinInetDLL name 'HttpQueryInfoA'; //HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH const AgentName: PAnsiChar = 'Launcher'; lpPOST: PAnsiChar = 'POST'; lpGET: PAnsiChar = 'GET'; HTTPVer: PAnsiChar = 'HTTP/1.1'; Boundary: string = 'ThisIsUniqueBoundary4POSTRequest'; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Процедуры работы с файловой системой и адресами: // Допускаются разделители "\" и "/" // Создаёт иерархию папок до конечной указанной папки включительно: procedure CreatePath(EndDir: string); var I: LongWord; PathLen: LongWord; TempPath: string; begin PathLen := Length(EndDir); if (EndDir[PathLen] = '\') or (EndDir[PathLen] = '/') then Dec(PathLen); TempPath := Copy(EndDir, 0, 3); for I := 4 to PathLen do begin if (EndDir[I] = '\') or (EndDir[I] = '/') then CreateDirectory(PAnsiChar(TempPath), nil); TempPath := TempPath + EndDir[I]; end; CreateDirectory(PAnsiChar(TempPath), nil); end; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Получает каталог, в котором лежит файл: function ExtractFileDir(Path: string): string; var I: LongWord; PathLen: LongWord; begin PathLen := Length(Path); I := PathLen; while (I <> 0) and (Path[I] <> '\') and (Path[I] <> '/') do Dec(I); Result := Copy(Path, 0, I); end; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Получает имя файла: function ExtractFileName(Path: string): string; var I: LongWord; PathLen: LongWord; begin PathLen := Length(Path); I := PathLen; while (Path[I] <> '\') and (Path[I] <> '/') and (I <> 0) do Dec(I); Result := Copy(Path, I + 1, PathLen - I); end; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Извлекает имя хоста: // http://site.ru/folder/script.php --> site.ru function ExtractHost(Path: string): string; var I: LongWord; PathLen: LongWord; begin PathLen := Length(Path); I := 8; // Длина "http://" while (I <= PathLen) and (Path[I] <> '\') and (Path[I] <> '/') do Inc(I); Result := Copy(Path, 8, I - 8); end; //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Извлекает имя объекта: // http://site.ru/folder/script.php --> folder/script.php function ExtractObject(Path: string): string; var I: LongWord; PathLen: LongWord; begin PathLen := Length(Path); I := 8; while (I <= PathLen) and (Path[I] <> '\') and (Path[I] <> '/') do Inc(I); Result := Copy(Path, I + 1, PathLen - I); end; //HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH // HTTP-Download //HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH type THTTPDownloadParams = record URL: string; Destination: string; SaveInMemory: boolean; MainHandle: THandle; Msg: LongWord; end; procedure HTTPDownload(URL, Destination: string; SaveInMemory: boolean; MainHandle: Cardinal; Msg: LongWord); procedure Download(Parameter: pointer); var hInet, hURL: hInternet; hFile: THandle; rSize: LongWord; rIndex: LongWord; Receiver: pointer; ReceivedBytes: LongWord; WriteBytes: LongWord; HTTPDownloadParams: THTTPDownloadParams; DownloadStatus: TDownloadStatus; iCounterPerSec: Int64; T1, T2: Int64; ElapsedTime: single; FilePtr: pointer; const Header: PAnsiChar = 'Content-Type: application/x-www-form-urlencoded'; ReceiverSize: LongWord = 131072; begin HTTPDownloadParams := THTTPDownloadParams(Parameter^); // Устанавливаем соединение: hInet := InternetOpen(@AgentName[1], 0, nil, nil, 0); hURL := InternetOpenURL(hInet, PAnsiChar(HTTPDownloadParams.URL), nil, 0, $4000000 + $100 + $80000000 + $800, 0); // Получаем размер файла: rSize := 4; rIndex := 0; HTTPQueryInfo( hURL, HTTP_QUERY_CONTENT_LENGTH or HTTP_QUERY_FLAG_NUMBER, @DownloadStatus.SizeOfFile, rSize, rIndex ); asm xor eax, eax mov FilePtr, eax mov DownloadStatus.FilePtr, eax mov hFile, eax end; if HTTPDownloadParams.SaveInMemory then begin // Выделяем память для файла: GetMem(FilePtr, DownloadStatus.SizeOfFile); DownloadStatus.FilePtr := FilePtr; end else begin // Создаём файл: CreatePath(ExtractFileDir(HTTPDownloadParams.Destination)); hFile := CreateFile( PAnsiChar(HTTPDownloadParams.Destination), GENERIC_READ + GENERIC_WRITE, 0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0 ); end; DownloadStatus.ReceivedBytes := 0; GetMem(Receiver, ReceiverSize); repeat QueryPerformanceFrequency(iCounterPerSec); QueryPerformanceCounter(T1); InternetReadFile(hURL, Receiver, ReceiverSize, ReceivedBytes); QueryPerformanceCounter(T2); ElapsedTime := (T2 - T1) / iCounterPerSec; if ReceivedBytes <> 0 then begin if HTTPDownloadParams.SaveInMemory = false then try WriteFile(hFile, Receiver^, ReceivedBytes, WriteBytes, nil); except MessageBoxA(HTTPDownloadParams.MainHandle, 'Не удалось записать данные в файл!'+#13+'Возможно, файл защищён от записи!', 'Ошибка!', MB_ICONERROR); Break; end else begin if FilePtr = nil then begin MessageBoxA(HTTPDownloadParams.MainHandle, 'Не удалось записать данные в память!'+#13+'Возможно, не хватает памяти!', 'Ошибка!', MB_ICONERROR); Break; end; Move(Receiver^, FilePtr^, ReceivedBytes); FilePtr := Pointer(LongWord(FilePtr) + ReceivedBytes); end; DownloadStatus.CurrentReceivedBytes := ReceivedBytes; DownloadStatus.CurrentElapsedTime := ElapsedTime; DownloadStatus.DownloadSpeed := ReceivedBytes / ElapsedTime; DownloadStatus.ReceivedBytes := DownloadStatus.ReceivedBytes + ReceivedBytes; DownloadStatus.RemainingTime := (DownloadStatus.SizeOfFile - DownloadStatus.ReceivedBytes) / DownloadStatus.DownloadSpeed; SendMessage(HTTPDownloadParams.MainHandle, HTTPDownloadParams.Msg, 0, LongWord(@DownloadStatus)); end; until ReceivedBytes = 0; FreeMem(Receiver); CloseHandle(hFile); InternetCloseHandle(hURL); InternetCloseHandle(hInet); SendMessage(HTTPDownloadParams.MainHandle, HTTPDownloadParams.Msg, $FFFF, LongWord(@DownloadStatus)); EndThread(0); end; var ThreadID: Cardinal; Params: THTTPDownloadParams; begin Params.URL := URL; Params.Destination := Destination; Params.MainHandle := MainHandle; Params.Msg := Msg; Params.SaveInMemory := SaveInMemory; CloseHandle(BeginThread(nil, 0, @Download, @Params, 0, ThreadID)); Sleep(50); // Гарантируем, что данные успешно запишутся в поток end; //HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH // POST-Request //HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH // Добавляет в запрос текстовое поле: procedure AddPOSTField(var Data: pointer; var Size: LongWord; Param, Value: string); var NewMemSize: LongWord; NewPtr: pointer; StrData: string; DataLen: LongWord; begin StrData := ''; if Size <> 0 then StrData := StrData + #13#10; StrData := StrData + '--' + Boundary + #13#10; StrData := StrData + 'Content-Disposition: form-data; name="' + Param + '"' + #13#10; StrData := StrData + #13#10; StrData := StrData + Value; DataLen := Length(StrData); NewMemSize := Size + DataLen; if Size = 0 then GetMem(Data, NewMemSize) else ReallocMem(Data, NewMemSize); // Установили указатель на конец старого блока и записали данные: NewPtr := Pointer(LongWord(Data) + Size); Move((@StrData[1])^, NewPtr^, DataLen); Size := NewMemSize; end; // Добавляет в запрос файл: procedure AddPOSTFile(var Data: pointer; var Size: LongWord; Param, Value, FilePath, ContentType: string); var hFile: THandle; FileSize, ReadBytes: LongWord; Buffer: pointer; NewMemSize: LongWord; NewPtr: pointer; StrData: string; DataLen: LongWord; begin hFile := CreateFile(PAnsiChar(FilePath), GENERIC_READ, 0, nil, OPEN_EXISTING, 128, 0); FileSize := GetFileSize(hFile, nil); GetMem(Buffer, FileSize); ReadFile(hFile, Buffer^, FileSize, ReadBytes, nil); CloseHandle(hFile); StrData := ''; if Size <> 0 then StrData := StrData + #13#10; StrData := StrData + '--' + Boundary + #13#10; StrData := StrData + 'Content-Disposition: form-data; name="' + Param + '"; filename="' + Value + '"' + #13#10; StrData := StrData + 'Content-Type: ' + ContentType + #13#10; StrData := StrData + #13#10; DataLen := Length(StrData); NewMemSize := Size + DataLen + ReadBytes; if Size = 0 then GetMem(Data, NewMemSize) else ReallocMem(Data, NewMemSize); // Установили указатель на конец старого блока и записали данные: NewPtr := Pointer(LongWord(Data) + Size); Move((@StrData[1])^, NewPtr^, DataLen); NewPtr := Pointer(LongWord(NewPtr) + DataLen); Move(Buffer^, NewPtr^, ReadBytes); FreeMem(Buffer); Size := NewMemSize; end; // Выполнение запроса: function HTTPPost(ScriptAddress: string; Data: pointer; Size: LongWord): string; var hInet, hConnect, hRequest: hInternet; ReceivedBytes: LongWord; Buffer: pointer; Response: string; Host: PAnsiChar; ScriptName: PAnsiChar; StrData: string; NewPtr: pointer; NewMemSize: LongWord; DataLen: LongWord; const Header: string = 'Content-Type: multipart/form-data; boundary='; ReceiverSize: LongWord = 512; begin Host := PAnsiChar(ExtractHost(ScriptAddress)); ScriptName := PAnsiChar(ExtractObject(ScriptAddress)); // Устанавливаем соединение: hInet := InternetOpen(@AgentName[1], 0, nil, nil, 0); hConnect := InternetConnect(hInet, Host, 80, nil, nil, 3, 0, 0); hRequest := HTTPOpenRequest(hConnect, lpPOST, ScriptName, HTTPVer, nil, nil, $4000000 + $100 + $80000000 + $800, 0); // Посылаем запрос: if Size = 0 then begin Result := 'Error at sending request: send data not present!'; Exit; end; StrData := #13#10 + '--' + Boundary + '--'; // Завершаем Boundary до вида "--boundary--" DataLen := LongWord(Length(StrData)); NewMemSize := DataLen + Size; ReallocMem(Data, NewMemSize); NewPtr := Pointer(LongWord(Data) + Size); Move((@StrData[1])^, NewPtr^, DataLen); HTTPSendRequest(hRequest, PAnsiChar(Header + Boundary), Length(Header + Boundary), Data, NewMemSize); FreeMem(Data); // Получаем ответ: GetMem(Buffer, ReceiverSize); Response := ''; repeat InternetReadFile(hRequest, Buffer, ReceiverSize, ReceivedBytes); if ReceivedBytes <> 0 then Response := Response + Copy(PAnsiChar(Buffer), 0, ReceivedBytes); until ReceivedBytes = 0; FreeMem(Buffer); InternetCloseHandle(hRequest); InternetCloseHandle(hConnect); InternetCloseHandle(hInet); Result := Response; end; //HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH // GET-Request //HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH function HTTPGet(ScriptAddress: string): string; var hInet, hConnect, hRequest: hInternet; ReceivedBytes: LongWord; Response: string; Host: PAnsiChar; ScriptName: PAnsiChar; Buffer: pointer; const ReceiverSize: LongWord = 512; begin Host := PAnsiChar(ExtractHost(ScriptAddress)); ScriptName := PAnsiChar(ExtractObject(ScriptAddress)); // Устанавливаем соединение: hInet := InternetOpen(@AgentName[1], 0, nil, nil, 0); hConnect := InternetConnect(hInet, Host, 80, nil, nil, 3, 0, 0); hRequest := HTTPOpenRequest(hConnect, lpGET, ScriptName, HTTPVer, nil, nil, $4000000 + $100 + $80000000 + $800, 0); // Посылаем запрос: HTTPSendRequest(hRequest, nil, 0, nil, 0); // Получаем ответ: GetMem(Buffer, ReceiverSize); Response := ''; repeat InternetReadFile(hRequest, Buffer, ReceiverSize, ReceivedBytes); Response := Response + Copy(PAnsiChar(Buffer), 0, ReceivedBytes); until ReceivedBytes = 0; FreeMem(Buffer); InternetCloseHandle(hRequest); InternetCloseHandle(hConnect); InternetCloseHandle(hInet); Result := Response; end; end.
uses GRAPH, CRT, { KeyPressed } KeyCodes, MathLib0; {max, min} { ---------------------------------------------------------------} PROCEDURE OpenGraph; VAR ErrorCode, GraphDriver, GraphMode : INTEGER; Begin GraphDriver := VGA { ATT400 }; GraphMode := VGAHi { ATT400HI }; InitGraph(GraphDriver,GraphMode,''); ErrorCode := GraphResult; { preserve error return } if ErrorCode <> grOK then { error? } Writeln('Graphics error: ', GraphErrorMsg(ErrorCode)); SetColor(Blue); end; { ---------------------------------------------------------------} PROCEDURE BoundRegion( VAR x1 : INTEGER; VAR y1 : INTEGER; VAR Side : INTEGER; color : INTEGER); CONST YSide = 10; Incr = 5; VAR X2, Y2, OrigColor, Key, RegionSize : WORD; Aspect : REAL; Img : POINTER; { returns location of crosshair when enter is pressed } BEGIN OrigColor := GetColor; SetColor(color); Aspect := GetMaxX / GetMaxY; X1 := GetMaxX div 2; Y1 := GetMaxY div 2; X2 := X1 + trunc(YSide * Aspect); Y2 := Y1 + YSide; RegionSize := ImageSize( X1,Y1, X2 , Y2); { locate the upper left corner } GetMem(Img,RegionSize); REPEAT GetImage(X1, Y1, X2, Y2, Img^); Rectangle(X1, Y1, X2, Y2); REPEAT UNTIL KeyPressed; { busy wait } Key := GetKey; PutImage(X1,Y1,Img^,CopyPut); CASE Key OF UpArrow : Y1 := min( 0, Y1 - 1); LeftArrow : X1 := min( 0, X1 - 1); RightArrow : Y1 := max( Y1+1, GetMaxY ); DownArrow : X1 := max( X1+1, GetMaxX ); END; { else do nothing } UNTIL Key = Enter; FreeMem(Img, RegionSize); SetWriteMode(XORPut); REPEAT REPEAT UNTIL KeyPressed; { busy wait } { erase old image via XOR } Rectangle(X1,Y1,X2,Y2); Key := GetKey; CASE Key OF UpArrow : Y2 := max( Y1+Yside, Y2 - Incr); LeftArrow : X2 := max( X1+trunc(Yside*Aspect), X2 - Incr); RightArrow : Y2 := min( Y2+Incr, GetMaxY ); DownArrow : X2 := min( X2+Incr, GetMaxX ); END; { else do nothing } { ensure marked area equals screen aspect ratio } X2 := min(X2,trunc((Y2-Y1) * Aspect)); Y2 := min(Y2,trunc((X2-X1) / Aspect)); { redraw } Rectangle(X1,Y1,X2,Y2); UNTIL Key = Enter; {routine is done so erase via XOR } Rectangle(X1,Y1,X2,Y2); { restore draw mode } SetWriteMode(XORPut); { restore color } SetColor(OrigColor); {restore original color} { return SIDE value } Side := Y1 - Y2; END; { BoundRegion } {----------------------------------------------} VAR X1,Y1, Side : INTEGER; BEGIN OpenGraph; BoundRegion(X1,Y1,Side, White); Writeln(X1:4,Y1:4,Side:4); END.
unit adot.Collections.VectorsNew; interface uses adot.Collections, adot.Collections.Types, adot.Types, adot.Collections.Slices, adot.Collections.Sets, adot.Tools, adot.Tools.Rtti, System.Generics.Collections, System.Generics.Defaults, System.SysUtils, System.RTLConsts; type TVectorDataStorage<T> = class(TList<T>) private { TList hides FComparer in private section, we have to keep the copy } FDataComparer: IComparer<T>; FDefaultComparer: boolean; FOwnsValues: boolean; FLockNotify: integer; constructor Create(ACapacity: Integer; const AComparer: IComparer<T>); reintroduce; procedure SetOwnsValues(const Value: boolean); property OwnsValues: boolean read FOwnsValues write SetOwnsValues; protected procedure Notify(const Item: T; Action: TCollectionNotification); override; end; TVector<T> = record private FData: TVectorDataStorage<T>; { valid as long as FDataIntf is alive } FDataIntf: IInterfacedObject<TObject>; { maintains lifecycle } procedure SetCount(ACount: NativeInt); procedure SetCapacity(ACapacity: integer); function GetCapacity: integer; function GetItem(ItemIndex: integer): T; procedure SetItem(ItemIndex: integer; const Value: T); function GetFirst: T; function GetLast: T; procedure SetFirst(const Value: T); procedure SetLast(const Value: T); function GetEmpty: Boolean; function GetTotalSizeBytes: int64; function VectorContains(const AValues: TArray<T>; AComparer: IComparer<T>): boolean; overload; function VectorContains(const AValues: TEnumerable<T>; AComparer: IComparer<T>): boolean; overload; function GetCount: NativeInt; function GetOwnsValues: boolean; procedure SetOwnsValues(const Value: boolean); function GetOnNotify: TCollectionNotifyEvent<T>; procedure SetOnNotify(const Value: TCollectionNotifyEvent<T>); public type TEnumerator = TVectorDataStorage<T>.TEnumerator; { Init is preferred over Create, it is obviously distinguished from classes. Class-like Create can be useful when new instance is param of some routine } procedure Init; overload; procedure Init(AComparer: IComparer<T>); overload; procedure Init(ACapacity: integer; AComparer: IComparer<T> = nil); overload; procedure Init(AValues: TEnumerable<T>; AComparer: IComparer<T> = nil); overload; procedure Init(AValues: TArray<T>; AComparer: IComparer<T> = nil); overload; procedure Init(AValues: TVector<T>; AComparer: IComparer<T> = nil); overload; class function Create: TVector<T>; overload; static; class function Create(AComparer: IComparer<T>): TVector<T>; overload; static; class function Create(ACapacity: integer; AComparer: IComparer<T> = nil): TVector<T>; overload; static; class function Create(AValues: TEnumerable<T>; AComparer: IComparer<T> = nil): TVector<T>; overload; static; class function Create(AValues: TArray<T>; AComparer: IComparer<T> = nil): TVector<T>; overload; static; class function Create(AValues: TVector<T>; AComparer: IComparer<T> = nil): TVector<T>; overload; static; { Slices are created on underlying array: - the slice is as efficient as possible (no data copying etc) - the slice is valid as long as TVector doesn't change the size } { Creates empty slice on underlying array } function GetSlice: TSlice<T>; overload; { Creates slice from range of underlying array } function GetSlice(AStartSliceIndexIncl,AEndSliceIndexExcl: integer): TSlice<T>; overload; { Creates slice on the array for items accepted by filter } function GetSlice(AItemsToSlice: TFuncFilterValueIndex<T>): TSlice<T>; overload; procedure Clear; { Unlike Init it does not initialize the structure, it only removes data, all props remain unchanged } procedure TrimExcess; function Add: integer; overload; function Add(const Value: T): integer; overload; procedure Add(const Values: TArray<T>); overload; procedure Add(const Values: TArray<T>; AStartIndex,ACount: integer); overload; procedure Add(const Values: TEnumerable<T>); overload; procedure Add(Values: TVector<T>); overload; function Copy: TVector<T>; procedure CopyFrom(Src: TVector<T>); function Insert(Index: integer; const Value: T): integer; procedure Delete(ItemIndex: integer); overload; procedure Delete(AStartIndex,ACount: integer); overload; procedure Delete(const AIndices: TArray<integer>); overload; procedure Delete(AIndices: TSet<integer>); overload; procedure DeleteLast; procedure Remove(const AValue: T; AComparer: IComparer<T> = nil); overload; procedure Remove(const AValues: TArray<T>; ASorted: boolean; AComparer: IComparer<T> = nil); overload; procedure Remove(AValues: TVector<T>; ASorted: boolean; AComparer: IComparer<T> = nil); overload; procedure Remove(const AValues: TEnumerable<T>; ASorted: boolean; AComparer: IComparer<T> = nil); overload; procedure Remove(AItemsToDelete: TFuncFilterValueIndex<T>); overload; function Extract(ItemIndex: integer): T; function ExtractAll: TArray<T>; function ExtractLast: T; procedure Move(SrcIndex, DstIndex: integer); procedure Exchange(Index1,Index2: integer); { Reverse( [1,2,3,4,5], 1, 3 ) = [1, 4,3,2, 5] } procedure Reverse; overload; procedure Reverse(AStartIndex,ACount: integer); overload; { RotateLeft( [1,2,3,4,5], 1, 3, 1 ) = [1, 3,4,2, 5] RotateLeft( [1,2,3,4,5], 1, 3,-1 ) = [1, 4,2,3, 5] } procedure RotateLeft(Index1,Index2,Shift: integer); { RotateRight( [1,2,3,4,5], 1, 3, 1 ) = [1, 4,2,3, 5] RotateRight( [1,2,3,4,5], 1, 3,-1 ) = [1, 3,4,2, 5] } procedure RotateRight(Index1,Index2,Shift: integer); { Shuffle items of the range in random order } procedure Shuffle; overload; procedure Shuffle(AStartIndex,ACount: integer); overload; { Generate all permutations. Permutations of [2,1,3]: [1,2,3] [1,3,2] [2,1,3] [2,3,1] [3,1,2] [3,2,1] } procedure FirstPermutation; function NextPermutation: boolean; function PrevPermutation: boolean; function Contains(const Value: T): boolean; overload; function Contains(const Value: T; Comparer: IComparer<T>): boolean; overload; function Contains(const Values: TArray<T>): boolean; overload; function Contains(const Values: TArray<T>; Comparer: IComparer<T>): boolean; overload; function Contains(const Values: TEnumerable<T>): boolean; overload; function Contains(const Values: TEnumerable<T>; Comparer: IComparer<T>): boolean; overload; function Sorted: boolean; overload; function Sorted(AStartIndex,ACount: integer; AComparer: IComparer<T>): boolean; overload; function Sorted(AStartIndex,ACount: integer; AComparison: TComparison<T>): boolean; overload; function IndexOf(const Value: T): integer; overload; function IndexOf(const Value: T; Comparer: IComparer<T>): integer; overload; function FindFirst(const Value: T; var Index: integer): boolean; overload; function FindFirst(const Value: T; var Index: integer; Comparer: IComparer<T>): boolean; overload; function FindNext(const Value: T; var Index: integer): boolean; overload; function FindNext(const Value: T; var Index: integer; Comparer: IComparer<T>): boolean; overload; procedure Sort; overload; procedure Sort(AIndex, ACount: Integer); overload; procedure Sort(AComparer: IComparer<T>); overload; procedure Sort(AComparer: IComparer<T>; AIndex, ACount: Integer); overload; procedure Sort(AComparison: TComparison<T>); overload; procedure Sort(AComparison: TComparison<T>; AIndex, ACount: Integer); overload; function BinarySearch(const Item: T; out FoundIndex: Integer): Boolean; overload; function BinarySearch(const Item: T; out FoundIndex: Integer; AComparer: IComparer<T>): Boolean; overload; function BinarySearch(const Item: T; out FoundIndex: Integer; AComparer: IComparer<T>; AIndex,ACount: Integer): Boolean; overload; function BinarySearch(const Item: T; out FoundIndex: Integer; AComparison: TComparison<T>): Boolean; overload; function BinarySearch(const Item: T; out FoundIndex: Integer; AComparison: TComparison<T>; AIndex,ACount: Integer): Boolean; overload; { TArray } function Compare(const B: TArray<T>; AComparer: IComparer<T> = nil): integer; overload; function Compare(const B: TArray<T>; AStartIndex,BStartIndex,ACount: integer; AComparer: IComparer<T> = nil): integer; overload; { TEnumerable } function Compare(B: TEnumerable<T>; AComparer: IComparer<T> = nil): integer; overload; function Compare(B: TEnumerable<T>; AStartIndex,BStartIndex,ACount: integer; AComparer: IComparer<T> = nil): integer; overload; { Trims and returns Items } function ToString: string; function ToText(const ValuesDelimiter: string = #13#10): string; function ToArray: TArray<T>; { for-in support } function GetEnumerator: TEnumerator<T>; class operator In(const a: T; b: TVector<T>) : Boolean; class operator In(a: TVector<T>; b: TVector<T>) : Boolean; class operator In(const a: TArray<T>; b: TVector<T>) : Boolean; class operator In(const a: TEnumerable<T>; b: TVector<T>) : Boolean; class operator Implicit(const a : T) : TVector<T>; class operator Implicit(const a : TArray<T>) : TVector<T>; class operator Implicit(const a : TEnumerable<T>) : TVector<T>; class operator Implicit(a : TVector<T>) : TArray<T>; class operator Explicit(const a : T) : TVector<T>; class operator Explicit(const a : TArray<T>) : TVector<T>; class operator Explicit(const a : TEnumerable<T>) : TVector<T>; class operator Explicit(a : TVector<T>) : TArray<T>; class operator Add(a: TVector<T>; const b: T): TVector<T>; class operator Add(a: TVector<T>; b: TVector<T>): TVector<T>; class operator Add(a: TVector<T>; const b: TArray<T>): TVector<T>; class operator Add(a: TVector<T>; const b: TEnumerable<T>): TVector<T>; class operator Add(const a: T; b: TVector<T>): TVector<T>; class operator Add(const a: TArray<T>; b: TVector<T>): TVector<T>; class operator Add(const a: TEnumerable<T>; b: TVector<T>): TVector<T>; class operator Subtract(a: TVector<T>; const b: T): TVector<T>; class operator Subtract(a: TVector<T>; b: TVector<T>): TVector<T>; class operator Subtract(a: TVector<T>; const b: TArray<T>): TVector<T>; class operator Subtract(a: TVector<T>; const b: TEnumerable<T>): TVector<T>; class operator Subtract(const a: T; b: TVector<T>): TVector<T>; class operator Subtract(const a: TArray<T>; b: TVector<T>): TVector<T>; class operator Subtract(const a: TEnumerable<T>; b: TVector<T>): TVector<T>; class operator Equal(a: TVector<T>; b: TVector<T>) : Boolean; class operator Equal(a: TVector<T>; const b: TArray<T>) : Boolean; class operator Equal(a: TVector<T>; const b: TEnumerable<T>) : Boolean; class operator Equal(const b: TArray<T>; a: TVector<T>): Boolean; class operator Equal(const b: TEnumerable<T>; a: TVector<T>): Boolean; class operator NotEqual(a: TVector<T>; b: TVector<T>): Boolean; class operator NotEqual(a: TVector<T>; const b: TArray<T>) : Boolean; class operator NotEqual(a: TVector<T>; const b: TEnumerable<T>) : Boolean; class operator NotEqual(const b: TArray<T>; a: TVector<T>): Boolean; class operator NotEqual(const b: TEnumerable<T>; a: TVector<T>): Boolean; class operator GreaterThanOrEqual(a: TVector<T>; b: TVector<T>): Boolean; class operator GreaterThanOrEqual(a: TVector<T>; const b: TArray<T>): Boolean; class operator GreaterThanOrEqual(a: TVector<T>; const b: TEnumerable<T>): Boolean; class operator GreaterThanOrEqual(const b: TArray<T>; a: TVector<T>): Boolean; class operator GreaterThanOrEqual(const b: TEnumerable<T>; a: TVector<T>): Boolean; class operator GreaterThan(a: TVector<T>; b: TVector<T>): Boolean; class operator GreaterThan(a: TVector<T>; const b: TArray<T>): Boolean; class operator GreaterThan(a: TVector<T>; const b: TEnumerable<T>): Boolean; class operator GreaterThan(const b: TArray<T>; a: TVector<T>): Boolean; class operator GreaterThan(const b: TEnumerable<T>; a: TVector<T>): Boolean; class operator LessThan(a: TVector<T>; b: TVector<T>): Boolean; class operator LessThan(a: TVector<T>; const b: TArray<T>): Boolean; class operator LessThan(a: TVector<T>; const b: TEnumerable<T>): Boolean; class operator LessThan(const b: TArray<T>; a: TVector<T>): Boolean; class operator LessThan(const b: TEnumerable<T>; a: TVector<T>): Boolean; class operator LessThanOrEqual(a: TVector<T>; b: TVector<T>): Boolean; class operator LessThanOrEqual(a: TVector<T>; const b: TArray<T>): Boolean; class operator LessThanOrEqual(a: TVector<T>; const b: TEnumerable<T>): Boolean; class operator LessThanOrEqual(const b: TArray<T>; a: TVector<T>): Boolean; class operator LessThanOrEqual(const b: TEnumerable<T>; a: TVector<T>): Boolean; property First: T read GetFirst write SetFirst; property Last: T read GetLast write SetLast; property Count: NativeInt read GetCount write SetCount; property Capacity: integer read GetCapacity write SetCapacity; property Elements[ItemIndex: integer]: T read GetItem write SetItem; default; property Empty: boolean read GetEmpty; property TotalSizeBytes: int64 read GetTotalSizeBytes; property OwnsValues: boolean read GetOwnsValues write SetOwnsValues; property OnNotify: TCollectionNotifyEvent<T> read GetOnNotify write SetOnNotify; end; implementation { TVectorDataStorage<T> } constructor TVectorDataStorage<T>.Create(ACapacity: Integer; const AComparer: IComparer<T>); begin FDefaultComparer := AComparer = nil; if FDefaultComparer then FDataComparer := TComparerUtils.DefaultComparer<T> else FDataComparer := AComparer; inherited Create(FDataComparer); end; procedure TVectorDataStorage<T>.Notify(const Item: T; Action: TCollectionNotification); begin if FLockNotify > 0 then Exit; inherited; if FOwnsValues and (Action = TCollectionNotification.cnRemoved) then PObject(@Item)^.DisposeOf; end; procedure TVectorDataStorage<T>.SetOwnsValues(const Value: boolean); begin if Value and not TRttiUtils.IsInstance<T> then raise Exception.Create('Generic type is not a class.'); FOwnsValues := Value; end; { TVector<T> } class function TVector<T>.Create: TVector<T>; begin result.Init; end; class function TVector<T>.Create(ACapacity: integer; AComparer: IComparer<T>): TVector<T>; begin result.Init(ACapacity, AComparer); end; class function TVector<T>.Create(AComparer: IComparer<T>): TVector<T>; begin result.Init(AComparer); end; class function TVector<T>.Create(AValues: TEnumerable<T>; AComparer: IComparer<T>): TVector<T>; begin result.Init(AValues, AComparer); end; class function TVector<T>.Create(AValues: TArray<T>; AComparer: IComparer<T>): TVector<T>; begin result.Init(AValues, AComparer); end; class function TVector<T>.Create(AValues: TVector<T>; AComparer: IComparer<T>): TVector<T>; begin result.Init(AValues, AComparer); end; procedure TVector<T>.Init; begin Init(0, nil); end; procedure TVector<T>.Init(AComparer: IComparer<T>); begin Init(0, AComparer); end; procedure TVector<T>.Init(ACapacity: integer; AComparer: IComparer<T>); begin Self := Default(TVector<T>); FData := TVectorDataStorage<T>.Create(ACapacity, AComparer); FDataIntf := TInterfacedObject<TObject>.Create(FData); end; procedure TVector<T>.Init(AValues: TEnumerable<T>; AComparer: IComparer<T>); begin Init(0, AComparer); Add(AValues); end; procedure TVector<T>.Init(AValues: TArray<T>; AComparer: IComparer<T>); begin Init(Length(AValues), AComparer); Add(AValues); end; procedure TVector<T>.Init(AValues: TVector<T>; AComparer: IComparer<T>); begin Init(AValues.Count, AComparer); Add(AValues); end; function TVector<T>.Add: integer; begin result := FData.Add(Default(T)); end; function TVector<T>.Add(const Value: T): integer; begin result := FData.Add(Value); end; procedure TVector<T>.Add(const Values: TArray<T>); var I: Integer; begin for I := Low(Values) to High(Values) do FData.Add(Values[I]); end; procedure TVector<T>.Add(const Values: TArray<T>; AStartIndex,ACount: integer); var I: Integer; begin if ACount <= 0 then Exit; I := FData.Count + ACount; if I > FData.Capacity then FData.Capacity := I; for I := AStartIndex to AStartIndex+ACount-1 do FData.Add(Values[I]); end; procedure TVector<T>.Add(const Values: TEnumerable<T>); var V: T; begin for V in Values do FData.Add(V); end; procedure TVector<T>.Clear; begin FData.Clear; end; procedure TVector<T>.TrimExcess; begin FData.TrimExcess; end; function TVector<T>.VectorContains(const AValues: TEnumerable<T>; AComparer: IComparer<T>): boolean; var DataSet: TDictionary<T, TEmptyRec>; EmptyRec: TEmptyRec; SortedData: TArray<T>; I: Integer; Value: T; begin { With default comparer we can use TDictionary as most efficient way } if FData.FDefaultComparer then begin DataSet := TDictionary<T, TEmptyRec>.Create(FData.Count*2); try for I := 0 to FData.Count-1 do DataSet.AddOrSetValue(FData[I], EmptyRec); for Value in AValues do if not DataSet.ContainsKey(Value) then Exit(False); Exit(True); finally Sys.FreeAndNil(DataSet); end; end; { We can't use TDictionary, because it needs IEqualityComparer.GetHash, IComparer can not be tranformed to IEqualityComparer } SortedData := FData.ToArray; TArray.Sort<T>(SortedData, AComparer); for Value in AValues do if not TArray.BinarySearch<T>(SortedData, Value, I, AComparer) then Exit(False); result := True; end; function TVector<T>.VectorContains(const AValues: TArray<T>; AComparer: IComparer<T>): boolean; var DataSet: TDictionary<T, TEmptyRec>; EmptyRec: TEmptyRec; SortedData: TArray<T>; I,J: Integer; begin { With default comparer we can use TDictionary as most efficient way } if FData.FDefaultComparer then begin DataSet := TDictionary<T, TEmptyRec>.Create(FData.Count*2); try for I := 0 to FData.Count-1 do DataSet.AddOrSetValue(FData[I], EmptyRec); for I := 0 to High(AValues) do if not DataSet.ContainsKey(AValues[I]) then Exit(False); Exit(True); finally Sys.FreeAndNil(DataSet); end; end; { We can't use TDictionary, because it needs IEqualityComparer.GetHash, IComparer can not be tranformed to IEqualityComparer } SortedData := FData.ToArray; TArray.Sort<T>(SortedData, AComparer); for I := 0 to High(AValues) do if not TArray.BinarySearch<T>(SortedData, AValues[I], J, AComparer) then Exit(False); result := True; end; function TVector<T>.Contains(const Value: T): boolean; begin result := FData.IndexOf(Value)>=0; end; function TVector<T>.Contains(const Value: T; Comparer: IComparer<T>): boolean; begin result := IndexOf(Value, Comparer)>=0; end; function TVector<T>.Contains(const Values: TArray<T>): boolean; begin result := VectorContains(Values, FData.FDataComparer); end; function TVector<T>.Contains(const Values: TArray<T>; Comparer: IComparer<T>): boolean; begin result := VectorContains(Values, Comparer); end; function TVector<T>.Compare(B: TEnumerable<T>; AComparer: IComparer<T>): integer; var Value: T; BItemsCount: integer; begin BItemsCount := 0; for Value in B do inc(BItemsCount); if FData.Count = BItemsCount then result := Compare(B,0,0,FData.Count, AComparer) else if FData.Count < BItemsCount then result := -1 else result := 1; end; function TVector<T>.Compare(const B: TArray<T>; AStartIndex, BStartIndex, ACount: integer; AComparer: IComparer<T>): integer; var I: Integer; begin if AComparer = nil then AComparer := FData.FDataComparer; Assert((ACount=0) or (ACount>0) and (AStartIndex>=0) and (AStartIndex+ACount-1<FData.Count)); Assert((ACount=0) or (ACount>0) and (BStartIndex>=0) and (BStartIndex+ACount-1<Length(B))); if ACount <= 0 then result := 0 else for I := 0 to ACount-1 do begin result := AComparer.Compare(FData[I+AStartIndex], B[I+BStartIndex]); if result <> 0 then Break; end; end; function TVector<T>.Compare(const B: TArray<T>; AComparer: IComparer<T>): integer; begin if Count = Length(B) then result := Compare(B,0,0,FData.Count, AComparer) else if FData.Count < Length(B) then result := -1 else result := 1; end; function TVector<T>.Compare(B: TEnumerable<T>; AStartIndex, BStartIndex, ACount: integer; AComparer: IComparer<T>): integer; var Value: T; BItemsCount: integer; begin if AComparer = nil then AComparer := FData.FDataComparer; BItemsCount := 0; for Value in B do inc(BItemsCount); Assert((ACount=0) or (ACount>0) and (AStartIndex>=0) and (AStartIndex+ACount-1<FData.Count)); Assert((ACount=0) or (ACount>0) and (BStartIndex>=0) and (BStartIndex+ACount-1<BItemsCount)); result := 0; for Value in B do if BStartIndex > 0 then dec(BStartIndex) else begin result := AComparer.Compare(FData[AStartIndex], Value); inc(AStartIndex); dec(ACount); if (result <> 0) or (ACount <= 0) then break; end; end; function TVector<T>.Contains(const Values: TEnumerable<T>): boolean; begin result := VectorContains(Values, FData.FDataComparer); end; function TVector<T>.Contains(const Values: TEnumerable<T>; Comparer: IComparer<T>): boolean; begin result := VectorContains(Values, Comparer); end; function TVector<T>.Copy: TVector<T>; begin result.CopyFrom(Self); end; procedure TVector<T>.CopyFrom(Src: TVector<T>); begin Init(Src.Count, Src.FData.FDataComparer); { Doesn't make sense to copy when OwnsValues=True (when item deleted in source, it became invalid) } assert(not Src.OwnsValues or Src.Empty); OwnsValues := Src.OwnsValues; OnNotify := Src.OnNotify; Add(Src); end; procedure TVector<T>.Delete(ItemIndex: integer); begin FData.Delete(ItemIndex); end; procedure TVector<T>.Delete(AStartIndex,ACount: integer); begin FData.DeleteRange(AStartIndex,ACount); end; procedure TVector<T>.Delete(const AIndices: TArray<integer>); begin Delete(TSet<integer>.Create(AIndices)); end; procedure TVector<T>.Delete(AIndices: TSet<integer>); begin Remove( function(const Value: T; Index:integer): Boolean begin result := Index in AIndices; end); end; procedure TVector<T>.DeleteLast; begin FData.Delete(FData.Count-1); end; class operator TVector<T>.Equal(a, b: TVector<T>): Boolean; begin result := A.Compare(B) = 0; end; class operator TVector<T>.Equal(a: TVector<T>; const b: TArray<T>): Boolean; begin result := A.Compare(B) = 0; end; class operator TVector<T>.Equal(a: TVector<T>; const b: TEnumerable<T>): Boolean; begin result := A.Compare(B) = 0; end; class operator TVector<T>.Equal(const b: TEnumerable<T>; a: TVector<T>): Boolean; begin result := A.Compare(B) = 0; end; class operator TVector<T>.Equal(const b: TArray<T>; a: TVector<T>): Boolean; begin result := A.Compare(B) = 0; end; procedure TVector<T>.Exchange(Index1, Index2: integer); begin FData.Exchange(Index1, Index2); end; class operator TVector<T>.Explicit(const a: T): TVector<T>; begin result.Init; result.Add(a); end; class operator TVector<T>.Explicit(const a: TArray<T>): TVector<T>; begin result.Init(a); end; class operator TVector<T>.Explicit(const a: TEnumerable<T>): TVector<T>; begin result.Init(a); end; class operator TVector<T>.Explicit(a: TVector<T>): TArray<T>; begin result := a.ToArray; end; function TVector<T>.ToString: string; begin result := ToText(' '); end; function TVector<T>.ToText(const ValuesDelimiter: string = #13#10): string; var S: TStringBuilder; I: Integer; begin S := TStringBuilder.Create; for I := 0 to FData.Count-1 do begin if S.Length > 0 then S.Append(ValuesDelimiter); S.Append(TRttiUtils.ValueAsString<T>(FData[I])); end; result := S.ToString; end; function TVector<T>.ToArray: TArray<T>; begin result := FData.ToArray; end; function TVector<T>.Extract(ItemIndex: integer): T; begin { TList<>.Extract doesn't support access by inde, only by value. That is strange for vector-like container, we have to workaround it... } if (ItemIndex < 0) or (ItemIndex >= FData.Count) then raise EArgumentOutOfRangeException.CreateRes(@SArgumentOutOfRange); System.Move(FData.List[ItemIndex], Result, SizeOf(T)); System.FillChar((@FData.List[ItemIndex])^, 0, SizeOf(T)); FData.Notify(Result, TCollectionNotification.cnExtracted); inc(FData.FLockNotify); { we already triggered cnExtracted, we don't need cnRemoved to be triggered } FData.Delete(ItemIndex); dec(FData.FLockNotify); end; function TVector<T>.ExtractAll: TArray<T>; var I: Integer; begin SetLength(result, FData.Count); if Length(Result) = 0 then Exit; System.Move(FData.List[0], Result[0], SizeOf(T)*Length(Result)); System.FillChar((@FData.List[0])^, 0, SizeOf(T)*FData.Count); for I := High(Result) downto 0 do FData.Notify(Result[I], TCollectionNotification.cnExtracted); inc(FData.FLockNotify); { we already triggered cnExtracted, we don't need cnRemoved to be triggered } FData.Clear; dec(FData.FLockNotify); end; function TVector<T>.ExtractLast: T; begin result := Extract(FData.Count-1); end; class operator TVector<T>.GreaterThanOrEqual(a, b: TVector<T>): Boolean; begin result := A.Compare(B) >= 0; end; class operator TVector<T>.GreaterThanOrEqual(a: TVector<T>; const b: TArray<T>): Boolean; begin result := A.Compare(B) >= 0; end; class operator TVector<T>.GreaterThanOrEqual(a: TVector<T>; const b: TEnumerable<T>): Boolean; begin result := A.Compare(B) >= 0; end; class operator TVector<T>.GreaterThanOrEqual(const b: TArray<T>; a: TVector<T>): Boolean; begin result := A.Compare(B) <= 0; end; class operator TVector<T>.GreaterThan(a, b: TVector<T>): Boolean; begin result := A.Compare(B) > 0; end; class operator TVector<T>.GreaterThan(a: TVector<T>; const b: TArray<T>): Boolean; begin result := A.Compare(B) > 0; end; class operator TVector<T>.GreaterThan(a: TVector<T>; const b: TEnumerable<T>): Boolean; begin result := A.Compare(B) > 0; end; class operator TVector<T>.GreaterThan(const b: TArray<T>; a: TVector<T>): Boolean; begin result := A.Compare(B) < 0; end; class operator TVector<T>.GreaterThan(const b: TEnumerable<T>; a: TVector<T>): Boolean; begin result := A.Compare(B) < 0; end; class operator TVector<T>.GreaterThanOrEqual(const b: TEnumerable<T>; a: TVector<T>): Boolean; begin result := A.Compare(B) <= 0; end; class operator TVector<T>.In(const a: T; b: TVector<T>): Boolean; begin result := B.Contains(A); end; class operator TVector<T>.In(a, b: TVector<T>): Boolean; begin result := B.Contains(A); end; class operator TVector<T>.In(const a: TArray<T>; b: TVector<T>): Boolean; begin result := B.Contains(A); end; class operator TVector<T>.Implicit(const a: T): TVector<T>; begin result.Init; result.Add(A); end; class operator TVector<T>.Implicit(const a: TArray<T>): TVector<T>; begin result.Init(a); end; class operator TVector<T>.Implicit(const a: TEnumerable<T>): TVector<T>; begin result.Init(a); end; class operator TVector<T>.Implicit(a: TVector<T>): TArray<T>; begin result := a.ToArray; end; class operator TVector<T>.In(const a: TEnumerable<T>; b: TVector<T>): Boolean; begin result := B.Contains(A); end; function TVector<T>.IndexOf(const Value: T; Comparer: IComparer<T>): integer; begin if not FindFirst(Value, Result, Comparer) then result := -1; end; function TVector<T>.IndexOf(const Value: T): integer; begin if not FindFirst(Value, Result, FData.FDataComparer) then result := -1; end; function TVector<T>.FindFirst(const Value: T; var Index: integer): boolean; begin Index := -1; result := FindNext(Value, Index, FData.FDataComparer); end; function TVector<T>.FindFirst(const Value: T; var Index: integer; Comparer: IComparer<T>): boolean; begin Index := -1; result := FindNext(Value, Index, Comparer); end; function TVector<T>.FindNext(const Value: T; var Index: integer): boolean; begin result := FindNext(Value, Index, FData.FDataComparer); end; function TVector<T>.FindNext(const Value: T; var Index: integer; Comparer: IComparer<T>): boolean; var I: Integer; L: TArray<T>; begin if Comparer = nil then Comparer := FData.FDataComparer; L := FData.List; for I := Index+1 to FData.Count-1 do if Comparer.Compare(L[I], Value)=0 then begin Index := I; Exit(True); end; result := False; end; procedure TVector<T>.FirstPermutation; begin Sort; end; function TVector<T>.Insert(Index: integer; const Value: T): integer; begin FData.Insert(Index, Value); end; class operator TVector<T>.LessThan(a, b: TVector<T>): Boolean; begin result := A.Compare(B) < 0; end; class operator TVector<T>.LessThan(a: TVector<T>; const b: TArray<T>): Boolean; begin result := A.Compare(B) < 0; end; class operator TVector<T>.LessThan(a: TVector<T>; const b: TEnumerable<T>): Boolean; begin result := A.Compare(B) < 0; end; class operator TVector<T>.LessThan(const b: TArray<T>; a: TVector<T>): Boolean; begin result := A.Compare(B) > 0; end; class operator TVector<T>.LessThan(const b: TEnumerable<T>; a: TVector<T>): Boolean; begin result := A.Compare(B) > 0; end; class operator TVector<T>.LessThanOrEqual(a, b: TVector<T>): Boolean; begin result := A.Compare(B) <= 0; end; class operator TVector<T>.LessThanOrEqual(a: TVector<T>; const b: TArray<T>): Boolean; begin result := A.Compare(B) <= 0; end; class operator TVector<T>.LessThanOrEqual(a: TVector<T>; const b: TEnumerable<T>): Boolean; begin result := A.Compare(B) <= 0; end; class operator TVector<T>.LessThanOrEqual(const b: TArray<T>; a: TVector<T>): Boolean; begin result := A.Compare(B) >= 0; end; class operator TVector<T>.LessThanOrEqual(const b: TEnumerable<T>; a: TVector<T>): Boolean; begin result := A.Compare(B) >= 0; end; procedure TVector<T>.Move(SrcIndex, DstIndex: integer); begin FData.Move(SrcIndex, DstIndex); end; function TVector<T>.NextPermutation: boolean; var i,x,n: integer; C: IComparer<T>; L: TArray<T>; begin C := FData.FDataComparer; { find max N where A[N] < A[N+1] } L := FData.List; n := -1; for i := FData.Count-2 downto 0 do if C.Compare(L[i], L[i+1]) < 0 then begin n := i; break; end; { if A[N] > A[N+1] for any N then there is no more permutations } result := n<>-1; if not result then exit; { let's order range [N+1; FCount-1] now it has reverse order so just call .reverse } Reverse(n+1,FData.Count-n-1); { find value next to A[N] in range [N+1; Count-1] such value exists because at least original A[N+1] > A[N] } x := -1; for i := N+1 to FData.Count-1 do if C.Compare(L[i], L[N]) > 0 then begin x := i; break; end; { swap A[N] and A[X] } FData.Exchange(n, x); { change position of A[X] to make range [N+1; FCoun-1] ordered again } i := x; while (i > n+1) and (C.Compare(L[i-1], L[x]) > 0) do dec(i); while (i < FData.Count-1) and (C.Compare(L[x], L[i+1]) > 0) do inc(i); if i<>x then FData.Move(x,i); end; class operator TVector<T>.NotEqual(a: TVector<T>; const b: TArray<T>): Boolean; begin result := A.Compare(B) <> 0; end; class operator TVector<T>.NotEqual(a, b: TVector<T>): Boolean; begin result := A.Compare(B) <> 0; end; class operator TVector<T>.NotEqual(a: TVector<T>; const b: TEnumerable<T>): Boolean; begin result := A.Compare(B) <> 0; end; class operator TVector<T>.NotEqual(const b: TArray<T>; a: TVector<T>): Boolean; begin result := A.Compare(B) <> 0; end; class operator TVector<T>.NotEqual(const b: TEnumerable<T>; a: TVector<T>): Boolean; begin result := A.Compare(B) <> 0; end; function TVector<T>.PrevPermutation: boolean; var i,x,n: integer; C: IComparer<T>; L: TArray<T>; begin C := FData.FDataComparer; { find max N where A[N] > A[N+1] } L := FData.List; n := -1; for i := FData.Count-2 downto 0 do if C.Compare(L[i], L[i+1]) > 0 then begin n := i; break; end; { if A[N] > A[N+1] for any N then there is no more permutations } result := n<>-1; if not result then exit; { let's order range [N+1; FCoun-1] now it has reverse order so just call .reverse } reverse(n+1,FData.Count-n-1); { find value previous to A[N] in range [N+1; FCount-1] such value exists because at least original A[N+1] < A[N] } x := -1; for i := N+1 to FData.Count-1 do if C.Compare(L[i], L[N]) < 0 then begin x := i; break; end; { swap A[N] and A[X] } FData.Exchange(n,x); { change position of A[X] to make range [N+1; FCoun-1] back ordered again } i := x; while (i > n+1) and (C.Compare(L[i-1], L[x]) < 0) do dec(i); while (i < FData.Count-1) and (C.Compare(L[x], L[i+1]) < 0) do inc(i); if i<>x then FData.Move(x,i); end; procedure TVector<T>.Remove(const AValue: T; AComparer: IComparer<T>); var I: Integer; L: TArray<T>; begin if AComparer = nil then FData.Remove(AValue) else if FindFirst(AValue, I, AComparer) then FData.Delete(I); end; procedure TVector<T>.Remove(const AValues: TArray<T>; ASorted: boolean; AComparer: IComparer<T>); var SortedValues: TArray<T>; DataList: TArray<T>; begin if AComparer = nil then AComparer := FData.FDataComparer; if ASorted then SortedValues := AValues else begin SortedValues := Sys.Copy<T>(AValues); TArray.Sort<T>(SortedValues, AComparer); end; DataList := FData.List; Remove( function(const Value: T; Index: integer): boolean var FoundIndex: Integer; begin result := TArray.BinarySearch<T>(SortedValues, DataList[Index], FoundIndex, AComparer); end); end; procedure TVector<T>.Remove(AValues: TVector<T>; ASorted: boolean; AComparer: IComparer<T>); var SortedValues: TArray<T>; DataList: TArray<T>; begin if AComparer = nil then AComparer := FData.FDataComparer; if ASorted then SortedValues := AValues.FData.List else begin SortedValues := Sys.Copy<T>(AValues.FData.List, 0, FData.Count); TArray.Sort<T>(SortedValues, AComparer); end; DataList := FData.List; Remove( function(const Value: T; Index: integer): boolean var FoundIndex: Integer; begin result := TArray.BinarySearch<T>(SortedValues, DataList[Index], FoundIndex, AComparer); end); end; procedure TVector<T>.Remove(const AValues: TEnumerable<T>; ASorted: boolean; AComparer: IComparer<T>); begin Remove(AValues.ToArray, ASorted, AComparer); end; procedure TVector<T>.Remove(AItemsToDelete: TFuncFilterValueIndex<T>); var StartIndex,DstIndex,I: Integer; DataList: TArray<T>; begin { find first item to delete } StartIndex := FData.Count; DataList := FData.List; for I := 0 to FData.Count-1 do if AItemsToDelete(DataList[I], I) then begin StartIndex := I; Break; end; { shift to the end all items we want to delete } DstIndex := StartIndex; for I := StartIndex+1 to FData.Count-1 do if not AItemsToDelete(DataList[I], I) then begin FData.Exchange(DstIndex, I); inc(DstIndex); end; { delete all items in one batch } FData.Count := DstIndex; end; procedure TVector<T>.Reverse; begin Reverse(0, Count); end; procedure TVector<T>.Reverse(AStartIndex, ACount: integer); var I: Integer; begin if ACount <= 1 then Exit; Assert((AStartIndex >= 0) and (AStartIndex + ACount <= Count)); inc(ACount, AStartIndex); dec(ACount); repeat FData.Exchange(AStartIndex, ACount); inc(AStartIndex); dec(ACount); until AStartIndex >= ACount; end; procedure TVector<T>.RotateLeft(Index1, Index2, Shift: integer); var I: integer; begin Assert((Index1>=0) and (Index1<Count) and (Index2>=0) and (Index2<Count)); if Index2 < Index1 then begin I := Index1; Index1 := Index2; Index2 := I; end; I := Index2-Index1+1; Shift := (I - (Shift mod I)) mod I; if Shift <= 0 then if Shift < 0 then Inc(Shift, I) else Exit; Reverse(Index1, Index2-Index1+1); Reverse(Index1, Shift); Reverse(Index1+Shift, Index2-Index1+1-Shift); end; procedure TVector<T>.RotateRight(Index1, Index2, Shift: integer); var I: integer; begin Assert((Index1>=0) and (Index1<Count) and (Index2>=0) and (Index2<Count)); if Index2 < Index1 then begin I := Index1; Index1 := Index2; Index2 := I; end; I := Index2-Index1+1; Shift := Shift mod I; if Shift <= 0 then if Shift < 0 then Inc(Shift, I) else Exit; Reverse(Index1, Index2-Index1+1); Reverse(Index1, Shift); Reverse(Index1+Shift, Index2-Index1+1-Shift); end; function TVector<T>.GetCapacity: integer; begin result := FData.Capacity; end; function TVector<T>.GetCount: NativeInt; begin result := FData.Count; end; procedure TVector<T>.SetCapacity(ACapacity: integer); begin FData.Capacity := ACapacity; end; function TVector<T>.GetEmpty: Boolean; begin Result := FData.Count = 0; end; function TVector<T>.GetEnumerator: TEnumerator<T>; begin result := FData.GetEnumerator; end; function TVector<T>.GetFirst: T; begin Result := FData.First; end; procedure TVector<T>.SetFirst(const Value: T); begin FData[0] := Value; end; function TVector<T>.GetLast: T; begin Result := FData.Last; end; function TVector<T>.GetOnNotify: TCollectionNotifyEvent<T>; begin result := FData.OnNotify; end; function TVector<T>.GetOwnsValues: boolean; begin result := FData.OwnsValues; end; function TVector<T>.GetSlice: TSlice<T>; begin result.Init(FData.List, FData.Count); end; function TVector<T>.GetSlice(AStartSliceIndexIncl, AEndSliceIndexExcl: integer): TSlice<T>; begin result.Init(FData.List, FData.Count); result.Add(AStartSliceIndexIncl, AEndSliceIndexExcl); end; function TVector<T>.GetSlice(AItemsToSlice: TFuncFilterValueIndex<T>): TSlice<T>; var DataList: TArray<T>; I: Integer; begin DataList := FData.List; result.Init(DataList, FData.Count); for I := 0 to FData.Count-1 do if AItemsToSlice(DataList[I], I) then result.Add(I); end; function TVector<T>.GetTotalSizeBytes: int64; begin result := FData.Count*SizeOf(T); end; procedure TVector<T>.SetLast(const Value: T); begin FData[FData.Count-1] := Value; end; procedure TVector<T>.SetOnNotify(const Value: TCollectionNotifyEvent<T>); begin FData.OnNotify := Value; end; procedure TVector<T>.SetOwnsValues(const Value: boolean); begin FData.OwnsValues := Value; end; procedure TVector<T>.Shuffle(AStartIndex, ACount: integer); var I: Integer; begin if ACount <= 1 then Exit; Assert((AStartIndex >= 0) and (AStartIndex + ACount <= Count)); for I := ACount-1 downto 1 do FData.Exchange(I+AStartIndex, Random(I+1)+AStartIndex); end; procedure TVector<T>.Shuffle; begin Shuffle(0, Count); end; function TVector<T>.GetItem(ItemIndex: integer): T; begin result := FData[ItemIndex]; end; procedure TVector<T>.SetItem(ItemIndex: integer; const Value: T); begin FData[ItemIndex] := Value; end; procedure TVector<T>.SetCount(ACount: NativeInt); begin FData.Count := ACount; end; procedure TVector<T>.Sort; begin FData.Sort; end; procedure TVector<T>.Sort(AIndex, ACount: Integer); var DataList: TArray<T>; begin assert((AIndex >= 0) and (AIndex + ACount <= FData.Count)); DataList := FData.List; TArray.Sort<T>(DataList, FData.FDataComparer, AIndex, ACount); end; procedure TVector<T>.Sort(AComparer: IComparer<T>); begin if AComparer = nil then AComparer := FData.FDataComparer; FData.Sort(AComparer); end; procedure TVector<T>.Sort(AComparer: IComparer<T>; AIndex, ACount: Integer); var DataList: TArray<T>; begin assert((AIndex >= 0) and (AIndex + ACount <= FData.Count)); if AComparer = nil then AComparer := FData.FDataComparer; DataList := FData.List; TArray.Sort<T>(DataList, AComparer, AIndex, ACount); end; procedure TVector<T>.Sort(AComparison: TComparison<T>); var C: IComparer<T>; begin if Assigned(AComparison) then C := TDelegatedComparer<T>.Create(AComparison) else C := FData.FDataComparer; FData.Sort(C); end; procedure TVector<T>.Sort(AComparison: TComparison<T>; AIndex, ACount: Integer); var C: IComparer<T>; DataList: TArray<T>; begin if Assigned(AComparison) then C := TDelegatedComparer<T>.Create(AComparison) else C := FData.FDataComparer; DataList := FData.List; TArray.Sort<T>(DataList, C, AIndex, ACount); end; function TVector<T>.Sorted: boolean; begin result := TArrayUtils.Sorted<T>(FData.List, 0, FData.Count, FData.FDataComparer); end; function TVector<T>.Sorted(AStartIndex, ACount: integer; AComparer: IComparer<T>): boolean; begin if AComparer = nil then AComparer := FData.FDataComparer; result := TArrayUtils.Sorted<T>(FData.List, 0, FData.Count, AComparer); end; function TVector<T>.Sorted(AStartIndex, ACount: integer; AComparison: TComparison<T>): boolean; var C: IComparer<T>; begin if Assigned(AComparison) then C := TDelegatedComparer<T>.Create(AComparison) else C := FData.FDataComparer; result := TArrayUtils.Sorted<T>(FData.List, 0, FData.Count, C); end; class operator TVector<T>.Subtract(a: TVector<T>; const b: TArray<T>): TVector<T>; begin result.Init; result.Add(A); result.Remove(B, False); end; class operator TVector<T>.Subtract(a, b: TVector<T>): TVector<T>; begin result.Init; result.Add(A); result.Remove(B, False); end; class operator TVector<T>.Subtract(a: TVector<T>; const b: T): TVector<T>; begin result.Init; result.Add(A); result.Remove(B); end; class operator TVector<T>.Subtract(a: TVector<T>; const b: TEnumerable<T>): TVector<T>; begin result.Init; result.Add(A); result.Remove(B, False); end; class operator TVector<T>.Subtract(const a: TEnumerable<T>; b: TVector<T>): TVector<T>; begin result.Init; result.Add(A); result.Remove(B, False); end; class operator TVector<T>.Subtract(const a: TArray<T>; b: TVector<T>): TVector<T>; begin result.Init; result.Add(A); result.Remove(B, False); end; class operator TVector<T>.Subtract(const a: T; b: TVector<T>): TVector<T>; begin result.Init; result.Add(A); result.Remove(B, False); end; function TVector<T>.BinarySearch(const Item: T; out FoundIndex: Integer): Boolean; begin result := TArray.BinarySearch<T>(FData.List, Item, FoundIndex, FData.FDataComparer, 0, FData.Count); end; function TVector<T>.BinarySearch(const Item: T; out FoundIndex: Integer; AComparer: IComparer<T>): Boolean; begin if AComparer = nil then AComparer := FData.FDataComparer; result := TArray.BinarySearch<T>(FData.List, Item, FoundIndex, AComparer, 0, FData.Count); end; function TVector<T>.BinarySearch(const Item: T; out FoundIndex: Integer; AComparer: IComparer<T>; AIndex,ACount: Integer): Boolean; begin if AComparer = nil then AComparer := FData.FDataComparer; result := TArray.BinarySearch<T>(FData.List, Item, FoundIndex, AComparer, AIndex,ACount); end; function TVector<T>.BinarySearch(const Item: T; out FoundIndex: Integer; AComparison: TComparison<T>; AIndex, ACount: Integer): Boolean; var C: IComparer<T>; begin if Assigned(AComparison) then C := TDelegatedComparer<T>.Create(AComparison) else C := FData.FDataComparer; result := BinarySearch(Item, FoundIndex, C, AIndex, ACount); end; function TVector<T>.BinarySearch(const Item: T; out FoundIndex: Integer; AComparison: TComparison<T>): Boolean; var C: IComparer<T>; begin if Assigned(AComparison) then C := TDelegatedComparer<T>.Create(AComparison) else C := FData.FDataComparer; result := BinarySearch(Item, FoundIndex, C, 0, Count); end; procedure TVector<T>.Add(Values: TVector<T>); var I: Integer; begin for I := 0 to Values.FData.Count-1 do FData.Add(Values.FData[I]); end; class operator TVector<T>.Add(a: TVector<T>; const b: TArray<T>): TVector<T>; begin result.Init; result.Add(A); result.Add(B); end; class operator TVector<T>.Add(a, b: TVector<T>): TVector<T>; begin result.Init; result.Add(A); result.Add(B); end; class operator TVector<T>.Add(a: TVector<T>; const b: T): TVector<T>; begin result.Init; result.Add(A); result.Add(B); end; class operator TVector<T>.Add(a: TVector<T>; const b: TEnumerable<T>): TVector<T>; begin result.Init; result.Add(A); result.Add(B); end; class operator TVector<T>.Add(const a: TEnumerable<T>; b: TVector<T>): TVector<T>; begin result.Init; result.Add(A); result.Add(B); end; class operator TVector<T>.Add(const a: TArray<T>; b: TVector<T>): TVector<T>; begin result.Init; result.Add(A); result.Add(B); end; class operator TVector<T>.Add(const a: T; b: TVector<T>): TVector<T>; begin result.Init; result.Add(A); result.Add(B); end; end.
unit Rotinas; interface uses Windows, Messages, SysUtils, Classes, Forms, Dialogs, Variants, Math; procedure PreencheLista(Lista: TStringList); function LocalizaMaiorNumero(Lista: TStringList): String; function MontarLista(Lista: TStringList): TStringList; function OrdenacaoCustomizada(List: TStringList; Index1, Index2: Integer): Integer; implementation procedure PreencheLista(Lista: TStringList); var i, intNum: Integer; begin Lista.Clear; Randomize; for i := 1 to 100 do begin intNum := Random(999); if (intNum mod 5) = 0 then intNum := intNum * 1000000; if (intNum mod 2) = 0 then intNum := intNum * -1; Lista.Add(IntToStr(intNum)); end; LocalizaMaiorNumero(Lista); end; function MontarLista(Lista: TStringList): TStringList; var i, intNum: Integer; begin Lista.Clear; Randomize; for i := 1 to 100 do begin intNum := Random(999); if (intNum mod 5) = 0 then intNum := intNum * 1000000; if (intNum mod 2) = 0 then intNum := intNum * -1; Lista.Add(IntToStr(intNum)); end; Lista.CustomSort(OrdenacaoCustomizada); Result := Lista; end; function LocalizaMaiorNumero(Lista: TStringList): String; var Valor: String; i: Integer; begin Valor := Lista[Lista.Count-1]; Result := Valor; end; function OrdenacaoCustomizada(List: TStringList; Index1, Index2: Integer): Integer; var Valor1, Valor2: Integer; begin Valor1 := StrToInt(List[Index1]); Valor2 := StrToInt(List[Index2]); if Valor1 < Valor2 then Result := -1 else if Valor2 < Valor1 then Result := 1 else Result := 0; end; end.
unit SolidRectangleButton; interface uses System.SysUtils, System.Classes, FMX.Types, FMX.Controls, System.Types, FMX.Objects, FMX.StdCtrls, System.UITypes, FMX.Graphics, FMX.Dialogs, System.Math, System.Math.Vectors, FMX.Edit, FMX.Layouts, FMX.Effects, TransparentRectangleButton, ColorClass; type TSolidRectangleButton = class(TTransparentRectangleButton) private { Private declarations } function GetFElevation: Boolean; procedure SetFElevation(const Value: Boolean); function GetFDark: Boolean; procedure SetFDark(const Value: Boolean); protected { Protected declarations } FBackgroundButton: TRectangle; FShadow: TShadowEffect; FContrastColor: TAlphaColor; procedure Paint; override; procedure Resize; override; procedure Painting; override; procedure BackgroundOnClick(Sender: TObject); override; procedure BackgroundOnEnter(Sender: TObject); override; procedure BackgroundOnExit(Sender: TObject); override; function GetFButtonClass: TColorClass; override; procedure SetFButtonClass(const Value: TColorClass); override; function GetFBackgroudColor: TAlphaColor; override; procedure SetFBackgroudColor(const Value: TAlphaColor); override; public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; published { Published declarations } { Additional properties } property Elevation: Boolean read GetFElevation write SetFElevation; property Dark: Boolean read GetFDark write SetFDark; end; procedure Register; implementation procedure Register; begin RegisterComponents('Componentes Customizados', [TSolidRectangleButton]); end; { TSolidRectangleButton } procedure TSolidRectangleButton.BackgroundOnClick(Sender: TObject); var CircleEffect: TCircle; Aux: Single; begin if FAnimationOnClick then begin CircleEffect := TCircle.Create(Self); CircleEffect.HitTest := False; CircleEffect.Parent := FBackgroundButton; CircleEffect.Align := TAlignLayout.Center; CircleEffect.Stroke.Kind := TBrushKind.None; CircleEffect.Fill.Color := FContrastColor; CircleEffect.SendToBack; FBackgroundButton.ClipChildren := True; Aux := Max(FBackgroundSelect.Width, FBackgroundSelect.Height); CircleEffect.Height := 0; CircleEffect.Width := 0; CircleEffect.Opacity := 0.4; CircleEffect.AnimateFloat('Height', Aux, 0.4, TAnimationType.Out, TInterpolationType.Circular); CircleEffect.AnimateFloat('Width', Aux, 0.4, TAnimationType.Out, TInterpolationType.Circular); CircleEffect.AnimateFloat('Opacity', 0, 0.4); end; if Assigned(FPointerOnClick) then FPointerOnClick(Sender); end; procedure TSolidRectangleButton.BackgroundOnEnter(Sender: TObject); begin if Elevation then begin FShadow.AnimateFloat('Distance', 5, 0.2, TAnimationType.InOut); FShadow.AnimateFloat('Softness', 0.3, 0.2, TAnimationType.InOut); end; FBackgroundSelect.AnimateFloat('Opacity', 0.1, 0.1, TAnimationType.InOut); if Assigned(FPointerOnMouseEnter) then FPointerOnMouseEnter(Sender); end; procedure TSolidRectangleButton.BackgroundOnExit(Sender: TObject); begin if Elevation then begin FShadow.AnimateFloat('Distance', 2, 0.2, TAnimationType.InOut); FShadow.AnimateFloat('Softness', 0.15, 0.2, TAnimationType.InOut); end; FBackgroundSelect.AnimateFloat('Opacity', 0, 0.1, TAnimationType.InOut); if Assigned(FPointerOnMouseExit) then FPointerOnMouseExit(Sender); end; constructor TSolidRectangleButton.Create(AOwner: TComponent); begin inherited; FContrastColor := TAlphaColor($FFFFFFFF); FBackgroundButton := TRectangle.Create(Self); Self.AddObject(FBackgroundButton); FBackgroundButton.SetSubComponent(True); FBackgroundButton.Stored := False; FBackgroundButton.Align := TAlignLayout.Contents; FBackgroundButton.Stroke.Kind := TBrushKind.None; FBackgroundButton.Fill.Color := TAlphaColor($FF1867C0); FBackgroundButton.XRadius := 4; FBackgroundButton.YRadius := 4; FBackgroundButton.OnMouseEnter := BackgroundOnEnter; FBackgroundButton.OnMouseLeave := BackgroundOnExit; FBackgroundButton.OnClick := BackgroundOnClick; FBackgroundButton.Cursor := crHandPoint; FBackgroundButton.SendToBack; FBackgroundSelect.Fill.Color := FContrastColor; FBackgroundSelect.BringToFront; FText.TextSettings.FontColor := FContrastColor; FText.BringToFront; FShadow := TShadowEffect.Create(Self); Self.AddObject(FShadow); FShadow.Direction := 90; FShadow.Distance := 2; FShadow.Opacity := 0.3; FShadow.Softness := 0.15; FShadow.Enabled := True; FShadow.SetSubComponent(True); FShadow.Stored := False; end; destructor TSolidRectangleButton.Destroy; begin if Assigned(FShadow) then FShadow.Free; if Assigned(FBackgroundButton) then FBackgroundButton.Free; inherited; end; function TSolidRectangleButton.GetFBackgroudColor: TAlphaColor; begin inherited; Result := FBackgroundSelect.Fill.Color; if Assigned(FBackgroundButton) then Result := FBackgroundButton.Fill.Color; end; function TSolidRectangleButton.GetFButtonClass: TColorClass; begin if FBackgroundButton.Fill.Color = SOLID_PRIMARY_COLOR then Result := TColorClass.Primary else if FBackgroundButton.Fill.Color = SOLID_SECONDARY_COLOR then Result := TColorClass.Secondary else if FBackgroundButton.Fill.Color = SOLID_ERROR_COLOR then Result := TColorClass.Error else if FBackgroundButton.Fill.Color = SOLID_WARNING_COLOR then Result := TColorClass.Warning else if FBackgroundButton.Fill.Color = SOLID_SUCCESS_COLOR then Result := TColorClass.Success else if FBackgroundButton.Fill.Color = SOLID_NORMAL_COLOR then Result := TColorClass.Normal else Result := TColorClass.Custom; end; function TSolidRectangleButton.GetFDark: Boolean; begin if FContrastColor = TAlphaColor($FF323232) then Result := True else Result := False; end; function TSolidRectangleButton.GetFElevation: Boolean; begin Result := FShadow.Enabled; end; procedure TSolidRectangleButton.Paint; begin inherited; if FIcon.Data.Data.Equals('') then begin FIcon.Visible := False; FText.TextSettings.HorzAlign := TTextAlign.Center; end else begin FIcon.Visible := True; SetFIconPosition(GetFIconPosition); end; FBackgroundSelect.Fill.Color := FContrastColor; FText.TextSettings.FontColor := FContrastColor; FIcon.Fill.Color := FContrastColor; end; procedure TSolidRectangleButton.Painting; begin inherited; end; procedure TSolidRectangleButton.Resize; begin inherited; end; procedure TSolidRectangleButton.SetFBackgroudColor(const Value: TAlphaColor); begin if Assigned(FBackgroundButton) then FBackgroundButton.Fill.Color := Value; end; procedure TSolidRectangleButton.SetFButtonClass(const Value: TColorClass); begin if Value = TColorClass.Primary then begin SetFBackgroudColor(SOLID_PRIMARY_COLOR); SetFDark(False); end else if Value = TColorClass.Secondary then begin SetFBackgroudColor(SOLID_SECONDARY_COLOR); SetFDark(False); end else if Value = TColorClass.Error then begin SetFBackgroudColor(SOLID_ERROR_COLOR); SetFDark(False); end else if Value = TColorClass.Warning then begin SetFBackgroudColor(SOLID_WARNING_COLOR); SetFDark(False); end else if Value = TColorClass.Normal then begin SetFBackgroudColor(SOLID_NORMAL_COLOR); SetFDark(True); end else if Value = TColorClass.Success then begin SetFBackgroudColor(SOLID_SUCCESS_COLOR); SetFDark(False); end else begin FBackgroundButton.Fill.Color := TAlphaColor($FF323232); SetFDark(False); end; end; procedure TSolidRectangleButton.SetFDark(const Value: Boolean); begin if Value then FContrastColor := TAlphaColor($FF323232) else FContrastColor := TAlphaColor($FFFFFFFF); end; procedure TSolidRectangleButton.SetFElevation(const Value: Boolean); begin FShadow.Enabled := Value; end; end.