text
stringlengths
14
6.51M
unit moneydbctrls; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, MoneyCtrls,StdCtrls,DB,DBCtrls; type {MoneyDBCheckBox} TMoneyDBCheckBox = class(TMoneyCheckBox) private FDataLink: TFieldDataLink; FValueCheck: string; FValueUncheck: string; procedure DataChange(Sender: TObject); function GetDataField: string; function GetDataSource: TDataSource; function GetField: TField; function GetReadOnly: Boolean; function GetFieldChecked:Boolean; procedure SetDataField(const Value: string); procedure SetDataSource(Value: TDataSource); procedure SetReadOnly(Value: Boolean); procedure SetValueCheck(const Value: string); procedure SetValueUncheck(const Value: string); procedure UpdateData(Sender: TObject); function ValueMatch(const ValueList, Value: string): Boolean; procedure CMExit(var Message: TCMExit); message CM_EXIT; procedure CMGetDataLink(var Message: TMessage); message CM_GETDATALINK; protected procedure Click; override; procedure KeyPress(var Key: Char); override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Checked; property Field: TField read GetField; published property Alignment; property Caption; property Color; property Ctl3D; property DataField: string read GetDataField write SetDataField; property DataSource: TDataSource read GetDataSource write SetDataSource; property DragCursor; property DragMode; property Enabled; property Font; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly: Boolean read GetReadOnly write SetReadOnly default False; property ShowHint; property TabOrder; property TabStop; property ValueChecked: string read FValueCheck write SetValueCheck; property ValueUnchecked: string read FValueUncheck write SetValueUncheck; property Visible; property OnClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; { TMoneyDBLookupControl } TMoneyDBLookupControl = class; TMoneyDataSourceLink = class(TDataLink) private FDBLookupControl: TMoneyDBLookupControl; protected procedure FocusControl(Field: TFieldRef); override; procedure ActiveChanged; override; procedure RecordChanged(Field: TField); override; end; TMoneySourceLink = class(TDataLink) private FDBLookupControl: TMoneyDBLookupControl; protected procedure ActiveChanged; override; procedure DataSetChanged; override; end; TMoneyDBLookupControl = class(TCustomControl) private FHeight:Integer; FLookupSource: TDataSource; FDataLink: TMoneyDataSourceLink; FListLink: TMoneySourceLink; FDataFieldName: string; FKeyFieldName: string; FListFieldName: string; FListFieldIndex: Integer; FDataField: TField; FMasterField: TField; FKeyField: TField; FListField: TField; FListFields: TList; FKeyValue: Variant; FSearchText: string; FLookupMode: Boolean; FListActive: Boolean; FFocused: Boolean; function CanModify: Boolean; procedure CheckNotCircular; procedure CheckNotLookup; procedure DataLinkActiveChanged; procedure DataLinkRecordChanged(Field: TField); function GetBorderSize: Integer; function GetDataSource: TDataSource; function GetKeyFieldName: string; function GetListSource: TDataSource; function GetReadOnly: Boolean; function GetTextHeight: Integer; procedure KeyValueChanged; virtual; procedure ListLinkActiveChanged; virtual; procedure ListLinkDataChanged; virtual; function LocateKey: Boolean; procedure ProcessSearchKey(Key: Char); procedure SelectKeyValue(const Value: Variant); procedure SetDataFieldName(const Value: string); procedure SetDataSource(Value: TDataSource); procedure SetKeyFieldName(const Value: string); procedure SetKeyValue(const Value: Variant); procedure SetListFieldName(const Value: string); procedure SetListSource(Value: TDataSource); procedure SetLookupMode(Value: Boolean); procedure SetReadOnly(Value: Boolean); procedure SetTextHeight(Value :Integer); procedure WMGetDlgCode(var Message: TMessage); message WM_GETDLGCODE; procedure WMKillFocus(var Message: TMessage); message WM_KILLFOCUS; procedure WMSetFocus(var Message: TMessage); message WM_SETFOCUS; protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; property DataField: string read FDataFieldName write SetDataFieldName; property DataSource: TDataSource read GetDataSource write SetDataSource; property KeyField: string read GetKeyFieldName write SetKeyFieldName; property KeyValue: Variant read FKeyValue write SetKeyValue; property ListField: string read FListFieldName write SetListFieldName; property ListFieldIndex: Integer read FListFieldIndex write FListFieldIndex default 0; property ListSource: TDataSource read GetListSource write SetListSource; property ParentColor default False; property ReadOnly: Boolean read GetReadOnly write SetReadOnly default False; property TabStop default True; property TextHeight:Integer read GetTextHeight write SetTextHeight; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Field: TField read FDataField; end; { TMoneyDBLookupListBox } TMoneyDBLookupListBox = class(TMoneyDBLookupControl) private FDrawBorder:Boolean; FSelectColor,FHighLightColor, FSecondColor,FBorderColor:TColor; FRecordIndex: Integer; FRecordCount: Integer; FRowCount: Integer; FBorderStyle: TBorderStyle; FPopup: Boolean; FKeySelected: Boolean; FTracking: Boolean; FTimerActive: Boolean; FLockPosition: Boolean; FMousePos: Integer; FSelectedItem: string; function GetKeyIndex: Integer; procedure KeyValueChanged; override; procedure ListLinkActiveChanged; override; procedure ListLinkDataChanged; override; procedure SelectCurrent; procedure SelectItemAt(X, Y: Integer); procedure SetBorderStyle(Value: TBorderStyle); procedure SetRowCount(Value: Integer); procedure StopTimer; procedure SetColor(Index:Integer; Value :TColor); procedure SetDrawBorder(Value:Boolean); procedure StopTracking; procedure TimerScroll; procedure UpdateScrollBar; procedure CMCtl3DChanged(var Message: TMessage); message CM_CTL3DCHANGED; procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; procedure WMCancelMode(var Message: TMessage); message WM_CANCELMODE; procedure WMTimer(var Message: TMessage); message WM_TIMER; procedure WMVScroll(var Message: TWMVScroll); message WM_VSCROLL; protected procedure CreateParams(var Params: TCreateParams); override; procedure CreateWnd; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure Paint; override; procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; public constructor Create(AOwner: TComponent); override; property KeyValue; property SelectedItem: string read FSelectedItem; published property SelectColor:TColor index 1 read FSelectColor write SetColor; property SecondColor:TColor index 3 read FSecondColor write SetColor; property HighLightColor:TColor index 2 read FHighLightColor write SetColor; property BorderColor:TColor index 4 read FBorderColor write SetColor; property TextHeight; property Align; property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsSingle; property DrawBorder: Boolean read FDrawBorder write SetDrawBorder; property Color; property Ctl3D; property DataField; property DataSource; property DragCursor; property DragMode; property Enabled; property Font; property ImeMode; property ImeName; property KeyField; property ListField; property ListFieldIndex; property ListSource; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly; property RowCount: Integer read FRowCount write SetRowCount stored False; property ShowHint; property TabOrder; property TabStop; property Visible; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; { TMoneyDBLookupComboBox } TMoneyPopupDataList = class(TMoneyDBLookupListBox) private procedure WMMouseActivate(var Message: TMessage); message WM_MOUSEACTIVATE; protected procedure CreateParams(var Params: TCreateParams); override; public constructor Create(AOwner: TComponent); override; end; TDropDownAlign = (daLeft, daRight, daCenter); TMoneyDBLookupComboBox = class(TMoneyDBLookupControl) private FAlwaysShow:Boolean; FBitmapDownBlack,FBitmapDownWhite:TBitmap; FDataList: TMoneyPopupDataList; FButtonWidth: Integer; FText: string; FDropDownRows: Integer; FDropDownWidth: Integer; FDropDownAlign: TDropDownAlign; FListVisible: Boolean; FPressed: Boolean; FHasMouse:Boolean; FTracking: Boolean; FAlignment: TAlignment; FLookupMode: Boolean; FOnDropDown: TNotifyEvent; FOnCloseUp: TNotifyEvent; procedure SetAlwaysShow(Value:Boolean); procedure KeyValueChanged; override; procedure ListLinkActiveChanged; override; procedure ListLinkDataChanged; override; procedure ListMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure StopTracking; function GetColor(Index:Integer):TColor; procedure SetColor(Index:Integer; Value:TColor); procedure TrackButton(X, Y: Integer); procedure CMCancelMode(var Message: TCMCancelMode); message CM_CANCELMODE; procedure CMCtl3DChanged(var Message: TMessage); message CM_CTL3DCHANGED; procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; procedure CMGetDataLink(var Message: TMessage); message CM_GETDATALINK; procedure WMCancelMode(var Message: TMessage); message WM_CANCELMODE; procedure WMKillFocus(var Message: TWMKillFocus); message WM_KILLFOCUS; procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER; procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; protected procedure CreateParams(var Params: TCreateParams); override; procedure Paint; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure CloseUp(Accept: Boolean); procedure DropDown; property KeyValue; property ListVisible: Boolean read FListVisible; property Text: string read FText; published property Color; property SecondColor:TColor index 1 read GetColor write SetColor; property SelectColor:TColor index 2 read GetColor write SetColor; property HighLightColor:TColor index 3 read GetColor write SetColor; property AlwaysShow:Boolean read FAlwaysShow write SetAlwaysShow; property Ctl3D; property DataField; property DataSource; property DragCursor; property DragMode; property DropDownAlign: TDropDownAlign read FDropDownAlign write FDropDownAlign default daLeft; property DropDownRows: Integer read FDropDownRows write FDropDownRows default 7; property DropDownWidth: Integer read FDropDownWidth write FDropDownWidth default 0; property Enabled; property Font; property ImeMode; property ImeName; property KeyField; property ListField; property ListFieldIndex; property ListSource; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ReadOnly; property ShowHint; property TabOrder; property TabStop; property Visible; property OnClick; property OnCloseUp: TNotifyEvent read FOnCloseUp write FOnCloseUp; property OnDragDrop; property OnDragOver; property OnDropDown: TNotifyEvent read FOnDropDown write FOnDropDown; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; TCustomMoneyDBComboBox = class(TCustomComboBox) private FValues: TStrings; FEnableValues: Boolean; FDataLink: TFieldDataLink; FPaintControl: TPaintControl; procedure SetEnableValues(Value: Boolean); procedure SetValues(Value: TStrings); procedure ValuesChanged(Sender: TObject); procedure SetComboStyle(Value:TMoneyComboStyle); function GetComboStyle:TMoneyComboStyle; procedure DataChange(Sender: TObject); procedure EditingChange(Sender: TObject); function GetComboText: string; function GetDataField: string; function GetDataSource: TDataSource; function GetField: TField; function GetReadOnly: Boolean; procedure SetComboText(const Value: string); procedure SetDataField(const Value: string); procedure SetDataSource(Value: TDataSource); procedure SetEditReadOnly; procedure SetItems(Value: TStrings); procedure SetReadOnly(Value: Boolean); procedure UpdateData(Sender: TObject); procedure CMEnter(var Message: TCMEnter); message CM_ENTER; procedure CMExit(var Message: TCMExit); message CM_EXIT; procedure CMGetDataLink(var Message: TMessage); message CM_GETDATALINK; procedure WMPaint(var Message: TWMPaint); message WM_PAINT; protected procedure Change; override; procedure Click; override; procedure ComboWndProc(var Message: TMessage; ComboWnd: HWnd; ComboProc: Pointer); override; procedure CreateWnd; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyPress(var Key: Char); override; procedure Loaded; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure SetStyle(Value: TComboboxStyle); override; procedure WndProc(var Message: TMessage); override; property ReadOnly: Boolean read GetReadOnly write SetReadOnly default False; property Values: TStrings read FValues write SetValues; property Style:TMoneyComboStyle read GetComboStyle write SetComboStyle; property DataField: string read GetDataField write SetDataField; property DataSource: TDataSource read GetDataSource write SetDataSource; property Items write SetItems; property EnableValues: Boolean read FEnableValues write SetEnableValues; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Field: TField read GetField; property Text; end; {MoneyDBComboBox} TMoneyDBComboBox = class(TCustomMoneyDBComboBox) private FCanvas:TCanvas; FBitmaps:array[1..2] of TBitmap; FButtonWidth: Integer; FDown :Boolean; FMouseInControl: Boolean; procedure WMPaint(var Message: TWMPaint); message WM_PAINT; procedure CMMouseEnter(var Msg:TMessage); message CM_MOUSEENTER; procedure CMMouseLeave(var Msg:TMessage); message CM_MOUSELEAVE; procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED; procedure InvalidateButton; function ButtonRect:TRect; procedure DrawControlBorder(DC: HDC); procedure DrawButton(DC: HDC; ARect:TRect); protected procedure UpdateTracking; procedure MouseEnter; virtual; procedure MouseLeave; virtual; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; public constructor Create(AOwner:TComponent); override; destructor Destroy; override; published property Style; property ShowHint; property Sorted; property TabOrder; property TabStop; property Visible; property OnChange; property ReadOnly; property Values; property DataField; property DataSource; property Items; property EnableValues; property DragMode; property DragCursor; property DropDownCount; property Enabled; property Font; property ImeMode; property ImeName; property ItemHeight; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnDropDown; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnStartDrag; property Color; property Ctl3D; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; end; {MoneyDBDateEdit} TMoneyDBDateEdit = class(TMoneyDateEdit) private FDataLink: TFieldDataLink; function GetDataField: string; function GetDataSource: TDataSource; procedure SetDataField(const Value: string); function GetField: TField; procedure SetDataSource(Value: TDataSource); procedure DataChange(Sender: TObject); procedure UpdateData(Sender: TObject); function GetReadOnly: Boolean; procedure SetReadOnly(Value: Boolean); procedure CMExit(var Message: TCMExit); message CM_EXIT; procedure CMGetDataLink(var Message: TMessage); message CM_GETDATALINK; protected procedure DoChange; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure KeyPress(var Key: Char); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Field: TField read GetField; published property ReadOnly: Boolean read GetReadOnly write SetReadOnly default False; property DataField: string read GetDataField write SetDataField; property DataSource: TDataSource read GetDataSource write SetDataSource; end; {MoneyDBLinker} TMoneyDBLinkerDataLink = class; TMoneyDBLinker = class(TComponent) private FControls:array[1..9] of TControl; FDataLink:TMoneyDBLinkerDataLink; procedure SetControl(Index: Integer; Value :TControl); function GetDataSource: TDataSource; procedure SetDataSource(Value: TDataSource); protected procedure DataChanged; procedure EditingChanged; procedure ActiveChanged; procedure Loaded; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property First:TControl index 1 read FControls[1] write SetControl; property Prev:TControl index 2 read FControls[2] write SetControl; property Next:TControl index 3 read FControls[3] write SetControl; property Last:TControl index 4 read FControls[4] write SetControl; property Insert:TControl index 5 read FControls[5] write SetControl; property Delete:TControl index 6 read FControls[6] write SetControl; property Edit:TControl index 7 read FControls[7] write SetControl; property Save:TControl index 8 read FControls[8] write SetControl; property Cancel:TControl index 9 read FControls[9] write SetControl; property DataSource: TDataSource read GetDataSource write SetDataSource; end; {TMoneyDBLinkerDataLink} TMoneyDBLinkerDataLink = class(TDataLink) private FDBLinker: TMoneyDBLinker; protected procedure EditingChanged; override; procedure DataSetChanged; override; procedure ActiveChanged; override; public constructor Create(AOwner: TMoneyDBLinker); destructor Destroy; override; end; procedure Register; implementation uses DBConsts; { TMoneyDBCheckBox } constructor TMoneyDBCheckBox.Create(AOwner: TComponent); begin inherited Create(AOwner); FValueCheck := STextTrue; FValueUncheck := STextFalse; FDataLink := TFieldDataLink.Create; FDataLink.Control := Self; FDataLink.OnDataChange := DataChange; FDataLink.OnUpdateData := UpdateData; end; destructor TMoneyDBCheckBox.Destroy; begin FDataLink.Free; FDataLink := nil; inherited Destroy; end; procedure TMoneyDBCheckBox.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (FDataLink <> nil) and (AComponent = DataSource) then DataSource := nil; end; function TMoneyDBCheckBox.GetFieldChecked:Boolean; var Text: string; begin if FDatalink.Field <> nil then if FDataLink.Field.IsNull then Result := False else if FDataLink.Field.DataType = ftBoolean then if FDataLink.Field.AsBoolean then Result := True else Result := False else begin Result := False; Text := FDataLink.Field.Text; if ValueMatch(FValueCheck, Text) then Result := True else if ValueMatch(FValueUncheck, Text) then Result := False; end else Result := False; end; procedure TMoneyDBCheckBox.DataChange(Sender: TObject); begin Checked:=GetFieldChecked; end; procedure TMoneyDBCheckBox.UpdateData(Sender: TObject); var Pos: Integer; S: string; begin if FDataLink.Field.DataType = ftBoolean then FDataLink.Field.AsBoolean := Checked else begin if Checked then S := FValueCheck else S := FValueUncheck; Pos := 1; FDataLink.Field.Text := ExtractFieldName(S, Pos); end; end; function TMoneyDBCheckBox.ValueMatch(const ValueList, Value: string): Boolean; var Pos: Integer; begin Result := False; Pos := 1; while Pos <= Length(ValueList) do if AnsiCompareText(ExtractFieldName(ValueList, Pos), Value) = 0 then begin Result := True; Break; end; end; procedure TMoneyDBCheckBox.Click; begin if FDataLink.Edit then begin inherited Click; FDataLink.Modified; end; end; function TMoneyDBCheckBox.GetDataSource: TDataSource; begin Result := FDataLink.DataSource; end; procedure TMoneyDBCheckBox.SetDataSource(Value: TDataSource); begin FDataLink.DataSource := Value; if Value <> nil then Value.FreeNotification(Self); end; function TMoneyDBCheckBox.GetDataField: string; begin Result := FDataLink.FieldName; end; procedure TMoneyDBCheckBox.SetDataField(const Value: string); begin FDataLink.FieldName := Value; end; function TMoneyDBCheckBox.GetReadOnly: Boolean; begin Result := FDataLink.ReadOnly; end; procedure TMoneyDBCheckBox.SetReadOnly(Value: Boolean); begin FDataLink.ReadOnly := Value; end; function TMoneyDBCheckBox.GetField: TField; begin Result := FDataLink.Field; end; procedure TMoneyDBCheckBox.KeyPress(var Key: Char); begin inherited KeyPress(Key); case Key of #8, ' ': FDataLink.Edit; #27: FDataLink.Reset; end; end; procedure TMoneyDBCheckBox.SetValueCheck(const Value: string); begin FValueCheck := Value; DataChange(Self); end; procedure TMoneyDBCheckBox.SetValueUncheck(const Value: string); begin FValueUncheck := Value; DataChange(Self); end; procedure TMoneyDBCheckBox.CMExit(var Message: TCMExit); begin try FDataLink.UpdateRecord; except SetFocus; raise; end; inherited; end; procedure TMoneyDBCheckBox.CMGetDataLink(var Message: TMessage); begin Message.Result := Integer(FDataLink); end; //////////////////////////////////////////////////// procedure TMoneyDataSourceLink.ActiveChanged; begin if FDBLookupControl <> nil then FDBLookupControl.DataLinkActiveChanged; end; procedure TMoneyDataSourceLink.RecordChanged(Field: TField); begin if FDBLookupControl <> nil then FDBLookupControl.DataLinkRecordChanged(Field); end; procedure TMoneyDataSourceLink.FocusControl(Field: TFieldRef); begin if (Field^ <> nil) and (Field^ = FDBLookupControl.Field) and (FDBLookupControl <> nil) and FDBLookupControl.CanFocus then begin Field^ := nil; FDBLookupControl.SetFocus; end; end; { TMoneySourceLink } procedure TMoneySourceLink.ActiveChanged; begin if FDBLookupControl <> nil then FDBLookupControl.ListLinkActiveChanged; end; procedure TMoneySourceLink.DataSetChanged; begin if FDBLookupControl <> nil then FDBLookupControl.ListLinkDataChanged; end; { TMoneyDBLookupControl } function VarEquals(const V1, V2: Variant): Boolean; begin Result := False; try Result := V1 = V2; except end; end; var SearchTickCount: Integer = 0; constructor TMoneyDBLookupControl.Create(AOwner: TComponent); begin inherited Create(AOwner); FHeight:=15; if NewStyleControls then ControlStyle := [csOpaque] else ControlStyle := [csOpaque, csFramed]; ParentColor := False; TabStop := True; FLookupSource := TDataSource.Create(Self); FDataLink := TMoneyDataSourceLink.Create; FDataLink.FDBLookupControl := Self; FListLink := TMoneySourceLink.Create; FListLink.FDBLookupControl := Self; FListFields := TList.Create; FKeyValue := Null; end; destructor TMoneyDBLookupControl.Destroy; begin FListFields.Free; FListLink.FDBLookupControl := nil; FListLink.Free; FDataLink.FDBLookupControl := nil; FDataLink.Free; inherited Destroy; end; function TMoneyDBLookupControl.CanModify: Boolean; begin Result := FListActive and not ReadOnly and ((FDataLink.DataSource = nil) or (FMasterField <> nil) and FMasterField.CanModify); end; procedure TMoneyDBLookupControl.CheckNotCircular; begin if FDataLink.Active and FDataLink.DataSet.IsLinkedTo(ListSource) then DatabaseError(SCircularDataLink); if FListLink.Active and FListLink.DataSet.IsLinkedTo(DataSource) then DatabaseError(SCircularDataLink); end; procedure TMoneyDBLookupControl.CheckNotLookup; begin if FLookupMode then DatabaseError(SPropDefByLookup); if FDataLink.DataSourceFixed then DatabaseError(SDataSourceFixed); end; procedure TMoneyDBLookupControl.DataLinkActiveChanged; begin FDataField := nil; FMasterField := nil; if FDataLink.Active and (FDataFieldName <> '') then begin CheckNotCircular; FDataField := GetFieldProperty(FDataLink.DataSet, Self, FDataFieldName); FMasterField := FDataField; end; SetLookupMode((FDataField <> nil) and (FDataField.FieldKind = fkLookup)); DataLinkRecordChanged(nil); end; procedure TMoneyDBLookupControl.DataLinkRecordChanged(Field: TField); begin if (Field = nil) or (Field = FMasterField) then if FMasterField <> nil then SetKeyValue(FMasterField.Value) else SetKeyValue(Null); end; function TMoneyDBLookupControl.GetBorderSize: Integer; var Params: TCreateParams; R: TRect; begin CreateParams(Params); SetRect(R, 0, 0, 0, 0); AdjustWindowRectEx(R, Params.Style, False, Params.ExStyle); Result := R.Bottom - R.Top; end; function TMoneyDBLookupControl.GetDataSource: TDataSource; begin Result := FDataLink.DataSource; end; function TMoneyDBLookupControl.GetKeyFieldName: string; begin if FLookupMode then Result := '' else Result := FKeyFieldName; end; function TMoneyDBLookupControl.GetListSource: TDataSource; begin if FLookupMode then Result := nil else Result := FListLink.DataSource; end; function TMoneyDBLookupControl.GetReadOnly: Boolean; begin Result := FDataLink.ReadOnly; end; function TMoneyDBLookupControl.GetTextHeight: Integer; begin Result := FHeight; end; procedure TMoneyDBLookupControl.KeyValueChanged; begin end; procedure TMoneyDBLookupControl.ListLinkActiveChanged; var DataSet: TDataSet; ResultField: TField; begin FListActive := False; FKeyField := nil; FListField := nil; FListFields.Clear; if FListLink.Active and (FKeyFieldName <> '') then begin CheckNotCircular; DataSet := FListLink.DataSet; FKeyField := GetFieldProperty(DataSet, Self, FKeyFieldName); try DataSet.GetFieldList(FListFields, FListFieldName); except DatabaseErrorFmt(SFieldNotFound, [Self.Name, FListFieldName]); end; if FLookupMode then begin ResultField := GetFieldProperty(DataSet, Self, FDataField.LookupResultField); if FListFields.IndexOf(ResultField) < 0 then FListFields.Insert(0, ResultField); FListField := ResultField; end else begin if FListFields.Count = 0 then FListFields.Add(FKeyField); if (FListFieldIndex >= 0) and (FListFieldIndex < FListFields.Count) then FListField := FListFields[FListFieldIndex] else FListField := FListFields[0]; end; FListActive := True; end; end; procedure TMoneyDBLookupControl.ListLinkDataChanged; begin end; function TMoneyDBLookupControl.LocateKey: Boolean; begin Result := False; try if not VarIsNull(FKeyValue) and FListLink.DataSet.Locate(FKeyFieldName, FKeyValue, []) then Result := True; except end; end; procedure TMoneyDBLookupControl.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if Operation = opRemove then begin if (FDataLink <> nil) and (AComponent = DataSource) then DataSource := nil; if (FListLink <> nil) and (AComponent = ListSource) then ListSource := nil; end; end; procedure TMoneyDBLookupControl.ProcessSearchKey(Key: Char); var TickCount: Integer; S: string; begin if (FListField <> nil) and (FListField.FieldKind = fkData) and (FListField.DataType = ftString) then case Key of #8, #27: FSearchText := ''; #32..#255: if CanModify then begin TickCount := GetTickCount; if TickCount - SearchTickCount > 2000 then FSearchText := ''; SearchTickCount := TickCount; if Length(FSearchText) < 32 then begin S := FSearchText + Key; if FListLink.DataSet.Locate(FListField.FieldName, S, [loCaseInsensitive, loPartialKey]) then begin SelectKeyValue(FKeyField.Value); FSearchText := S; end; end; end; end; end; procedure TMoneyDBLookupControl.SelectKeyValue(const Value: Variant); begin if FMasterField <> nil then begin if FDataLink.Edit then FMasterField.Value := Value; end else SetKeyValue(Value); Repaint; Click; end; procedure TMoneyDBLookupControl.SetDataFieldName(const Value: string); begin if FDataFieldName <> Value then begin FDataFieldName := Value; DataLinkActiveChanged; end; end; procedure TMoneyDBLookupControl.SetDataSource(Value: TDataSource); begin FDataLink.DataSource := Value; if Value <> nil then Value.FreeNotification(Self); end; procedure TMoneyDBLookupControl.SetKeyFieldName(const Value: string); begin CheckNotLookup; if FKeyFieldName <> Value then begin FKeyFieldName := Value; ListLinkActiveChanged; end; end; procedure TMoneyDBLookupControl.SetKeyValue(const Value: Variant); begin if not VarEquals(FKeyValue, Value) then begin FKeyValue := Value; KeyValueChanged; end; end; procedure TMoneyDBLookupControl.SetListFieldName(const Value: string); begin if FListFieldName <> Value then begin FListFieldName := Value; ListLinkActiveChanged; end; end; procedure TMoneyDBLookupControl.SetListSource(Value: TDataSource); begin CheckNotLookup; FListLink.DataSource := Value; if Value <> nil then Value.FreeNotification(Self); end; procedure TMoneyDBLookupControl.SetLookupMode(Value: Boolean); begin if FLookupMode <> Value then if Value then begin FMasterField := GetFieldProperty(FDataField.DataSet, Self, FDataField.KeyFields); FLookupSource.DataSet := FDataField.LookupDataSet; FKeyFieldName := FDataField.LookupKeyFields; FLookupMode := True; FListLink.DataSource := FLookupSource; end else begin FListLink.DataSource := nil; FLookupMode := False; FKeyFieldName := ''; FLookupSource.DataSet := nil; FMasterField := FDataField; end; end; procedure TMoneyDBLookupControl.SetReadOnly(Value: Boolean); begin FDataLink.ReadOnly := Value; end; procedure TMoneyDBLookupControl.SetTextHeight(Value :Integer); begin if FHeight<>Value then begin FHeight:=Value; Repaint; end; end; procedure TMoneyDBLookupControl.WMGetDlgCode(var Message: TMessage); begin Message.Result := DLGC_WANTARROWS or DLGC_WANTCHARS; end; procedure TMoneyDBLookupControl.WMKillFocus(var Message: TMessage); begin FFocused := False; Inherited; Invalidate; end; procedure TMoneyDBLookupControl.WMSetFocus(var Message: TMessage); begin if FListActive and Enabled then FFocused := True; Inherited; Invalidate; end; { TMoneyDBLookupListBox } constructor TMoneyDBLookupListBox.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle + [csDoubleClicks]; Width := 121; Color:=$00E0F0F0; FSelectColor:=$009EE0F1; FBorderColor:=$00BFCFCF; FHighLightColor:=clBlack; FSecondColor:=$00E0F0F0; FBorderStyle := bsSingle; RowCount := 7; end; procedure TMoneyDBLookupListBox.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params do if FBorderStyle = bsSingle then if NewStyleControls and Ctl3D then ExStyle := ExStyle or WS_EX_CLIENTEDGE else Style := Style or WS_BORDER; end; procedure TMoneyDBLookupListBox.CreateWnd; begin inherited CreateWnd; UpdateScrollBar; end; function TMoneyDBLookupListBox.GetKeyIndex: Integer; var FieldValue: Variant; begin if not VarIsNull(FKeyValue) then for Result := 0 to FRecordCount - 1 do begin FListLink.ActiveRecord := Result; FieldValue := FKeyField.Value; FListLink.ActiveRecord := FRecordIndex; if VarEquals(FieldValue, FKeyValue) then Exit; end; Result := -1; end; procedure TMoneyDBLookupListBox.KeyDown(var Key: Word; Shift: TShiftState); var Delta, KeyIndex: Integer; begin inherited KeyDown(Key, Shift); if CanModify then begin Delta := 0; case Key of VK_UP, VK_LEFT: Delta := -1; VK_DOWN, VK_RIGHT: Delta := 1; VK_PRIOR: Delta := 1 - FRowCount; VK_NEXT: Delta := FRowCount - 1; VK_HOME: Delta := -Maxint; VK_END: Delta := Maxint; end; if Delta <> 0 then begin FSearchText := ''; if Delta = -Maxint then FListLink.DataSet.First else if Delta = Maxint then FListLink.DataSet.Last else begin KeyIndex := GetKeyIndex; if KeyIndex >= 0 then FListLink.DataSet.MoveBy(KeyIndex - FRecordIndex) else begin KeyValueChanged; Delta := 0; end; FListLink.DataSet.MoveBy(Delta); end; SelectCurrent; end; end; end; procedure TMoneyDBLookupListBox.KeyPress(var Key: Char); begin inherited KeyPress(Key); ProcessSearchKey(Key); end; procedure TMoneyDBLookupListBox.KeyValueChanged; begin if FListActive and not FLockPosition then if not LocateKey then FListLink.DataSet.First; if FListField <> nil then FSelectedItem := FListField.DisplayText else FSelectedItem := ''; end; procedure TMoneyDBLookupListBox.ListLinkActiveChanged; begin try inherited; finally if FListActive then KeyValueChanged else ListLinkDataChanged; end; end; procedure TMoneyDBLookupListBox.ListLinkDataChanged; begin if FListActive then begin FRecordIndex := FListLink.ActiveRecord; FRecordCount := FListLink.RecordCount; FKeySelected := not VarIsNull(FKeyValue) or not FListLink.DataSet.BOF; end else begin FRecordIndex := 0; FRecordCount := 0; FKeySelected := False; end; if HandleAllocated then begin UpdateScrollBar; Invalidate; end; end; procedure TMoneyDBLookupListBox.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Button = mbLeft then begin FSearchText := ''; if not FPopup then begin SetFocus; if not FFocused then Exit; end; if CanModify then if ssDouble in Shift then begin if FRecordIndex = Y div GetTextHeight then DblClick; end else begin MouseCapture := True; FTracking := True; SelectItemAt(X, Y); end; end; inherited MouseDown(Button, Shift, X, Y); end; procedure TMoneyDBLookupListBox.MouseMove(Shift: TShiftState; X, Y: Integer); begin if FTracking then begin SelectItemAt(X, Y); FMousePos := Y; TimerScroll; end; inherited MouseMove(Shift, X, Y); end; procedure TMoneyDBLookupListBox.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if FTracking then begin StopTracking; SelectItemAt(X, Y); end; inherited MouseUp(Button, Shift, X, Y); end; procedure TMoneyDBLookupListBox.Paint; var I, J, W, X, TextWidth, TextHeight, LastFieldIndex: Integer; S: string; R: TRect; Selected: Boolean; Field: TField; begin Canvas.Font := Font; TextWidth := Canvas.TextWidth('0'); TextHeight :=GetTextHeight; LastFieldIndex := FListFields.Count - 1; if ColorToRGB(Color) <> ColorToRGB(clBtnFace) then Canvas.Pen.Color := clBtnFace else Canvas.Pen.Color := clBtnShadow; for I := 0 to FRowCount - 1 do begin Canvas.Font.Color := Font.Color; if ((i mod 2) =1) then Canvas.Brush.Color :=FSecondColor else Canvas.Brush.Color :=Color; Selected := not FKeySelected and (I = 0); R.Top := I * TextHeight; R.Bottom := R.Top + TextHeight; if I < FRecordCount then begin FListLink.ActiveRecord := I; if not VarIsNull(FKeyValue) and VarEquals(FKeyField.Value, FKeyValue) then begin Canvas.Font.Color := FHighLightColor; Canvas.Brush.Color := FSelectColor; Selected := True; end; R.Right := 0; for J := 0 to LastFieldIndex do begin Field := FListFields[J]; if J < LastFieldIndex then W := Field.DisplayWidth * TextWidth + 4 else W := ClientWidth - R.Right; S := Field.DisplayText; X := 2; case Field.Alignment of taRightJustify: X := W - Canvas.TextWidth(S) - 3; taCenter: X := (W - Canvas.TextWidth(S)) div 2; end; R.Left := R.Right; R.Right := R.Right + W; Canvas.TextRect(R, R.Left + X, R.Top, S); {if J < LastFieldIndex then begin } Canvas.MoveTo(R.Right, R.Top); Canvas.LineTo(R.Right, R.Bottom); Inc(R.Right); if R.Right >= ClientWidth then Break; {end;} end; end; R.Left := 0; R.Right := ClientWidth; if I >= FRecordCount then Canvas.FillRect(R); {Draw Border} if FDrawBorder then begin Canvas.Pen.Color := FBorderColor; Canvas.MoveTo(R.Left,R.Bottom-1); Canvas.LineTo(R.Right,R.Bottom-1); end; if Selected and (FFocused or FPopup) then Canvas.DrawFocusRect(R); end; if FRecordCount <> 0 then FListLink.ActiveRecord := FRecordIndex; end; procedure TMoneyDBLookupListBox.SelectCurrent; begin FLockPosition := True; try SelectKeyValue(FKeyField.Value); finally FLockPosition := False; end; end; procedure TMoneyDBLookupListBox.SelectItemAt(X, Y: Integer); var Delta: Integer; begin if Y < 0 then Y := 0; if Y >= ClientHeight then Y := ClientHeight - 1; Delta := Y div GetTextHeight - FRecordIndex; FListLink.DataSet.MoveBy(Delta); SelectCurrent; end; procedure TMoneyDBLookupListBox.SetBorderStyle(Value: TBorderStyle); begin if FBorderStyle <> Value then begin FBorderStyle := Value; RecreateWnd; RowCount := RowCount; end; end; procedure TMoneyDBLookupListBox.SetDrawBorder(Value:Boolean); begin if FDrawBorder<>Value then begin FDrawBorder:=Value; Invalidate; end; end; procedure TMoneyDBLookupListBox.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); var BorderSize, TextHeight, Rows: Integer; begin BorderSize := GetBorderSize; TextHeight := GetTextHeight; Rows := (AHeight - BorderSize) div TextHeight; if Rows < 1 then Rows := 1; FRowCount := Rows; if FListLink.BufferCount <> Rows then begin FListLink.BufferCount := Rows; ListLinkDataChanged; end; {inherited SetBounds(ALeft, ATop, AWidth, Rows * TextHeight + BorderSize);} inherited SetBounds(ALeft, ATop, AWidth,AHeight); end; procedure TMoneyDBLookupListBox.SetRowCount(Value: Integer); begin if Value < 1 then Value := 1; if Value > 100 then Value := 100; Height := Value * GetTextHeight + GetBorderSize; end; procedure TMoneyDBLookupListBox.SetColor(Index:Integer; Value :TColor); begin case Index of 1:if FSelectColor<>Value then begin FSelectColor:=Value; Repaint; end; 2:if FHighLightColor<>Value then begin FHighLightColor:=Value; Repaint; end; 3:if FSecondColor<>Value then begin FSecondColor:=Value; Repaint; end; 4:if FBorderColor<>Value then begin FBorderColor:=Value; Repaint; end; end; end; procedure TMoneyDBLookupListBox.StopTimer; begin if FTimerActive then begin KillTimer(Handle, 1); FTimerActive := False; end; end; procedure TMoneyDBLookupListBox.StopTracking; begin if FTracking then begin StopTimer; FTracking := False; MouseCapture := False; end; end; procedure TMoneyDBLookupListBox.TimerScroll; var Delta, Distance, Interval: Integer; begin Delta := 0; Distance := 0; if FMousePos < 0 then begin Delta := -1; Distance := -FMousePos; end; if FMousePos >= ClientHeight then begin Delta := 1; Distance := FMousePos - ClientHeight + 1; end; if Delta = 0 then StopTimer else begin if FListLink.DataSet.MoveBy(Delta) <> 0 then SelectCurrent; Interval := 200 - Distance * 15; if Interval < 0 then Interval := 0; SetTimer(Handle, 1, Interval, nil); FTimerActive := True; end; end; procedure TMoneyDBLookupListBox.UpdateScrollBar; var Pos, Max: Integer; ScrollInfo: TScrollInfo; begin Pos := 0; Max := 0; if FRecordCount = FRowCount then begin Max := 4; if not FListLink.DataSet.BOF then if not FListLink.DataSet.EOF then Pos := 2 else Pos := 4; end; ScrollInfo.cbSize := SizeOf(TScrollInfo); ScrollInfo.fMask := SIF_POS or SIF_RANGE; if not GetScrollInfo(Handle, SB_VERT, ScrollInfo) or (ScrollInfo.nPos <> Pos) or (ScrollInfo.nMax <> Max) then begin ScrollInfo.nMin := 0; ScrollInfo.nMax := Max; ScrollInfo.nPos := Pos; SetScrollInfo(Handle, SB_VERT, ScrollInfo, True); end; end; procedure TMoneyDBLookupListBox.CMCtl3DChanged(var Message: TMessage); begin if NewStyleControls and (FBorderStyle = bsSingle) then begin RecreateWnd; RowCount := RowCount; end; inherited; end; procedure TMoneyDBLookupListBox.CMFontChanged(var Message: TMessage); begin inherited; Height := Height; end; procedure TMoneyDBLookupListBox.WMCancelMode(var Message: TMessage); begin StopTracking; inherited; end; procedure TMoneyDBLookupListBox.WMTimer(var Message: TMessage); begin TimerScroll; end; procedure TMoneyDBLookupListBox.WMVScroll(var Message: TWMVScroll); begin FSearchText := ''; with Message, FListLink.DataSet do case ScrollCode of SB_LINEUP: MoveBy(-FRecordIndex - 1); SB_LINEDOWN: MoveBy(FRecordCount - FRecordIndex); SB_PAGEUP: MoveBy(-FRecordIndex - FRecordCount + 1); SB_PAGEDOWN: MoveBy(FRecordCount - FRecordIndex + FRecordCount - 2); SB_THUMBPOSITION: begin case Pos of 0: First; 1: MoveBy(-FRecordIndex - FRecordCount + 1); 2: Exit; 3: MoveBy(FRecordCount - FRecordIndex + FRecordCount - 2); 4: Last; end; end; SB_BOTTOM: Last; SB_TOP: First; end; end; { TXPopupDataList } constructor TMoneyPopupDataList.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle + [csNoDesignVisible, csReplicatable]; FPopup := True; end; procedure TMoneyPopupDataList.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params do begin Style := WS_POPUP or WS_BORDER; ExStyle := WS_EX_TOOLWINDOW; WindowClass.Style := CS_SAVEBITS; end; end; procedure TMoneyPopupDataList.WMMouseActivate(var Message: TMessage); begin Message.Result := MA_NOACTIVATE; end; { TMoneyDBLookupComboBox } constructor TMoneyDBLookupComboBox.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle + [csReplicatable]; Width := 145; Height := 0; ParentCtl3D:=False; Ctl3D:=False; FBitmapDownBlack:=TBitmap.Create; FBitmapDownBlack.Transparent:=True; FBitmapDownBlack.LoadFromResourceName(hInstance,'MSPIN_DOWNBLACK'); FBitmapDownWhite:=TBitmap.Create; FBitmapDownWhite.Transparent:=True; FBitmapDownWhite.LoadFromResourceName(hInstance,'MSPIN_DOWNWHITE'); FDataList := TMoneyPopupDataList.Create(Self); FDataList.SecondColor:=Color; FDataList.Visible := False; FDataList.Parent := Self; FDataList.OnMouseUp := ListMouseUp; FButtonWidth := GetSystemMetrics(SM_CXVSCROLL)+1; FDropDownRows := 7; end; destructor TMoneyDBLookupComboBox.Destroy; begin FBitmapDownBlack.Free; FBitmapDownWhite.Free; inherited Destroy; end; procedure TMoneyDBLookupComboBox.CloseUp(Accept: Boolean); var ListValue: Variant; begin if FListVisible then begin if GetCapture <> 0 then SendMessage(GetCapture, WM_CANCELMODE, 0, 0); ListValue := FDataList.KeyValue; SetWindowPos(FDataList.Handle, 0, 0, 0, 0, 0, SWP_NOZORDER or SWP_NOMOVE or SWP_NOSIZE or SWP_NOACTIVATE or SWP_HIDEWINDOW); FListVisible := False; FDataList.ListSource := nil; Invalidate; FSearchText := ''; if Accept and CanModify then SelectKeyValue(ListValue); if Assigned(FOnCloseUp) then FOnCloseUp(Self); end; end; procedure TMoneyDBLookupComboBox.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params do if NewStyleControls and Ctl3D then ExStyle := ExStyle or WS_EX_CLIENTEDGE else Style := Style or WS_BORDER; end; procedure TMoneyDBLookupComboBox.DropDown; var P: TPoint; I, Y: Integer; S: string; begin if not FListVisible and FListActive then begin if Assigned(FOnDropDown) then FOnDropDown(Self); FDataList.Color := Color; FDataList.Font := Font; if FDropDownWidth > 0 then FDataList.Width := FDropDownWidth else FDataList.Width := Width; FDataList.ReadOnly := not CanModify; FDataList.RowCount := FDropDownRows; FDataList.KeyField := FKeyFieldName; for I := 0 to FListFields.Count - 1 do S := S + TField(FListFields[I]).FieldName + ';'; FDataList.ListField := S; FDataList.ListFieldIndex := FListFields.IndexOf(FListField); FDataList.ListSource := FListLink.DataSource; FDataList.KeyValue := KeyValue; P := Parent.ClientToScreen(Point(Left, Top)); Y := P.Y + Height; if Y + FDataList.Height > Screen.Height then Y := P.Y - FDataList.Height; case FDropDownAlign of daRight: Dec(P.X, FDataList.Width - Width); daCenter: Dec(P.X, (FDataList.Width - Width) div 2); end; SetWindowPos(FDataList.Handle, HWND_TOP, P.X, Y, 0, 0, SWP_NOSIZE or SWP_NOACTIVATE or SWP_SHOWWINDOW); FListVisible := True; Repaint; end; end; procedure TMoneyDBLookupComboBox.KeyDown(var Key: Word; Shift: TShiftState); var Delta: Integer; begin inherited KeyDown(Key, Shift); if FListActive and ((Key = VK_UP) or (Key = VK_DOWN)) then if ssAlt in Shift then begin if FListVisible then CloseUp(True) else DropDown; Key := 0; end else if not FListVisible then begin if not LocateKey then FListLink.DataSet.First else begin if Key = VK_UP then Delta := -1 else Delta := 1; FListLink.DataSet.MoveBy(Delta); end; SelectKeyValue(FKeyField.Value); Key := 0; end; if (Key <> 0) and FListVisible then FDataList.KeyDown(Key, Shift); end; procedure TMoneyDBLookupComboBox.KeyPress(var Key: Char); begin inherited KeyPress(Key); if FListVisible then if Key in [#13, #27] then CloseUp(Key = #13) else FDataList.KeyPress(Key) else ProcessSearchKey(Key); end; procedure TMoneyDBLookupComboBox.KeyValueChanged; begin if FLookupMode then begin FText := FDataField.DisplayText; FAlignment := FDataField.Alignment; end else if FListActive then begin FAlignment := FListField.Alignment; if FAlwaysShow then FText := FListField.DisplayText else begin if LocateKey then FText := FListField.DisplayText else FText:=''; end; end else begin FText := ''; FAlignment := taLeftJustify; end; Invalidate; end; procedure TMoneyDBLookupComboBox.ListLinkActiveChanged; begin inherited; KeyValueChanged; end; {Added 12/16/98} procedure TMoneyDBLookupComboBox.ListLinkDataChanged; begin inherited; if not (Assigned(DataSource) or Assigned(Field)) then begin FText := FListField.DisplayText; Invalidate; end; end; procedure TMoneyDBLookupComboBox.SetAlwaysShow(Value:Boolean); begin if FAlwaysShow<>Value then begin FAlwaysShow:=Value; KeyValueChanged; end; end; function TMoneyDBLookupComboBox.GetColor(Index:Integer):TColor; begin Case Index of 1:result:=FDataList.FSecondColor; 2:result:=FDataList.FSelectColor; 3:result:=FDataList.FHighLightColor; else result:=Color; end; end; procedure TMoneyDBLookupComboBox.SetColor(Index:Integer; Value:TColor); begin case Index of 1:FDataList.SecondColor:=Value; 2:FDataList.SelectColor:=Value; 3:FDataList.HighLightColor:=Value; end; end; procedure TMoneyDBLookupComboBox.ListMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Button = mbLeft then CloseUp(PtInRect(FDataList.ClientRect, Point(X, Y))); end; procedure TMoneyDBLookupComboBox.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if Button = mbLeft then begin if FListActive then SetFocus; if not FFocused then Exit; if FListVisible then CloseUp(False) else if FListActive then begin MouseCapture := True; FTracking := True; TrackButton(X, Y); DropDown; end; end; inherited MouseDown(Button, Shift, X, Y); end; procedure TMoneyDBLookupComboBox.MouseMove(Shift: TShiftState; X, Y: Integer); var ListPos: TPoint; MousePos: TSmallPoint; begin if FTracking then begin TrackButton(X, Y); if FListVisible then begin ListPos := FDataList.ScreenToClient(ClientToScreen(Point(X, Y))); if PtInRect(FDataList.ClientRect, ListPos) then begin StopTracking; MousePos := PointToSmallPoint(ListPos); SendMessage(FDataList.Handle, WM_LBUTTONDOWN, 0, Integer(MousePos)); Exit; end; end; end; inherited MouseMove(Shift, X, Y); end; procedure TMoneyDBLookupComboBox.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin StopTracking; inherited MouseUp(Button, Shift, X, Y); end; procedure TMoneyDBLookupComboBox.Paint; var W, X,L,T: Integer; Text: string; Alignment: TAlignment; Selected: Boolean; R: TRect; begin Canvas.Font := Font; Canvas.Brush.Color := Color; Selected := FFocused and not FListVisible and not (csPaintCopy in ControlState); if Selected then begin Canvas.Font.Color := clHighlightText; Canvas.Brush.Color := clHighlight; end; if (csPaintCopy in ControlState) and (FDataField <> nil) then begin Text := FDataField.DisplayText; Alignment := FDataField.Alignment; end else begin Text := FText; Alignment := FAlignment; end; W := ClientWidth - FButtonWidth; X := 2; case Alignment of taRightJustify: X := W - Canvas.TextWidth(Text) - 3; taCenter: X := (W - Canvas.TextWidth(Text)) div 2; end; SetRect(R, 1, 1, W - 1, ClientHeight - 1); Canvas.TextRect(R, X, 2, Text); if Selected then Canvas.DrawFocusRect(R); SetRect(R, W, 0, ClientWidth, ClientHeight); if not FListActive then Canvas.Brush.Color:=clBtnFace else if FPressed then Canvas.Brush.Color:=clBlack else Canvas.Brush.Color:=clMoneybtnFace; Canvas.FillRect(R); Canvas.Brush.Color:=clBlack; Canvas.MoveTo(R.Left,R.Top); Canvas.LineTo(R.Left,R.Bottom); L:=R.Left+(((R.Right-R.Left) div 2)-(FBitmapDownBlack.Width div 2)); T:=R.Top+(Height-FBitmapDownBlack.Height) div 2; if Ctl3D then T:=T-2 else T:=T-1; if FHasMouse and FListActive then Canvas.Draw(L,T,FBitmapDownWhite) else Canvas.Draw(L,T,FBitmapDownBlack); end; procedure TMoneyDBLookupComboBox.CMMouseEnter(var Message: TMessage); begin inherited; FHasMouse:=True; Invalidate; end; procedure TMoneyDBLookupComboBox.CMMouseLeave(var Message: TMessage); begin inherited; FHasMouse:=False; Invalidate; end; procedure TMoneyDBLookupComboBox.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); begin inherited SetBounds(ALeft, ATop, AWidth, GetTextHeight + GetBorderSize + 4); end; procedure TMoneyDBLookupComboBox.StopTracking; begin if FTracking then begin TrackButton(-1, -1); FTracking := False; MouseCapture := False; end; end; procedure TMoneyDBLookupComboBox.TrackButton(X, Y: Integer); var NewState: Boolean; begin NewState := PtInRect(Rect(ClientWidth - FButtonWidth, 0, ClientWidth, ClientHeight), Point(X, Y)); if FPressed <> NewState then begin FPressed := NewState; Repaint; end; end; procedure TMoneyDBLookupComboBox.CMCancelMode(var Message: TCMCancelMode); begin if (Message.Sender <> Self) and (Message.Sender <> FDataList) then CloseUp(False); end; procedure TMoneyDBLookupComboBox.CMCtl3DChanged(var Message: TMessage); begin if NewStyleControls then begin RecreateWnd; Height := 0; end; inherited; end; procedure TMoneyDBLookupComboBox.CMFontChanged(var Message: TMessage); begin inherited; Height := 0; end; procedure TMoneyDBLookupComboBox.CMGetDataLink(var Message: TMessage); begin Message.Result := Integer(FDataLink); end; procedure TMoneyDBLookupComboBox.WMCancelMode(var Message: TMessage); begin StopTracking; inherited; end; procedure TMoneyDBLookupComboBox.WMKillFocus(var Message: TWMKillFocus); begin inherited; CloseUp(False); end; constructor TCustomMoneyDBComboBox.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle + [csReplicatable]; FDataLink := TFieldDataLink.Create; FDataLink.Control := Self; FDataLink.OnDataChange := DataChange; FDataLink.OnUpdateData := UpdateData; FDataLink.OnEditingChange := EditingChange; FPaintControl := TPaintControl.Create(Self, 'COMBOBOX'); FValues := TStringList.Create; TStringList(FValues).OnChange := ValuesChanged; EnableValues := False; end; destructor TCustomMoneyDBComboBox.Destroy; begin FPaintControl.Free; FDataLink.Free; FDataLink := nil; TStringList(FValues).OnChange := nil; FValues.Free; inherited Destroy; end; procedure TCustomMoneyDBComboBox.Loaded; begin inherited Loaded; if (csDesigning in ComponentState) then DataChange(Self); end; procedure TCustomMoneyDBComboBox.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (FDataLink <> nil) and (AComponent = DataSource) then DataSource := nil; end; procedure TCustomMoneyDBComboBox.CreateWnd; begin inherited CreateWnd; SetEditReadOnly; end; procedure TCustomMoneyDBComboBox.DataChange(Sender: TObject); begin if DroppedDown then Exit; if FDataLink.Field <> nil then SetComboText(FDataLink.Field.Text) else if csDesigning in ComponentState then SetComboText(Name) else SetComboText(''); end; procedure TCustomMoneyDBComboBox.UpdateData(Sender: TObject); begin FDataLink.Field.Text := GetComboText; end; procedure TCustomMoneyDBComboBox.ValuesChanged(Sender: TObject); begin if FEnableValues then DataChange(Self); end; procedure TCustomMoneyDBComboBox.SetComboText(const Value: string); var I: Integer; Redraw: Boolean; begin if Value <> GetComboText then begin if inherited Style <> csDropDown then begin Redraw := (inherited Style <> csSimple) and HandleAllocated; if Redraw then SendMessage(Handle, WM_SETREDRAW, 0, 0); try if Value = '' then I := -1 else if FEnableValues then I := Values.IndexOf(Value) else I := Items.IndexOf(Value); if I >= Items.Count then I := -1; ItemIndex := I; finally if Redraw then begin SendMessage(Handle, WM_SETREDRAW, 1, 0); Invalidate; end; end; if I >= 0 then Exit; end; if inherited Style in [csDropDown, csSimple] then Text := Value; end; end; function TCustomMoneyDBComboBox.GetComboText: string; var I: Integer; begin if (inherited Style in [csDropDown, csSimple]) and (not FEnableValues) then Result := Text else begin I := ItemIndex; if (I < 0) or (FEnableValues and (FValues.Count < I + 1)) then Result := '' else if FEnableValues then Result := FValues[I] else Result := Items[I]; end; end; procedure TCustomMoneyDBComboBox.SetEnableValues(Value: Boolean); begin if FEnableValues <> Value then begin if Value and (inherited Style in [csDropDown, csSimple]) then inherited Style := csDropDownList; FEnableValues := Value; DataChange(Self); end; end; procedure TCustomMoneyDBComboBox.SetValues(Value: TStrings); begin FValues.Assign(Value); end; procedure TCustomMoneyDBComboBox.Change; begin FDataLink.Edit; inherited Change; FDataLink.Modified; end; procedure TCustomMoneyDBComboBox.Click; begin FDataLink.Edit; inherited Click; FDataLink.Modified; end; function TCustomMoneyDBComboBox.GetDataSource: TDataSource; begin Result := FDataLink.DataSource; end; procedure TCustomMoneyDBComboBox.SetDataSource(Value: TDataSource); begin FDataLink.DataSource := Value; if Value <> nil then Value.FreeNotification(Self); end; function TCustomMoneyDBComboBox.GetDataField: string; begin Result := FDataLink.FieldName; end; procedure TCustomMoneyDBComboBox.SetDataField(const Value: string); begin FDataLink.FieldName := Value; end; function TCustomMoneyDBComboBox.GetReadOnly: Boolean; begin Result := FDataLink.ReadOnly; end; procedure TCustomMoneyDBComboBox.SetReadOnly(Value: Boolean); begin FDataLink.ReadOnly := Value; end; function TCustomMoneyDBComboBox.GetField: TField; begin Result := FDataLink.Field; end; procedure TCustomMoneyDBComboBox.KeyDown(var Key: Word; Shift: TShiftState); begin inherited KeyDown(Key, Shift); if Key in [VK_BACK, VK_DELETE, VK_UP, VK_DOWN, 32..255] then begin if not FDataLink.Edit and (Key in [VK_UP, VK_DOWN]) then Key := 0; end; end; procedure TCustomMoneyDBComboBox.KeyPress(var Key: Char); begin inherited KeyPress(Key); if (Key in [#32..#255]) and (FDataLink.Field <> nil) and not FDataLink.Field.IsValidChar(Key) then begin MessageBeep(0); Key := #0; end; case Key of ^H, ^V, ^X, #32..#255: FDataLink.Edit; #27: begin FDataLink.Reset; SelectAll; end; end; end; procedure TCustomMoneyDBComboBox.EditingChange(Sender: TObject); begin SetEditReadOnly; end; procedure TCustomMoneyDBComboBox.SetEditReadOnly; begin if (inherited Style in [csDropDown, csSimple]) and HandleAllocated then SendMessage(EditHandle, EM_SETREADONLY, Ord(not FDataLink.Editing), 0); end; procedure TCustomMoneyDBComboBox.WndProc(var Message: TMessage); begin if not (csDesigning in ComponentState) then case Message.Msg of WM_COMMAND: if TWMCommand(Message).NotifyCode = CBN_SELCHANGE then if not FDataLink.Edit then begin if inherited Style <> csSimple then PostMessage(Handle, CB_SHOWDROPDOWN, 0, 0); Exit; end; CB_SHOWDROPDOWN: if Message.WParam <> 0 then FDataLink.Edit else if not FDataLink.Editing then DataChange(Self); {Restore text} WM_CREATE, WM_WINDOWPOSCHANGED, CM_FONTCHANGED: FPaintControl.DestroyHandle; end; inherited WndProc(Message); end; procedure TCustomMoneyDBComboBox.ComboWndProc(var Message: TMessage; ComboWnd: HWnd; ComboProc: Pointer); begin if not (csDesigning in ComponentState) then case Message.Msg of WM_LBUTTONDOWN: if (inherited Style = csSimple) and (ComboWnd <> EditHandle) then if not FDataLink.Edit then Exit; end; inherited ComboWndProc(Message, ComboWnd, ComboProc); end; procedure TCustomMoneyDBComboBox.CMEnter(var Message: TCMEnter); begin inherited; if SysLocale.FarEast and FDataLink.CanModify then SendMessage(EditHandle, EM_SETREADONLY, Ord(False), 0); end; procedure TCustomMoneyDBComboBox.CMExit(var Message: TCMExit); begin try FDataLink.UpdateRecord; except SelectAll; SetFocus; raise; end; inherited; end; procedure TCustomMoneyDBComboBox.WMPaint(var Message: TWMPaint); var S: string; R: TRect; P: TPoint; Child: HWND; begin if csPaintCopy in ControlState then begin if FDataLink.Field <> nil then S := FDataLink.Field.Text else S := ''; if inherited Style = csDropDown then begin SendMessage(FPaintControl.Handle, WM_SETTEXT, 0, Longint(PChar(S))); SendMessage(FPaintControl.Handle, WM_PAINT, Message.DC, 0); Child := GetWindow(FPaintControl.Handle, GW_CHILD); if Child <> 0 then begin Windows.GetClientRect(Child, R); Windows.MapWindowPoints(Child, FPaintControl.Handle, R.TopLeft, 2); GetWindowOrgEx(Message.DC, P); SetWindowOrgEx(Message.DC, P.X - R.Left, P.Y - R.Top, nil); IntersectClipRect(Message.DC, 0, 0, R.Right - R.Left, R.Bottom - R.Top); SendMessage(Child, WM_PAINT, Message.DC, 0); end; end else begin SendMessage(FPaintControl.Handle, CB_RESETCONTENT, 0, 0); if Items.IndexOf(S) <> -1 then begin SendMessage(FPaintControl.Handle, CB_ADDSTRING, 0, Longint(PChar(S))); SendMessage(FPaintControl.Handle, CB_SETCURSEL, 0, 0); end; SendMessage(FPaintControl.Handle, WM_PAINT, Message.DC, 0); end; end else inherited; end; procedure TCustomMoneyDBComboBox.SetItems(Value: TStrings); begin Items.Assign(Value); DataChange(Self); end; procedure TCustomMoneyDBComboBox.SetStyle(Value: TComboboxStyle); begin if (Value <> csSimple) then begin if (Value = csDropDown) and FEnableValues then Value:=csDropDownList; inherited SetStyle(Value); end; end; procedure TCustomMoneyDBComboBox.SetComboStyle(Value:TMoneyComboStyle); begin if GetComboStyle<>Value then begin if Value=mcsDropDown then inherited Style:=csDropDown else inherited Style:=csDropDownList; end; end; function TCustomMoneyDBComboBox.GetComboStyle:TMoneyComboStyle; begin if inherited Style = csDropDown then result:=mcsDropDown else result:=mcsDropDownList; end; procedure TCustomMoneyDBComboBox.CMGetDatalink(var Message: TMessage); begin Message.Result := Integer(FDataLink); end; {MoneyDBComboBox} function TMoneyDBComboBox.ButtonRect:TRect; var ARect:TRect; begin GetWindowRect(Handle, ARect); OffsetRect(ARect, -ARect.Left, -ARect.Top); Inc(ARect.Left, ClientWidth - FButtonWidth); InflateRect(ARect, -1, -1); result:=ARect; end; procedure TMoneyDBComboBox.WMPaint(var Message: TWMPaint); var DC: HDC; PaintStruct: TPaintStruct; begin if Message.DC = 0 then DC := BeginPaint(Handle, PaintStruct) else DC := Message.DC; try if TComboBox(Self).Style <> csSimple then begin DrawButton(DC,ButtonRect); ExcludeClipRect(DC, ClientWidth - FButtonWidth , 1, ClientWidth-1, ClientHeight-1); end; PaintWindow(DC); DrawControlBorder(DC); finally if Message.DC = 0 then EndPaint(Handle, PaintStruct); end; end; procedure TMoneyDBComboBox.DrawControlBorder(DC: HDC); var ARect: TRect; BorderBrush, ConrolBrush: HBRUSH; begin BorderBrush := CreateSolidBrush(0); ConrolBrush := CreateSolidBrush(ColorToRGB(Color)); try GetWindowRect(Handle, ARect); OffsetRect(ARect, -ARect.Left, -ARect.Top); FrameRect(DC, ARect, BorderBrush); InflateRect(ARect, -1, -1); FrameRect(DC, ARect, ConrolBrush); finally DeleteObject(ConrolBrush); DeleteObject(BorderBrush); end; end; procedure TMoneyDBComboBox.DrawButton(DC: HDC; ARect:TRect); var BorderBrush, ButtonBrush: HBRUSH; X,Y,i:Integer; C:Integer; begin BorderBrush := CreateSolidBrush(0); if FDown then begin C:=0; i:=2; end else if FMouseInControl then begin C:=$009BA8A8; i:=2; end else begin C:=$009BA8A8; i:=1; end; ButtonBrush := CreateSolidBrush(ColorToRGB(C)); try FillRect(DC,ARect,ButtonBrush); try X:=ARect.Left+((ARect.Right-ARect.Left) div 2)-(FBitmaps[i].Width div 2)-1; Y:=ARect.Top+((ARect.Bottom-ARect.Top) div 2)-(FBitmaps[i].Height div 2); FCanvas.Handle:=DC; FCanvas.Draw(X,Y,FBitmaps[i]); finally FCanvas.Handle:=0; end; InflateRect(ARect,1,1); FrameRect(DC,ARect,BorderBrush); finally DeleteObject(ButtonBrush); DeleteObject(BorderBrush); end; end; constructor TMoneyDBComboBox.Create(AOwner:TComponent); const c:array[1..2] of string =('MSPIN_DOWNBLACK','MSPIN_DOWNWHITE'); var i:Integer; begin inherited Create(AOwner); FCanvas:=TCanvas.Create; for i:=1 to 2 do begin FBitmaps[i]:=TBitmap.Create; FBitmaps[i].LoadFromResourceName(hInstance,C[i]); FBitmaps[i].Transparent:=True; end; FButtonWidth := GetSystemMetrics(SM_CXVSCROLL)+2; end; destructor TMoneyDBComboBox.Destroy; var i:Integer; begin for i:=1 to 2 do FBitmaps[i].Free; FCanvas.Free; inherited Destroy; end; procedure TMoneyDBComboBox.UpdateTracking; var P: TPoint; begin if Enabled then begin GetCursorPos(P); FMouseInControl := not (FindDragTarget(P, True) = Self); if FMouseInControl then Perform(CM_MOUSELEAVE, 0, 0) else Perform(CM_MOUSEENTER, 0, 0); end; end; procedure TMoneyDBComboBox.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited MouseDown(Button, Shift, X, Y); if (Button = mbLeft) and Enabled then begin //if not Focused and TabStop then SetFocus; FDown := DroppedDown; InvalidateButton; end; end; procedure TMoneyDBComboBox.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin FDown:=False; UpdateTracking; inherited MouseUp(Button, Shift, X, Y); end; procedure TMoneyDBComboBox.MouseMove(Shift: TShiftState; X, Y: Integer); begin inherited MouseMove(Shift, X, Y); end; procedure TMoneyDBComboBox.MouseEnter; begin if not FMouseInControl and Enabled then begin FMouseInControl := True; InvalidateButton; end; end; procedure TMoneyDBComboBox.MouseLeave; begin if FMouseInControl and Enabled then begin FMouseInControl := False; FDown:=False; InvalidateButton; end; end; procedure TMoneyDBComboBox.CMMouseEnter(var Msg:TMessage); begin inherited; MouseEnter; end; procedure TMoneyDBComboBox.CMMouseLeave(var Msg:TMessage); begin inherited; MouseLeave; end; procedure TMoneyDBComboBox.CMEnabledChanged(var Message: TMessage); begin Repaint; inherited; end; procedure TMoneyDBComboBox.InvalidateButton; var ARect:TRect; begin if HandleAllocated then begin ARect:=ButtonRect; InvalidateRect(Handle,@ARect,True) end; end; {MoneyDBDateEdit} constructor TMoneyDBDateEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); FDataLink := TFieldDataLink.Create; FDataLink.Control := Self; FDataLink.OnDataChange := DataChange; FDataLink.OnUpdateData := UpdateData; end; destructor TMoneyDBDateEdit.Destroy; begin FDataLink.OnDataChange := nil; FDataLink.OnUpdateData := nil; FDataLink.Free; FDataLink:=nil; inherited Destroy; end; procedure TMoneyDBDateEdit.DataChange(Sender: TObject); begin if FDataLink.Field = nil then SetDate(0) else SetDate(FDataLink.Field.AsDateTime); end; procedure TMoneyDBDateEdit.UpdateData(Sender: TObject); var D: TDateTime; begin D := Self.Date; if (Text<>'') or (D <> 0) then FDataLink.Field.AsDateTime := D else FDataLink.Field.Clear; end; procedure TMoneyDBDateEdit.DoChange; begin if FDataLink.Edit then begin inherited DoChange; FDataLink.Modified; end; end; procedure TMoneyDBDateEdit.KeyPress(var Key: Char); begin inherited KeyPress(Key); case Key of #27: FDataLink.Reset; end; end; function TMoneyDBDateEdit.GetReadOnly: Boolean; begin Result := FDataLink.ReadOnly; end; procedure TMoneyDBDateEdit.SetReadOnly(Value: Boolean); begin FDataLink.ReadOnly := Value; inherited ReadOnly := Value; end; function TMoneyDBDateEdit.GetField: TField; begin Result := FDataLink.Field; end; function TMoneyDBDateEdit.GetDataField: string; begin Result := FDataLink.FieldName; end; function TMoneyDBDateEdit.GetDataSource: TDataSource; begin Result := FDataLink.DataSource; end; procedure TMoneyDBDateEdit.SetDataField(const Value: string); begin FDataLink.FieldName := Value; end; procedure TMoneyDBDateEdit.SetDataSource(Value: TDataSource); begin FDataLink.DataSource := Value; if Value <> nil then Value.FreeNotification(Self); end; procedure TMoneyDBDateEdit.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (FDataLink <> nil) and (AComponent = DataSource) then DataSource := nil; end; procedure TMoneyDBDateEdit.CMExit(var Message: TCMExit); begin try FDataLink.UpdateRecord; except SelectAll; if CanFocus then SetFocus; raise; end; inherited; end; procedure TMoneyDBDateEdit.CMGetDataLink(var Message: TMessage); begin Message.Result := Integer(FDataLink); end; {MoneyDBLinker} constructor TMoneyDBLinker.Create(AOwner: TComponent); begin inherited Create(AOwner); FDataLink :=TMoneyDBLinkerDataLink.Create(Self); end; destructor TMoneyDBLinker.Destroy; var i:Integer; begin FDataLink.Free; FDataLink := nil; for i:=9 downto 1 do FControls[i]:=nil; inherited Destroy; end; procedure TMoneyDBLinker.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) then begin if (FDataLink <> nil) and (AComponent = DataSource) then DataSource := nil; if (FControls[1] <> nil) and (AComponent = First) then First := nil; if (FControls[2] <> nil) and (AComponent = Prev) then Prev := nil; if (FControls[3] <> nil) and (AComponent = Next) then Next := nil; if (FControls[4] <> nil) and (AComponent = Last) then Last := nil; if (FControls[5] <> nil) and (AComponent = Insert) then Insert := nil; if (FControls[6] <> nil) and (AComponent = Delete) then Delete := nil; if (FControls[7] <> nil) and (AComponent = Edit) then Edit := nil; if (FControls[8] <> nil) and (AComponent = Save) then Save := nil; if (FControls[9] <> nil) and (AComponent = Cancel) then Cancel := nil; end; end; procedure TMoneyDBLinker.DataChanged; var UpEnable, DnEnable: Boolean; begin UpEnable := FDataLink.Active and not FDataLink.DataSet.BOF and not FDataLink.Editing; DnEnable := FDataLink.Active and not FDataLink.DataSet.EOF and not FDataLink.Editing; {First} if Assigned(FControls[1]) then FControls[1].Enabled:=UpEnable; {Next} if Assigned(FControls[2]) then FControls[2].Enabled:=UpEnable; {Prev} if Assigned(FControls[3]) then FControls[3].Enabled:=DnEnable; {Last} if Assigned(FControls[4]) then FControls[4].Enabled:=DnEnable; end; procedure TMoneyDBLinker.EditingChanged; var CanModify: Boolean; begin DataChanged; CanModify :=FDataLink.Active and FDataLink.DataSet.CanModify; {Insert} if Assigned(FControls[5]) then FControls[5].Enabled:= CanModify and not FDataLink.Editing; {Edit} if Assigned(FControls[7]) then FControls[7].Enabled:= CanModify and not FDataLink.Editing; {Save} if Assigned(FControls[8]) then FControls[8].Enabled:= CanModify and FDataLink.Editing; {Cancel} if Assigned(FControls[9]) then FControls[9].Enabled:= CanModify and FDataLink.Editing; {Delete} if Assigned(FControls[6]) then FControls[6].Enabled:= FDataLink.Active and FDataLink.DataSet.CanModify and not FDataLink.Editing and not (FDataLink.DataSet.BOF and FDataLink.DataSet.EOF); end; procedure TMoneyDBLinker.ActiveChanged; var i:Integer; begin if not (FDataLink.Active) then begin for i:=9 downto 1 do if Assigned(FControls[i]) then FControls[i].Enabled:=False; end else begin DataChanged; EditingChanged; end; end; procedure TMoneyDBLinker.SetDataSource(Value: TDataSource); begin FDataLink.DataSource := Value; if not (csLoading in ComponentState) then ActiveChanged; if Value <> nil then Value.FreeNotification(Self); end; function TMoneyDBLinker.GetDataSource: TDataSource; begin Result := FDataLink.DataSource; end; procedure TMoneyDBLinker.SetControl(Index: Integer; Value :TControl); begin FControls[Index] := Value; if Value <> nil then Value.FreeNotification(Self); end; procedure TMoneyDBLinker.Loaded; begin inherited Loaded; ActiveChanged; end; {TMoneyDBLinkerDataLink} constructor TMoneyDBLinkerDataLink.Create(AOwner: TMoneyDBLinker); begin inherited Create; FDBLinker:=AOwner; end; destructor TMoneyDBLinkerDataLink.Destroy; begin FDBLinker := nil; inherited Destroy; end; procedure TMoneyDBLinkerDataLink.EditingChanged; begin if FDBLinker <> nil then FDBLinker.EditingChanged; end; procedure TMoneyDBLinkerDataLink.DataSetChanged; begin if FDBLinker <> nil then FDBLinker.DataChanged; end; procedure TMoneyDBLinkerDataLink.ActiveChanged; begin if FDBLinker <> nil then FDBLinker.ActiveChanged; end; procedure Register; begin RegisterComponents('Money DB Controls', [TMoneyDBLinker, TMoneyDBCheckBox, TMoneyDBComboBox, TMoneyDBDateEdit, TMoneyDBLookupListBox, TMoneyDBLookupComboBox]); end; end.
unit DPM.Controls.AutoComplete; interface uses System.Classes, Winapi.Windows, Winapi.ShlObj, Winapi.ActiveX; type IACList = interface(IUnknown) ['{77A130B0-94FD-11D0-A544-00C04FD7d062}'] function Expand(pszExpand : POLESTR) : HResult; stdcall; end; const //options for IACList2 ACLO_NONE = 0; // don't enumerate anything ACLO_CURRENTDIR = 1; // enumerate current directory ACLO_MYCOMPUTER = 2; // enumerate MyComputer ACLO_DESKTOP = 4; // enumerate Desktop Folder ACLO_FAVORITES = 8; // enumerate Favorites Folder ACLO_FILESYSONLY = 16; // enumerate only the file system type IACList2 = interface(IACList) ['{470141a0-5186-11d2-bbb6-0060977b464c}'] function SetOptions(dwFlag : DWORD) : HResult; stdcall; function GetOptions(var pdwFlag : DWORD) : HResult; stdcall; end; IAutoComplete = interface(IUnknown) ['{00bb2762-6a77-11d0-a535-00c04fd7d062}'] function Init(hwndEdit : HWND; const punkACL : IUnknown; pwszRegKeyPath, pwszQuickComplete : POLESTR) : HResult; stdcall; function Enable(fEnable : BOOL) : HResult; stdcall; end; const //options for IAutoComplete2 ACO_NONE = 0; ACO_AUTOSUGGEST = $1; ACO_AUTOAPPEND = $2; ACO_SEARCH = $4; ACO_FILTERPREFIXES = $8; ACO_USETAB = $10; ACO_UPDOWNKEYDROPSLIST = $20; ACO_RTLREADING = $40; ACO_WORD_FILTER = $080; ACO_NOPREFIXFILTERING = $100; type IAutoComplete2 = interface(IAutoComplete) ['{EAC04BC0-3791-11d2-BB95-0060977B464C}'] function SetOptions(dwFlag : DWORD) : HResult; stdcall; function GetOptions(out pdwFlag : DWORD) : HResult; stdcall; end; IDelphiEnumString = interface(IEnumString) ['{D8C2C4C1-A8B6-449E-BE32-4317D3485027}'] function GetStrings : TStringList; property Strings : TStringList read GetStrings; end; TEnumString = class(TInterfacedObject, IDelphiEnumString, IEnumString) private type TPointerList = array[0..0] of Pointer; //avoid bug of Classes.pas declaration TPointerList = array of Pointer; var FStrings : TStringList; FCurrIndex : integer; protected //IEnumString function Next(celt : Longint; out elt; pceltFetched : PLongint) : HResult; stdcall; function Skip(celt : Longint) : HResult; stdcall; function Reset : HResult; stdcall; function Clone(out enm : IEnumString) : HResult; stdcall; //IDelphiEnumString function GetStrings : TStringList; public //VCL constructor Create; constructor CreateClone(const index : integer; const strings : TStrings); destructor Destroy; override; end; implementation { TEnumString } function TEnumString.Clone(out enm : IEnumString) : HResult; begin Result := E_NOTIMPL; //S_OK;// // enm := TEnumString.CreateClone(FCurrIndex, FStrings); Pointer(enm) := nil; end; constructor TEnumString.Create; begin inherited Create; FStrings := TStringList.Create; FCurrIndex := 0; end; constructor TEnumString.CreateClone(const index : integer; const strings : TStrings); begin Create; FStrings.Assign(strings); FCurrIndex := index; end; destructor TEnumString.Destroy; begin FStrings.Free; inherited; end; function TEnumString.GetStrings : TStringList; begin result := FStrings; end; function TEnumString.Next(celt : Integer; out elt; pceltFetched : PLongint) : HResult; var I : Integer; wStr : WideString; begin I := 0; while (I < celt) and (FCurrIndex < FStrings.Count) do begin wStr := FStrings[FCurrIndex]; TPointerList(elt)[I] := CoTaskMemAlloc(2 * (Length(wStr) + 1)); StringToWideChar(wStr, TPointerList(elt)[I], 2 * (Length(wStr) + 1)); Inc(I); Inc(FCurrIndex); end; if pceltFetched <> nil then pceltFetched^ := I; if I = celt then Result := S_OK else Result := S_FALSE; end; function TEnumString.Reset : HResult; begin FCurrIndex := 0; Result := S_OK; end; function TEnumString.Skip(celt : Integer) : HResult; begin if (FCurrIndex + celt) <= FStrings.Count then begin Inc(FCurrIndex, celt); Result := S_OK; end else begin FCurrIndex := FStrings.Count; Result := S_FALSE; end; end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [SOCIO] The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit SocioVO; {$mode objfpc}{$H+} interface uses VO, Classes, SysUtils, FGL, SocioDependenteVO, SocioParticipacaoSocietariaVO; type TSocioVO = class(TVO) private FID: Integer; FID_QUADRO_SOCIETARIO: Integer; FLOGRADOURO: String; FNUMERO: Integer; FCOMPLEMENTO: String; FBAIRRO: String; FMUNICIPIO: String; FUF: String; FCEP: String; FFONE: String; FCELULAR: String; FEMAIL: String; FPARTICIPACAO: Extended; FQUOTAS: Integer; FINTEGRALIZAR: Extended; FDATA_INGRESSO: TDateTime; FDATA_SAIDA: TDateTime; //Transientes FListaSocioDependenteVO : TListaSocioDependenteVO; FListaSocioParticipacaoSocietariaVO: TListaSocioParticipacaoSocietariaVO; published constructor Create; override; destructor Destroy; override; property Id: Integer read FID write FID; property IdQuadroSocietario: Integer read FID_QUADRO_SOCIETARIO write FID_QUADRO_SOCIETARIO; property Logradouro: String read FLOGRADOURO write FLOGRADOURO; property Numero: Integer read FNUMERO write FNUMERO; property Complemento: String read FCOMPLEMENTO write FCOMPLEMENTO; property Bairro: String read FBAIRRO write FBAIRRO; property Municipio: String read FMUNICIPIO write FMUNICIPIO; property Uf: String read FUF write FUF; property Cep: String read FCEP write FCEP; property Fone: String read FFONE write FFONE; property Celular: String read FCELULAR write FCELULAR; property Email: String read FEMAIL write FEMAIL; property Participacao: Extended read FPARTICIPACAO write FPARTICIPACAO; property Quotas: Integer read FQUOTAS write FQUOTAS; property Integralizar: Extended read FINTEGRALIZAR write FINTEGRALIZAR; property DataIngresso: TDateTime read FDATA_INGRESSO write FDATA_INGRESSO; property DataSaida: TDateTime read FDATA_SAIDA write FDATA_SAIDA; //Transientes property ListaSocioDependenteVO: TListaSocioDependenteVO read FListaSocioDependenteVO write FListaSocioDependenteVO; property ListaSocioParticipacaoSocietariaVO: TListaSocioParticipacaoSocietariaVO read FListaSocioParticipacaoSocietariaVO write FListaSocioParticipacaoSocietariaVO; end; TListaSocioVO = specialize TFPGObjectList<TSocioVO>; implementation constructor TSocioVO.Create; begin inherited; FListaSocioDependenteVO := TListaSocioDependenteVO.Create; FListaSocioParticipacaoSocietariaVO := TListaSocioParticipacaoSocietariaVO.Create; end; destructor TSocioVO.Destroy; begin FreeAndNil(FListaSocioDependenteVO); FreeAndNil(FListaSocioParticipacaoSocietariaVO); inherited; end; initialization Classes.RegisterClass(TSocioVO); finalization Classes.UnRegisterClass(TSocioVO); end.
unit uFormPassword; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, sSkinProvider, sButton, sEdit, sLabel; type TFormPassword = class(TForm) Edit1: TsEdit; Label1: TsLabel; Label2: TsLabel; Edit2: TsEdit; Button1: TsButton; Button2: TsButton; sSkinProvider1: TsSkinProvider; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } public { Public declarations } procedure StringToComponent(Component: TComponent; Value: string); end; //короче делаем так: //эта форма создается динамически(не фиг память занимать) ф-цией ShowPasswordForm() //на вход ф-ции передается режим работы формы. Если GetPassword = true //значит форма работает в режиме получения пароля. Название линии //должно быть передано в переменной pLineName и выведено пользователю //без возможности редактирования. Т.е. это режим при входе в существующую линию. //И 2й режим GetPassword = false. Это режим для создания линии //Форма читает название линии введенное пользователем и пароль. //При закрытии возвращает строку вида: //'"LineName" "Password"' FUNCTION ShowPasswordForm(GetPassword:boolean;pLineName: PChar; var ResultString: PChar):TModalResult; var FormPassword: TFormPassword; res: String; GetPasswordMode: boolean; implementation uses uFormMain, uPathBuilder; {$R *.DFM} procedure TFormPassword.StringToComponent(Component: TComponent; Value: string); var StrStream:TStringStream; ms: TMemoryStream; begin StrStream := TStringStream.Create(Value); try ms := TMemoryStream.Create; try ObjectTextToBinary(StrStream, ms); ms.position := 0; ms.ReadComponent(Component); finally ms.Free; end; finally StrStream.Free; end; end; FUNCTION ShowPasswordForm(GetPassword:boolean;pLineName: PChar;var ResultString: PChar):TModalResult; var //strlist:TStringList; si, sc:string; BEGIN GetPasswordMode := GetPassword; si := TPathBuilder.GetImagesFolderName(); //ExtractFilePath(Application.ExeName) + 'images\'; sc := TPathBuilder.GetComponentsFolderName();// ExtractFilePath(Application.ExeName) + 'Components\'; //strlist := TStringList.Create; //strlist.LoadFromFile(sc + 'FFormPassword.txt'); FormPassword := TFormPassword.Create(nil); //FormPassword.StringToComponent(FormPassword, strlist.text); FormPassword.Button2.Caption := fmInternational.Strings[I_CANCEL]; FormPassword.Label1.Caption := fmInternational.Strings[I_LINENAME]; FormPassword.Label2.Caption := fmInternational.Strings[I_PASSWORD]; if GetPasswordMode = true then begin FormPassword.Caption := fmInternational.Strings[I_INPUTPASSWORD];//'Введите пароль для входа в линию:'; FormPassword.Button1.Caption := fmInternational.Strings[I_COMING];//'Войти'; FormPassword.Edit1.ReadOnly := true; FormPassword.Edit1.Enabled := false; FormPassword.Edit1.Text := pLineName; FormPassword.Edit2.Text := ''; end else begin FormPassword.Caption := fmInternational.Strings[I_INPUTPASSANDLINENAME]; FormPassword.Button1.Caption := fmInternational.Strings[I_CREATE]; FormPassword.Edit1.Text := fmInternational.Strings[I_NEWLINE]; FormPassword.Edit2.Text := ''; end; FormPassword.ShowModal; ResultString := PChar(res); result := FormPassword.ModalResult; FormPassword.Destroy; END; procedure TFormPassword.Button1Click(Sender: TObject); begin if GetPasswordMode = true then begin res := '"' + FormPassword.Edit1.Text + '" ' + '"' + FormPassword.Edit2.Text + '"'; FormPassword.ModalResult := mrOk; end else begin if length(FormPassword.Edit1.Text) > 0 then begin res := '"' + FormPassword.Edit1.Text + '" ' + '"' + FormPassword.Edit2.Text + '"'; FormPassword.ModalResult := mrOk; end; end; end; procedure TFormPassword.Button2Click(Sender: TObject); begin FormPassword.Close; end; end.
unit CC95_Register; interface uses Classes, sysutils, DesignIntf, DesignEditors, typinfo, ComCtrls95; {$IFDEF ver90} //remove this line for explict D2 usage {$DEFINE delphi2} //Create .DCU for D2 {$ENDIF} //remove this line for explict D2 usage {$IFDEF ver110} //This is for BCB3 Do not remove! {$DEFINE delphi4} {$DEFINE BCB3} {$ENDIF} {$IFDEF ver120} //remove this line for explict D4 usage {$DEFINE delphi4} //Create .DCU for D4 {$ENDIF} //remove this line for explict D4 usage {$IFDEF ver130} {$DEFINE Delphi4} {$ENDIF} type TPage95ControlEditor = class(TComponentEditor) private procedure NewPage; procedure ChangePage(Forward: boolean); public function GetVerb(index: integer): string; override; function GetVerbCount: integer; override; procedure ExecuteVerb(index: integer); override; procedure Edit; override; end; procedure Register; implementation function TPage95ControlEditor.GetVerb(index: integer): string; begin case index of 0: result := 'New Page'; 1: result := 'Next Page'; 2: result := 'Previous Page'; end; end; function TPage95ControlEditor.GetVerbCount: integer; begin result := 3; end; procedure TPage95ControlEditor.Edit; var eventname: string; changeevent: TNotifyEvent; ppi: PPropInfo; pagecontrol: tpage95control; begin if component is ttab95sheet then pagecontrol := ttab95sheet(component).pagecontrol else pagecontrol := tpage95control(component); changeevent := pagecontrol.OnChange; if assigned(changeevent) then eventname := designer.getmethodname(tmethod(changeevent)) else begin eventname := pagecontrol.name + 'Change'; ppi := GetPropInfo(pagecontrol.classinfo, 'OnChange'); {$IFDEF delphi2} changeevent := tnotifyevent(designer.createmethod(eventname, gettypedata(ppi.proptype))); {$ELSE} changeevent := tnotifyevent(designer.createmethod(eventname, gettypedata(ppi.proptype^))); {$ENDIF} pagecontrol.onchange := changeevent; designer.modified; end; designer.showmethod(eventname); end; procedure TPage95ControlEditor.ExecuteVerb(index: integer); begin case index of 0: NewPage; 1: ChangePage(true); //Next Page 2: ChangePage(False); //Previous Page end; end; procedure TPage95ControlEditor.NewPage; begin end; procedure TPage95ControlEditor.ChangePage(forward: boolean); begin end; procedure Register; begin RegisterComponents('ConTEXT Components', [TTab95Control, TPage95Control]); RegisterClass(TTab95Sheet); RegisterComponentEditor(TPage95Control, TPage95ControlEditor); RegisterComponentEditor(TTab95Sheet, TPage95ControlEditor); end; end.
//****************************************************************************** // Пакет для редактирования записи // из таблицы Z_Current - зарплатные текущие выплаты // Параметры: AOwner - компонент от которого создается форма для редактирования // DB_Handle - база для подключения // AZControlFormStyle - тип формы: редактрирование, удаление, добавление, просмотр // AID - если добавление, то RMoving, иначе ID_Current //****************************************************************************** unit Current_ZarControl; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, ExtCtrls, cxMaskEdit, cxDropDownEdit, cxCalendar, cxTextEdit, cxButtonEdit, cxContainer, cxEdit, cxLabel, cxControls, cxGroupBox, StdCtrls, cxButtons, Registry, PackageLoad, DB, FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet, IBase, ZTypes, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, GlobalSpr, cxDBEdit, cxSpinEdit, cxMemo, Dates, cxCalc, FIBQuery, pFIBQuery, pFIBStoredProc, ZProc, ZMessages, ActnList, Unit_ZGlobal_Consts, Current_Dmodule, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxDBData, cxGridTableView, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridDBTableView, cxGrid, Unit_NumericConsts, dxStatusBar, Menus, CurrentCtrl_AutoSumma, CurrentCtrl_ByHours, CurrentCtrl_ByAvg, CurrentCtrl_ByPrev, cxCheckBox, CurrentCtrl_ByAvgSm; type TFZCurrentControl = class(TForm) YesBtn: TcxButton; CancelBtn: TcxButton; BoxMain: TcxGroupBox; PrikazBox: TcxGroupBox; EditPrikaz: TcxMaskEdit; LabelPrikaz: TcxLabel; LabelPeriod: TcxLabel; MonthesList: TcxComboBox; YearSpinEdit: TcxSpinEdit; LabelSumma: TcxLabel; Bevel2: TBevel; IdMovingBox: TcxGroupBox; LabelManMoving: TcxLabel; LabelMan: TcxLabel; EditMan: TcxDBButtonEdit; ActionList1: TActionList; Action1: TAction; Grid1DBTableView1: TcxGridDBTableView; Grid1Level1: TcxGridLevel; Grid1: TcxGrid; cxStyleRepository1: TcxStyleRepository; GridTableViewStyleSheetDevExpress: TcxGridTableViewStyleSheet; cxStyle1: TcxStyle; cxStyle2: TcxStyle; cxStyle3: TcxStyle; cxStyle4: TcxStyle; cxStyle5: TcxStyle; cxStyle6: TcxStyle; cxStyle7: TcxStyle; cxStyle8: TcxStyle; cxStyle9: TcxStyle; cxStyle10: TcxStyle; cxStyle11: TcxStyle; cxStyle12: TcxStyle; cxStyle13: TcxStyle; cxStyle14: TcxStyle; Grid1ClDepartment: TcxGridDBColumn; Grid1ClCategory: TcxGridDBColumn; Grid1ClDateBeg: TcxGridDBColumn; Grid1ClDateEnd: TcxGridDBColumn; BoxChild: TcxGroupBox; EditSmeta: TcxButtonEdit; LabelSmeta: TcxLabel; LabelSmetaName: TcxLabel; LabelVidOpl: TcxLabel; EditVidOpl: TcxButtonEdit; LabelVidOplName: TcxLabel; Action2: TAction; dxStatusBar1: TdxStatusBar; SummaPopupMenu: TPopupMenu; SummaByHoursBtn: TMenuItem; SummaAverageBtn: TMenuItem; SummaPrevPeriodBtn: TMenuItem; UpdateSvodsBtn: TMenuItem; CheckBoxNowPay: TcxCheckBox; SummaAvgSmetsBtn: TMenuItem; LabelRmoving: TcxLabel; GridRmoving: TcxGrid; GridRmovingDBTableView1: TcxGridDBTableView; Grd2ClRMoving: TcxGridDBColumn; Grid2ClPeriodBeg: TcxGridDBColumn; Grid2ClPeriodEnd: TcxGridDBColumn; Grid2ClNameSovmest: TcxGridDBColumn; GridRmovingLevel1: TcxGridLevel; Grid1ClOklad: TcxGridDBColumn; Action3: TAction; EditSumma: TcxCalcEdit; EditPrikazB: TcxButtonEdit; CheckDS: TpFIBDataSet; Label1: TLabel; LabelHours: TcxLabel; EditHours: TcxCalcEdit; LabelTarif: TcxLabel; EditTarif: TcxCalcEdit; procedure CancelBtnClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure Action1Execute(Sender: TObject); procedure EditVidOplExit(Sender: TObject); procedure EditSmetaExit(Sender: TObject); procedure Grid1ClDepartmentGetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); procedure MonthesListExit(Sender: TObject); procedure EditSmetaPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure EditVidOplPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure RestoreFromBuffer(Sender:TObject); procedure Action2Execute(Sender: TObject); procedure FormShow(Sender: TObject); procedure SummaByHoursBtnClick(Sender: TObject); procedure SummaAverageBtnClick(Sender: TObject); procedure SummaPopupMenuPopup(Sender: TObject); procedure SummaPrevPeriodBtnClick(Sender: TObject); procedure FormResize(Sender: TObject); procedure UpdateSvodsBtnClick(Sender: TObject); procedure SummaAvgSmetsBtnClick(Sender: TObject); procedure Action3Execute(Sender: TObject); procedure EditPrikazBPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure EditHoursPropertiesEditValueChanged(Sender: TObject); procedure EditTarifPropertiesEditValueChanged(Sender: TObject); private PId_VidOpl:LongWord; PId_Smeta:LongWord; PId_Man:LongWord; PResault:Variant; PParameter:TZCurrentParameters; PLanguageIndex:Byte; PKodSetup:integer; DM:TDM; PNumDays:integer; PTaxTex:string; PIsNumDays:boolean; PSumClock:double; PIsSumClock:boolean; PNumClock:double; PIsNumClock:boolean; PPercent:double; PIsPercent:boolean; PIsProverka:boolean; PIsTaxText:Boolean; PSumma:double; pIdSession:Variant; pNumPredpr:integer; pDefaultPercent:Variant; pDefaultSumma:Variant; function CheckPochas(id_vo:Integer; isInserting:Boolean):Boolean; public constructor Create(AParameter:TZCurrentParameters);reintroduce; property resault:Variant read PResault; end; implementation uses Math, UPochasOrders; {$R *.dfm} constructor TFZCurrentControl.Create(AParameter:TZCurrentParameters); var CurrKodSetup:Integer; CheckDS1:TpFIBDataSet; begin inherited Create(AParameter.Owner); PLanguageIndex:=LanguageIndex; //****************************************************************************** //EditSumma.Properties.EditMask := '[-]?\d\d?\d?\d?\d?\d?\d?\d?\d?\d?\d?\d?\d? (['+ZSystemDecimalSeparator+']\d\d?)?'; //****************************************************************************** LabelMan.Caption := LabelMan_Caption[PLanguageIndex]; LabelSumma.Caption := LabelSumma_Caption[PLanguageIndex]; LabelVidOpl.Caption := LabelVidOpl_Caption[PLanguageIndex]; LabelSmeta.Caption := LabelSmeta_Caption[PLanguageIndex]; LabelManMoving.Caption := LabelManMoving_Caption[PLanguageIndex]; LabelPeriod.Caption := LabelPeriod_Caption[PLanguageIndex]; LabelPrikaz.Caption := LabelPrikaz_Caption[PLanguageIndex]; SummaByHoursBtn.Caption := ByHours_Const[PLanguageIndex]; SummaAverageBtn.Caption := Average_Const[PLanguageIndex]; SummaPrevPeriodBtn.Caption := PrevPeriod_Const[PLanguageIndex]; UpdateSvodsBtn.Caption := CorrectSvod_Const[PLanguageIndex]; MonthesList.Properties.Items.Text := MonthesList_Text[PLanguageIndex]; YesBtn.Caption := YesBtn_Caption[PLanguageIndex]; YesBtn.Hint := YesBtn.Caption; CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex]; CancelBtn.Hint := CancelBtn.Caption+' (Esc)'; //****************************************************************************** Grid1ClDepartment.Caption := LabelDepartment_Caption[PLanguageIndex]; Grid1ClCategory.Caption := LabelCategory_Caption[PLanguageIndex]; Grid1ClDateBeg.Caption := GridClBegPeriod_Caption[PLanguageIndex]; Grid1ClDateEnd.Caption := GridClEndPeriod_Caption[PLanguageIndex]; Grid1ClOklad.Caption := 'Оклад'; //****************************************************************************** Grid2ClPeriodBeg.Caption := GridClBegPeriod_Caption[PLanguageIndex]; Grid2ClPeriodEnd.Caption := GridClEndPeriod_Caption[PLanguageIndex]; Grid2ClNameSovmest.Caption:= GridClNameSovmest_Caption[PLanguageIndex]; //****************************************************************************** PParameter:=AParameter; PResault := NULL; dxStatusBar1.Panels[0].Text := ToBufferBtn_Hint[PLanguageIndex]; dxStatusBar1.Panels[1].Text := YesBtn_Hint[PLanguageIndex]; dxStatusBar1.Panels[2].Text := CancelBtn_Hint[PLanguageIndex]; //****************************************************************************** PIsNumDays:=False; PIsSumClock:=False; PIsNumClock:=False; PIsPercent:=False; //****************************************************************************** DM:=TDM.Create(self,PParameter); CheckDS.Database:=DM.DataBase; CheckDS.Transaction:=DM.DefaultTransaction; if PParameter.ControlFormStyle=zcfsDelete then Exit; //****************************************************************************** if PParameter.ControlFormStyle=zcfsUpdate then begin if PParameter.ControlFormStyle=zcfsInsert then CheckPochas(DM.DSetAllData['ID_VIDOPL'], true); if PParameter.ControlFormStyle=zcfsUpdate then CheckPochas(DM.DSetAllData['ID_VIDOPL'], false); end; if (DM.DSetAllData.FieldByName('POCHAS_ORDER').Value>0) then begin EditPrikaz.Visible:=False; EditPrikazB.Visible:=True; EditPrikazB.Text:='Наказ від '+DM.DSetAllData.FieldByName('date_order').AsString+' № '+DM.DSetAllData.FieldByName('num_order').AsString; LabelSumma.Enabled :=False; EditSumma.Enabled :=False; EditSumma.PopupMenu:=nil; EditTarif.Value:=DM.DSetAllData.FieldByName('SUM_CLOCK').Value; EditHours.Value:=DM.DSetAllData.FieldByName('CLOCK').Value; LabelHours.Visible :=True; EditHours.Visible :=True; LabelTarif.Visible :=True; EditTarif.Visible :=True; if DM.DSetAllData.FieldByName('POCHAS_ORDER').Value<>null then EditPrikazB.Tag:=DM.DSetAllData.FieldByName('POCHAS_ORDER').Value; end; if VarIsNull(DM.DSetAllData['NDAY']) then begin PNumDays := 0; PIsNumDays := False; end else begin PNumDays := DM.DSetAllData['NDAY']; PIsNumDays := True; end; if VarIsNull(DM.DSetAllData['CLOCK']) then begin PNumClock := 0; PIsNumClock := False; end else begin PNumClock := DM.DSetAllData['CLOCK']; PIsNumClock := True; end; if VarIsNull(DM.DSetAllData['SUM_CLOCK']) then begin PSumClock := 0; PIsSumClock := False; end else begin PSumClock := DM.DSetAllData['SUM_CLOCK']; PIsSumClock := True; end; if VarIsNull(DM.DSetAllData['PERCENT']) then begin PPercent := 0; PIsPercent := False; end else begin PPercent := DM.DSetAllData['PERCENT']; PIsPercent := True; end; if VarIsNull(DM.DSetAllData['TAX_TEXT']) then begin PTaxTex := ''; PIsTaxText := False; end else begin PTaxTex := VarToStr(DM.DSetAllData['TAX_TEXT']); PIsTaxText := True; end; if VarIsNull(DM.DSetAllData['ID_MAN']) then begin PId_Man := 0; EditMan.Text := ''; end else begin PId_Man:=DM.DSetAllData['ID_MAN']; EditMan.Text := IfThen(VarIsNull(DM.DSetAllData['TN']),'',VarToStr(DM.DSetAllData['TN'])+' - '+VarToStr(DM.DSetAllData['FIO'])); end; //****************************************************************************** if VarIsNull(Dm.DSetAllData['ID_SMETA']) then begin PId_Smeta:=0; EditSmeta.Text := ''; end else begin PId_Smeta := DM.DSetAllData['ID_SMETA']; EditSmeta.Text := VarToStr(DM.DSetAllData['KOD_SMETA']); LabelSmetaName.Caption := VarToStr(DM.DSetAllData['NAME_SMETA']); end; if VarIsNull(DM.DSetAllData['ID_VIDOPL']) then begin PId_VidOpl:=0; EditVidOpl.Text := ''; end else begin PId_VidOpl := DM.DSetAllData['ID_VIDOPL']; EditVidOpl.Text := VarToStr(DM.DSetAllData['KOD_VIDOPL']); LabelVidOplName.Caption := VarToStr(DM.DSetAllData['NAME_VIDOPL']); end; if VarIsNull(DM.DSetAllData['PRIKAZ']) then EditPrikaz.Text := '' else EditPrikaz.Text := varToStr(DM.DSetAllData['PRIKAZ']); if VarIsNull(DM.DSetAllData['KOD_SETUP']) then begin CurrKodSetup:=CurrentKodSetup(PParameter.Db_Handle); self.MonthesList.ItemIndex := YearMonthFromKodSetup(CurrKodSetup,False)-1; self.YearSpinEdit.Value := YearMonthFromKodSetup(CurrKodSetup); end else begin self.MonthesList.ItemIndex := YearMonthFromKodSetup(DM.DSetAllData['KOD_SETUP'],False)-1; self.YearSpinEdit.Value := YearMonthFromKodSetup(DM.DSetAllData['KOD_SETUP']); end; PIsProverka:=False; PSumma:=0; if not VarIsNull(DM.DSetAllData['SUMMA']) then begin EditSumma.Text := FloatToStrF(DM.DSetAllData['SUMMA'],ffFixed,17,2); PIsProverka:=True; PSumma := DM.DSetAllData['SUMMA']; end; CheckBoxNowPay.Checked := not (DM.DSetAllData['NOW_PAY']='T'); //****************************************************************************** case PParameter.ControlFormStyle of zcfsInsert: begin Caption:=ZCurrentCtrl_Caption_Insert[PLanguageIndex]; BoxMain.Enabled:=False; GridRmovingDBTableView1.DataController.DataSource := DM.DSourceRmoving; Grid1DBTableView1.DataController.DataSource:=DM.DSourceMoving; SummaAvgSmetsBtn.Visible := True; end; zcfsUpdate: begin Caption:=ZCurrentCtrl_Caption_Update[PLanguageIndex]; BoxMain.Enabled:=False; GridRmovingDBTableView1.DataController.DataSource := DM.DSourceRmoving; GridRmovingDBTableView1.DataController.LocateByKey(DM.DSetAllData['RMOVING']); Grid1DBTableView1.DataController.DataSource:=DM.DSourceMoving; Grid1DBTableView1.DataController.LocateByKey(DM.DSetAllData['ID_MOVING']); SummaAvgSmetsBtn.Visible := False; end; zcfsShowDetails: begin Caption:=ZCurrentCtrl_Caption_Detail[PLanguageIndex]; BoxChild.Enabled := False; BoxMain.Enabled := False; IdMovingBox.Enabled:=False; PrikazBox.Enabled:=False; YesBtn.Visible :=False; CancelBtn.Caption := ExitBtn_Caption[PLanguageIndex]; Grid1ClDateBeg.Visible := False; Grid1ClDateEnd.Visible := False; Grid1DBTableView1.OptionsCustomize.ColumnHorzSizing := True; Grid1DBTableView1.OptionsView.ColumnAutoWidth:=True; GridRmovingDBTableView1.DataController.DataSource := DM.DSourceRmoving; GridRmovingDBTableView1.DataController.LocateByKey(DM.DSetAllData['RMOVING']); Grid1DBTableView1.DataController.DataSource:=DM.DSourceMoving; Grid1DBTableView1.DataController.LocateByKey(DM.DSetAllData['ID_MOVING']); end; end; PKodSetup := PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1); pNumPredpr := StrToInt(VarToStrDef(ValueFieldZSetup(Dm.DataBase.Handle,'NUM_PREDPR'),'2')); SummaAvgSmetsBtn.Visible := pNumPredpr<>1; try CheckDS1:=TpFIBDataSet.Create(self); CheckDS1.Database :=DM.DataBase; CheckDS1.Transaction:=DM.DefaultTransaction; CheckDS1.SelectSQL.Text:='select Z_POCHAS_TARIF_MAY_EDIT from Z_POCHAS_TARIF_MAY_EDIT'; CheckDS1.Open; if (CheckDS1.RecordCount>0) then begin if (CheckDS1.FieldByName('Z_POCHAS_TARIF_MAY_EDIT').Value=1) then EditTarif.Enabled:=true else EditTarif.Enabled:=false; end; CheckDS1.Close; CheckDS1.Free; except on e:exception do begin end; end; end; procedure TFZCurrentControl.CancelBtnClick(Sender: TObject); begin ModalResult := mrCancel; end; procedure TFZCurrentControl.FormClose(Sender: TObject; var Action: TCloseAction); begin DM.Free; end; procedure TFZCurrentControl.FormCreate(Sender: TObject); begin CheckDS.Database :=DM.DataBase; CheckDS.Transaction:=DM.DefaultTransaction; FormResize(Sender); If PParameter.ControlFormStyle=zcfsDelete then begin if ZShowMessage(ZCurrentCtrl_Caption_Delete[PLanguageIndex], DeleteRecordQuestion_Text[PLanguageIndex],mtConfirmation,[mbYes,mbNo])=mrYes then with DM do try DataBase.Handle := PParameter.Db_Handle; StoredProc.Database := DataBase; StoredProc.Transaction := WriteTransaction; StoredProc.Transaction.StartTransaction; StoredProc.StoredProcName := 'Z_CURRENT_D'; StoredProc.Prepare; StoredProc.ParamByName('ID_CURRENT').AsInteger := PParameter.ID; StoredProc.ExecProc; StoredProc.Transaction.Commit; ModalResult:=mrYes; except on E:Exception do begin ZShowMessage(Error_Caption[PLanguageIndex],E.Message,mtError,[mbOK]); WriteTransaction.Rollback; end; end else ModalResult:=mrCancel; end; end; procedure TFZCurrentControl.Action1Execute(Sender: TObject); var CheckSP:TpFIBStoredProc; ExitFlag:Boolean; begin if EditPrikazB.Visible and (EditPrikazB.Tag=0) then begin if CheckDS.RecordCount>0 then begin if CheckDS.FieldByName('need_order').Value=1 then begin ShowMessage('Не вибрано наказ для погодинної оплати праці!'); EditPrikazB.SetFocus; Exit; end; end; end; if DM.DSetMoving.IsEmpty then begin ZShowMessage(ZeInputError_Caption[PLanguageIndex],ZeManMoving_NotAvailable_Text[PLanguageIndex],mtInformation,[mbOK]); CancelBtn.SetFocus; Exit; end; if EditMan.Text='' then begin ZShowMessage(ZeInputError_Caption[PLanguageIndex],ManInput_ErrorText[PLanguageIndex],mtInformation,[mbOK]); EditMan.SetFocus; Exit; end; if EditSumma.Text='' then begin ZShowMessage(ZeInputError_Caption[PLanguageIndex],SummaInput_ErrorText[PLanguageIndex],mtInformation,[mbOK]); EditSumma.SetFocus; Exit; end; if PId_VidOpl=0 then begin ZShowMessage(ZeInputError_Caption[PLanguageIndex],VidOplInput_ErrorText[PLanguageIndex],mtInformation,[mbOK]); EditVidOpl.SetFocus; Exit; end; if PId_Smeta=0 then begin ZShowMessage(ZeInputError_Caption[PLanguageIndex],SmetaInput_ErrorText[PLanguageIndex],mtInformation,[mbOK]); EditSmeta.SetFocus; Exit; end; if EditPrikazB.Visible then begin CheckSP:=TpFIBStoredProc.Create(self); CheckSP.Database:=DM.DataBase; CheckSP.Transaction:=DM.DefaultTransaction; CheckSP.StoredProcName:='Z_POCHAS_CHECK'; CheckSP.Prepare; case PParameter.ControlFormStyle of zcfsInsert: CheckSP.ParamByName('id_current').Value :=0; zcfsUpdate: CheckSP.ParamByName('id_current').Value :=DM.DSetAllData['ID_CURRENT']; end; CheckSP.ParamByName('id_pochas_plan').Value:=EditPrikazB.Tag; CheckSP.ParamByName('id_vo').AsInt64 :=PId_VidOpl; CheckSP.ParamByName('hours').Value :=PNumClock; CheckSP.ParamByName('kod_setup').Value :=PKodSetup; CheckSP.ParamByName('id_man').Value :=DM.DSetAllData['ID_MAN']; CheckSP.ExecProc; ExitFlag:=false; if CheckSP.ParamByName('result').Value=0 then begin ZShowMessage(ZeInputError_Caption[PLanguageIndex], CheckSP.ParamByName('error_msg').AsString ,mtInformation,[mbOK]); ExitFlag:=true; end; CheckSP.Free; if ExitFlag then Exit; end; case PParameter.ControlFormStyle of zcfsInsert: with DM do try StoredProc.Database := DataBase; StoredProc.Transaction := WriteTransaction; StoredProc.Transaction.StartTransaction; StoredProc.StoredProcName := 'Z_CURRENT_INSERT'; StoredProc.Prepare; StoredProc.ParamByName('KOD_SETUP').AsInteger := PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1); StoredProc.ParamByName('KOD_SETUP_O1').AsInteger := PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1); StoredProc.ParamByName('KOD_SETUP_O2').AsInteger := PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1); if not VarIsNull(DSetAllData['ID_MAN']) then StoredProc.ParamByName('ID_MAN').AsInteger := DSetAllData.FieldValues['ID_MAN']; if not VarIsNull(DSetAllData['TN']) then StoredProc.ParamByName('TN').AsInteger := DSetAllData.FieldValues['TN']; StoredProc.ParamByName('ID_VIDOPL').AsInteger := PId_VidOpl; StoredProc.ParamByName('ID_DEPARTMENT').AsVariant := DSetMoving['ID_DEPARTMENT']; StoredProc.ParamByName('ID_CATEGORY').AsVariant := DSetMoving['ID_CATEGORY']; StoredProc.ParamByName('ID_MOVING').AsVariant := DSetMoving['ID_MOVING']; StoredProc.ParamByName('RMOVING').AsInteger := DSetRmoving['RMOVING']; StoredProc.ParamByName('SUMMA').AsFloat := StrToFloat(EditSumma.Text); StoredProc.ParamByName('KOD_SMET').AsInteger := PId_Smeta; StoredProc.ParamByName('DATE_REG').AsDate := Date; if EditPrikaz.Visible then begin StoredProc.ParamByName('PRIKAZ').AsString := EditPrikaz.Text; end else begin StoredProc.ParamByName('PRIKAZ').AsString := EditPrikazB.Text; end; StoredProc.ParamByName('P_OLD').AsString := 'F'; StoredProc.ParamByName('ID_SESSION').AsVariant := pIdSession; if EditPrikazB.Visible then if EditPrikazB.Tag>0 then StoredProc.ParamByName('POCHAS_ORDER').AsInt64 := EditPrikazB.Tag else StoredProc.ParamByName('POCHAS_ORDER').Value := null else StoredProc.ParamByName('POCHAS_ORDER').Value := null; if CheckBoxNowPay.Checked then StoredProc.ParamByName('NOW_PAY').AsString := 'F' else StoredProc.ParamByName('NOW_PAY').AsString := 'T'; if (PSumma<>StrToFloat(EditSumma.Text)) and (PIsProverka) then begin StoredProc.ParamByName('NDAY').AsVariant := Null; StoredProc.ParamByName('PERCENT').AsVariant := Null; StoredProc.ParamByName('SUM_CLOCK').AsVariant := Null; StoredProc.ParamByName('CLOCK').AsVariant := Null; StoredProc.ParamByName('TAX_TEXT').AsVariant := Null; end else begin if EditPrikazB.Visible then begin StoredProc.ParamByName('PERCENT').AsVariant := 100; StoredProc.ParamByName('NDAY').AsVariant := Null; StoredProc.ParamByName('CLOCK').AsDouble :=EditHours.Value; StoredProc.ParamByName('SUM_CLOCK').AsDouble :=EditTarif.Value; StoredProc.ParamByName('TAX_TEXT').AsVariant := Null; end else begin if PIsNumDays then StoredProc.ParamByName('NDAY').AsInteger := PNumDays else StoredProc.ParamByName('NDAY').AsVariant := Null; if PIsPercent then StoredProc.ParamByName('PERCENT').AsDouble := PPercent else StoredProc.ParamByName('PERCENT').AsVariant := Null; if PIsSumClock then StoredProc.ParamByName('SUM_CLOCK').AsDouble := PSumClock else StoredProc.ParamByName('SUM_CLOCK').AsVariant := Null; if PIsNumClock then StoredProc.ParamByName('CLOCK').AsDouble := PNumClock else StoredProc.ParamByName('CLOCK').AsVariant := Null; if PIsTaxText then StoredProc.ParamByName('TAX_TEXT').AsString := PTaxTex else StoredProc.ParamByName('TAX_TEXT').AsVariant := Null; end; end; StoredProc.ExecProc; PResault := StoredProc.ParamByName('ID_CURRENT').AsInteger; StoredProc.Transaction.Commit; ModalResult := mrYes; except on E:Exception do begin ZShowMessage(Error_caption[PLanguageIndex],E.Message,mtError,[mbOK]); WriteTransaction.Rollback; end; end; zcfsUpdate: with DM do try StoredProc.Database := DataBase; StoredProc.Transaction := WriteTransaction; StoredProc.Transaction.StartTransaction; StoredProc.StoredProcName := 'Z_CURRENT_UPDATE'; StoredProc.Prepare; StoredProc.ParamByName('ID_CURRENT').AsInteger := DSetAllData['ID_CURRENT']; StoredProc.ParamByName('KOD_SETUP').AsInteger := PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1); StoredProc.ParamByName('KOD_SETUP_O1').AsInteger := PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1); StoredProc.ParamByName('KOD_SETUP_O2').AsInteger := PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1); if not VarIsNull(DSetAllData['ID_MAN']) then StoredProc.ParamByName('ID_MAN').AsInteger := DSetAllData.FieldValues['ID_MAN']; if not VarIsNull(DSetAllData['TN']) then StoredProc.ParamByName('TN').AsInteger := DSetAllData.FieldValues['TN']; StoredProc.ParamByName('ID_VIDOPL').AsInteger := PId_VidOpl; StoredProc.ParamByName('ID_DEPARTMENT').AsVariant := DSetMoving['ID_DEPARTMENT']; StoredProc.ParamByName('ID_CATEGORY').AsVariant := DSetMoving['ID_CATEGORY']; StoredProc.ParamByName('ID_MOVING').AsVariant := DSetMoving['ID_MOVING']; if not VarIsNull(DSetAllData['RMOVING']) then StoredProc.ParamByName('RMOVING').AsInteger := DSetRmoving['RMOVING']; StoredProc.ParamByName('SUMMA').AsFloat := StrToFloat(EditSumma.Text); StoredProc.ParamByName('KOD_SMET').AsInteger := PId_Smeta; StoredProc.ParamByName('DATE_REG').AsDate := Date; if EditPrikaz.Visible then StoredProc.ParamByName('PRIKAZ').AsString := EditPrikaz.Text else StoredProc.ParamByName('PRIKAZ').AsString := EditPrikazB.Text; if EditPrikazB.Visible then if EditPrikazB.Tag>0 then StoredProc.ParamByName('POCHAS_ORDER').AsInt64 := EditPrikazB.Tag else StoredProc.ParamByName('POCHAS_ORDER').Value := null else StoredProc.ParamByName('POCHAS_ORDER').Value := null; StoredProc.ParamByName('P_OLD').AsString := 'F'; if CheckBoxNowPay.Checked then StoredProc.ParamByName('NOW_PAY').AsString := 'F' else StoredProc.ParamByName('NOW_PAY').AsString := 'T'; if EditPrikazB.Visible then begin StoredProc.ParamByName('PERCENT').AsVariant := 100; StoredProc.ParamByName('NDAY').AsVariant := Null; StoredProc.ParamByName('CLOCK').AsDouble :=EditHours.Value; StoredProc.ParamByName('SUM_CLOCK').AsDouble :=EditTarif.Value; StoredProc.ParamByName('TAX_TEXT').AsVariant := Null; end else begin if PIsNumDays then StoredProc.ParamByName('NDAY').AsInteger := PNumDays else StoredProc.ParamByName('NDAY').AsVariant := Null; if PIsPercent then StoredProc.ParamByName('PERCENT').AsDouble := PPercent else StoredProc.ParamByName('PERCENT').AsVariant := Null; if PIsSumClock then StoredProc.ParamByName('SUM_CLOCK').AsDouble := PSumClock else StoredProc.ParamByName('SUM_CLOCK').AsVariant := Null; if PIsNumClock then StoredProc.ParamByName('CLOCK').AsDouble := PNumClock else StoredProc.ParamByName('CLOCK').AsVariant := Null; if PIsTaxText then StoredProc.ParamByName('TAX_TEXT').AsString := PTaxTex else StoredProc.ParamByName('TAX_TEXT').AsVariant := Null; end; StoredProc.ExecProc; StoredProc.Transaction.Commit; ModalResult := mrYes; except on E:Exception do begin ZShowMessage(Error_caption[PlanguageIndex],E.Message,mtError,[mbOK]); WriteTransaction.Rollback; end; end; end; end; procedure TFZCurrentControl.EditVidOplExit(Sender: TObject); var Vo:variant; begin if EditVidOpl.Text<>'' then begin VO:=VoByKod(StrToInt(EditVidOpl.Text),Date,DM.DataBase.Handle,ZCurrentVidOplProp); if not VarIsNull(VO) then begin PId_VidOpl:=VO[0]; LabelVidOplName.Caption:=VarToStr(VO[2]); //Проверяем является ли выбранный вид оплат "почасовкой" if PParameter.ControlFormStyle=zcfsInsert then CheckPochas(VO[0], true); if PParameter.ControlFormStyle=zcfsUpdate then CheckPochas(VO[0], false); end else EditVidOpl.SetFocus; end; end; procedure TFZCurrentControl.EditSmetaExit(Sender: TObject); var Smeta:variant; begin if EditSmeta.Text<>'' then begin Smeta:=SmetaByKod(StrToInt(EditSmeta.Text),DM.DataBase.Handle); if not VarIsNull(Smeta) then begin PId_Smeta:=Smeta[0]; LabelSmetaName.Caption:=VarToStr(Smeta[2]); end else EditSmeta.SetFocus; end end; procedure TFZCurrentControl.Grid1ClDepartmentGetDisplayText( Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord; var AText: String); begin AText:=Grid1DBTableView1.DataController.DataSource.DataSet['KOD_DEPARTMENT']+' - '+AText; end; procedure TFZCurrentControl.MonthesListExit(Sender: TObject); var UpdateTarifDS:TpFIBDataSet; begin if PKodSetup=PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1) then Exit else PKodSetup:=PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1); if DM.DSetMoving.Active then DM.DSetMoving.Close; if DM.DSetRmoving.Active then DM.DSetRMoving.Close; case PParameter.ControlFormStyle of zcfsInsert: begin DM.DSetRmoving.SQLs.SelectSQL.Text := 'SELECT * FROM Z_GET_RMOVINGS('+ IntToStr(PParameter.ID)+','+ IntToStr(PKodSetup)+') order by date_end descending'; DM.DSetMoving.SQLs.SelectSQL.Text := 'SELECT * FROM Z_MAN_MOVINGS_BY_R(?RMOVING,'+ IntToStr(PKodSetup)+ ') ORDER BY DATE_END'; DM.DSetRmoving.Open; DM.DSetMoving.Open; if EditPrikazB.Tag>0 then begin UpdateTarifDS:=TpFIBDataSet.Create(self); UpdateTarifDS.Database:=DM.DataBase; UpdateTarifDS.Transaction:=DM.DefaultTransaction; UpdateTarifDS.SelectSQL.Text:='SELECT * FROM Z_POCHAS_GET_TARIF('+IntTostr(EditPrikazB.Tag)+','+iNTTOSTR(PKodSetup)+')'; UpdateTarifDS.Open; if (UpdateTarifDS.RecordCount>0) then begin EditTarif.Value:=UpdateTarifDS.Fieldbyname('tarif').Value; end; UpdateTarifDS.Close; UpdateTarifDS.Free; end; end; zcfsUpdate: begin DM.DSetRmoving.SQLs.SelectSQL.Text := 'SELECT * FROM Z_GET_RMOVINGS('+ VarToStr(DM.DSetAllData['ID_MAN'])+','+ IntToStr(PKodSetup)+') order by date_end descending'; DM.DSetMoving.SQLs.SelectSQL.Text:='SELECT * FROM Z_MAN_MOVINGS_BY_R(?RMOVING,'+ IntToStr(PKodSetup)+ ') ORDER BY DATE_END'; DM.DSetRmoving.Open; DM.DSetMoving.Open; if DM.DSetAllData.FieldByName('POCHAS_ORDER').Value>0 then begin UpdateTarifDS:=TpFIBDataSet.Create(self); UpdateTarifDS.Database:=DM.DataBase; UpdateTarifDS.Transaction:=DM.DefaultTransaction; UpdateTarifDS.SelectSQL.Text:='SELECT * FROM Z_POCHAS_GET_TARIF('+DM.DSetAllData.FieldByName('POCHAS_ORDER').AsString+','+iNTTOSTR(PKodSetup)+')'; UpdateTarifDS.Open; if (UpdateTarifDS.RecordCount>0) then begin if UpdateTarifDS.Fieldbyname('tarif').Value<>null then EditTarif.Value:=UpdateTarifDS.Fieldbyname('tarif').Value else EditTarif.Value:=0; end; UpdateTarifDS.Close; UpdateTarifDS.Free; end; end; else Exit; end; end; procedure TFZCurrentControl.EditSmetaPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); var Smeta:Variant; begin Smeta:=GetSmets(self,PParameter.Db_Handle,Date,psmSmet); if VarArrayDimCount(Smeta)> 0 then If Smeta[0]<>NULL then begin EditSmeta.Text := Smeta[3]; LabelSmetaName.Caption := Smeta[2]; PId_Smeta := Smeta[0]; end; end; procedure TFZCurrentControl.EditVidOplPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var VidOpl:Variant; begin VidOPl:=LoadVidOpl(self, PParameter.Db_Handle,zfsModal, ValueFieldZSetup(PParameter.Db_Handle,'ID_VO_PROP_CURRENT'), ValueFieldZSetup(PParameter.Db_Handle,'Z_ID_SYSTEM')); if VarArrayDimCount(VidOpl)> 0 then begin if VidOpl[0]<> NULL then begin EditVidOpl.Text := VidOpl[2]; LabelVidOplName.Caption := VidOpl[1]; PId_VidOpl := VidOpl[0]; //Проверяем является ли выбранный вид оплат "почасовкой" if PParameter.ControlFormStyle=zcfsInsert then CheckPochas(VidOpl[0], true); if PParameter.ControlFormStyle=zcfsUpdate then CheckPochas(VidOpl[0], false); end; end; end; procedure TFZCurrentControl.RestoreFromBuffer(Sender:TObject); var reg:TRegistry; Kod:integer; begin reg := TRegistry.Create; reg.RootKey:=HKEY_CURRENT_USER; if not reg.OpenKey('\Software\Zarplata\CurrentCtrl\',False) then begin reg.free; Exit; end; try kod := reg.ReadInteger('IsBuffer'); if kod<=0 then begin reg.Free; Exit; end; except reg.Free; exit; end; try Kod := reg.ReadInteger('KodSmeta'); if Kod>0 then begin EditSmeta.Text := IntToStr(Kod); EditSmetaExit(sender); end; except Kod:=0; end; try Kod := reg.ReadInteger('KodVidOpl'); if Kod>0 then begin EditVidOpl.Text := IntToStr(Kod); EditVidOplExit(sender); end; except Kod:=0; end; try EditPrikaz.Text := reg.ReadString('Prikaz'); except EditPrikaz.Text := ''; end; try Kod := reg.ReadInteger('KodSetup'); if Kod>0 then begin MonthesList.ItemIndex := YearMonthFromKodSetup(Kod,False)-1; YearSpinEdit.Value := YearMonthFromKodSetup(Kod); end; except Kod:=0; end; try Kod := reg.ReadInteger('NOW_PAY'); if Kod>0 then CheckBoxNowPay.Checked := (Kod=0); except Kod:=0; end; editSumma.SetFocus; Reg.Free; end; procedure TFZCurrentControl.Action2Execute(Sender: TObject); var reg: TRegistry; begin reg:=TRegistry.Create; try reg.RootKey:=HKEY_CURRENT_USER; reg.OpenKey('\Software\Zarplata\CurrentCtrl\',True); reg.WriteInteger('IsBuffer',1); reg.WriteInteger('KodSmeta',StrToInt(EditSmeta.Text)); reg.WriteInteger('KodVidOpl',StrToInt(EditVidOpl.Text)); reg.WriteInteger('KodSetup',PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1)); reg.WriteString('Prikaz',EditPrikaz.Text); if CheckBoxNowPay.Checked then reg.WriteInteger('NOW_PAY',0) else reg.WriteInteger('NOW_PAY',1); finally reg.Free; end; end; procedure TFZCurrentControl.FormShow(Sender: TObject); var KodSmeta:variant; begin if PParameter.ControlFormStyle=zcfsInsert then begin KodSmeta := ValueFieldZSetup(DM.DataBase.Handle,'Z_DEFAULT_KOD_SM'); if not VarIsNull(KodSmeta) then begin EditSmeta.Text := VarToStr(KodSmeta); EditSmetaExit(self); EditVidOpl.SetFocus; end; RestoreFromBuffer(self); end; end; procedure TFZCurrentControl.SummaByHoursBtnClick(Sender: TObject); var Res:TFByHours_Result; defOrder, InfoDS:TpFIBDataSet; FS:TFormatSettings; begin //Проверяем является ли выбранный вид оплат "почасовкой" if PParameter.ControlFormStyle=zcfsInsert then CheckPochas(PId_VidOpl, true); if PParameter.ControlFormStyle=zcfsUpdate then CheckPochas(PId_VidOpl, false); If PParameter.ControlFormStyle=zcfsUpdate then begin InfoDS:=TpFIBDataSet.Create(self); InfoDS.Database:=DM.DataBase; InfoDS.Transaction:=DM.DefaultTransaction; InfoDS.SelectSQL.Text:='SELECT * FROM Z_CURRENT WHERE ID_CURRENT='+IntToStr(PParameter.ID); InfoDS.Open; if InfoDS.RecordCount>0 then begin if InfoDS.FieldByName('clock').Value<>null then PSumClock:=InfoDS.FieldByName('clock').Value; if InfoDS.FieldByName('percent').Value<>null then PPercent :=InfoDS.FieldByName('percent').Value; if InfoDS.FieldByName('sum_clock').Value<>null then PSumma :=InfoDS.FieldByName('sum_clock').Value; end; InfoDS.Close; InfoDS.Free; Res:=SumForHours(self,DM.DataBase.Handle,DM.DSetMoving['ID_MOVING'],pDefaultPercent,pDefaultSumma,PPercent,PSumClock,PSumma); PSumClock:=0; PPercent :=0; PSumma :=0; end else Res:=SumForHours(self,DM.DataBase.Handle,DM.DSetMoving['ID_MOVING'],pDefaultPercent,pDefaultSumma,pDefaultPercent,null,null); if Res.ModalResult=mrYes then begin PIsProverka:=False; PIsNumDays:=False; PIsSumClock:=False; PIsNumClock:=False; PIsPercent:=False; PIsTaxText:=False; pIdSession:=null; if Trim(res.Clock)='' then PNumClock:=0 else PNumClock:=StrToFloat(Res.Clock); PSumClock:=Res.Sum_Clock; PPercent:=Res.Percent; PIsNumClock:=True; PIsSumClock:=True; PIsPercent:=True; EditSumma.Text:=FloatToStrF(res.Summa,ffFixed,17,2); EditSmeta.Enabled := True; if CheckDS.Active then begin if CheckDS.RecordCount>0 then begin if CheckDS.FieldByName('need_order').Value=1 then begin //Подтягиваем приказ по умолчанию если таковой найдется defOrder:=TpFIBDataSet.Create(self); defOrder.Database:=DM.DataBase; defOrder.Transaction:=DM.DefaultTransaction; FS.DecimalSeparator:='.'; defOrder.SelectSQL.Text:=' SELECT * FROM Z_POCHAS_GET_ORDERS_BY_PC('+IntToStr(PKodSetup)+','+VarToStr(DM.DSetAllData['ID_MAN'])+') where rest>='+FloatToStr(PNumClock,FS); defOrder.Open; if (defOrder.RecordCount>0) then begin EditPrikazB.Text:='Наказ від '+defOrder.FieldByName('date_order').AsString+' № '+defOrder.FieldByName('num_order').AsString; EditPrikazB.Tag :=defOrder.FieldByName('id_pochas_plan').Value; end; defOrder.Close; defOrder.Free; end; end; end; end; end; procedure TFZCurrentControl.SummaAverageBtnClick(Sender: TObject); var Res:TFAvgDays_Result; begin Res:=SumForAvg(self,DM.DataBase.Handle,DM.DSetRmoving['RMOVING'],PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1),PNumDays); if Res.ModalResult=mrYes then begin PIsProverka:=False; PIsNumDays:=False; PIsSumClock:=False; PIsNumClock:=False; PIsPercent:=False; PIsTaxText:=False; pIdSession:=null; EditSmeta.Enabled := True; PNumDays:=Res.NumDays; PIsNumDays:=True; EditSumma.Text:=FloatToStrF(Res.Summa,ffFixed,17,2); end; end; procedure TFZCurrentControl.SummaPopupMenuPopup(Sender: TObject); begin if VarIsNULL(DM.DSetMoving['ID_MOVING']) then begin SummaByHoursBtn.Enabled := False; SummaAvgSmetsBtn.Enabled := False; SummaAverageBtn.Enabled := False; SummaPrevPeriodBtn.Enabled := False; UpdateSvodsBtn.Enabled := False; end else begin SummaByHoursBtn.Enabled := True; SummaAvgSmetsBtn.Enabled := True; SummaAverageBtn.Enabled := True; SummaPrevPeriodBtn.Enabled := True; UpdateSvodsBtn.Enabled := PId_VidOpl>0; end; end; procedure TFZCurrentControl.SummaPrevPeriodBtnClick(Sender: TObject); var Res:TFPrev_Result; begin Res:=SumForPrevPeriod(self,DM.DataBase.Handle,DM.DSetAllData['ID_MAN'],PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1)-1,DM.DSetAllData['PERCENT']); if Res.ModalResult=mrYes then begin PIsProverka:=False; PIsNumDays:=False; PIsSumClock:=False; PIsNumClock:=False; PIsPercent:=False; PIsTaxText:=False; pIdSession:=null; PPercent:=Res.Percent; PIsPercent:=True; EditSumma.Text:=FloatToStrF(Res.Summa,ffFixed,17,2); EditSmeta.Enabled := True; end; end; procedure TFZCurrentControl.FormResize(Sender: TObject); var i:integer; begin for i:=0 to dxStatusBar1.Panels.Count-1 do dxStatusBar1.Panels[i].Width := Width div dxStatusBar1.Panels.Count; end; procedure TFZCurrentControl.UpdateSvodsBtnClick(Sender: TObject); var TaxText:Variant; begin TaxText:=LoadTaxesForCurrent(Self,DM.DataBase.Handle,PId_VidOpl,PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1)); if not VarIsNull(TaxText) then begin PTaxTex:=TaxText; PIsNumDays:=false; PIsSumClock:=False; PIsNumClock:=False; PIsPercent:=False; PIsProverka:=False; PIsTaxText:=True; pIdSession:=null; EditSmeta.Enabled := True; end; end; procedure TFZCurrentControl.SummaAvgSmetsBtnClick(Sender: TObject); var Res:TFAvgDaysSm_Result; begin Res:=SumForAvgSmets(self,DM.DataBase.Handle,DM.DSetRmoving['RMOVING'],PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1),PNumDays); if Res.ModalResult=mrYes then begin PIsProverka:=False; PIsNumDays:=False; PIsSumClock:=False; PIsNumClock:=False; PIsPercent:=False; PIsTaxText:=False; pIdSession := Res.IdSession; PNumDays:=Res.NumDays; PIsNumDays:=True; EditSumma.Text:=FloatToStrF(Res.Summa,ffFixed,17,2); EditSmeta.Text := ''; LabelSmeta.Caption := ''; EditSmeta.Enabled := False; end; end; procedure TFZCurrentControl.Action3Execute(Sender: TObject); begin SendKeyDown(Self.ActiveControl,VK_TAB,[]); end; procedure TFZCurrentControl.EditPrikazBPropertiesButtonClick( Sender: TObject; AButtonIndex: Integer); var T:TfrmPochasOrders; begin T:=TfrmPochasOrders.Create(self, DM.DataBase.Handle, DM.DSetAllData['ID_MAN'], PKodSetup); if T.ShowModal=mrYes then begin EditPrikazB.Text:='Наказ від '+T.OrdersDataSet.FieldByName('date_order').AsString+' № '+T.OrdersDataSet.FieldByName('num_order').AsString; EditPrikazB.Tag :=T.OrdersDataSet.FieldByName('id_pochas_plan').Value; EditTarif.Text:=T.OrdersDataSet.FieldByName('tarif').Value; end; T.Free; end; function TFZCurrentControl.CheckPochas(id_vo: Integer; isInserting:Boolean): Boolean; var DefDS:TpFIBDataSet; rmoving:Integer; begin if CheckDS.Active then CheckDS.Close; CheckDS.SelectSQL.Text:=' SELECT * FROM Z_POCHAS_GET_VO WHERE ID_VIDOPL='+IntToStr(id_vo); CheckDS.Open; CheckDS.FetchAll; if CheckDS.RecordCount>0 then begin if (CheckDS.FieldByName('NEED_ORDER').Value=1) then begin EditPrikaz.Visible:=false; EditPrikazB.Visible:=true; LabelSumma.Enabled :=False; EditSumma.Enabled :=False; EditSumma.PopupMenu:=nil; LabelHours.Visible :=True; EditHours.Visible :=True; LabelTarif.Visible :=True; EditTarif.Visible :=True; end else begin EditPrikaz.Visible :=true; EditPrikazB.Visible:=false; LabelSumma.Enabled :=true; EditSumma.Enabled :=true; EditSumma.PopupMenu:=SummaPopupMenu; LabelHours.Visible :=false; EditHours.Visible :=false; LabelTarif.Visible :=false; EditTarif.Visible :=false; PIsNumClock:=false; PIsSumClock:=false; end; end else begin EditPrikaz.Visible:=true; EditPrikazB.Visible:=false; LabelSumma.Enabled :=true; EditSumma.Enabled :=true; EditSumma.PopupMenu:=SummaPopupMenu; LabelHours.Visible :=false; EditHours.Visible :=false; LabelTarif.Visible :=false; EditTarif.Visible :=false; PIsNumClock:=false; PIsSumClock:=false; end; if (DM.DSourceRmoving.DataSet.RecordCount>0) then begin rmoving:=DM.DSourceRmoving.DataSet['RMOVING']; end else begin rmoving:=-1; end; DefDS:=TpFIBDataSet.Create(self); DefDS.Database:=DM.DataBase; DefDS.Transaction:=DM.DefaultTransaction; if not isInserting then begin DefDS.SelectSQL.Text:=' SELECT * FROM Z_GET_VO_DEF_PERC('+IntToStr(id_vo)+','+ DM.DSetAllData.FieldByName('KOD_SETUP').asString+','+ IntToStr(rmoving)+')'; end else begin DefDS.SelectSQL.Text:=' SELECT * FROM Z_GET_VO_DEF_PERC('+IntToStr(id_vo)+','+ IntToStr(PeriodToKodSetup(YearSpinEdit.Value,MonthesList.ItemIndex+1))+','+ IntToStr(rmoving)+')'; end; DefDS.Open; if (DefDS.RecordCount>0) then begin pDefaultPercent:=DefDS.FieldByName('percent').Value; pDefaultSumma :=DefDS.FieldByName('summa').Value; end else begin pDefaultPercent:=null; pDefaultSumma :=null; end; DefDS.Close; DefDS.Free; end; procedure TFZCurrentControl.EditHoursPropertiesEditValueChanged( Sender: TObject); begin try EditSumma.Value:=RoundTo(EditHours.Value*EditTarif.Value,-2); except on E:Exception do begin end; end; end; procedure TFZCurrentControl.EditTarifPropertiesEditValueChanged( Sender: TObject); begin try EditSumma.Value:=RoundTo(EditHours.Value*EditTarif.Value,-2); except on E:Exception do begin end; end; end; end.
unit Ils.Utils.SaaS; interface uses Redis.Client, Ils.Utils, Windows, JsonDataObjects, DateUtils, SysUtils, Ils.Logger, IniFiles, Ils.Utils.Debug, Redis.NetLib.INDY, Ils.Redis.Conf; type TRedisActivityReporter = class private FRedisConfig: TRedisConf; FInstance, FName, FVersion, FConnectionHostName, FConnectionDatabase: string; FStarted: TDateTime; FTimeOut: Integer; FRedisClient: TRedisClient; FConnected: Boolean; public function Connect: Boolean; procedure SaveLastActivity(const AOperations: Integer; const ATime: TTime); constructor Create( const ARedisConfig: TRedisConf; const AInstance, AName, AVersion, AConnectionHostName, AConnectionDatabase: string; const ATimeOut: Integer = 600 ); destructor Destroy; override; end; implementation { TRedisActivity } function TRedisActivityReporter.Connect: Boolean; begin if not FConnected then try FRedisClient.Connect; FRedisClient.AUTH(FRedisConfig.Password); FConnected := True; except on E: Exception do ToLog('TRedisActivity.Create - ' + E.ClassName + ':' + E.Message); end; Result := FConnected; end; constructor TRedisActivityReporter.Create( const ARedisConfig: TRedisConf; const AInstance, AName, AVersion, AConnectionHostName, AConnectionDatabase: string; const ATimeOut: Integer = 600 ); begin FRedisConfig := ARedisConfig; FInstance := AInstance; FName := AName; FVersion := AVersion; FConnectionHostName := AConnectionHostName; FConnectionDatabase := AConnectionDatabase; FTimeOut := ATimeOut; FStarted := NowUTC; FRedisClient := TRedisClient.Create(FRedisConfig.Host, FRedisConfig.Port); FConnected := False; if FRedisConfig.Enabled then Connect; end; destructor TRedisActivityReporter.Destroy; begin if FConnected then FRedisClient.Disconnect; FRedisClient.Free; inherited; end; procedure TRedisActivityReporter.SaveLastActivity(const AOperations: Integer; const ATime: TTime); function ComputerName: string; const MAX_COMPUTERNAME = MAX_PATH; var b: array[0 .. MAX_COMPUTERNAME - 1] of Char; l: dword; begin l := MAX_COMPUTERNAME; if GetComputerName(b, l) then Result := b else Result := '' end; var jo: TJsonObject; Key: string; begin if not FRedisConfig.Enabled then Exit; if not FConnected then Exit; try try jo := TJsonObject.Create; try jo.S['Instance'] := LowerCase(FInstance); jo.S['Name'] := LowerCase(FName); jo.I['Process'] := GetCurrentProcessId; jo.S['Version'] := FVersion; jo.S['Host'] := ComputerName; jo.S['DB'] := FConnectionHostName + ':' + FConnectionDatabase; jo.I['Memory'] := MemoryUsed;// FormatMemoryUsed('bytes');// ''; jo.I['StartTime'] := DateTimeToUnix(FStarted); jo.I['LastTime'] := DateTimeToUnix(NowUTC); jo.I['TimeOut'] := FTimeOut; jo.I['Operations'] := AOperations; jo.F['TimeOfOperations'] := ATime * SecsPerDay; Key := LowerCase(FInstance + '_' + FName + '_' + IntToStr(GetCurrentProcessId)); FRedisClient.&SET(Key, jo.ToJSON()); FRedisClient.EXPIRE(Key, FTimeOut); finally jo.Free; end; except on E: Exception do begin ToLog('TRedisActivity.SaveLastActivity - ' + E.ClassName + ':' + E.Message); FConnected := False; FRedisClient.Disconnect; end; end; except on E: Exception do begin ToLog('TRedisActivity.SaveLastActivity (L2) - ' + E.ClassName + ':' + E.Message); end; end; end; end.
unit Chapter06._05_Solution1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, DeepStar.Utils, DeepStar.DSA.Linear.Queue; // 279. Perfect Squares // https://leetcode.com/problems/perfect-squares/description/ // 时间复杂度: O(n) // 空间复杂度: O(n) type TSolution = class(TObject) public function numSquares(n: integer): integer; end; procedure Main; implementation procedure Main; begin with TSolution.Create do begin WriteLn(numSquares(12)); WriteLn(numSquares(13)); Free; end; end; { TSolution } function TSolution.numSquares(n: integer): integer; type TPair = record a: integer; b: integer; end; TQueue_pair = specialize TQueue<TPair>; function __pair__(a, b: integer): TPair; begin Result.a := a; Result.b := b; end; var q: TQueue_pair; p: TPair; visited: TArr_bool; num, step, i, a: integer; begin if n = 0 then Exit(0); q := TQueue_pair.Create; try q.EnQueue(__pair__(n, 0)); SetLength(visited, n + 1); visited[n] := true; while not q.IsEmpty do begin p := q.DeQueue; num := p.a; step := p.b; i := 1; while num - i * i >= 0 do begin a := num - i * i; if not visited[a] then begin if a = 0 then Exit(step); q.EnQueue(__pair__(a, step + 1)); visited[a] := true; end; i += 1; end; end; Result := step; finally q.Free; end; end; end.
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmDGT Purpose : To have a non-visual Directed Graph Tree component. Date : 04-10-2001 Author : Ryan J. Mills Version : 1.92 Notes : This unit was partially based upon the work of Patrick O'Keeffe. ================================================================================} unit rmDGT; interface {$I CompilerDefines.INC} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; type { TTreeNode } TAddMode = (taAddFirst, taAdd, taInsert); TNodeAttachMode = (naAdd, naAddFirst, naAddChild, naAddChildFirst, naInsert); PDGNodeInfo = ^TDGNodeInfo; TDGNodeInfo = packed record Count: Integer; Index : integer; Text: Char; end; TrmCustomDGTree = class; TrmDGTreeNodes = class; TrmDGTreeNode = class; TrmDGTreeNode = class(TPersistent) private FOwner: TrmDGTreeNodes; FText: Char; FData: Integer; FChildList : TList; FDeleting: Boolean; FParent: TrmDGTreeNode; function GetLevel: Integer; function GetParent: TrmDGTreeNode; procedure SetParent(Value : TrmDGTreeNode); function GetChildren: Boolean; function GetIndex: Integer; function GetItem(Index: Integer): TrmDGTreeNode; function GetCount: Integer; function GeTrmDGTree: TrmCustomDGTree; function IsEqual(Node: TrmDGTreeNode): Boolean; procedure ReadData(Stream: TStream; Info: PDGNodeInfo); procedure SetData(Value: Integer); procedure SetItem(Index: Integer; Value: TrmDGTreeNode); procedure SetText(const S: Char); procedure WriteData(Stream: TStream; Info: PDGNodeInfo); public constructor Create(AOwner: TrmDGTreeNodes); destructor Destroy; override; procedure Assign(Source: TPersistent); override; procedure Delete; procedure DeleteChildren; function GetFirstChild: TrmDGTreeNode; function GetLastChild: TrmDGTreeNode; function GetNext: TrmDGTreeNode; function GetNextChild(Value: TrmDGTreeNode): TrmDGTreeNode; function GetNextSibling: TrmDGTreeNode; function GetPrev: TrmDGTreeNode; function GetPrevChild(Value: TrmDGTreeNode): TrmDGTreeNode; function getPrevSibling: TrmDGTreeNode; function HasAsParent(Value: TrmDGTreeNode): Boolean; function IndexOf(Value: TrmDGTreeNode): Integer; function MoveTo(Destination: TrmDGTreeNode; Mode: TNodeAttachMode):TrmDGTreeNode; property Count: Integer read GetCount; property Data: Integer read FData write SetData; property Deleting: Boolean read FDeleting; property HasChildren: Boolean read GetChildren; property Index: Integer read GetIndex; property Item[Index: Integer]: TrmDGTreeNode read GetItem write SetItem; default; property Level: Integer read GetLevel; property Owner: TrmDGTreeNodes read FOwner; property Parent: TrmDGTreeNode read GetParent write SetParent; property DGTree: TrmCustomDGTree read GeTrmDGTree; property Text: Char read FText write SetText; end; TrmDGTreeNodes = class(TPersistent) private FOwner: TrmCustomDGTree; FRootNodeList : TList; function GetNodeFromIndex(Index: Integer): TrmDGTreeNode; procedure ReadData(Stream: TStream); procedure WriteData(Stream: TStream); protected function InternalAddObject(Node: TrmDGTreeNode; const S: Char; Ptr: Integer; AddMode: TAddMode): TrmDGTreeNode; procedure DefineProperties(Filer: TFiler); override; function GetCount: Integer; procedure SetItem(Index: Integer; Value: TrmDGTreeNode); public constructor Create(AOwner: TrmCustomDGTree); destructor Destroy; override; function AddChildFirst(Node: TrmDGTreeNode; const S: Char): TrmDGTreeNode; function AddChild(Node: TrmDGTreeNode; const S: Char): TrmDGTreeNode; function AddChildObjectFirst(Node: TrmDGTreeNode; const S: Char; Ptr: Integer): TrmDGTreeNode; function AddChildObject(Node: TrmDGTreeNode; const S: Char; Ptr: Integer): TrmDGTreeNode; function AddFirst(Node: TrmDGTreeNode; const S: Char): TrmDGTreeNode; function Add(Node: TrmDGTreeNode; const S: Char): TrmDGTreeNode; function AddObjectFirst(Node: TrmDGTreeNode; const S: Char; Ptr: Integer): TrmDGTreeNode; function AddObject(Node: TrmDGTreeNode; const S: Char; Ptr: Integer): TrmDGTreeNode; procedure Assign(Source: TPersistent); override; procedure Clear; procedure Delete(Node: TrmDGTreeNode); function GetFirstNode: TrmDGTreeNode; function Insert(Node: TrmDGTreeNode; const S: Char): TrmDGTreeNode; function InsertObject(Node: TrmDGTreeNode; const S: Char; Ptr: Integer): TrmDGTreeNode; property Count: Integer read GetCount; property Item[Index: Integer]: TrmDGTreeNode read GetNodeFromIndex; default; property Owner: TrmCustomDGTree read FOwner; end; { TDGCustomDGTree } TrmDGTreeEvent = procedure(Sender: TObject; Node: TrmDGTreeNode) of object; EDGTreeError = class(Exception); TrmCustomDGTree = class(TComponent) private FMemStream: TMemoryStream; FTreeNodes: TrmDGTreeNodes; FOnDeletion: TrmDGTreeEvent; procedure SetrmDGTreeNodes(Value: TrmDGTreeNodes); protected function CreateNode: TrmDGTreeNode; virtual; procedure Delete(Node: TrmDGTreeNode); dynamic; property Items: TrmDGTreeNodes read FTreeNodes write SeTrmDGTreeNodes; property OnDeletion: TrmDGTreeEvent read FOnDeletion write FOnDeletion; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; TrmDGTree = class(TrmCustomDGTree) private { Private declarations } protected { Protected declarations } public { Public declarations } published { Published declarations } property Items; property OnDeletion; end; implementation procedure DGTreeError(const Msg: string); begin raise EDGTreeError.Create(Msg); end; constructor TrmDGTreeNode.Create(AOwner: TrmDGTreeNodes); begin inherited Create; FOwner := AOwner; FChildList := TList.Create; end; destructor TrmDGTreeNode.Destroy; begin FDeleting := True; FChildList.Free; inherited Destroy; end; function TrmDGTreeNode.GeTrmDGTree: TrmCustomDGTree; begin Result := Owner.Owner; end; function TrmDGTreeNode.HasAsParent(Value: TrmDGTreeNode): Boolean; begin if Value <> Nil then begin if Parent = nil then Result := False else if Parent = Value then Result := True else Result := Parent.HasAsParent(Value); end else Result := True; end; procedure TrmDGTreeNode.SetText(const S: Char); begin FText := S; end; procedure TrmDGTreeNode.SetData(Value: Integer); begin FData := Value; end; function TrmDGTreeNode.GetChildren: Boolean; begin Result := FChildList.Count > 0; end; function TrmDGTreeNode.GetParent: TrmDGTreeNode; begin Result := FParent; end; procedure TrmDGTreeNode.SetParent(Value : TrmDGTreeNode); begin FParent := Value; end; function TrmDGTreeNode.GetNextSibling: TrmDGTreeNode; var CurIdx : Integer; begin if Parent <> nil then begin CurIdx := Parent.FChildList.IndexOf(Self); if (CurIdx + 1) < Parent.FChildList.Count then Result := Parent.FChildList.Items[CurIdx + 1] else Result := nil; end else begin CurIdx := Owner.FRootNodeList.IndexOf(Self); if (CurIdx + 1) < Owner.FRootNodeList.Count then Result := Owner.FRootNodeList.Items[CurIdx + 1] else Result := nil; end; end; function TrmDGTreeNode.GetPrevSibling: TrmDGTreeNode; var CurIdx : Integer; begin if Parent <> nil then begin CurIdx := Parent.FChildList.IndexOf(Self); if (CurIdx - 1) < 0 then Result := Parent.FChildList.Items[CurIdx - 1] else Result := nil; end else begin CurIdx := Owner.FRootNodeList.IndexOf(Self); if (CurIdx - 1) < Owner.FRootNodeList.Count then Result := Owner.FRootNodeList.Items[CurIdx - 1] else Result := nil; end; end; function TrmDGTreeNode.GetNextChild(Value: TrmDGTreeNode): TrmDGTreeNode; begin if Value <> nil then Result := Value.GetNextSibling else Result := nil; end; function TrmDGTreeNode.GetPrevChild(Value: TrmDGTreeNode): TrmDGTreeNode; begin if Value <> nil then Result := Value.GetPrevSibling else Result := nil; end; function TrmDGTreeNode.GetFirstChild: TrmDGTreeNode; begin if FChildList.Count > 0 then begin Result := FChildList.Items[0]; end else Result := nil; end; function TrmDGTreeNode.GetLastChild: TrmDGTreeNode; begin if FChildList.Count > 0 then begin Result := FChildList.Items[FChildList.Count - 1] end else Result := nil; end; function TrmDGTreeNode.GetNext: TrmDGTreeNode; var N : TrmDGTreeNode; P : TrmDGTreeNode; begin if HasChildren then N := GetFirstChild else begin N := GetNextSibling; if N = nil then begin P := Parent; while P <> nil do begin N := P.GetNextSibling; if N <> nil then Break; P := P.Parent; end; end; end; Result := N; end; function TrmDGTreeNode.GetPrev: TrmDGTreeNode; var Node: TrmDGTreeNode; begin Result := GetPrevSibling; if Result <> nil then begin Node := Result; repeat Result := Node; Node := Result.GetLastChild; until Node = nil; end else Result := Parent; end; function TrmDGTreeNode.GetIndex: Integer; var Node: TrmDGTreeNode; begin Result := -1; Node := Self; while Node <> nil do begin Inc(Result); Node := Node.GetPrevSibling; end; end; function TrmDGTreeNode.GetItem(Index: Integer): TrmDGTreeNode; begin Result := GetFirstChild; while (Result <> nil) and (Index > 0) do begin Result := GetNextChild(Result); Dec(Index); end; if Result = nil then DGTreeError('List Index Out of Bounds'); end; procedure TrmDGTreeNode.SetItem(Index: Integer; Value: TrmDGTreeNode); begin item[Index].Assign(Value); end; function TrmDGTreeNode.IndexOf(Value: TrmDGTreeNode): Integer; var Node: TrmDGTreeNode; begin Result := -1; Node := GetFirstChild; while (Node <> nil) do begin Inc(Result); if Node = Value then Break; Node := GetNextChild(Node); end; if Node = nil then Result := -1; end; function TrmDGTreeNode.MoveTo(Destination: TrmDGTreeNode; Mode: TNodeAttachMode) : TrmDGTreeNode; {var AddMode : TAddMode; node : TrmDGTreeNode; } begin Result := nil; { if (Destination = nil) or not Destination.HasAsParent(Self) then begin AddMode := taAdd; if (Destination <> nil) and not (Mode in [naAddChild, naAddChildFirst]) then Node := Destination.Parent else Node := Destination; case Mode of naAdd, naAddChild: AddMode := taAdd; naAddFirst, naAddChildFirst: AddMode := taAddFirst; naInsert: begin Destination := Destination.GetPrevSibling; if Destination = nil then AddMode := taAddFirst else AddMode := taInsert; end; end; result := owner.InternalAddObject(Destination, Text, data, AddMode); delete; end else result:=self;} end; function TrmDGTreeNode.GetCount: Integer; var Node: TrmDGTreeNode; begin Result := 0; Node := GetFirstChild; while Node <> nil do begin Inc(Result); Node := Node.GetNextChild(Node); end; end; function TrmDGTreeNode.GetLevel: Integer; var Node: TrmDGTreeNode; begin Result := 0; Node := Parent; while Node <> nil do begin Inc(Result); Node := Node.Parent; end; end; procedure TrmDGTreeNode.Delete; begin if HasChildren then DeleteChildren; TrmCustomDGTree(Owner.Owner).Delete(Self); if Parent <> nil then begin Parent.FChildList.Delete(Parent.FChildList.IndexOf(Self)); Parent.FChildList.Pack; end else begin Owner.FRootNodeList.Delete(Owner.FRootNodeList.IndexOf(Self)); Owner.FRootNodeList.Pack; end; Free; end; procedure TrmDGTreeNode.DeleteChildren; var Node: TrmDGTreeNode; begin Node := GetFirstChild; while Node <> nil do begin Node.Delete; Node := GetFirstChild; end; end; procedure TrmDGTreeNode.Assign(Source: TPersistent); var Node: TrmDGTreeNode; begin if Source is TrmDGTreeNode then begin Node := TrmDGTreeNode(Source); Text := Node.Text; Data := Node.Data; end else inherited Assign(Source); end; function TrmDGTreeNode.IsEqual(Node: TrmDGTreeNode): Boolean; begin Result := (Text = Node.Text) and (Data = Node.Data); end; procedure TrmDGTreeNode.ReadData(Stream: TStream; Info: PDGNodeInfo); var I, Size, ItemCount: Integer; begin Stream.ReadBuffer(Size, SizeOf(Size)); Stream.ReadBuffer(Info^, Size); Text := Info^.Text; ItemCount := Info^.Count; Data := Info^.Index; for I := 0 to ItemCount - 1 do Owner.AddChild(Self, #0).ReadData(Stream, Info); end; procedure TrmDGTreeNode.WriteData(Stream: TStream; Info: PDGNodeInfo); var I, Size, ItemCount: Integer; begin Size := SizeOf(TDGNodeInfo); Info^.Text := Text; ItemCount := Count; Info^.Count := ItemCount; Info^.Index := Data; Stream.WriteBuffer(Size, SizeOf(Size)); Stream.WriteBuffer(Info^, Size); for I := 0 to ItemCount - 1 do Item[I].WriteData(Stream, Info); end; { TrmDGTreeNodes } constructor TrmDGTreeNodes.Create(AOwner: TrmCustomDGTree); begin inherited Create; FOwner := AOwner; FRootNodeList := TList.Create; end; destructor TrmDGTreeNodes.Destroy; begin Clear; FRootNodeList.Free; inherited Destroy; end; function TrmDGTreeNodes.GetCount: Integer; var N : TrmDGTreeNode; begin N := GetFirstNode; Result := 0; while N <> nil do begin Result := Result + 1; N := N.GetNext; end; end; procedure TrmDGTreeNodes.Delete(Node: TrmDGTreeNode); begin Node.Delete; end; procedure TrmDGTreeNodes.Clear; var N : TrmDGTreeNode; begin N := GetFirstNode; While N <> nil do begin N.Delete; N := GetFirstNode; end; end; function TrmDGTreeNodes.AddChildFirst(Node: TrmDGTreeNode; const S: Char): TrmDGTreeNode; begin Result := AddChildObjectFirst(Node, S, -1); end; function TrmDGTreeNodes.AddChildObjectFirst(Node: TrmDGTreeNode; const S: Char; Ptr: Integer): TrmDGTreeNode; begin Result := InternalAddObject(Node, S, Ptr, taAddFirst); end; function TrmDGTreeNodes.AddChild(Node: TrmDGTreeNode; const S: char): TrmDGTreeNode; begin Result := AddChildObject(Node, S, -1); end; function TrmDGTreeNodes.AddChildObject(Node: TrmDGTreeNode; const S: char; Ptr: integer): TrmDGTreeNode; begin Result := InternalAddObject(Node, S, Ptr, taAdd); end; function TrmDGTreeNodes.AddFirst(Node: TrmDGTreeNode; const S: char): TrmDGTreeNode; begin Result := AddObjectFirst(Node, S, -1); end; function TrmDGTreeNodes.AddObjectFirst(Node: TrmDGTreeNode; const S: char; Ptr: integer): TrmDGTreeNode; begin if Node <> nil then Node := Node.Parent; Result := InternalAddObject(Node, S, Ptr, taAddFirst); end; function TrmDGTreeNodes.Add(Node: TrmDGTreeNode; const S: char): TrmDGTreeNode; begin Result := AddObject(Node, S, -1); end; function TrmDGTreeNodes.AddObject(Node: TrmDGTreeNode; const S: char; Ptr: integer): TrmDGTreeNode; begin if Node <> nil then Node := Node.Parent; Result := InternalAddObject(Node, S, Ptr, taAdd); end; function TrmDGTreeNodes.Insert(Node: TrmDGTreeNode; const S: char): TrmDGTreeNode; begin Result := InsertObject(Node, S, -1); end; function TrmDGTreeNodes.InsertObject(Node: TrmDGTreeNode; const S: char; Ptr: Integer): TrmDGTreeNode; var Parent : TrmDGTreeNode; AddMode : TAddMode; begin AddMode := taInsert; if Node <> nil then begin Parent := Node.Parent; if Parent <> nil then Node := Node.GetPrevSibling; if Node = nil then AddMode := taAddFirst; end; Result := InternalAddObject(Node, S, Ptr, AddMode); end; function TrmDGTreeNodes.InternalAddObject(Node: TrmDGTreeNode; const S: char; Ptr: integer; AddMode: TAddMode): TrmDGTreeNode; begin Result := Owner.CreateNode; try case AddMode of taAddFirst: begin if Node = nil then begin FRootNodeList.Insert(0, Result); Result.Parent := nil; end else begin Node.FChildList.Insert(0, Result); Result.Parent := Node; end; try Result.Data := Ptr; Result.Text := S; except raise; end; end; taAdd: begin if Node = nil then begin FRootNodeList.Add(Result); Result.Parent := nil; end else begin Node.FChildList.Add(Result); Result.Parent := Node; end; try Result.Data := Ptr; Result.Text := S; except raise; end; end; taInsert: begin end; end; except raise; end; end; function TrmDGTreeNodes.GetFirstNode: TrmDGTreeNode; begin if FRootNodeList.Count = 0 then Result := nil else Result := FRootNodeList.Items[0]; end; function TrmDGTreeNodes.GetNodeFromIndex(Index: Integer): TrmDGTreeNode; var I: Integer; begin Result := GetFirstNode; I := Index; while (I <> 0) and (Result <> nil) do begin Result := Result.GetNext; Dec(I); end; if Result = nil then DGTreeError('Index out of range'); end; procedure TrmDGTreeNodes.SetItem(Index: Integer; Value: TrmDGTreeNode); begin GetNodeFromIndex(Index).Assign(Value); end; procedure TrmDGTreeNodes.Assign(Source: TPersistent); var TreeNodes: TrmDGTreeNodes; MemStream: TMemoryStream; begin if Source is TrmDGTreeNodes then begin TreeNodes := TrmDGTreeNodes(Source); Clear; MemStream := TMemoryStream.Create; try TreeNodes.WriteData(MemStream); MemStream.Position := 0; ReadData(MemStream); finally MemStream.Free; end; end else inherited Assign(Source); end; procedure TrmDGTreeNodes.DefineProperties(Filer: TFiler); function WriteNodes: Boolean; var I: Integer; Nodes: TrmDGTreeNodes; begin Nodes := TrmDGTreeNodes(Filer.Ancestor); if Nodes = nil then Result := Count > 0 else if Nodes.Count <> Count then Result := True else begin Result := False; for I := 0 to Count - 1 do begin Result := not Item[I].IsEqual(Nodes[I]); if Result then Break; end end; end; begin inherited DefineProperties(Filer); Filer.DefineBinaryProperty('Data', ReadData, WriteData, WriteNodes); end; procedure TrmDGTreeNodes.ReadData(Stream: TStream); var I, Count: Integer; Info : TDGNodeInfo; begin Clear; Stream.ReadBuffer(Count, SizeOf(Count)); for I := 0 to Count - 1 do Add(nil, #0).ReadData(Stream, @Info); end; procedure TrmDGTreeNodes.WriteData(Stream: TStream); var I: Integer; Node: TrmDGTreeNode; Info : TDGNodeInfo; begin I := 0; Node := GetFirstNode; while Node <> nil do begin Inc(I); Node := Node.GetNextSibling; end; Stream.WriteBuffer(I, SizeOf(I)); Node := GetFirstNode; while Node <> nil do begin Node.WriteData(Stream, @Info); Node := Node.GetNextSibling; end; end; { TrmCustomDGTree } constructor TrmCustomDGTree.Create(AOwner: TComponent); begin inherited Create(AOwner); FTreeNodes := TrmDGTreeNodes.Create(Self); end; destructor TrmCustomDGTree.Destroy; begin Items.Free; FMemStream.Free; inherited Destroy; end; procedure TrmCustomDGTree.SetrmDGTreeNodes(Value: TrmDGTreeNodes); begin Items.Assign(Value); end; procedure TrmCustomDGTree.Delete(Node: TrmDGTreeNode); begin if Assigned(FOnDeletion) then FOnDeletion(Self, Node); end; function TrmCustomDGTree.CreateNode: TrmDGTreeNode; begin Result := TrmDGTreeNode.Create(Items); end; end.
unit API_MVC_DB; interface uses API_DB, API_MVC, System.Generics.Collections; type TModelDB = class abstract(TModelAbstract) protected FDBEngine: TDBEngine; public constructor Create(aDataObj: TObjectDictionary<string, TObject>; aTaskIndex: Integer = 0); override; end; TControllerDB = class abstract(TControllerAbstract) private FDBEngine: TDBEngine; procedure ConnectToDB(aDBEngine: TDBEngine); protected FConnectOnCreate: Boolean; FConnectParams: TConnectParams; FDBEngineClass: TDBEngineClass; function CreateDBEngine: TDBEngine; procedure AfterCreate; virtual; procedure BeforeDestroy; virtual; procedure CallModel<T: TModelAbstract>(aThreadCount: Integer = 1); procedure CallModelAsync<T: TModelAbstract>(aThreadCount: Integer = 1); /// <summary> /// Override this procedure for assign FDBEngineClass and set FConnectParams. /// </summary> procedure InitDB(var aDBEngineClass: TDBEngineClass; out aConnectParams: TConnectParams; out aConnectOnCreate: Boolean); virtual; abstract; procedure ModelListener(const aMsg: string; aModel: TModelAbstract); override; public constructor Create; override; destructor Destroy; override; property DBEngine: TDBEngine read FDBEngine write FDBEngine; end; implementation uses System.SysUtils; procedure TControllerDB.CallModelAsync<T>(aThreadCount: Integer = 1); begin FIsAsyncModelRunMode := True; CallModel<T>(aThreadCount); FIsAsyncModelRunMode := False; end; procedure TControllerDB.ModelListener(const aMsg: string; aModel: TModelAbstract); begin if (aMsg = aModel.EndMessage) and (aModel.InheritsFrom(TModelDB)) and (aModel.TaskIndex > 0) then TModelDB(aModel).FDBEngine.Free; inherited; end; function TControllerDB.CreateDBEngine: TDBEngine; begin Result := FDBEngineClass.Create(FConnectParams); if FConnectOnCreate then ConnectToDB(Result); end; procedure TControllerDB.CallModel<T>(aThreadCount: Integer = 1); var DBEngine: TDBEngine; DBEngineList: TObjectList<TDBEngine>; i: Integer; begin DBEngineList := TObjectList<TDBEngine>.Create(False); try DBEngineList.Add(FDBEngine); for i := 2 to aThreadCount do begin DBEngine := CreateDBEngine; DBEngineList.Add(DBEngine); end; FDataObj.AddOrSetValue('DBEngineList', DBEngineList); inherited CallModel<T>(aThreadCount); finally DBEngineList.Free; end; end; constructor TModelDB.Create(aDataObj: TObjectDictionary<string, TObject>; aTaskIndex: Integer = 0); var DBEngineList: TObjectList<TDBEngine>; begin inherited; DBEngineList := aDataObj.Items['DBEngineList'] as TObjectList<TDBEngine>; FDBEngine := DBEngineList[aTaskIndex]; end; procedure TControllerDB.BeforeDestroy; begin end; procedure TControllerDB.AfterCreate; begin end; destructor TControllerDB.Destroy; begin BeforeDestroy; inherited; if FDBEngine.IsConnected then FDBEngine.CloseConnection; FDBEngine.Free; end; procedure TControllerDB.ConnectToDB(aDBEngine: TDBEngine); begin aDBEngine.OpenConnection; end; constructor TControllerDB.Create; begin inherited; try InitDB(FDBEngineClass, FConnectParams, FConnectOnCreate); except on e:EAbstractError do raise Exception.Create('Necessary procedure InitDB of Controller is absent!'); else raise; end; if not Assigned(FDBEngineClass) then raise Exception.Create('FDBEngineClass isn`t assigned!'); FDBEngine := CreateDBEngine; AfterCreate; end; end.
unit uDemo; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, DB, DBClient, uHTMLBuilder, ShellAPI; type TfrmDemo = class(TForm) btnSampleDataSet: TButton; cdsProducts: TClientDataSet; cdsProductsproduct: TStringField; cdsProductsprice: TStringField; btnMultiHeader: TButton; procedure FormCreate(Sender: TObject); procedure btnSampleDataSetClick(Sender: TObject); procedure btnMultiHeaderClick(Sender: TObject); private { Private declarations } procedure PopulateDataSet(dataSet: TDataSet); procedure OpenHTMLDocument(report: THTMLReport); function GetReportStyle:string; public { Public declarations } end; var frmDemo: TfrmDemo; implementation uses Math; const cNUMBER_PRODUCT=50; {$R *.dfm} procedure TfrmDemo.PopulateDataSet(dataSet: TDataSet); var i: Integer; product, price: TField; begin product := dataSet.FieldByName('product'); price := dataSet.FieldByName('price'); for i := 1 to cNUMBER_PRODUCT do begin dataSet.Append; product.AsString := 'PRODUCT ' + FormatFloat('00', i); price.AsString := '$' + FormatFloat('#,###.00', RandomRange(1, cNUMBER_PRODUCT)*10); dataSet.Post; end; end; procedure TfrmDemo.OpenHTMLDocument(report: THTMLReport); var htmlFile: string; begin htmlFile := IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName)) + 'teste.html'; report.SaveToFile(htmlFile); ShellExecute(Handle, 'Open', 'iexplore.exe', PChar(htmlFile), '', SW_SHOWNORMAL); end; function TfrmDemo.GetReportStyle:string; var style: TStringList; begin style := TStringList.Create; try style.Clear; style.Add('* {font-family:Arial;font-size:11pt}'); style.Add('html, body {height:100%;}'); style.Add('table {width:100% ;border-collapse: collapse;}'); Result := style.Text; finally style.Free; end; end; procedure TfrmDemo.FormCreate(Sender: TObject); begin cdsProducts.CreateDataSet; PopulateDataSet(cdsProducts); end; procedure TfrmDemo.btnSampleDataSetClick(Sender: TObject); const cPARAGRAPH_STYLE='style="font-weight:bold;font-size:15pt;text-align:center;"'; var html: THTMLReport; table: THTMLTable; begin html := THTMLReport.Create(GetReportStyle); table := THTMLTable.Create; try table.SetDataSet(cdsProducts, '#909090', '#FFFFFF', '#D0D0D0'); html.AddParagraph('Test using dataset', cPARAGRAPH_STYLE); html.AddTable(table); OpenHTMLDocument(html); finally FreeAndNil(html); end; end; procedure TfrmDemo.btnMultiHeaderClick(Sender: TObject); const cPARAGRAPH_STYLE='style="font-weight:bold;font-size:15pt;text-align:center;"'; cHEADER_STYLE='style="font-weight:bold;background-color:silver"'; var html: THTMLReport; table: THTMLTable; product, price: THTMLCell; discount10, discount5, fullprice: THTMLCell; priceValue: Integer; i: Integer; begin html := THTMLReport.Create(GetReportStyle); try table := THTMLTable.Create('border="1px solid black"'); product := THTMLCell.Create('Product', 'rowspan=2 ' + cHEADER_STYLE); price := THTMLCell.Create('Price', 'colspan=3 align=center ' + cHEADER_STYLE); discount10 := THTMLCell.Create('10% discount', 'width="15%" ' + cHEADER_STYLE); discount5 := THTMLCell.Create('5% discount', 'width="15%" ' + cHEADER_STYLE); fullprice := THTMLCell.Create('full price', 'width="20%" ' + cHEADER_STYLE); //header table.AddRow([product, price], ''); //sub header table.AddRow([fullprice, discount5, discount10], ''); //lines for i := 1 to cNUMBER_PRODUCT do begin priceValue := RandomRange(1, cNUMBER_PRODUCT)*10; table.AddRow([THTMLCell.Create('PRODUCT'+IntToStr(i), ''), THTMLCell.Create('$' + FormatFloat('#,###.00', priceValue), ''), THTMLCell.Create('$' + FormatFloat('#,###.00', (priceValue*0.95)), ''), THTMLCell.Create('$' + FormatFloat('#,###.00', (priceValue*0.9)), '')], ''); end; html.AddParagraph('Test using multi header', cPARAGRAPH_STYLE); html.AddTable(table); OpenHTMLDocument(html); finally FreeAndNil(html); end; end; end.
unit htMarkup; interface uses Classes, Contnrs, htTag; type ThtMarkup = class private FDocType: string; protected procedure InitMarkup; public Body: ThtTag; Head: ThtTag; Includes: ThtTag; Styles: ThtTag; Script: ThtTag; //InitCode: ThtTag; //ResizeCode: ThtTag; constructor Create; destructor Destroy; override; function AddJavaScriptInclude(const inSrc: string = ''): ThtTag; function AddJavaScript(const inCode: string = ''): ThtTag; function CreateFunctionTag(const inFuncSig: string): ThtTag; function CreateJavaScriptNode: ThtTag; function CreateStyleNode: ThtTag; procedure Add(const inString: string); procedure Build(inStrings: TStrings); procedure SaveToFile(const inFilename: string); property DocType: string read FDocType write FDocType; end; implementation { ThtMarkup } constructor ThtMarkup.Create; begin InitMarkup; end; destructor ThtMarkup.Destroy; begin Head.Free; Body.Free; inherited; end; function ThtMarkup.CreateJavaScriptNode: ThtTag; begin Result := ThtTag.Create('script', [ tfLineBreak ]); Result.Attributes['type'] := 'text/javascript'; Result.Attributes['language'] := 'javascript'; end; function ThtMarkup.CreateStyleNode: ThtTag; begin Result := ThtTag.Create('style'); Result.Attributes['type'] := 'text/css'; end; procedure ThtMarkup.InitMarkup; begin DocType := '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">'; // Styles := CreateStyleNode; //Styles.Content.Add('td { vertical-align: top; }'); // Includes := ThtTag.Create; // Script := CreateJavaScriptNode; Script.Flags := Script.Flags + [ tfHideIfEmpty ]; // //InitCode := CreateFunctionTag('init()'); //ResizeCode := CreateFunctionTag('resize'); // Head := ThtTag.Create('head', [ tfLineBreak ]); Head.Add(Styles); Head.Add(Includes); Head.Add(Script); // Body := ThtTag.Create('body', [ tfLineBreak ]); //Body.Attributes['onload'] := 'init()'; //Body.Attributes['onresize'] := 'resize()'; end; function ThtMarkup.CreateFunctionTag(const inFuncSig: string): ThtTag; var tag: ThtTag; begin tag := ThtTag.Create; tag.Content.Add('function ' + inFuncSig); tag.Content.Add('{'); Script.Add(tag); Result := ThtTag.Create; Script.Add(Result); tag := ThtTag.Create; Script.Add(tag); tag.Content.Add('}'); end; procedure ThtMarkup.Add(const inString: string); begin Body.Add(inString); end; function ThtMarkup.AddJavaScript(const inCode: string): ThtTag; begin Result := CreateJavaScriptNode; Result.Content.Text := inCode; Head.Add(Result); end; function ThtMarkup.AddJavaScriptInclude(const inSrc: string): ThtTag; begin Result := CreateJavaScriptNode; Result.Attributes['src'] := inSrc; Head.Add(Result); end; procedure ThtMarkup.Build(inStrings: TStrings); begin with inStrings do begin Add(DocType); Add('<html>'); Add(Head.Html); Add(Body.Html); Add('</html>'); end; end; procedure ThtMarkup.SaveToFile(const inFilename: string); var s: TStringList; begin s := TStringList.Create; try Build(s); s.SaveToFile(inFilename); finally s.Free; end; end; end.
unit ErrorMessages; interface uses Classes, Generics.Collections; type TAnsiStringList = TList<AnsiString>; var ErrorValues: TAnsiStringList; WarningValues: TAnsiStringList; // These are error messages that start with a number. NumberErrorValues: TAnsiStringList; implementation Procedure AssignErrorStrings; begin ErrorValues.Add('INVALID VALUE FOR IFREQ PARAMETER:'); ErrorValues.Add('INSUFFICIENT MEMORY FOR DE4 SOLVER:'); ErrorValues.Add('ERROR IN GMG INPUT'); ErrorValues.Add('ALLOCATION ERROR IN SUBROUTINE GMG1ALG'); ErrorValues.Add('GMG ASSEMBLY ERROR IN SUBROUTINE GMG1AP'); ErrorValues.Add('DIS file must be specified for MODFLOW to run'); ErrorValues.Add('SSFLAG MUST BE EITHER "SS" OR "TR"'); ErrorValues.Add('STOP EXECUTION'); ErrorValues.Add('THERE MUST BE AT LEAST ONE TIME STEP IN EVERY STRESS PERIOD'); ErrorValues.Add('PERLEN MUST NOT BE 0.0 FOR TRANSIENT STRESS PERIODS'); ErrorValues.Add('TSMULT MUST BE GREATER THAN 0.0'); ErrorValues.Add('PERLEN CANNOT BE LESS THAN 0.0 FOR ANY STRESS PERIOD'); ErrorValues.Add('ERROR READING OUTPUT CONTROL INPUT DATA:'); ErrorValues.Add('CANNOT OPEN'); ErrorValues.Add('FIRST ENTRY IN NAME FILE MUST BE "LIST".'); ErrorValues.Add('ILLEGAL FILE TYPE IN NAME FILE:'); ErrorValues.Add('NAME FILE IS EMPTY.'); ErrorValues.Add('BAS PACKAGE FILE HAS NOT BEEN OPENED.'); ErrorValues.Add('ERROR OPENING FILE'); ErrorValues.Add('ARRAY OPERAND HAS NOT BEEN PREVIOUSLY DEFINED:'); ErrorValues.Add('NPVAL IN PARAMETER INPUT FILE MUST BE'); ErrorValues.Add('BUT THE MAXIMUM NUMBER OF PARAMETERS IS'); ErrorValues.Add('ERROR FOUND IN PARAMETER INPUT FILE. SEARCH ABOVE'); ErrorValues.Add('ERROR ENCOUNTERED IN READING PARAMETER INPUT FILE'); // ErrorValues.Add('IS GREATER THAN'); ErrorValues.Add('IS GREATER THAN MXACTC'); ErrorValues.Add('NO-FLOW CELLS CANNOT BE CONVERTED TO SPECIFIED HEAD'); ErrorValues.Add('IS GREATER THAN MXACTD'); ErrorValues.Add('IS GREATER THAN MXADRT'); ErrorValues.Add('is outside of the grid'); ErrorValues.Add('Blank parameter name in the'); ErrorValues.Add('Parameter type conflict:'); ErrorValues.Add('Blank instance name'); ErrorValues.Add('file specifies undefined instance'); ErrorValues.Add('*** ERROR: PARAMETER'); ErrorValues.Add('IS GREATER THAN THE MAXIMUM ALLOWED'); ErrorValues.Add('file specifies an undefined parameter'); ErrorValues.Add('Parameter type must be'); ErrorValues.Add('ILLEGAL ET OPTION CODE'); ErrorValues.Add('INVALID LAYER NUMBER IN IEVT FOR COLUMN'); ErrorValues.Add('SIMULATION ABORTING'); ErrorValues.Add('Aborting. Weights for Auxiliary variables cannot'); ErrorValues.Add('ABORTING'); ErrorValues.Add('*** ERROR'); ErrorValues.Add('IS GREATER THAN MXACTB'); ErrorValues.Add('INSTANCES ARE NOT SUPPORTED FOR HFB'); ErrorValues.Add('ERROR DETECTED IN LOCATION DATA OF BARRIER NO.'); ErrorValues.Add('LAYWT is not 0 and LTHUF is 0 for layer:'); ErrorValues.Add('Invalid parameter type'); ErrorValues.Add('Simulation is transient and no storage parameters are'); ErrorValues.Add('Simulation is steady state and storage parameters are'); ErrorValues.Add('Simulation is transient and has convertible'); ErrorValues.Add('Simulation has SYTP parameter(s) defined but has a'); ErrorValues.Add('STOP SGWF2HUF7VKA'); ErrorValues.Add('CONSTANT-HEAD CELL WENT DRY'); ErrorValues.Add('Sy not defined for cell at'); ErrorValues.Add('***ERROR***'); ErrorValues.Add('INTERBED STORAGE INAPPROPRIATE FOR A STEADY-STATE'); ErrorValues.Add('GSFLOW-1.0 cannot simulate transport'); ErrorValues.Add('--program stopping'); ErrorValues.Add('MAXIMUM NUMBER OF GRID CELLS ADJACENT TO LAKES'); ErrorValues.Add('LAK Package requires BCF or LPF'); ErrorValues.Add('PROGRAM STOPPING'); ErrorValues.Add('ERROR - NO AQUIFER UNDER LAKE CELL'); ErrorValues.Add('***NLAKES too large for BUFF in Subroutine GWF2'); ErrorValues.Add('LAYWET is not 0 and LAYTYP is 0 for layer'); ErrorValues.Add('LAYWET must be 0 if LAYTYP is 0'); ErrorValues.Add('IS AN INVALID LAYAVG VALUE -- MUST BE 0, 1, or 2'); ErrorValues.Add('Negative cell thickness at (layer,row,col)'); ErrorValues.Add('SIMULATION ABORTED'); ErrorValues.Add('Negative confining bed thickness below cell (Layer,row,col)'); ErrorValues.Add('exceeds maximum of'); ErrorValues.Add('IS GREATER THAN mxwel2'); ErrorValues.Add('ERROR opening auxillary input file'); ErrorValues.Add('ILLEGAL RECHARGE OPTION CODE'); ErrorValues.Add('INVALID LAYER NUMBER IN IRCH'); ErrorValues.Add('IS GREATER THAN MXACTR'); ErrorValues.Add('SEGMENT MUST BE GREATER THAN 0 AND LESS THAN NSS'); ErrorValues.Add('SEGMENTS MUST BE IN ORDER FROM 1 THROUGH NSS'); ErrorValues.Add('REACHES MUST BE NUMBERED CONSECUTIVELY'); ErrorValues.Add('RESIDUAL WATER CONTENT IS EQUAL OR GREATER THAN'); ErrorValues.Add('INITIAL WATER CONTENT IS GREATER THAN SATURATED'); ErrorValues.Add('PROGRAM TERMINATED'); ErrorValues.Add('CANNOT SPECIFY MORE THAN NSS STREAM SEGMENTS'); ErrorValues.Add('CODE STOPPING'); ErrorValues.Add('SEGMENT NUMBER (NSEG) OUT OF RANGE:'); ErrorValues.Add('Blank instance name'); ErrorValues.Add('GREATER THAN MXACTS'); ErrorValues.Add('SUBSIDENCE CANNOT BE USED'); ErrorValues.Add('STOPPING'); ErrorValues.Add('IMPROPER LAYER ASSIGNMENT'); ErrorValues.Add('GREATER THAN MXACTW'); ErrorValues.Add('Duplicate parameter name'); ErrorValues.Add('The number of parameters has exceeded the maximum'); ErrorValues.Add('Multiplier array has not been defined'); ErrorValues.Add('There were no zone values specified in the cluster'); ErrorValues.Add('Zone array has not been defined'); ErrorValues.Add('NH LESS THAN OR EQUAL TO 0'); ErrorValues.Add('ERROR:'); ErrorValues.Add('An observation cannot be placed'); ErrorValues.Add('NQTCH LESS THAN OR EQUAL TO 0'); ErrorValues.Add('SEE ABOVE FOR ERROR MESSAGE'); ErrorValues.Add('DRAIN PACKAGE OF GWF IS NOT OPEN'); ErrorValues.Add('NUMBER OF OBSERVATIONS LESS THAN OR EQUAL TO 0'); ErrorValues.Add('GHB PACKAGE OF GWF IS NOT OPEN'); ErrorValues.Add('RIVER PACKAGE OF GWF IS NOT OPEN'); ErrorValues.Add('EXCEEDED THE MAXIMUM NUMBER OF INSTANCES:'); ErrorValues.Add('The above parameter must be defined prior to its use'); ErrorValues.Add('Number of parameters exceeds MXPAR'); ErrorValues.Add('EXCEEDED THE MAXIMUM NUMBER OF LIST ENTRIES:'); ErrorValues.Add('EXCEEDED THE MAXIMUM NUMBER OF INSTANCES:'); ErrorValues.Add('Parameter type must be:'); ErrorValues.Add('ERROR CONVERTING'); ErrorValues.Add('ERROR READING ARRAY CONTROL RECORD'); ErrorValues.Add('INVALID INTERBLOCK T CODE:'); ErrorValues.Add('INVALID LAYER TYPE:'); ErrorValues.Add('LAYER TYPE 1 IS ONLY ALLOWED IN TOP LAYER'); ErrorValues.Add('FAILED TO MEET SOLVER CONVERGENCE CRITERIA'); ErrorValues.Add('nlakes dimension problem in lak7'); ErrorValues.Add('MAXIMUM NUMBER OF GRID CELLS ADJACENT TO LAKES HAS BEEN EXCEEDED WITH CELL'); ErrorValues.Add('LAK Package requires BCF, LPF, or HUF'); ErrorValues.Add('THIS WILL CAUSE PROBLEMS IN COMPUTING LAKE STAGE USING THE NEWTON METHOD.'); // ErrorValues.Add('***NLAKES too large for BUFF in Subroutine GWF2LAK7SFR7RPS*** STOP EXECUTION'); ErrorValues.Add('FAILED TO CONVERGE'); ErrorValues.Add('Can''t find name file'); ErrorValues.Add('INVALID INPUT FOR GRIDSTATUS IN LGR INPUT FILE:'); ErrorValues.Add('GRIDSTATUS MUST BE PARENTONLY, CHILDONLY, OR PARENTANDCHILD'); ErrorValues.Add('IBFLG MUST BE < 0 FOR CHILD GRID'); ErrorValues.Add('RELAXATION FACTORS RELAXH AND RELAXF MUST BE > 0'); ErrorValues.Add('NPLBEG IS NOT = 1 REFINEMENT MUST BEGIN IN TOP LAYER'); ErrorValues.Add('NCPP MUST BE AN ODD INTEGER'); ErrorValues.Add('NROW AND NCPP DOES NOT ALIGN WITH NPREND - NPRBEG'); ErrorValues.Add('NCOL AND NCPP DOES NOT ALIGN WITH NPCEND - NPCBEG'); ErrorValues.Add('NCPPL MUST BE AN ODD INTEGER'); ErrorValues.Add('VERTICAL REFINEMENT DOES NOT ALIGN WITH NLAY'); ErrorValues.Add('HEAD BELOW BOTTOM AT SHARED NODE'); ErrorValues.Add('INVALID INPUT IN BFH FILE:'); ErrorValues.Add('ISCHILD AND BTEXT ARE NOT COMPATIBLE'); ErrorValues.Add('MNW1 and MNW2 cannot both be active in the same grid'); ErrorValues.Add('MNW1 and MNW2 cannot both be active in the same simulation'); ErrorValues.Add('Failure to converge'); ErrorValues.Add('NSTACK too small in index'); ErrorValues.Add('ELEVATION OF STREAM OUTLET MUST BE GREATER THAN OR EQUAL TO THE LOWEST ELEVATION OF THE LAKE.'); ErrorValues.Add('If the BCF Package is used and unsaturated flow is active then ISFROPT must equal 3 or 5.'); ErrorValues.Add('Streambed has lower altitude than GW cell bottom. Model stopping'); ErrorValues.Add('STOPPING SIMULATION'); ErrorValues.Add('***ERROR: MNW2 PACKAGE DOES NOT SUPPORT'); ErrorValues.Add('*** BAD RECORD ENCOUNTERED, PCGN DATA INPUT ***'); ErrorValues.Add('***BAD DATA READ, SUBROUTINE PCGNRP***'); ErrorValues.Add('UNABLE TO ALLOCATE STORAGE REQUIRED FOR PCG SOLVER'); ErrorValues.Add('ERROR ENCOUNTERED IN SUBROUTINE PCGNRP'); ErrorValues.Add('ERROR ENCOUNTERED IN SUBROUTINE PCG_INIT'); ErrorValues.Add('ERROR ENCOUNTERED IN SUBROUTINE PCG'); ErrorValues.Add('DIMENSION MISMATCH DISCOVERED'); ErrorValues.Add('UNKNOWN ERROR'); ErrorValues.Add('DID NOT CONVERGE'); ErrorValues.Add('Allocation error in subroutine PCG_init'); ErrorValues.Add('ARRAY DIAG CONTAINS A NEGATIVE ELEMENT AT NODE'); ErrorValues.Add('Allocation error in subroutine PCG'); ErrorValues.Add('Dimension mismatch in subroutine PCG'); ErrorValues.Add('NOT DEFINED FOR PARAMETER TYPE'); ErrorValues.Add('HUF and LAK cannot be used together in a simulation'); ErrorValues.Add('IS LISTED MORE THAN ONCE IN PARAMETER FILE'); ErrorValues.Add('IN PARAMETER INPUT FILE HAS NOT BEEN DEFINED'); ErrorValues.Add('ERROR: Proportion must be between 0.0 and 1.0'); ErrorValues.Add('ERROR DETECTED IN LOCATION DATA OF BARRIER'); ErrorValues.Add('LAYWT must be 0 if LTHUF is 0'); ErrorValues.Add('Vertical K is zero in row'); ErrorValues.Add('Horizontal K is zero in row'); ErrorValues.Add('MULTKDEP is zero in row'); ErrorValues.Add('LVDA cannot calculate sensitivities'); ErrorValues.Add('LAYVKA entered for layer'); ErrorValues.Add('parameters of type VK can apply only to layers for which'); ErrorValues.Add('parameters of type VANI can apply only to layers for which'); ErrorValues.Add('MNWOBS MUST BE > 0'); ErrorValues.Add('ALLOCATION OF MNW ROUTING ARRAY FAILED'); ErrorValues.Add('MNW2 NODE ARRAY ALLOCATION INSUFFICIENT'); ErrorValues.Add('MNW2 Node not in grid; Layer, Row, Col='); ErrorValues.Add('ILLEGAL OPTION CODE. SIMULATION ABORTING'); ErrorValues.Add('Model stopping'); ErrorValues.Add('CANNOT BE READ FROM RESTART RECORDS'); ErrorValues.Add('IMPROPER LAYER ASSIGNMENT FOR SUB-WT SYSTEM OF'); ErrorValues.Add('SUB-WT CANNOT BE USED IN CONJUNCTION WITH QUASI-3D'); ErrorValues.Add('NEGATIVE EFFECTIVE STRESS VALUE AT (ROW,COL,LAY):'); ErrorValues.Add('ERROR READING LMT PACKAGE INPUT DATA'); ErrorValues.Add('ERROR IN LMT PACKAGE INPT DATA:'); ErrorValues.Add('ERROR IN LMT PACKAGE INPUT DATA:'); ErrorValues.Add('BETWEEN 1 AND NPER (OF THE DISCRETIZATION INPUT FILE'); ErrorValues.Add('STREAMFLOW PACKAGE OF GWF IS NOT OPEN'); ErrorValues.Add('Package has not been defined'); ErrorValues.Add('MATRIX IS SEVERELY NON-DIAGONALLY DOMINANT'); ErrorValues.Add('CONJUGATE-GRADIENT METHOD FAILED'); ErrorValues.Add('DIVIDE BY 0 IN SIP AT LAYER'); // ErrorValues.Add('NOT FOUND (STOP EXECUTION(GWF2HUF7RPGD))'); NumberErrorValues.Add('CLUSTERS WERE SPECIFIED, BUT THERE IS SPACE FOR ONLY'); NumberErrorValues.Add(' NaN'); // MODFLOW-NWT ErrorValues.Add('THIS WILL CAUSE PROBLEMS IN COMPUTING LAKE STAGE USING THE NEWTON METHOD.'); ErrorValues.Add('***ERROR: MNW PACKAGE DOES NOT SUPPORT HEAD-DEPENDENT'); ErrorValues.Add('THICKNESS OPTION OF SELECTED FLOW PACKAGE'); ErrorValues.Add('(MNW DOES FULLY SUPPORT BCF, LPF, AND HUF PACKAGES)'); ErrorValues.Add('NSTRM IS NEGATIVE AND THIS METHOD FOR SPECIFYING INFORMATION BY REACH HAS BEEN REPLACED BY THE KEYWORD OPTION "REACHINPUT"--PROGRAM STOPPING'); ErrorValues.Add('Streambed has lower altitude than GW cell bottom. Model stopping'); ErrorValues.Add('TOO MANY WAVES IN UNSAT CELL'); ErrorValues.Add('PROGRAM TERMINATED IN UZFLOW-1'); ErrorValues.Add('***Erroneous value for Input value "Options."***'); ErrorValues.Add('Check input. Model Stopping.'); ErrorValues.Add('***Incorrect value for Linear solution method specified. Check input.***'); ErrorValues.Add('Error in Preconditioning:'); ErrorValues.Add('Linear solver failed to converge:'); ErrorValues.Add('Error in gmres: '); ErrorValues.Add('***Incorrect value for variable Nonmeth was specified. Check input.***'); ErrorValues.Add('error in data structure!!'); ErrorValues.Add('too many iterations!!'); ErrorValues.Add('error in xmdsfacl'); ErrorValues.Add('no diagonal in L\U: row number'); ErrorValues.Add('error in min. degree ordering'); ErrorValues.Add('error in subroutine xmdRedBlack'); ErrorValues.Add('need more space in integer temp. array'); ErrorValues.Add('error in red-black ordering'); ErrorValues.Add('error in xmdnfctr (xmbnfac)'); ErrorValues.Add('error in xmdprpc (xmdordng)'); ErrorValues.Add('error in xmdprpc (xmdrowrg)'); ErrorValues.Add('error in xmdprecl (xmdsfacl)'); ErrorValues.Add('error in xmdprecd (xmdsfacd)'); ErrorValues.Add('error in xmdcheck'); ErrorValues.Add('SWR PROCESS REQUIRES LAYCON OF 1 OR 3 FOR'); ErrorValues.Add('SWR PROCESS REQUIRES USE OF THE BCF, LPF,'); ErrorValues.Add('COULD NOT PARSE NTABRCH FOR TABULAR DATA ITEM'); ErrorValues.Add('CONFINED AQUIFERS CANNOT BE SIMULATED WITH SWR'); ErrorValues.Add('FLOW PACKAGE SPECIFIED INCONSISTENT WITH SWR'); ErrorValues.Add('SWR 4D: COULD NOT PARSE NTABRCH'); ErrorValues.Add('ERROR CANNOT REUSE'); ErrorValues.Add('ERROR REACH ITEM'); ErrorValues.Add('MUST BE GREATER THAN'); // THETA MUST BE LESS THAN is an informative message not an error message. // ErrorValues.Add('MUST BE LESS THAN'); ErrorValues.Add('MUST BE LESS THAN OR'); ErrorValues.Add('MUST BE LESS THAN 4'); ErrorValues.Add('MUST NOT EQUAL'); ErrorValues.Add('RTMAX EXCEEDS MODFLOW DELT'); ErrorValues.Add('REACHNO EXCEEDS NREACHES'); ErrorValues.Add('REACHNO LESS THAN ONE'); ErrorValues.Add('NCONN LESS THAN ZERO'); ErrorValues.Add('ICONN EXCEEDS NREACHES'); ErrorValues.Add('ICONN LESS THAN ONE'); ErrorValues.Add('REACH LAYER EXCEEDS NLAY'); ErrorValues.Add('REACH ROW EXCEEDS NROW'); ErrorValues.Add('REACH COL EXCEEDS NCOL'); ErrorValues.Add('MUST BE EQUAL TO NREACHES'); ErrorValues.Add('MUST NOT EXCEED NREACHES'); ErrorValues.Add('ERROR SPECIFYING ISWRBND'); ErrorValues.Add('POSITIVE REACH RAIN VALUE REQUIRED'); ErrorValues.Add('POSITIVE REACH EVAP VALUE REQUIRED'); ErrorValues.Add('ISTRRCH.LT.1 OR .GT.NREACHES'); ErrorValues.Add('ISTRNUM.LT.1 OR .GT.REACH(ISTRRCH)%NSTRUCT'); ErrorValues.Add('SIMULATED SWR1 STAGE STRCRIT ONLY FOR'); ErrorValues.Add('PROGRAMMING ERROR: UNDEFINED ISTRTYPE'); ErrorValues.Add('SWR SOLUTION DID NOT CONVERGE'); ErrorValues.Add('COULD NOT READ FROM UNIT Iu'); ErrorValues.Add('jstack.GT.nstack GWFSWR'); ErrorValues.Add('SPECIFIED STRUCTURE CONNECTION ERRORS:'); ErrorValues.Add('INVALID STRUCTURE CONNECTION FOR REACH'); ErrorValues.Add('ERRORS IN SPECIFIED REACH'); ErrorValues.Add('4B: ASSYMETRY IN REACH CONNECTIONS'); ErrorValues.Add('COULD NOT ALLOCATE RCHGRP(n)%REACH'); ErrorValues.Add('MULTIPLE DW CONNECTIONS TO THE SAME DW RCHGRP'); ErrorValues.Add('MULT. ROUTING APPROACHES FOR AT LEAST'); ErrorValues.Add('KRCH MUST BE SET TO 1 FOR REACH'); ErrorValues.Add('PROGRAMMING ERROR:'); ErrorValues.Add('SWR STAGE FILE NOT'); ErrorValues.Add('NO DATA READ FROM SPECIFIED SWR1 STAGE FILE'); // FMP ErrorValues.Add('INPUT-ERROR:'); ErrorValues.Add('CROP CONSUMPTIVE USE FLAG MUST BE 1,2,3,OR 4!'); ErrorValues.Add('NON-ROUTED SW-DELIVERY FLAG MUST BE 0 OR 1!'); ErrorValues.Add('IRDFL MUST BE -1, 0, OR 1!'); ErrorValues.Add('NOT A VALID ENTRY IF SFR PACKAGE IS USED'); ErrorValues.Add('ROUTED SW-DELIVERY FLAG MUST BE -1 OR 1!'); ErrorValues.Add('SOIL-ID CANNOT BE ZERO IN CELLS THAT HOLD A NON-ZERO FARM-ID:'); ErrorValues.Add('INPUT ERROR:'); ErrorValues.Add('YOU HAVE TWO OPTIONS TO CORRECT THE ERROR:'); ErrorValues.Add('FRACTION OF INEFFICIENT LOSSES TO SURFACEWATER RUNOFF'); ErrorValues.Add('THE SCALE FACTOR DOES NOT APPLY TO ANY FIELD'); ErrorValues.Add('NUMBER OF CONSTRAINTS NOT EQUAL TO LHS<=RHS + LHS>=RHS + LHS=RHS'); ErrorValues.Add('BAD INPUT TABLEAU IN LINOPT'); ErrorValues.Add('ROOT MUST BE BRACKETED IN RTFUNC'); ErrorValues.Add('TOO MANY BISECTIONS WHEN SOLVING ANALTYICAL FUNCTION'); ErrorValues.Add('IS GREATER THAN MXACTFW'); ErrorValues.Add('CANNOT BE COMBINED WITH IALLOT>1'); ErrorValues.Add('MUST HAVE A NEGATIVE FARM-WELL ID'); ErrorValues.Add('Blank instance name in the'); ErrorValues.Add('HAS ALREADY BEEN ACTIVATED THIS STRESS PERIOD'); ErrorValues.Add('THE LINK OF WELL IN ROW'); // SWR ErrorValues.Add('DIRECT RUNOFF UNIT MUST BE >= 0'); ErrorValues.Add('MUST BE GREATER THAN'); ErrorValues.Add('MUST BE GREATER THAN'); ErrorValues.Add('ISOLVER MUST MUST BE'); ErrorValues.Add('ISOLVER MUST BE'); ErrorValues.Add('NOUTER MUST NOT EQUAL 0'); ErrorValues.Add('MUST BE LESS THAN'); ErrorValues.Add('EXCEEDS NREACHES'); ErrorValues.Add('LESS THAN ONE'); ErrorValues.Add('LESS THAN ZERO'); ErrorValues.Add('REACH LAYER EXCEEDS NLAY'); ErrorValues.Add('REACH ROW EXCEEDS NROW'); ErrorValues.Add('REACH COL EXCEEDS NCOL'); ErrorValues.Add('COULD NOT PARSE NTABRCH'); ErrorValues.Add('CONFINED AQUIFERS CANNOT BE SIMULATED WITH SWR'); ErrorValues.Add('FLOW PACKAGE SPECIFIED INCONSISTENT WITH SWR'); ErrorValues.Add('MUST BE EQUAL TO'); ErrorValues.Add('MUST NOT EXCEED'); ErrorValues.Add('SHOULD BE SPECIFIED AS'); ErrorValues.Add('POSITIVE REACH RAIN VALUE REQUIRED'); ErrorValues.Add('POSITIVE REACH EVAP VALUE REQUIRED'); ErrorValues.Add('ISTRRCH.LT.1 OR .GT.NREACHES'); ErrorValues.Add('ISTRNUM.LT.1 OR .GT.REACH(ISTRRCH)%NSTRUCT'); ErrorValues.Add('SIMULATED SWR1 STAGE STRCRIT ONLY FOR'); ErrorValues.Add('STAGE CANNOT BE SPECIFIED USING ANOTHER'); ErrorValues.Add('INVALID SOURCE REACH DEFINING STAGE FOR'); ErrorValues.Add('INVALID STRUCTURE CONNECTION'); ErrorValues.Add('ASSYMETRY IN REACH CONNECTIONS'); ErrorValues.Add('COULD NOT ALLOCATE'); ErrorValues.Add('MULTIPLE DW CONNECTIONS TO THE SAME DW RCHGRP'); ErrorValues.Add('ROUTING APPROACHES FOR AT LEAST'); ErrorValues.Add('KRCH MUST BE SET TO 1'); // ErrorValues.Add('aaa'); // ErrorValues.Add('aaa'); // ErrorValues.Add('aaa'); // ErrorValues.Add('aaa'); // ErrorValues.Add('aaa'); // ErrorValues.Add('aaa'); // ErrorValues.Add('aaa'); // ErrorValues.Add('aaa'); // ErrorValues.Add('aaa'); // ErrorValues.Add('aaa'); // ErrorValues.Add('aaa'); // ErrorValues.Add('aaa'); // ErrorValues.Add('aaa'); // WarningValues.Add('**WARNING**'); // WarningValues.Add('*** WARNING ***'); // WarningValues.Add('***WARNING*** FOR CHD CELL'); WarningValues.Add('OUTPUT CONTROL WAS SPECIFIED FOR A NONEXISTENT'); WarningValues.Add('NO FLOW EQUATION TO SOLVE IN TIME STEP'); WarningValues.Add('CELL CONVERSIONS FOR ITER'); WarningValues.Add('****Units are undefined'); WarningValues.Add('ELIMINATED BECAUSE ALL HYDRAULIC'); WarningValues.Add('Nodes are often elminated for the following reasons'); // WarningValues.Add('WARNING-- COMPUTED STAGE OF '); WarningValues.Add('IF WETDRY FLAG NOT TURNED ON, VERTICAL LEAKANCES ARE NOT SAVED:'); WarningValues.Add('THEREFORE, LAKE/AQUIFER CONDUCTANCES ARE BASED SOLELY ON LAKEBED SPECIFICATION'); WarningValues.Add('NODE(S) ADJACENT TO LAKE IN CONFINED LAYER:'); WarningValues.Add('LAKE/AQUIFER CONDUCTANCES BASED SOLELY ON LAKEBED SPECIFICATION'); WarningValues.Add('NOTE: INFORMATION ABOUT CALCULATED LAKE/AQUIFER CONDUCTANCES WHEN USING BCF PACKAGE FOLLOWS:'); // WarningValues.Add('*** WARNING: IBOUND = '); // WarningValues.Add('WARNING -- SUM OF INTERLAKE FLUXES '); // WarningValues.Add(' WARNING**** OUTFLOWING STREAM SEGMENT'); WarningValues.Add('Note: Solution may be sensitive to value of HWtol;'); WarningValues.Add('adjust value if solution fails to converge'); WarningValues.Add('deactivated this time step because'); // WarningValues.Add('deactivated this time step because Hnew<bottom elev. of cell'); // WarningValues.Add('deactivated this time step because IBOUND=0'); WarningValues.Add('DEACTIVATED THIS STRESS PERIOD BECAUSE ALL NODES WERE DEACTIVATED'); // WarningValues.Add('***WARNING*** Specified-head condition should not exist in same cell as a multi-node well'); // WarningValues.Add('***WARNING*** CWC<0 in Well '); // WarningValues.Add('***WARNING*** CWC<0 reset to CWC=0'); WarningValues.Add('WARNING'); WarningValues.Add('LARGE RESIDUAL L2 NORM FOR THIS SOLUTION'); WarningValues.Add('CHECK THAT MASS BALANCE ERROR NOT EXCESSIVE'); WarningValues.Add('MXLGRITER EXCEEDED FOR GRID NUMBER'); WarningValues.Add('CHECK BUDGET OF PARENT GRID TO ASSESS QUALITY OF THE LGR SOLUTION'); WarningValues.Add('INITIAL WATER CONTENT IS LESS THAN RESIDUAL WATER CONTENT FOR STREAM SEGMENT'); WarningValues.Add('A NEGATIVE VALUE FOR FLOW WAS SPECIFIED IN A SFR TABULAR INFLOW FILE. VALUE WILL BE RESET TO ZERO'); WarningValues.Add(' ***Warning in SFR2*** '); WarningValues.Add('Fraction of diversion for each cell in group sums to a value greater than one.'); WarningValues.Add('NEGATIVE LAKE OUTFLOW NOT ALLOWED;'); WarningValues.Add('PET DIFF ERROR'); WarningValues.Add('FAILURE TO MEET SOLVER CONVERGENCE CRITERIA'); WarningValues.Add('CONTINUING EXECUTION'); WarningValues.Add('OMITTED BECAUSE IBOUND=0 FOR CELL(S)'); WarningValues.Add('REQUIRED FOR MULTILAYER INTERPOLATION'); WarningValues.Add('For the cells listed below, one of two conditions exist'); WarningValues.Add('ISOLATED CELL IS BEING ELIMINATED'); WarningValues.Add('INCONSISTANT DATA HAS BEEN ENTERED'); WarningValues.Add('PCGN ASSEMBLER HAS DISCOVERED AN ADDITIONAL INACTIVE CELL'); WarningValues.Add('***PROVISIONAL CONVERGENCE***'); // WarningValues.Add('WARNING: RATIO_E NEGATIVE IN SUBROUTINE NONLINEAR'); WarningValues.Add('A ZERO PIVOT WAS ENCOUNTERED AT LOCATION'); WarningValues.Add('A NEGATIVE PIVOT WAS ENCOUNTERED AT LOCATION'); WarningValues.Add('PRECONDITIONED CONJUGATE GRADIENT SOLVER CANNOT'); WarningValues.Add('THE DOMAIN INTEGRITY ANALYSIS IS DEFECTIVE'); WarningValues.Add('THE DOMAIN INTEGRITY APPEARS TO BE COMPROMIZED'); WarningValues.Add('SECTIONS OF THE LAKE BOTTOM HAVE BECOME DRY'); WarningValues.Add('OMITTED BECAUSE IBOUND=0'); WarningValues.Add('IS DRY -- OMIT'); WarningValues.Add('ARE BELOW THE BOTTOM'); WarningValues.Add('When solver convergence criteria are not met'); WarningValues.Add('NPVAL in parameter file is 0'); WarningValues.Add('FHB STEADY-STATE OPTION FLAG WILL BE IGNORED'); WarningValues.Add('SPECIFIED-HEAD VALUE IGNORED AT ROW'); WarningValues.Add('GAGE PACKAGE ACTIVE EVEN THOUGH SFR AND LAK'); WarningValues.Add('NUMGAGE=0, SO GAGE IS BEING TURNED OFF'); WarningValues.Add('Warning'); WarningValues.Add('IOHUFFLWS NOT FOUND AND WILL BE SET TO BE ZERO'); WarningValues.Add('Simulation is steady state and SYTP parameter(s) are'); WarningValues.Add('Invalid array type was found on the following'); WarningValues.Add('Hydrograph Record will be ignored.'); WarningValues.Add('Coordinates of the following record are'); WarningValues.Add('Invalid interpolation type was found on the'); WarningValues.Add('Invalid streamflow array was found on the following'); WarningValues.Add('Hydrograph specified for non-existent stream reach'); WarningValues.Add('Invalid SFR array was found on the following'); WarningValues.Add('Hydrograph specified for non-existent stream reach'); WarningValues.Add('BEEN SUPERSEDED BY THE SUBSIDENCE AND AQUIFER-SYSTEM'); WarningValues.Add('JUST GONE DRY'); WarningValues.Add('IS DRY'); WarningValues.Add('SECTIONS OF THE LAKE BOTTOM HAVE BECOME DRY.'); WarningValues.Add('MNW2 node in dry cell, Q set to 0.0'); WarningValues.Add('Note-- the following MNW2 well went dry:'); WarningValues.Add('Partial penetration solution did not'); WarningValues.Add('Note: z2>z1 & distal part of well is shallower.'); WarningValues.Add('PROGRAM CONTINUES TO NEXT TIME STEP BECAUSE NNN'); WarningValues.Add('SFR PACKAGE BEING TURNED OFF'); WarningValues.Add('NUMBER OF TRAILING WAVES IS LESS THAN ZERO'); WarningValues.Add('RESETTING UNSATURATED FLOW TO BE INACTIVE'); WarningValues.Add('IS LESS THAN 1.0E-07: SETTING SLOPE TO'); WarningValues.Add('SECANT METHOD FAILED TO FIND SOLUTION FOR'); WarningValues.Add('HIGHEST DEPTH LISTED IN RATING TABLE OF '); WarningValues.Add('two cross-section points are identical'); WarningValues.Add('Non-convergence in ROUTE_CHAN'); WarningValues.Add('VERTICAL FLOW IN VADOSE ZONE IS'); WarningValues.Add('SETTING UZF PACKAGE TO INACTIVE'); WarningValues.Add('NUMBER OF TRAILING WAVES IS LESS THAN ZERO'); WarningValues.Add('RESETTING THE NUMBER OF WAVE SETS TO BE 20'); WarningValues.Add('SETTING UNSATURATED FLOW IN CELL TO INACTIVE'); WarningValues.Add('Removing gage'); WarningValues.Add('SETTING RATE TO ZERO'); WarningValues.Add('SETTING DEPTH TO ONE'); WarningValues.Add('SETTING EXTINCTION WATER CONTENT EQUAL TO RESIDUAL WATER CONTENT'); WarningValues.Add('UNSATURATED FLOW WILL NOT BE ADDED TO ANY LAYER--'); WarningValues.Add('Deactivating the Well Package because MXACTW=0'); WarningValues.Add('WARNING READING LMT PACKAGE INPUT DATA:'); WarningValues.Add('INTERPOLATION FOR HEAD OBS#'); WarningValues.Add('Observation within a steady-state time step has'); WarningValues.Add('the observation type does not allow this'); WarningValues.Add('The observation is being moved to the end of the time step.'); WarningValues.Add('An observation cannot be placed at the very'); WarningValues.Add('HEADS AT DRAIN CELLS ARE BELOW THE'); WarningValues.Add('ALL CELLS INCLUDED IN THIS OBSERVATION ARE DRY'); WarningValues.Add('THESE CONDITIONS DIMINISH THE IMPACT'); WarningValues.Add('these conditions can diminish the impact'); WarningValues.Add('COMBINED LAKE/AQUIFER CONDUCTANCES BASED SOLELY ON LAKEBED'); WarningValues.Add('Well is inactive'); WarningValues.Add('Extremely thin cell'); WarningValues.Add('EXTINCTION WATER CONTENT FOR CELL'); WarningValues.Add('ROOTING DEPTH FOR CELL'); // MODFLOW-NWT // WarningValues.Add('*** WARNING *** NEGATIVE LAKE OUTFLOW NOT ALLOWED;'); WarningValues.Add('NEGATIVE PUMPING RATES WILL BE REDUCED IF HEAD '); WarningValues.Add('FALLS WITHIN THE INTERVAL PSIRAMP TIMES THE CELL'); WarningValues.Add('THICKNESS. THE VALUE SPECIFIED FOR PHISRAMP IS'); WarningValues.Add('TO AVOID PUMPING WATER FROM A DRY CELL'); WarningValues.Add('THE PUMPING RATE WAS REDUCED FOR CELL'); WarningValues.Add('warning in xmdcheck'); WarningValues.Add('UNRECOGNIZED SWR1 OPTION:'); WarningValues.Add('*** MODFLOW CONVERGENCE FAILURE ***'); WarningValues.Add('**Active cell surrounded by inactive cells**'); WarningValues.Add('**Resetting cell to inactive**'); // FMP WarningValues.Add('CORRECTION FOR'); WarningValues.Add('SOLVER CONTINUES TO ITERATE WITH ADJUSTED'); WarningValues.Add('HCLOSE MUST BE SMALLER'); WarningValues.Add('RESOURCES THAT ARE AVAILABLE AT THE RATE OF A CONSTRAINED SUPPLY'); WarningValues.Add('GROUNDWATER PUMPING REQ. < CUMULATIVE MAXIMUM CAPACITY'); WarningValues.Add('ROUTED SURFACE-WATER REQ. < AVAILABLE ROUTED SW DELIVERY'); WarningValues.Add('NON-ROUTED SW. REQ. < AVAILABLE NON-ROUTED SW DELIVERY'); WarningValues.Add('NO ACTIVE FARM CANAL REACHES ARE WITHIN'); WarningValues.Add('NO POINT OF DIVERSION FOR SEMI-ROUTED DELIVERY SPECIFIED:'); WarningValues.Add('NO ACTIVE FARM DRAIN REACHES ARE WITHIN'); WarningValues.Add('NO POINT OF RECHARGE FOR SEMI-ROUTED RETURNFLOW SPECIFIED:'); // WarningValues.Add('aaa'); // WarningValues.Add('aaa'); // WarningValues.Add('aaa'); // WarningValues.Add('aaa'); // WarningValues.Add('aaa'); end; initialization ErrorValues := TAnsiStringList.Create; WarningValues := TAnsiStringList.Create; NumberErrorValues := TAnsiStringList.Create; AssignErrorStrings; finalization NumberErrorValues.Free; ErrorValues.Free; WarningValues.Free; end.
unit SDIMAIN; interface uses Winapi.Windows, System.Classes, Vcl.Graphics, Vcl.Forms, Vcl.Controls, Vcl.Menus, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.ImgList, Vcl.StdActns, Vcl.ActnList, Vcl.ToolWin, RLReport, System.ImageList, System.Actions, Data.DB, Data.Win.ADODB, RLFilters, RLRichFilter, RLPreview, RLPreviewForm, RLPDFFilter, Vcl.Grids, Vcl.DBGrids, SysUtils; type TSDIAppForm = class(TForm) OpenDialog: TOpenDialog; SaveDialog: TSaveDialog; ToolBar1: TToolBar; ToolButton9: TToolButton; ToolButton1: TToolButton; ToolButton2: TToolButton; ToolButton3: TToolButton; ToolButton4: TToolButton; ToolButton5: TToolButton; ToolButton6: TToolButton; ActionList1: TActionList; FileNew1: TAction; FileOpen1: TAction; FileSave1: TAction; FileSaveAs1: TAction; FileExit1: TAction; EditCut1: TEditCut; EditCopy1: TEditCopy; EditPaste1: TEditPaste; HelpAbout1: TAction; StatusBar: TStatusBar; ImageList1: TImageList; MainMenu1: TMainMenu; File1: TMenuItem; FileNewItem: TMenuItem; FileOpenItem: TMenuItem; FileSaveItem: TMenuItem; FileSaveAsItem: TMenuItem; N1: TMenuItem; FileExitItem: TMenuItem; Edit1: TMenuItem; CutItem: TMenuItem; CopyItem: TMenuItem; PasteItem: TMenuItem; Help1: TMenuItem; HelpAboutItem: TMenuItem; PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; memoSqlText: TMemo; rgSqlQueries: TRadioGroup; btnLoadVioSql: TButton; btnRunSqlQuery: TButton; pnlDriveReports: TPanel; mDriveReports: TMemo; Button1: TButton; gbRoutes: TGroupBox; lblSelectRoutes: TLabel; cbAllRoutes: TCheckBox; eSelectRoutes: TEdit; rgAndOr: TRadioGroup; gbAcdrNumbers: TGroupBox; lblSelectAcdrNumbers: TLabel; cbAllAcdrNumbers: TCheckBox; eSelectAcdrNumbers: TEdit; rgReportType: TRadioGroup; RLPreviewSetup1: TRLPreviewSetup; ADOQuery1: TADOQuery; ADOConnection1: TADOConnection; ADOTable1: TADOTable; DataSource1: TDataSource; DBGrid1: TDBGrid; procedure FileNew1Execute(Sender: TObject); procedure FileOpen1Execute(Sender: TObject); procedure FileSave1Execute(Sender: TObject); procedure FileExit1Execute(Sender: TObject); procedure HelpAbout1Execute(Sender: TObject); procedure btnLoadVioSqlClick(Sender: TObject); procedure btnRunSqlQueryClick(Sender: TObject); procedure Button1Click(Sender: TObject); procedure cbAllRoutesClick(Sender: TObject); procedure cbAllAcdrNumbersClick(Sender: TObject); procedure eSelectRoutesClick(Sender: TObject); procedure eSelectAcdrNumbersClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var SDIAppForm: TSDIAppForm; implementation uses About, VioUpdateReport, VioStatusReport, Ini_File; {$R *.dfm} procedure TSDIAppForm.FileNew1Execute(Sender: TObject); begin { Do nothing } end; procedure TSDIAppForm.FileOpen1Execute(Sender: TObject); begin OpenDialog.Execute; end; procedure TSDIAppForm.FileSave1Execute(Sender: TObject); begin SaveDialog.Execute; end; procedure TSDIAppForm.btnLoadVioSqlClick(Sender: TObject); begin with memoSqlText.Lines do begin Clear; Append('SELECT * FROM ViolationStatusReport'); Append('WHERE houseacct in (120, 240, 999998, 999999)'); Append('OR driveRoute = 2.5'); end; if (RLPreviewSetup1.ShowModal) then ShowMessage('yeah baby'); VioStatusReport.Form1.RLReport1.Preview(); end; procedure TSDIAppForm.btnRunSqlQueryClick(Sender: TObject); var i, reportIndex: Integer; queryText: string; begin VioStatusReport.Form1.ADOQuery1.Active := False; VioStatusReport.Form1.ADOQuery1.SQL.Clear; memoSqlText.Lines.Clear; reportIndex := rgSqlQueries.ItemIndex; case reportIndex of 0: begin ADOTable1.Active := False; ADOTable1.TableName := 'ViolationStatusReport'; memoSqlText.Lines.Append('SELECT * FROM ViolationStatusReport '); memoSqlText.Lines.Append('WHERE legal IS NOT NULL '); memoSqlText.Lines.Append ('ORDER BY driveRoute, streetOrder, streetNumber, openDate, statusDate;'); end; 1: begin with ADOTable1 do begin Active := False; TableName := 'Just_209_Vio'; Active := True; First; memoSqlText.Lines.Append('SELECT * FROM ViolationStatusReport '); memoSqlText.Lines.Append('WHERE houseAcct IN ('); memoSqlText.Lines.Append(FieldByName('houseAcct').AsString); for i := 1 to ADOTable1.RecordCount - 1 do begin Next; memoSqlText.Lines.Append(', ' + FieldByName('houseAcct').AsString); end; memoSqlText.Lines.Append(')'); memoSqlText.Lines.Append ('ORDER BY driveRoute, streetOrder, streetNumber, openDate, statusDate;'); end; end; 2: begin with ADOTable1 do begin Active := False; TableName := 'Just_4OL_Vio'; Active := True; First; memoSqlText.Lines.Append('SELECT * FROM ViolationStatusReport '); memoSqlText.Lines.Append('WHERE houseAcct IN ('); memoSqlText.Lines.Append(FieldByName('houseAcct').AsString); for i := 1 to ADOTable1.RecordCount - 1 do begin Next; memoSqlText.Lines.Append(', ' + FieldByName('houseAcct').AsString); end; memoSqlText.Lines.Append(')'); memoSqlText.Lines.Append ('ORDER BY driveRoute, streetOrder, streetNumber, openDate, statusDate;'); end; end; 3: begin with ADOTable1 do begin Active := False; TableName := 'Just_3OL_Vio'; Active := True; First; memoSqlText.Lines.Append('SELECT * FROM ViolationStatusReport '); memoSqlText.Lines.Append('WHERE houseAcct IN ('); memoSqlText.Lines.Append(FieldByName('houseAcct').AsString); for i := 1 to ADOTable1.RecordCount - 1 do begin Next; memoSqlText.Lines.Append(', ' + FieldByName('houseAcct').AsString); end; memoSqlText.Lines.Append(')'); memoSqlText.Lines.Append ('ORDER BY driveRoute, streetOrder, streetNumber, openDate, statusDate;'); end; end; end; for i := 0 to memoSqlText.Lines.Count - 1 do begin queryText := memoSqlText.Lines[i]; VioStatusReport.Form1.ADOQuery1.SQL.Append(queryText); end; VioStatusReport.Form1.ADOQuery1.Active := True; VioStatusReport.Form1.RLReport1.Preview(); memoSqlText.Lines.Clear; end; procedure TSDIAppForm.Button1Click(Sender: TObject); var sqlText: TStrings; begin sqlText := TStringList.Create; sqlText.Add('SELECT * FROM ViolationStatusReport '); if (cbAllRoutes.Checked AND cbAllAcdrNumbers.Checked) then begin // do something here end else if (cbAllRoutes.Checked and (Length(eSelectAcdrNumbers.Text) > 0)) then begin sqlText.Append('WHERE accAccount in (' + eSelectAcdrNumbers.Text + ')'); end else if (cbAllAcdrNumbers.Checked and (Length(eSelectRoutes.Text) > 0)) then begin sqlText.Append('WHERE driveRoute IN (' + eSelectRoutes.Text + ')'); end else begin sqlText.Append('WHERE driveRoute IN (' + eSelectRoutes.Text + ')'); if (rgAndOr.ItemIndex = 0) then sqlText.Append('AND') else sqlText.Append('OR'); sqlText.Append('accAccount in (' + eSelectAcdrNumbers.Text + ')'); end; sqlText.Append ('ORDER BY driveRoute, streetOrder, streetNumber, violationNumber, statusDate ASC'); mDriveReports.Lines.Clear; mDriveReports.Lines.AddStrings(sqlText); if (rgReportType.ItemIndex = 0) then begin with VioStatusReport.Form1.ADOQuery1 do begin Active := False; SQL.Clear; SQL.AddStrings(sqlText); Active := True; end; VioStatusReport.Form1.RLReport1.Preview(); end else begin with VioUpdateReport.dsVioUpdateReport.ADOQuery1 do begin Active := False; SQL.Clear; SQL.AddStrings(sqlText); Active := True; end; VioUpdateReport.dsVioUpdateReport.RLReport1.Preview(); end; sqlText.Free; end; procedure TSDIAppForm.cbAllAcdrNumbersClick(Sender: TObject); begin eSelectAcdrNumbers.Text := ''; end; procedure TSDIAppForm.cbAllRoutesClick(Sender: TObject); begin eSelectRoutes.Text := ''; end; procedure TSDIAppForm.eSelectRoutesClick(Sender: TObject); begin cbAllRoutes.Checked := False; end; procedure TSDIAppForm.eSelectAcdrNumbersClick(Sender: TObject); begin cbAllAcdrNumbers.Checked := False; end; procedure TSDIAppForm.FileExit1Execute(Sender: TObject); begin Close; end; procedure TSDIAppForm.HelpAbout1Execute(Sender: TObject); begin AboutBox.ShowModal; end; end.
//**************************************************************************// // Unit: uReplicationClasses.pas // // Descrição: Implementação das classes de replicação // // utilizando arquivos XML // //**************************************************************************// unit uReplicationClasses; interface Uses Classes, SysUtils, ADODB, Provider, DBClient, DB, Dialogs, Variants; const ERR_NO_DATA_LOADED = 'Dados não carregados.'; DEFAULT_SQL_BATCH_COUNT = 10; { Alex 12/27/2011 - New special caracters table } //SPECIAL_CHARS : array [1..7] of Byte =(10, 13, 34, 180, 94, 96, 126); SPECIAL_CHARS : array [1..4] of Byte =(10, 13, 180, 96); CRLF = #13#10; type TServerType = (stMSSQL2000, stOracle9i); TReplicationClass = class(TComponent) private quExec : TADOCommand; FServerType : TServerType; FConnection : TAdoConnection; FPrimaryKeys : TStringList; FTableName : String; FConstraints : TStringList; FDataLoaded : Boolean; FSelectWhereClause: String; FFieldTypes: TStringList; FDateFields: TStringList; procedure SetTableName(const Value: String);virtual;abstract; procedure SetConnection(const Value: TADOConnection);virtual; procedure GenerateOnDeleteTrigger(sTrigger: String); function TriggerExists(TriggerName: String): Boolean; procedure CreateReplicationColumn; function GenerateOnInsUpdTrigger(sTrigger: String): String; function GenerateInsUpdProcedureParameters : String; function GenerateInsertFieldsValues(IsValue: boolean): String; function GenerateInsertUpdateSetFieldsValues: String; function GenerateInsertUpdateWhereFieldsValues: String; protected procedure SetSelectWhereClause(const Value: String);virtual; procedure CreateInsUpdProcedure; virtual; property Connection: TAdoConnection read FConnection write SetConnection; property Constraints: TStringList read FConstraints write FConstraints; property DataLoaded: Boolean read FDataLoaded write FDataLoaded; property TableName: String read FTableName write SetTableName; property PrimaryKeys: TStringList read FPrimaryKeys; property FieldTypes: TStringList read FFieldTypes; property DateFields: TStringList read FDateFields; property SelectWhereClause: String read FSelectWhereClause write SetSelectWhereClause; property ServerType: TServerType read FServerType write FServerType; procedure ReadPrimaryKeys;virtual; procedure ReadFieldTypes;virtual; procedure CreateReplicationFeatures(CreateDeleteTrigger: Boolean = False); procedure RunSQL(sSQL: String); procedure FillRepDate; public function GenerateInsUpdProcedure: String; virtual; constructor Create(AOwner: TComponent);override; destructor Destroy;override; end; TTableToXML = class(TReplicationClass) private Query : TAdoQuery; Provider : TDataSetProvider; ClientDataSet : TClientDataSet; FReplicateSince: Integer; FSaveEmptyTable: Boolean; function LoadDataFromTable(TableName : String) : String; public property ReplicateSince: Integer read FReplicateSince write FReplicateSince; property SaveEmptyTable: Boolean read FSaveEmptyTable write FSaveEmptyTable default False; property SelectWhereClause; constructor Create(AOwner : TComponent);Override; destructor Destroy;override; function SaveToXML(FileName : String): String; procedure UnloadData; property TableName; protected function GenerateInsUpdProcedure: String;override; procedure SetTableName(const Value: String);override; procedure SetConnection(const Value: TADOConnection);override; published property Connection; end; TXMLToTable = class(TReplicationClass) private Query : TAdoQuery; ClientDataSet : TClientDataSet; FPrimaryKeys: TStringList; FSQLBatchCount: Cardinal; FJustInsert: Boolean; function GenerateWhereClause(TableName : String): String; function GenerateUpdateClause(TableName : String): String; //procedure DisableTriggers(sTable: String); //procedure EnableTriggers(sTable: String); function ConvertQuoted(S: String): String; function MSSQL2000ConvertQuoted(S: String): String; function GenerateSelectClause(TableName: String): String; function GenerateStoredProcedureCall: String; function GenerateVariableSET: String; function GenerateVariableDeclare: String; protected procedure SetTableName(const Value: String);override; procedure SetConnection(const Value: TADOConnection);override; procedure SetSelectWhereClause(const Value: String);override; public property JustInsert: Boolean read FJustInsert write FJustInsert default False; property SelectWhereClause; property TableName; constructor Create(AOwner : TComponent);Override; destructor Destroy;override; function LoadDataFromXML(FileName : String): String; procedure UnloadData; function SaveDataToTable(TableName : String): String; function GetFieldValue(Field: TField) : String; function GenerateSQLInsert(TableName: String): String; published property SQLBatchCount : Cardinal read FSQLBatchCount write FSQLBatchCount default DEFAULT_SQL_BATCH_COUNT; property Connection; end; procedure ModifyAllConstraints(ServerType: TServerType; AConnection : TADOConnection; Enable : Boolean); procedure CreateDeletionTable(ServerType: TServerType; AConnection : TADOConnection); implementation uses uNumericFunctions, uReplicationConsts; function StringListToFormatedText(Lista: TStrings; Separator: String; prefix: String = ''): String; var i: Integer; Prefixed : String; begin Result := ''; for i := 0 to Pred(Lista.Count) do begin if Prefix <> '' then Prefixed := prefix + Lista[I] else Prefixed := Lista[I]; if i <> Pred(Lista.Count) then Result := Result + Prefixed + Separator else Result := Result + Prefixed; end; end; { TReplicationClass } constructor TReplicationClass.Create(AOwner: TComponent); begin inherited Create(AOwner); FPrimaryKeys := TStringList.Create; FConstraints := TStringList.Create; FFieldTypes := TStringList.Create; FDateFields := TStringList.Create; quExec := TADOCommand.Create(AOwner); quExec.Connection := Self.Connection; quExec.ExecuteOptions := quExec.ExecuteOptions + [eoExecuteNoRecords]; quExec.CommandType := cmdText; //quExec.Prepared := True; end; destructor TReplicationClass.Destroy; begin FPrimaryKeys.Free; FConstraints.Free; FFieldTypes.Free; FDateFields.Free; //quExec.Prepared := False; quExec.Free; inherited Destroy; end; procedure TReplicationClass.ReadPrimaryKeys; var sSQL : String; begin FPrimaryKeys.Clear; with TADOQuery.Create(nil) do try Connection := Self.Connection; case Self.ServerType of stMSSQL2000: sSQL := MSSQL2000_SELECT_PK; stOracle9i: sSQL := ''; end; Connection.Open; SQL.Clear; SQL.Add(Format(sSQL, [FTableName, Connection.DefaultDatabase])); Open; while not EOF do begin FPrimaryKeys.Add(FieldByName(PK_COLUMN_NAME).AsString); Next; end; finally Close; Free; end; end; procedure TReplicationClass.ReadFieldTypes; var sSQL : String; sDDLExpression : String; begin FFieldTypes.Clear; FDateFields.Clear; { Alex - 09/05/2011 } with TADOQuery.Create(nil) do try Connection := Self.Connection; case Self.ServerType of stMSSQL2000: sSQL := MSSQL2000_SELECT_FIELD_TYPES; stOracle9i: sSQL := ''; end; Connection.Open; SQL.Clear; SQL.Add(Format(sSQL, [FTableName, Connection.DefaultDatabase])); Open; while not EOF do begin sDDLExpression := FieldByName(DDL_EXPRESSION_CONST).AsString; { Alex 12/27/2011 - Don't process image type fields } If ( Pos( 'image', LowerCase( sDDLExpression ) ) > 0 ) Then Begin Next; Continue; End; FFieldTypes.Add(FieldByName(COLUMN_NAME_CONST).AsString + '=' + sDDLExpression); if (LowerCase(sDDLExpression) = 'datetime') or (LowerCase(sDDLExpression) = 'smalldatetime') then FDateFields.Add(FieldByName(COLUMN_NAME_CONST).AsString); Next; end; finally Close; Free; end; end; procedure TReplicationClass.RunSQL(sSQL : String); begin quExec.CommandText := sSQL; quExec.Execute(); end; procedure TReplicationClass.CreateReplicationColumn; var sSQL: String; begin sSQL := 'IF NOT EXISTS(SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '+ QuotedStr(FTableName) + ' AND COLUMN_NAME = ' + QuotedStr(REPCOLUMN) + ') ' + 'BEGIN ' + CRLF + 'ALTER TABLE ' + FTableName + ' ADD ' + REPCOLUMN + ' DateTime NULL ' + CRLF + 'CREATE INDEX PI_' + FTableName + '_' + REPCOLUMN + ' ON ' + FTableName + ' (' + REPCOLUMN + ')' + CRLF + 'END'; RunSQL(sSQL); RunSQL('UPDATE ' + FTableName + ' SET ' + REPCOLUMN + ' = GETDATE() WHERE ' + REPCOLUMN + ' IS NULL'); end; function TReplicationClass.GenerateOnInsUpdTrigger(sTrigger: String): String; var sIns, sDel, sSQL : String; I : Integer; begin sIns := ''; sDel := ''; for I := 0 to FPrimaryKeys.Count-1 do begin sIns := sIns + 'INSERTED.' + FPrimaryKeys[I] + ' = ' + FTableName + '.' + FPrimaryKeys[I] + CRLF; sDel := sDel + 'DELETED.' + FPrimaryKeys[I] + ' = ' + FTableName + '.' + FPrimaryKeys[I] + CRLF; if (FPrimaryKeys.Count > 1) and (I <> FPrimaryKeys.Count-1) then begin sIns := sIns + 'AND' + CRLF; sDel := sDel + 'AND' + CRLF; end; end; if (sIns <> '') then begin sIns := ' WHERE ' + sIns; sDel := ' WHERE ' + sDel; end; sSQL := 'CREATE TRIGGER ' + sTrigger + ' ON ' + FTableName + ' FOR INSERT,UPDATE NOT FOR REPLICATION AS ' + CRLF + 'SET NOCOUNT ON ' + CRLF + 'IF ISNULL(APP_NAME(), '+ QuotedStr('') +') = ' + QuotedStr('MRREPLICATION') + CRLF + ' RETURN' + CRLF + 'IF NOT UPDATE(' + REPCOLUMN + ')' + CRLF + 'BEGIN' + CRLF + ' UPDATE ' + FTableName + ' SET ' + REPCOLUMN + ' = GETDATE() FROM INSERTED ' + sIns + CRLF + ' UPDATE ' + FTableName + ' SET ' + REPCOLUMN + ' = GETDATE() FROM DELETED ' + sDel + CRLF + 'END'; RunSQL(sSQL); end; procedure TReplicationClass.CreateReplicationFeatures(CreateDeleteTrigger: Boolean = False); var sTrigger: String; begin CreateReplicationColumn; sTrigger := '[dbo].[tr_' + FTableName + '_Repl_InsUpt]'; if not TriggerExists(sTrigger) then GenerateOnInsUpdTrigger(sTrigger); if CreateDeleteTrigger then begin sTrigger := '[dbo].[tr_' + FTableName + '_Repl_Del]'; if not TriggerExists(sTrigger) then GenerateOnDeleteTrigger(sTrigger); end; end; (* Carlos MacLeod - Updated 3/23/2011 *) function TReplicationClass.GenerateInsUpdProcedure : String; var parameters : String; insertFields : String; insertValues : String; theSetFieldValues: String; whereFileds : String; strResult : WideString; begin ReadFieldTypes; parameters := GenerateInsUpdProcedureParameters; insertFields := GenerateInsertFieldsValues(false); insertValues := GenerateInsertFieldsValues(true); theSetFieldValues := GenerateInsertUpdateSetFieldsValues; whereFileds := GenerateInsertUpdateWhereFieldsValues; strResult := MSSQL2000_CMD_CREATE_RPL_INS_UPD_STORED_PROCEDURE; result := format(strResult, [FTableName, FTableName, FTableName, parameters, FTableName, insertFields, insertValues, FTableName, TheSetFieldValues, whereFileds]); { Alex - 11/10/2011 } If ( Trim( whereFileds ) = '' ) Then Begin Raise Exception.Create( ' Table ' + FTableName + ' has no Primary Key' ); End; end; procedure TReplicationClass.CreateInsUpdProcedure; const CRAZY_STRING = CRLF + 'GO' + CRLF; var sSQL, sSQL2 : String; iCrazyPos : Integer; begin sSQL := GenerateInsUpdProcedure(); iCrazyPos := pos(CRAZY_STRING, sSQL); sSQL2 := Copy(sSQL, 1, iCrazyPos); RunSQL(sSQL2); delete(sSQL, 1, iCrazyPos + length(CRAZY_STRING) - 1); try RunSQL(sSQL); except on Exception do raise Exception.Create(FTableName); end; end; (* Carlos MacLeod - Updated 2/25/2011 *) function TReplicationClass.GenerateInsUpdProcedureParameters : String; var I : Integer; stlParameters : TStringList; begin stlParameters := TStringList.Create; try for I := 0 to FFieldTypes.Count - 1 do stlParameters.Add( '@' + FFieldTypes.Names[I] + ' ' + FFieldTypes.Values[FFieldTypes.Names[I]] ); result := StringListToFormatedText(stlParameters, ','); finally stlParameters.Free; end; end; function TReplicationClass.GenerateInsertFieldsValues(IsValue: boolean) : String; var I : Integer; stlFields : TStringList; begin stlFields := TStringList.Create; try for I := 0 to FFieldTypes.Count - 1 do stlFields.Add(FFieldTypes.Names[I]); if IsValue then Result := StringListToFormatedText(stlFields, ',', '@') else Result := StringListToFormatedText(stlFields, ','); finally stlFields.Free; end; end; (* Carlos MacLeod - Updated 2/25/2011 *) function TReplicationClass.GenerateInsertUpdateSetFieldsValues: String; var I : Integer; stlSetFields : TStringList; begin stlSetFields := TStringList.Create; try for I := 0 to FFieldTypes.Count - 1 do begin if FPrimaryKeys.IndexOf(FFieldTypes.Names[I]) < 0 then stlSetFields.Add(FFieldTypes.Names[I] + ' = @' + FFieldTypes.Names[I] ); end; Result := StringListToFormatedText(stlSetFields, ',' + CRLF); finally stlSetFields.Free; end; end; (* Carlos MacLeod - Updated 3/23/2011 *) function TReplicationClass.GenerateInsertUpdateWhereFieldsValues: String; var I : Integer; stlUpdateWhereFields : TStringList; begin stlUpdateWhereFields := TStringList.Create; try for I := 0 to FPrimaryKeys.Count - 1 do begin stlUpdateWhereFields.Add(FPrimaryKeys[I] + ' = @' + FPrimaryKeys[I] ); end; Result := StringListToFormatedText(stlUpdateWhereFields, ' AND' + CRLF); finally stlUpdateWhereFields.Free; end; end; function TReplicationClass.TriggerExists(TriggerName: String): Boolean; var sSQL: string; begin sSQL := 'select * from dbo.sysobjects where id = object_id(N' + QuotedStr(TriggerName) + ') and OBJECTPROPERTY(id, N' + QuotedStr('IsTrigger') + ') = 1'; with TADOQuery.Create(nil) do try Connection := Self.Connection; SQL.Clear; SQL.Add(sSQL); Open; Result := not IsEmpty; finally Close; Free; end; end; procedure TReplicationClass.GenerateOnDeleteTrigger(sTrigger: String); var I : Integer; sInsert: String; sCampoDelete: String; sSQL: String; lstPK : TStringList; QueryFields: TADOQuery; begin try lstPK := TStringList.Create; try if FPrimaryKeys.Count <> 0 then lstPK.AddStrings(FPrimaryKeys) else begin QueryFields := TADOQuery.Create(nil); try QueryFields.Connection := FConnection; QueryFields.SQL.Clear; QueryFields.SQL.Add('select * from ' + FTableName + ' where 1 = 0'); QueryFields.Open; for I := 0 to QueryFields.FieldCount - 1 do lstPK.Add(QueryFields.Fields[I].FieldName); finally QueryFields.Close; QueryFields.Free; end; end; I := lstPK.IndexOf(REPCOLUMN); if I <> -1 then lstPK.Delete(I); sInsert := 'INSERT INTO ' + REP_DELETION_TABLE + ' (' + REP_DELETION_TABLE_NAME + ', ' + REP_DELETION_TABLE_SCRIPT + ', ' + REPCOLUMN + ') ' + CRLF + 'SELECT ' + QuotedStr(FTableName) + ', '; sCampoDelete := QuotedStr('DELETE FROM ' + FTableName + ' WHERE ') + ' + '; for I := 0 to lstPK.Count - 1 do begin sCampoDelete := sCampoDelete + QuotedStr('Convert(varchar, ' + lstPK[I] + ') ' + ' = ') + ' + QuoteName(Convert(varchar, DELETED.' + lstPK[I] + '), CHAR(39))'; if I < lstPK.Count - 1 then sCampoDelete := sCampoDelete + ' + ' + QuotedStr(' AND ') + ' + '; end; sCampoDelete := sCampoDelete + ', GetDate() FROM DELETED'; sSQL := 'CREATE TRIGGER ' + sTrigger + ' ON ' + FTableName + ' FOR DELETE NOT FOR REPLICATION AS ' + CRLF + 'SET NOCOUNT ON ' + CRLF + 'IF ISNULL(APP_NAME(), '+ QuotedStr('') +') = ' + QuotedStr('MRREPLICATION') + CRLF + ' RETURN' + CRLF + 'IF NOT UPDATE(' + REPCOLUMN + ')' + CRLF + 'BEGIN' + CRLF + ' ' + sInsert + sCampoDelete + CRLF + 'END'; RunSQL(sSQL); finally lstPK.Free; end; except end; end; procedure TReplicationClass.FillRepDate; begin RunSQL('UPDATE ' + FTableName + ' SET ' + REPCOLUMN + ' = GETDATE() WHERE ' + REPCOLUMN + ' IS NULL'); end; procedure TReplicationClass.SetConnection(const Value: TADOConnection); begin FConnection := Value; quExec.Connection := FConnection; end; procedure TReplicationClass.SetSelectWhereClause(const Value: String); begin if (FSelectWhereClause <> Value) then FSelectWhereClause := Value; end; { TTableToXML } constructor TTableToXML.Create(AOwner : TComponent); begin inherited Create(AOwner); FDataLoaded := False; FSaveEmptyTable := False; Query := TAdoQuery.Create(Self); Provider := TDataSetProvider.Create(Self); Provider.Name := 'pvd' + Self.Name; ClientDataSet := TClientDataSet.Create(Self); Query.LockType := ltReadOnly; Provider.DataSet := Query; ClientDataSet.ProviderName := Provider.Name; end; function TTableToXML.GenerateInsUpdProcedure: String; begin result := inherited GenerateInsUpdProcedure; end; destructor TTableToXML.Destroy; begin UnloadData; ClientDataSet.Free; Provider.Free; Query.Free; inherited; end; function TTableToXML.LoadDataFromTable(TableName: String): String; var sSelectedFields : String; stlSelectedFields : TStringList; i : Integer; begin Result := ''; sSelectedFields := ''; //Listar os campos para montar o XML try stlSelectedFields := TStringList.Create; try ClientDataSet.Close; Query.Connection := Connection; Query.SQL.Clear; Query.SQL.Add(Format(ANSI_FMT_TABLE_SELECT, [TableName])); ClientDataSet.Open; for I :=0 to (ClientDataSet.FieldCount-1) do //Selecionar os campos marcado com readlony = false if not( ClientDataSet.Fields[I].ReadOnly or ( ClientDataSet.Fields[I].DataType = ftBlob ) ) then stlSelectedFields.Add(ClientDataSet.Fields[I].FieldName); sSelectedFields := StringListToFormatedText(stlSelectedFields, ','); finally Query.SQL.Clear; ClientDataSet.Close; stlSelectedFields.Clear; FreeAndNil(stlSelectedFields); end; ClientDataSet.Close; //Query.EnableBCD := False; Query.Connection := Connection; Query.SQL.Clear; Query.SQL.Add(Format(ANSI_FMT_TABLE_SELECT_FILEDS, [sSelectedFields, TableName])); if (SelectWhereClause <> '') or (FReplicateSince >= 0) then Query.SQL.Add('WHERE'); if SelectWhereClause <> '' then Query.SQL.Add('(' + SelectWhereClause + ')'); if (FReplicateSince >= 0) then begin if SelectWhereClause <> '' then Query.SQL.Add('AND'); case ServerType of stMSSQL2000: begin Query.SQL.Add(Format(MSSQL2000_WHERE_REP_SINCE, [FReplicateSince])); end; stOracle9i: begin end; end; end; ClientDataSet.Open; except on E: Exception do begin Result := Format('TableName: %S -->', [FTableName]) + E.Message; try ClientDataSet.Close; except end; end; end; if Result = '' Then FDataLoaded := True; end; function TTableToXML.SaveToXML(FileName: String): String; begin Result := ''; try if (not FSaveEmptyTable) and (ClientDataSet.IsEmpty) then Exit; if ExtractFileExt(FileName) <> '.xml' Then FileName := FileName + '.xml'; ClientDataSet.SaveToFile(FileName, dfXMLUTF8); except on E: Exception do Result := E.Message; end; end; procedure TTableToXML.SetConnection(const Value: TADOConnection); begin inherited SetConnection(Value); FConnection := Value; end; procedure TTableToXML.SetTableName(const Value: String); var sError: String; begin sError := ''; if (FTableName <> Value) then begin FTableName := Value; if FTableName = '' then Exit; if FTableName <> REP_DELETION_TABLE then begin ReadPrimaryKeys; CreateReplicationFeatures(True); CreateInsUpdProcedure; end; sError := LoadDataFromTable(FTableName); if sError <> '' then raise Exception.Create(sError); end; end; procedure TTableToXML.UnloadData; begin ClientDataSet.Close; FTableName := ''; FDataLoaded := False; end; { TXMLToTable } constructor TXMLToTable.Create(AOwner: TComponent); begin inherited; FDataLoaded := False; FSQLBatchCount := DEFAULT_SQL_BATCH_COUNT; // Criação de objetos FPrimaryKeys := TStringList.Create; ClientDataSet := TClientDataSet.Create(AOwner); Query := TADOQuery.Create(AOwner); Query.LockType := ltReadOnly; end; destructor TXMLToTable.Destroy; begin UnloadData; Query.Free; ClientDataSet.Free; FPrimaryKeys.Free; inherited; end; function TXMLToTable.GenerateUpdateClause(TableName: String): String; Var I : Integer; strSQL : String; stlNotPrimaryKeys: TStringList; begin strSQL := Format(ANSI_FMT_SQL_UPDATE, [TableName]); stlNotPrimaryKeys := TStringList.Create; try for I := 0 to ClientDataSet.Fields.Count - 1 do if (PrimaryKeys.IndexOf(ClientDataSet.Fields[I].FieldName) < 0) then stlNotPrimaryKeys.Add(ClientDataSet.Fields[I].FieldName); for I := 0 to stlNotPrimaryKeys.Count - 1 do begin strSQL := strSQL + Format('%S = %S', [stlNotPrimaryKeys[I], GetFieldValue(ClientDataSet.FieldByName(stlNotPrimaryKeys[I]))]); if I <> (stlNotPrimaryKeys.Count - 1) then strSQL := strSQL + ', '; end; finally stlNotPrimaryKeys.Free; end; Result := strSQL; (* strSQL := Format(ANSI_FMT_SQL_UPDATE, [TableName]); for I := 0 to ClientDataSet.Fields.Count - 1 do If (PrimaryKeys.IndexOf(ClientDataSet.Fields[I].FieldName) < 0) then begin strSQL := strSQL + Format('%S = %S', [ClientDataSet.Fields[I].FieldName, GetFieldValue(ClientDataSet.Fields[I])]); if I <> (ClientDataSet.Fields.Count - 1) then strSQL := strSQL + ', '; end; Result := strSQL; *) end; function TXMLToTable.GenerateSelectClause(TableName: String): String; begin Result := Format(ANSI_FMT_SQL_SELECT, [REPCOLUMN, TableName]); end; function TXMLToTable.GenerateWhereClause(TableName: String): String; Var I : Integer; strSQL : String; stlFields : TStringList; begin stlFields := TStringList.Create; try if PrimaryKeys.Count = 0 then begin for I :=0 to ClientDataSet.FieldCount - 1 do if not((ClientDataSet.Fields[I].DataType in [ftBlob, ftMemo]) or (ClientDataSet.Fields[I].FieldName = REPCOLUMN)) then stlFields.Add(ClientDataSet.Fields[I].FieldName) end else stlFields.Assign(PrimaryKeys); strSQL := 'WHERE '; for I := 0 to stlFields.Count - 1 do begin strSQL := strSQL + Format('%S = %S', [stlFields[I], GetFieldValue(ClientDataSet.FieldByName(stlFields[I]))]); if I <> (stlFields.Count - 1) then strSQL := strSQL + ' AND '; end; strSQL := strSQL + ' AND ' + REPCOLUMN + ' < ' + GetFieldValue(ClientDataSet.FieldByName(REPCOLUMN)); Result := strSQL; finally FreeAndNil(stlFields); end; end; function TXMLToTable.GenerateSQLInsert(TableName: String): String; Var sFields, sValues : String; I : Integer; begin sFields := ''; sValues := ''; for I := 0 to ClientDataSet.Fields.Count-1 Do begin sFields := sFields + ClientDataSet.Fields[I].FieldName; sValues := sValues + GetFieldValue(ClientDataSet.Fields[I]); if I <> (ClientDataSet.Fields.Count-1) then begin sFields := sFields + ','; sValues := sValues + ','; end; end; Result := Format(ANSI_FMT_SQL_INSERT, [TableName, sFields, sValues]); end; function TXMLToTable.GenerateStoredProcedureCall(): String; var I: Integer; stlParameters: TStringList; begin stlParameters := TStringList.Create; try for I := 0 to FFieldTypes.Count - 1 do begin if FDateFields.IndexOf(FFieldTypes.Names[I]) > -1 then begin // We will not add the field value to the SP call // will use the parameter instead stlParameters.Add('@' + FFieldTypes.Names[I]); end else begin stlParameters.Add( GetFieldValue( ClientDataSet.FieldByName( FFieldTypes.Names[I] ) ) ); end; end; Result := StringListToFormatedText(stlParameters, ' ,'); finally stlParameters.Free; end; end; function TXMLToTable.GenerateVariableDeclare(): String; var I : Integer; stlVariable : TStringList; begin stlVariable := TStringList.Create; try for I := 0 to FDateFields.Count - 1 do stlVariable.Add(format('DECLARE @%S %S', [ FDateFields[I], FFieldTypes.Values[FDateFields[I]] ])); Result := StringListToFormatedText(stlVariable, CRLF); finally stlVariable.Free; end; end; function TXMLToTable.GenerateVariableSET(): String; var I : Integer; stlVariable : TStringList; begin stlVariable := TStringList.Create; try for I := 0 to FDateFields.Count - 1 do stlVariable.Add(format('SET @%S = %S', [FDateFields[I], GetFieldValue(ClientDataSet.FieldByName(FDateFields[I]))])); Result := StringListToFormatedText(stlVariable, CRLF); finally stlVariable.Free; end; end; function TXMLToTable.GetFieldValue(Field: TField): String; Var sNomeCampo, OldShortDateFormat : String; begin Result := ''; sNomeCampo := Field.FieldName; if Field.IsNull then Result := 'NULL' else case Field.DataType of ftInteger: Result := Field.AsString; ftDate : begin OldShortDateFormat := ShortDateFormat; try ShortDateFormat := 'DD/MM/YY'; Result := Format('Convert(DateTime, %S, 3)', [QuotedStr(FormatDateTime('dd/mm/yy', Field.AsDateTime))]); finally ShortDateFormat := OldShortDateFormat; end; end; ftDateTime : begin OldShortDateFormat := ShortDateFormat; try ShortDateFormat := 'yyyy-mm-dd hh:nn:ss'; Result := Format('Convert(DateTime, %S, 20)', [QuotedStr(FormatDateTime('yyyy-mm-dd hh:nn:ss', Field.AsDateTime))]); finally ShortDateFormat := OldShortDateFormat; end; end; ftBCD, ftCurrency, ftFloat: begin Result := MyFormatCur(Field.AsFloat, '.'); end; ftBoolean: Result := IntToStr(Byte(Field.AsBoolean)); ftString: Result := ConvertQuoted(Field.AsString) else Result := QuotedStr(Field.AsString); end; end; function TXMLToTable.ConvertQuoted(S: String): String; begin case ServerType of stMSSQL2000: Result := MSSQL2000ConvertQuoted(S); stOracle9i: Result := QuotedStr(S); end; end; function TXMLToTable.MSSQL2000ConvertQuoted(S: String): String; var I : Integer; begin Result := QuotedStr(S); for I := 1 to Length(SPECIAL_CHARS) do Result := StringReplace(Result, CHR(SPECIAL_CHARS[I]), QuotedStr(Format(' + CHAR(%D) + ', [SPECIAL_CHARS[I]])), [rfReplaceAll]); { Alex 12/26/2011 Result := StringReplace(Result, #13#10, QuotedStr(' + CHAR(13) + CHAR(10) + '), [rfReplaceAll]); Result := StringReplace(Result, '"', QuotedStr(' + CHAR(34)f + '), [rfReplaceAll]); } end; function TXMLToTable.LoadDataFromXML(FileName: String): String; begin Result := ''; try UnloadData; ClientDataSet.LoadFromFile(FileName); if SelectWhereClause <> '' then begin ClientDataSet.Filter := SelectWhereClause; ClientDataSet.Filtered := True; end else begin ClientDataSet.Filter := ''; ClientDataSet.Filtered := False; end; FDataLoaded := True; except on E: Exception do Result := E.Message; end; end; function TXMLToTable.SaveDataToTable(TableName: String): String; Var sSQLWhere, sSQLUpdate, sSQLInsert : String; stlExecuteBuffer: TStringList; sBatchBegin, sBatchBody, sBatchEnd : String; iBatchRows : Cardinal; IsInsUpd: Boolean; begin IsInsUpd := TableName <> REP_DELETION_TABLE; if FDataLoaded Then begin Result := ''; if IsInsUpd then case ServerType of stMSSQL2000: begin sBatchBegin := MSSQL2000_CMD_REPLICATE_BATCH_BEGIN; (* Old Version - Pure SQL Statment *) // sBatchBody := MSSQL2000_CMD_REPLICATE_BATCH_BODY; (* New Version - Stored Procedure Call *) sBatchBody := MSSQL2000_CMD_REPLICATE_BATCH_BODY_SP; sBatchEnd := MSSQL2000_CMD_REPLICATE_BATCH_END; end; stOracle9i: begin sBatchBegin := ''; sBatchBody := ''; sBatchEnd := ''; end; end; try {if IsInsUpd then DisableTriggers(TableName);} try //FillRepDate; stlExecuteBuffer := TStringList.Create; try iBatchRows := 0; if IsInsUpd then begin stlExecuteBuffer.Add(sBatchBegin); { Alex - Define variables declaration } stlExecuteBuffer.Add(GenerateVariableDeclare()); end; while not ClientDataSet.Eof do begin Inc(iBatchRows); { Alex - Aqui gera os valores das variaveis das colunas da tabela } stlExecuteBuffer.Add(GenerateVariableSET()); if IsInsUpd then begin // Here the magic happens if JustInsert then sSQLUpdate := GenerateSelectClause(TableName) else (* Old Version - Pure SQL Statment *) //sSQLUpdate := GenerateUpdateClause(TableName); (* New Version - Stored Procedure Call *) sSQLUpdate := GenerateStoredProcedureCall; (* Old Version - Pure SQL Statment *) //sSQLWhere := GenerateWhereClause(TableName); //sSQLInsert := GenerateSQLInsert(TableName); //stlExecuteBuffer.Add(Format(sBatchBody, [sSQLUpdate + CRLF + sSQLWhere, sSQLInsert])); (* New Version - Stored Procedure Call *) stlExecuteBuffer.Add(Format(sBatchBody, [FTableName, sSQLUpdate])); end else // No stored procedure needed, since the script is provided "as it is" stlExecuteBuffer.Add(ClientDataSet.FieldByName(REP_DELETION_TABLE_SCRIPT).AsString); if iBatchRows >= FSQLBatchCount then begin if IsInsUpd then stlExecuteBuffer.Add(sBatchEnd); try RunSQL(StringListToFormatedText(stlExecuteBuffer, CRLF)); except on Err: Exception do begin //stlExecuteBuffer.Text := StringListToFormatedText(stlExecuteBuffer, CRLF); //stlExecuteBuffer.savetofile('c:\teste.txt'); stlExecuteBuffer.Insert(0, Err.Message); stlExecuteBuffer.SaveToFile('ERROR_' + TableName + FormatDateTime('YYYYMMDD-HHNNSS', NOW) + '.SQL'); raise; end; end; stlExecuteBuffer.Clear; { Alex 12/10/2011 - Include - ...GenerateVariableDeclare()); } if IsInsUpd then begin stlExecuteBuffer.Add(sBatchBegin); stlExecuteBuffer.Add(GenerateVariableDeclare()); end; iBatchRows := 0; end; ClientDataSet.Next; if (ClientDataSet.Eof) and (iBatchRows <> 0)then begin if IsInsUpd then stlExecuteBuffer.Add(sBatchEnd); try RunSQL(StringListToFormatedText(stlExecuteBuffer, CRLF)); except on Err: Exception do begin stlExecuteBuffer.Insert(0, Err.Message); stlExecuteBuffer.SaveToFile('ERROR_' + TableName + FormatDateTime('YYYYMMDD-HHNNSS', NOW) + '.SQL'); raise; end; end; end; end; finally stlExecuteBuffer.Free; end; finally {if IsInsUpd then EnableTriggers(TableName);} end; except on E: Exception do Result := E.Message; end; end else begin raise Exception.Create(ERR_NO_DATA_LOADED); end; end; procedure TXMLToTable.SetTableName(const Value: String); begin inherited; if (FTableName <> Value) then begin FTableName := Value; if FTableName = '' then Exit; if FTableName <> REP_DELETION_TABLE then begin ReadPrimaryKeys; ReadFieldTypes; CreateReplicationFeatures(); { Alex 12/07/2011 } CreateInsUpdProcedure; end; end; end; // NÃO REMOVER !!! (* procedure TXMLToTable.DisableTriggers(sTable: String); var sSrvNativeSQL : String; begin case ServerType of stMSSQL2000 : sSrvNativeSQL := MSSQL2000_CMD_DISABLE_ALL_TRIGGERS; stOracle9i: sSrvNativeSQL := ''; end; RunSQL(Format(sSrvNativeSQL, [sTable])); end; *) // NÃO REMOVER !!! (* procedure TXMLToTable.EnableTriggers(sTable: String); var sSrvNativeSQL : String; begin case ServerType of stMSSQL2000 : sSrvNativeSQL := MSSQL2000_CMD_ENABLE_ALL_TRIGGERS; stOracle9i: sSrvNativeSQL := ''; end; RunSQL(Format(sSrvNativeSQL, [sTable])); end; *) procedure TXMLToTable.UnloadData; begin ClientDataSet.Close; ClientDataSet.Filtered := False; FPrimaryKeys.Clear; end; procedure ModifyAllConstraints(ServerType: TServerType; AConnection : TADOConnection; Enable : Boolean); var sSQLGetConstraints, sSQLModify: String; quSelect, quRun : TADOQuery; begin quSelect := TADOQuery.Create(nil); with quSelect do try Connection := AConnection; case ServerType of stMSSQL2000: begin sSQLGetConstraints := MSSQL2000_SELECT_FK; if Enable then sSQLModify := MSSQL2000_CMD_ENABLE_CONSTRAINT else sSQLModify := MSSQL2000_CMD_DISABLE_CONSTRAINT; end; stOracle9i: begin sSQLGetConstraints := ''; sSQLModify := ''; end; end; SQL.Clear; SQL.Add(sSQLGetConstraints); Open; quRun := TADOQuery.Create(Nil); try quRun.Connection := AConnection; while not EOF do begin quRun.SQL.Clear; quRun.SQL.Add(Format(sSQLModify, [FieldByName('TabelaDerivada').AsString, FieldByName('ConstraintName').AsString])); quRun.ExecSQL; Next; end; finally quRun.Free; end; finally Close; Free; end; end; procedure CreateReplicationInsUpdProcedureExists(ATableName: String; AConnection : TADOConnection); var sSQL: String; quRun: TADOQuery; begin (* sSQL := 'if not exists (select * from dbo.sysobjects where xtype = '#39'P'#39' and name = '#39REPLICATION_STORED_PROCEDURE_NAME_FORMAT#39')' + CRLF + 'CREATE TABLE [dbo].['+REP_DELETION_TABLE+'] (' + CRLF + REP_DELETION_TABLE_NAME +' varchar(40) NOT NULL ,' + CRLF + REP_DELETION_TABLE_SCRIPT + ' varchar(255) NOT NULL,' + CRLF + REPCOLUMN + ' datetime NOT NULL' + CRLF + ')'; quRun := TADOQuery.Create(Nil); try quRun.Connection := AConnection; quRun.SQL.Clear; quRun.SQL.Add(sSQL); quRun.ExecSQL; finally quRun.Free; end; *) end; procedure CreateDeletionTable(ServerType: TServerType; AConnection : TADOConnection); var sSQL: String; quRun: TADOQuery; begin sSQL := 'if not exists (select * from dbo.sysobjects where id = object_id(N' + QuotedStr(Format('[dbo].[%S]', [REP_DELETION_TABLE])) +') ' + CRLF + 'and OBJECTPROPERTY(id, N' + QuotedStr('IsUserTable') + ') = 1)' + CRLF + 'CREATE TABLE [dbo].['+REP_DELETION_TABLE+'] (' + CRLF + REP_DELETION_TABLE_NAME +' varchar(40) NOT NULL ,' + CRLF + REP_DELETION_TABLE_SCRIPT + ' varchar(255) NOT NULL,' + CRLF + REPCOLUMN + ' datetime NOT NULL' + CRLF + ')'; quRun := TADOQuery.Create(Nil); try quRun.Connection := AConnection; quRun.SQL.Clear; quRun.SQL.Add(sSQL); quRun.ExecSQL; finally quRun.Free; end; end; procedure TXMLToTable.SetConnection(const Value: TADOConnection); begin inherited SetConnection(Value); FConnection := Value; end; procedure TXMLToTable.SetSelectWhereClause(const Value: String); begin inherited; (* if SelectWhereClause = '' then begin ClientDataSet.Filter := ''; ClientDataSet.Filtered := False; end else begin ClientDataSet.Filter := SelectWhereClause; ClientDataSet.Filtered := True; end; *) end; end.
unit TDlgSFXTag; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, AnimationSeekBarImpl1; type TSFXTagDialog = class(TForm) Lable_SFXTagList: TLabel; Combo_SFXTagList: TComboBox; Group_SFXTagContent: TGroupBox; BindEdit: TButton; Label_SFXPlayMode: TLabel; Combo_PlayMode: TComboBox; Label_PlaySpeed: TLabel; Edit_PlaySpeed: TEdit; Check_AdaptSpeedToMotion: TCheckBox; Check_Interruptable: TCheckBox; Check_MotionFinishKeep: TCheckBox; Check_NotifyRepresent: TCheckBox; Button_Delete: TButton; Button_Copy: TButton; Group_DataContent: TGroupBox; Label_BindIndex: TLabel; Label_BindFileName: TLabel; Edit_BindFileName: TEdit; Label_BindIndexNum: TLabel; Label_SFXFileName: TLabel; Edit_SFXFileName: TEdit; Button_New: TButton; Label_TagName: TLabel; Edit_TagName: TEdit; Button_Paste: TButton; procedure BindEditClick(Sender: TObject); procedure Combo_SFXTagListSelect(Sender: TObject); procedure Button_NewClick(Sender: TObject); procedure Button_DeleteClick(Sender: TObject); procedure Edit_TagNameKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure UpdateUIControlState(); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure Button_CopyClick(Sender: TObject); procedure Button_PasteClick(Sender: TObject); private { Private declarations } procedure UpdateUI(nPlayType: Integer; fPlaySpeed: Single; nAutoAdaptSpeed: Integer; nInterruptable: Integer; nKeepMotionFinish: Integer; nNotify: Integer; nBindIndex: Integer; strSFXFileName: WideString; strTagName: WideString); public { Public declarations } m_nLastItem : Integer; m_nFrame : Integer; m_AnimationSeekBar : TAnimationSeekBar; procedure OnInitDialog(nFrame : Integer); procedure FillTagList(nFrame : Integer); end; var SFXTagDialog: TSFXTagDialog; implementation {$R *.dfm} procedure TSFXTagDialog.BindEditClick(Sender: TObject); var nTagID : Integer; begin nTagID := Integer(Combo_SFXTagList.Items.Objects[Combo_SFXTagList.ItemIndex]); m_AnimationSeekBar.OnSFXFileButton(nTagID); ModalResult := mrOK; end; procedure TSFXTagDialog.UpdateUI(nPlayType: Integer; fPlaySpeed: Single; nAutoAdaptSpeed: Integer; nInterruptable: Integer; nKeepMotionFinish: Integer; nNotify: Integer; nBindIndex: Integer; strSFXFileName: WideString; strTagName : WideString); begin UpdateUIControlState(); if Combo_SFXTagList.ItemIndex <> -1 then begin Combo_PlayMode.ItemIndex := nPlayType; Edit_PlaySpeed.Text := FloatToStr(fPlaySpeed); Check_AdaptSpeedToMotion.Checked := BOOL(nAutoAdaptSpeed); Check_Interruptable.Checked := BOOL(nInterruptable); Check_MotionFinishKeep.Checked := BOOL(nKeepMotionFinish); Check_NotifyRepresent.Checked := BOOL(nNotify); Edit_BindFileName.Text := 'None'; Label_BindIndexNum.Caption := IntToStr(nBindIndex); Edit_SFXFileName.Text := strSFXFileName; Edit_TagName.Text := strTagName; end; end; procedure TSFXTagDialog.Combo_SFXTagListSelect(Sender: TObject); var nLastTagID : Integer; nCurrentTagID : Integer; nPlayType : Integer; fPlaySpeed : Single; nAdapt : Integer; nInterruptable : Integer; nMotionKeep : Integer; nNotify : Integer; nBindIndex : Integer; strSFXFileName : WideString; strTagName : WideString; nLastItem : Integer; begin if Combo_SFXTagList.ItemIndex = -1 then Exit; nLastItem := Combo_SFXTagList.ItemIndex; nCurrentTagID := Integer(Combo_SFXTagList.Items.Objects[Combo_SFXTagList.ItemIndex]); if m_nLastItem <> -1 then begin nLastTagID := Integer(Combo_SFXTagList.Items.Objects[m_nLastItem]); nPlayType := Combo_PlayMode.ItemIndex; fPlaySpeed := StrtoFloat(Edit_PlaySpeed.Text); nAdapt := Integer(Check_AdaptSpeedToMotion.Checked); nInterruptable := Integer(Check_Interruptable.Checked); nMotionKeep := Integer(Check_MotionFinishKeep.Checked); nNotify := Integer(Check_NotifyRepresent.Checked); strTagName := WideString(Edit_TagName.Text); m_AnimationSeekBar.FEvents.OnSFXTagSave(nLastTagID, nPlayType, fPlaySpeed, nAdapt, nInterruptable, nMotionKeep, nNotify, strTagName, StrToInt(Label_BindIndexNum.Caption)); end; m_AnimationSeekBar.FEvents.OnSFXTagLoad(nCurrentTagID, nPlayType, fPlaySpeed, nAdapt, nInterruptable, nMotionKeep, nNotify, nBindIndex, strSFXFileName, strTagName); UpdateUI(nPlayType, fPlaySpeed, nAdapt, nInterruptable, nMotionKeep, nNotify, nBindIndex, strSFXFileName, strTagName); m_nLastItem := nLastItem; end; procedure TSFXTagDialog.Button_NewClick(Sender: TObject); var nID : Integer; begin m_AnimationSeekBar.FEvents.OnSFXTagNew(nID, m_nFrame); FillTagList(m_nFrame); Combo_SFXTagList.ItemIndex := Combo_SFXTagList.Items.Count - 1; Combo_SFXTagListSelect(nil); end; procedure TSFXTagDialog.Button_DeleteClick(Sender: TObject); var nID : Integer; nItemIndex : Integer; begin begin if Combo_SFXTagList.ItemIndex = -1 then Exit; nItemIndex := Combo_SFXTagList.ItemIndex - 1; if nItemIndex = -1 then nItemIndex := 0; nID := Integer(Combo_SFXTagList.Items.Objects[Combo_SFXTagList.ItemIndex]); if m_nLastItem = Combo_SFXTagList.ItemIndex then m_nLastItem := -1; m_AnimationSeekBar.FEvents.OnSFXTagDelete(nID); FillTagList(m_nFrame); if Combo_SFXTagList.Items.Count <> 0 then begin Combo_SFXTagList.ItemIndex := nItemIndex; Combo_SFXTagListSelect(nil); end; end end; procedure TSFXTagDialog.OnInitDialog(nFrame : Integer); begin m_AnimationSeekBar := TAnimationSeekBar(Owner); Combo_SFXTagList.Clear(); m_nLastItem := -1; m_nFrame := nFrame; FillTagList(nFrame); Edit_BindFileName.Enabled := false; Edit_SFXFileName.Enabled := false; end; procedure TSFXTagDialog.FillTagList(nFrame : Integer); var nReturn : Integer; strTagName : WideString; nID : Integer; nCount : Integer; begin nReturn := 0; nCount := 0; Combo_SFXTagList.Clear(); if m_AnimationSeekBar.FEvents <> nil then begin m_AnimationSeekBar.FEvents.OnSFXTagFillTagList(nFrame, nCount, strTagName, nID, nReturn); while nReturn <> 0 do begin nCount := nCount + 1; Combo_SFXTagList.AddItem(strTagName, TObject(nID)); m_AnimationSeekBar.FEvents.OnSFXTagFillTagList(nFrame, nCount, strTagName, nID, nReturn); end; if Combo_SFXTagList.Items.Count <> 0 then begin Combo_SFXTagList.ItemIndex := 0; Combo_SFXTagListSelect(nil); end; end; UpdateUIControlState(); end; procedure TSFXTagDialog.UpdateUIControlState(); var bTagSelected : boolean; begin bTagSelected := true; if Combo_SFXTagList.ItemIndex = -1 then bTagSelected := false; Combo_PlayMode.Enabled := bTagSelected; Edit_PlaySpeed.Enabled := bTagSelected; Check_AdaptSpeedToMotion.Enabled := bTagSelected; Check_Interruptable.Enabled := bTagSelected; Check_MotionFinishKeep.Enabled := bTagSelected; Check_NotifyRepresent.Enabled := bTagSelected; Edit_TagName.Enabled := bTagSelected; end; procedure TSFXTagDialog.Edit_TagNameKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var nCurrentID, nID, nPlayType, nAdapt, nInterruptable, nMotionKeep, nNotify : Integer; fPlaySpeed : Single; strTagName : WideString; begin if Combo_SFXTagList.ItemIndex = -1 then Exit; if Key = VK_RETURN then begin nID := Integer(Combo_SFXTagList.Items.Objects[Combo_SFXTagList.ItemIndex]); if m_AnimationSeekBar.FEvents <> nil then begin nPlayType := Combo_PlayMode.ItemIndex; fPlaySpeed := StrToFloat(Edit_PlaySpeed.Text); nAdapt := Integer(Check_AdaptSpeedToMotion.Checked); nInterruptable := Integer(Check_Interruptable.Checked); nMotionKeep := Integer(Check_MotionFinishKeep.Checked); nNotify := Integer(Check_NotifyRepresent.Checked); strTagName := WideString(Edit_TagName.Text); m_AnimationSeekBar.FEvents.OnSFXTagSave(nID, nPlayType, fPlaySpeed, nAdapt, nInterruptable, nMotionKeep, nNotify, strTagName, StrToInt(Label_BindIndexNum.Caption)); nCurrentID := Combo_SFXTagList.ItemIndex; FillTagList(m_nFrame); Combo_SFXTagList.ItemIndex := nCurrentID; Combo_SFXTagListSelect(nil); end end end; procedure TSFXTagDialog.FormClose(Sender: TObject; var Action: TCloseAction); var Key : Word; begin Key := VK_RETURN; Edit_TagNameKeyDown(nil, Key, []); end; procedure TSFXTagDialog.Button_CopyClick(Sender: TObject); begin m_AnimationSeekBar.m_nSFXTagSrCFrame := m_nFrame; end; procedure TSFXTagDialog.Button_PasteClick(Sender: TObject); begin if m_AnimationSeekBar.FEvents <> nil then m_AnimationSeekBar.FEvents.OnSFXTagCopy(m_AnimationSeekBar.m_nSFXTagSrcFrame, m_nFrame); end; end.
program AccountScrapping; {$mode objfpc}{$H+} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes, InstagramScrapper, eventlog, SysUtils, fphttpclientbroker; var Instagram: TInstagramParser; S: String; ALogger: TEventLog; begin TbFPHTTPClient.RegisterClientClass; // You must register any http client class (now available only fphttpclient) ALogger:=TEventLog.Create(nil); ALogger.FileName:=ChangeFileExt(ApplicationName, '.log'); ALogger.LogType:=ltFile; Instagram:=TInstagramParser.Create; Instagram.Logger:=ALogger; try try repeat WriteLn('Please input Instagram user alias (Username)'); ReadLn(S); Instagram.ParseGetAccount(S); Writeln('Follows: '+IntToStr(Instagram.Follows)+', FolowedBy: '+IntToStr(Instagram.FollowedBy)); Write('Are You want to continue? (Y/N): '); Readln(S); until lowercase(S)<>'y'; finally Instagram.Free; end; except on E: Exception do ALogger.Log(etError, '[Unhandled exception] '+e.ClassName+': '+e.Message); end; ALogger.Free; end.
unit UGlobals; interface uses Winapi.Windows, System.SysUtils, VCL.Graphics, GLColor, GLTexture; const SELDIRHELP: INTEGER = 180; type PrefRecord = record {first line of file serves as Version ID} PHiddenString, PShpPath, PEarthDataPath, PEarthModelPath,PEarthPhotoPath, PEarthHRPath: string[255]; PStartedNameNumber: string[25]; PMapBordersColor,PMapGridsColor, PMapDatasColor,PMapBacksColor:TColor; PGlowUpDowni,PColorreg:Integer; PStarted:TDateTime; PClassStartPanelColor, PEditingColor, PBackgroundColor, PHighlightColor, PEditColor, PCurrentColor: TColor; PErrorBeepOn, PWarningBeepOn ,PInfoBeepOn , PConfirmBeepOn, PCompletedBeepOn :Boolean; PSelectionRadius: Integer; {X Y Location of forms} PEarthFormY, PEarthFormX, PAboutFormX, PAboutFormY, PGlsSmdQcFormX,PGlsSmdQcFormY, PGlsSmdLoadMdlFormX,PGlsSmdLoadMdlFormY, PGLSViewerFormX,PGLSViewerFormY, PABCreatorFormX,PABCreatorFormY, PHoloFormY, PHoloFormX, PAboutHolographicsX, PAboutHolographicsY, PMessageX, PMessageY, PSystemInfoFormX, PSystemInfoFormY : Integer; end; type PrefFile = file of PrefRecord; var PreRcd:PrefRecord; HiddenString, StartedNameNumber: String; AppPath, ShpPath, EarthDataPath, EarthModelPath, EarthPhotoPath, EarthHRPath: TFileName; GlowUpDowni,Colorreg:Integer; MyPixelFormat: TPixelFormat; {pf24bit pf32bit} PixelScanSize: Byte; Started:TDateTime; PrintBigChecked, UseThumbnails, AutoDisPlay, VoicesON, DoneBeepOn, ErrorBeepOn, bAutoSave:Boolean; CurrentColor: TColor; EarthFormX,EarthFormY, GlsSmdQcFormX,GlsSmdQcFormY, GlsSmdLoadMdlFormX,GlsSmdLoadMdlFormY, GLSViewerFormX,GLSViewerFormY, ABCreatorFormX,ABCreatorFormY, AboutFormX, AboutFormY, AboutHolographicsX, AboutHolographicsY, MessageX, MessageY, HoloFormY, HoloFormX, SystemInfoFormX, SystemInfoFormY : Integer; var ThumbColor, MapBordersColor, MapGridsColor, MapDatasColor, MapBacksColor: TColor; EditingColor, ClassStartPanelColor, BackgroundColor, HighlightColor, EditColor{, CurrentColor}: TColor; SelectionRadius:Integer; StillOpen, FilePreviews,Skip32BitNotice,SkipIntroScreen, ScaleBarVisible, WarningBeepOn ,InfoBeepOn , ConfirmBeepOn, CompletedBeepOn:Boolean; DotColorArray: array of TColorVector; MarkerIndex, ColorIndex : integer; MMSysHandle: THandle; PlaySound: function(lpszSoundName: PAnsiChar; uFlags: UINT): BOOL; stdcall; procedure DoLoader; procedure SetPreferences; procedure DoSaver; procedure GetPreferences; //-------------------------------------------------------------------- implementation //-------------------------------------------------------------------- {uses LOResMess;} procedure DoLoader; var P_File: PrefFile; var PathS: string; begin PathS := ExtractFilePath(ParamStr(0)) + 'EarthGLS.pof'; if FileExists(PathS) then begin AssignFile(P_File, PathS); Reset(P_File); if IoResult <> 0 then begin{ DoRezError(22)}; end; Read(P_File, PreRcd); CloseFile(P_File); SetPreferences; end else {DoRezError(24)}; end; procedure SetPreferences; begin {after loading} with PreRcd do begin EarthDataPath:=PEarthDataPath; ShpPath:=PShpPath; EarthModelPath:=PEarthModelPath; EarthPhotoPath:=PEarthPhotoPath; EarthHRPath:=PEarthHRPath; EditingColor:=PEditingColor; BackgroundColor:=PBackgroundColor; HighlightColor:=PHighlightColor; ClassStartPanelColor:=PClassStartPanelColor; EditColor:=PEditColor; CurrentColor:=PCurrentColor; ErrorBeepOn:=PErrorBeepOn; WarningBeepOn:=PWarningBeepOn; InfoBeepOn :=PInfoBeepOn; ConfirmBeepOn:=PConfirmBeepOn; CompletedBeepOn:=PCompletedBeepOn; Started := PStarted; StartedNameNumber := PStartedNameNumber; Colorreg := PColorreg; SelectionRadius:=PSelectionRadius; GlowUpDowni:=PGlowUpDowni; MapBordersColor := PMapBordersColor; MapGridsColor := PMapGridsColor; MapDatasColor := PMapDatasColor; MapBacksColor := PMapBacksColor; MessageX := PMessageX; MessageY := PMessageY; EarthFormX:=PEarthFormX; EarthFormY:=PEarthFormY; AboutFormX:=PAboutFormX; AboutFormY:=PAboutFormY; ABCreatorFormX:=PABCreatorFormX; ABCreatorFormY:=PABCreatorFormY; AboutHolographicsX := PAboutHolographicsX; AboutHolographicsY := PAboutHolographicsY; HoloFormY := PHoloFormY; HoloFormX := PHoloFormX; SystemInfoFormX := PSystemInfoFormX; SystemInfoFormY := PSystemInfoFormY; end; end; {---------------------------------------------------------------------} procedure DoSaver; var P_File: PrefFile; var PathS: string; begin PathS := ExtractFilePath(ParamStr(0)) + 'EarthGLS.pof'; GetPreferences; AssignFile(P_File, PathS ); Rewrite(P_File); if IoResult <> 0 then {DorezError(23)}; write(P_File, PreRcd); CloseFile(P_File); end; {---------------------------------------------------------------------} procedure GetPreferences; begin {before saving} with PreRcd do begin {This is my secret string ? as text?} PHiddenString :=HiddenString; PEarthDataPath:=EarthDataPath; PShpPath:=ShpPath; PEarthModelPath:=EarthModelPath; PEarthPhotoPath:=EarthPhotoPath; PEarthHRPath:=EarthHRPath; PEditingColor:=EditingColor; PBackgroundColor:=BackgroundColor; PHighlightColor:=HighlightColor; PClassStartPanelColor:=ClassStartPanelColor; PEditColor:=EditColor; PCurrentColor:=CurrentColor; PErrorBeepOn:=ErrorBeepOn; PWarningBeepOn:=WarningBeepOn; PInfoBeepOn :=InfoBeepOn; PConfirmBeepOn:=ConfirmBeepOn; PCompletedBeepOn:=CompletedBeepOn; PGlowUpDowni:=GlowUpDowni; PSelectionRadius:=SelectionRadius; PColorreg := Colorreg; PStarted := Started; PStartedNameNumber := StartedNameNumber; PMapBordersColor := MapBordersColor; PMapGridsColor := MapGridsColor; PMapDatasColor := MapDatasColor; PMapBacksColor := MapBacksColor; PEarthFormX:=EarthFormX; PEarthFormY:=EarthFormY; PAboutFormX:=AboutFormX; PAboutFormY:=AboutFormY; PABCreatorFormX:=ABCreatorFormX; PABCreatorFormY:=ABCreatorFormY; PMessageX := MessageX; PMessageY := MessageY; PAboutHolographicsX := AboutHolographicsX; PAboutHolographicsY := AboutHolographicsY; PHoloFormY := HoloFormY; PHoloFormX := HoloFormX; PSystemInfoFormX := SystemInfoFormX; PSystemInfoFormY := SystemInfoFormY; end; end; {---------------------------------------------------------------------} end.
unit UDrawing; //This unit contains all the code for drawing objects interface uses W3System, W3Graphics, UPlayer, UAi, UE, UPlat, UBullet, UGameText, UTurret, UOptionsButton, UGlobals, UGlobalsNoUserTypes; procedure DrawButton(Button : TOptionsButton; FontSize : integer; Canvas: TW3Canvas); procedure DrawControlButton(Button : TOptionsButton; FontSize : integer; Canvas: TW3Canvas); procedure DrawPlayer(player : UPlayer.TPlayer; Canvas: TW3Canvas); procedure DrawAI(AI : array of UAi.TAi; Canvas: TW3Canvas); procedure DrawDoors(Door : array of UE.TE; Canvas: TW3Canvas); procedure DrawDoor(Door : UE.TE; Canvas: TW3Canvas; Locked : boolean = false); procedure DrawPlats(Plat : array of UPlat.TPlat; Canvas: TW3Canvas); procedure DrawBullet(Bullet : array of UBullet.TBullet; Canvas: TW3Canvas); procedure DrawText(text : array of UGameText.TText; Canvas: TW3Canvas; FontSize : integer = 10); procedure DrawTurret(Turrets : array of TTurret; Canvas: TW3Canvas); function OnScreen(x, y, x2, y2 : float) : boolean; implementation procedure DrawButton(Button : TOptionsButton; FontSize : integer; Canvas: TW3Canvas); begin Canvas.FillStyle := 'red'; Canvas.BeginPath; Canvas.FillRectF(Button.X, Button.Y, Button.Width, Button.Height); Canvas.ClosePath; Canvas.Fill; Canvas.FillStyle := 'blue'; Canvas.Font := IntToStr(FontSize) + 'pt verdana'; Canvas.FillTextF(Button.Text, Button.TextX, Button.TextY, Button.Width - (2 * (Button.TextX - Button.X))); end; procedure DrawControlButton(Button : TOptionsButton; FontSize : integer; Canvas: TW3Canvas); begin var AlphaBlendingValue := 0.3; //The value we shall use for the Alpha blending if gamemode = levelselector then //If the gamemode is the level selector begin for var i := 0 to High(Selector.Text) do //Goes through the text in the level selector begin var Len := Selector.Text[i].text.Length * 10; //The length of the text. we time it //by 10 as we use font size 10 so it it //a rough estimation of the length if (Selector.Text[i].x - offsetX < Button.X + Button.Width) and //Works out if the x overlaps (Selector.Text[i].x - offsetX + Len > Button.X) then begin if (Selector.Text[i].y - offsetY < Button.Y + Button.Height) and //Works out if the y overlaps (Selector.Text[i].y - offsetY + 10 > Button.Y) then AlphaBlendingValue := 0.05; //If it does, make it more transparent so the text can be read with ease end; end; end else //Otherwise it is in the maingame begin for var i := 0 to High(gameText) do //Goes through the gameTexts begin var Len := gameText[i].text.Length * 10; //The length of the text. We multiply it //by 10 as we use font size 10 so it it //a rough estimation of the length if (gameText[i].x - offsetX < Button.X + Button.Width) and //Works out if the x overlaps (gameText[i].x - offsetX + Len > Button.X) then begin if (gameText[i].y - offsetY < Button.Y + Button.Height) and //Works out if the y overlaps (gameText[i].y - offsetY + 10 > Button.Y) then AlphaBlendingValue := 0.05; //If it does, make it more transparent so the text can be read with ease end; end; end; Canvas.FillStyle := 'rgba(130, 130, 130, ' + floatToStr(AlphaBlendingValue) + ')'; Canvas.BeginPath; Canvas.FillRectF(Button.X, Button.Y, Button.Width, Button.Height); Canvas.ClosePath; Canvas.Fill; Canvas.FillStyle := 'rgba(0, 0, 0, ' + floatToStr(AlphaBlendingValue) + ')'; Canvas.Font := IntToStr(FontSize) + 'pt verdana'; Canvas.FillTextF(Button.Text, Button.TextX, Button.TextY, Button.Width - (2 * (Button.TextX - Button.X))); end; procedure DrawPlayer(player : UPlayer.TPlayer; Canvas: TW3Canvas); begin if (OnScreen(player.X,player.Y,player.X + PLAYERHEAD,player.Y + PLAYERHEIGHT)) then begin //Draw the body Canvas.FillStyle := player.colour; Canvas.BeginPath; Canvas.Ellipse(player.X - offsetX, player.Y - offsetY, player.X + PLAYERHEAD - offsetX, player.Y + PLAYERHEAD - offsetY); Canvas.Ellipse(player.X - offsetX, player.Y + PLAYERHEAD - offsetY, player.X + PLAYERHEAD - offsetX, player.Y + PLAYERHEAD + 10 - offsetY); Canvas.FillRectF(player.X - offsetX, player.Y + PLAYERHEAD + 5 - offsetY, PLAYERHEAD, PLAYERHEIGHT - PLAYERHEAD - 5); Canvas.ClosePath; Canvas.Fill; //Draw the gun if player.FaceLeft then begin Canvas.FillStyle := 'black'; Canvas.BeginPath; Canvas.FillRectF(player.X - UBullet.WIDTH + 3 - offsetX, player.Y + PLAYERHEAD + 3 - offsetY, UBullet.WIDTH, UBullet.HEIGHT); Canvas.FillRectF(player.X - 1 - offsetX, player.Y + PLAYERHEAD + 3 + UBullet.HEIGHT - offsetY, 4, 8); Canvas.ClosePath; Canvas.Fill; end else begin Canvas.FillStyle := 'black'; Canvas.BeginPath; Canvas.FillRectF(player.X + PLAYERHEAD - 3 - offsetX, player.Y + PLAYERHEAD + 3 - offsetY, UBullet.WIDTH, UBullet.HEIGHT); Canvas.FillRectF(player.X + PLAYERHEAD - 3 - offsetX, player.Y + PLAYERHEAD + 3 + UBullet.HEIGHT - offsetY, 4, 8); Canvas.ClosePath; Canvas.Fill; end; //Draw the health if player.Health >= 1 then //State health above player begin Canvas.Font := '10pt verdana'; Canvas.FillStyle := player.Colour; Canvas.FillTextF(IntToStr(Round(player.Health)), player.x - offsetX, player.y - offsetY - 10, PLAYERHEAD); end else //Says dead if the player is dead begin Canvas.Font := '10pt verdana'; Canvas.FillStyle := player.Colour; Canvas.FillTextF("Dead", player.x - offsetX, player.y - offsetY - 10, PLAYERHEAD); end; end; end; procedure DrawAI(AI : array of UAi.TAi; Canvas: TW3Canvas); begin var i := 0; while i <= High(AI) do //Iterate through the Ai Units begin DrawPlayer(AI[i], Canvas); //Draws the ai using the draw player code i := 1; //Selects the next Ai unit end; end; procedure DrawDoors(Door : array of UE.TE; Canvas: TW3Canvas); //Mainly for all the doors in the level selector begin var i := 0; while i <= High(Door) do //iterate through the doors begin if (i + 1 > UnlockedDoors) then DrawDoor(Door[i], Canvas, true) //Draws the current door using the drawDoor procedure else DrawDoor(Door[i], Canvas); i += 1; //Select next door end; end; procedure DrawDoor(Door : UE.TE; Canvas: TW3Canvas; Locked : boolean = false); begin if (OnScreen(Door.X,Door.Y,Door.X + UE.WIDTH,Door.Y + UE.HEIGHT)) then begin if (Locked) then //If the door is locked make it slightly transparent Canvas.FillStyle := 'rgba(0, 0, 205, 0.4)' else Canvas.FillStyle := 'rgb(0, 0, 205)'; Canvas.BeginPath; Canvas.FillRectF(Door.X - offsetX, Door.Y - offsetY, UE.WIDTH, UE.HEIGHT); Canvas.ClosePath; Canvas.Fill; end; end; procedure DrawPlats(Plat : array of UPlat.TPlat; Canvas: TW3Canvas); begin var i := 0; while i <= High(Plat) do //Iterate through the platforms begin if (OnScreen(Plat[i].X,Plat[i].Y,Plat[i].X + Plat[i].Width,Plat[i].Y + Plat[i].Height)) then begin //First set the colour depending on the type of platform it is if Plat[i].Crumble then //If it is a crumbling platform begin Canvas.FillStyle := 'rgba(90, 65, 35, 0.9)'; //set the colour end else if Plat[i].horizontal then //If the platform is horizontal begin if Plat[i].jumpThrough then //and you can jump through it begin if Plat[i].noFall then //but cannot fall through it Canvas.FillStyle := 'rgba(100, 0, 0, 0.9)' //make it dark red else //and can fall through it Canvas.FillStyle := 'rgba(0, 50, 0, 0.9)'; //make it dark green end else //and you cannot jump through it begin if Plat[i].noFall then //but cannot fall through it Canvas.FillStyle := 'rgba(0, 0, 100, 0.9)' //make it dark blue else //and can fall through it Canvas.FillStyle := 'rgba(0, 0, 0, 0.9)'; //make it black end; end else //if it is vertical begin if Plat[i].noFall then //and you cannot fall through it begin if Plat[i].NoWallJump then //and you cannot wall jump off it Canvas.FillStyle := 'rgba(250, 100, 190, 0.9)' //Make it pink else //and you can wall jump off it Canvas.FillStyle := 'rgba(255, 80, 0, 0.9)'; //make it orange end else //and you can fall through it begin if Plat[i].NoWallJump then //and you cannot wall jump off it Canvas.FillStyle := 'rgba(190, 10, 120, 0.9)' //Make it purple else //and you can wall jump off it Canvas.FillStyle := 'rgba(100, 100, 100, 0.9)'; //make it grey end; end; Canvas.BeginPath; //Draw the platform Canvas.FillRectF(Plat[i].X - offsetX, Plat[i].Y - offsetY, Plat[i].Width, Plat[i].Height); Canvas.ClosePath; Canvas.Fill; end; if Plat[i].Moves then //Updates moving platforms begin var VectorforPlayer := Plat[i].MoveUpdate(Player.X,Player.Y,Player.X + PLAYERHEAD,Player.Y + PLAYERHEIGHT); Player.X += VectorforPlayer[0]; //add the needed x change from being on a moving platform Player.Y += VectorforPlayer[1]; //add the needed y change from being on a moving platform end; if (Plat[i].Crumble) and (Plat[i].Y <= maxY + 2500) then Plat[i].CrumbleUpdate(); //Update the crumble platforms i += 1; //Select the next platform end; end; procedure DrawBullet(Bullet : array of UBullet.TBullet; Canvas: TW3Canvas); begin Canvas.FillStyle := 'green'; var i := 0; while i <= High(Bullet) do //iterate through the bullets begin if (OnScreen(Bullet[i].X,Bullet[i].Y,Bullet[i].X + UBullet.WIDTH,Bullet[i].Y + UBullet.HEIGHT)) then begin //Set 0, 0 point to the centre of the Bullet Canvas.Translate(Bullet[i].X + UBullet.WIDTH/2 - offsetX, Bullet[i].Y + UBullet.HEIGHT/2 - offsetY); //Rotate the Bullet Canvas.Rotate((Bullet[i].Angle + 90) * PI / 180); //Restore the 0, 0 point back to 0, 0 Canvas.Translate(-(Bullet[i].X + UBullet.WIDTH/2 - offsetX), -(Bullet[i].Y + UBullet.HEIGHT/2 - offsetY)); Canvas.BeginPath; Canvas.FillRectF(Bullet[i].X - offsetX, Bullet[i].Y - offsetY, UBullet.WIDTH, UBullet.HEIGHT); Canvas.ClosePath; Canvas.Fill; //Set 0, 0 point to the centre of the Bullet Canvas.Translate(Bullet[i].X + UBullet.WIDTH/2 - offsetX, Bullet[i].Y + UBullet.HEIGHT/2 - offsetY); //Rotate the Canvas to normal Canvas.Rotate(-(Bullet[i].Angle + 90) * PI / 180); //Restore the 0, 0 point back to 0, 0 Canvas.Translate(-(Bullet[i].X + UBullet.WIDTH/2 - offsetX), -(Bullet[i].Y + UBullet.HEIGHT/2 - offsetY)); end; i += 1; //Select the next bullet end; end; procedure DrawText(text : array of UGameText.TText; Canvas: TW3Canvas; FontSize : integer = 10); begin var i := 0; while i <= High(text) do //Iterate through the text begin Canvas.Font := IntToStr(FontSize) + 'pt verdana'; Canvas.FillStyle := text[i].Colour; Canvas.FillTextF(text[i].text, text[i].x - offsetX, text[i].y - offsetY, MAX_INT); i += 1; //Select the next text item end; Canvas.Font := '10pt verdana'; Canvas.FillStyle := 'red'; if gamemode = maingame then //Draws text needed always in levels begin Canvas.FillTextF('Level: ' + IntToStr(Level), 240, 40, MAX_INT); end else if gamemode = levelselector then //Draws text always needed in the level selector begin Canvas.FillTextF('Level Selector', 80, 40, MAX_INT); end; end; procedure DrawTurret(Turrets : array of TTurret; Canvas: TW3Canvas); //different side support begin for var i := 0 to High(Turrets) do begin if OnScreen(Turrets[i].X, Turrets[i].Y, Turrets[i].X + UTurret.WIDTH, Turrets[i].Y + UTurret.HEIGHT) then begin var TurretRotation : float; //Sets the angle of the turret, so the rounded part faces the correct way if Turrets[i].Placement = Bottom then TurretRotation := 0 else if Turrets[i].Placement = Top then TurretRotation := 180 else if Turrets[i].Placement = Left then TurretRotation := 270 else if Turrets[i].Placement = Right then TurretRotation := 90; //Set the 0, 0 point to the centre of the Turret Canvas.Translate(Turrets[i].X + UTurret.WIDTH/2 - offsetX, Turrets[i].Y + UTurret.HEIGHT/2 - offsetY); //Rotate the angle of the Turret according to what side it is placed on Canvas.Rotate((TurretRotation) * PI / 180); //Restore the 0, 0 point back to 0, 0 Canvas.Translate(-(Turrets[i].X + UTurret.WIDTH/2 - offsetX), -(Turrets[i].Y + UTurret.HEIGHT/2 - offsetY)); Canvas.FillStyle := 'blue'; Canvas.BeginPath; Canvas.Ellipse(Turrets[i].X - offsetX, Turrets[i].Y - offsetY, Turrets[i].X + UTurret.WIDTH - offsetX, Turrets[i].Y + ((UTurret.HEIGHT/3) * 2) - offsetY); Canvas.FillRectF(Turrets[i].X - offsetX, Turrets[i].Y + (UTurret.HEIGHT/3) - offsetY, UTurret.WIDTH, (UTurret.HEIGHT/3) * 2); Canvas.ClosePath; Canvas.Fill; //Set the 0, 0 point to the centre of the Turret Canvas.Translate(Turrets[i].X + UTurret.WIDTH/2 - offsetX, Turrets[i].Y + UTurret.HEIGHT/2 - offsetY); //Rotate back to normal Canvas.Rotate(-(TurretRotation) * PI / 180); //Restore the 0, 0 point back to 0, 0 Canvas.Translate(-(Turrets[i].X + UTurret.WIDTH/2 - offsetX), -(Turrets[i].Y + UTurret.HEIGHT/2 - offsetY)); //Set 0, 0 point to the centre of the Turret Canvas.Translate(Turrets[i].X + UTurret.WIDTH/2 - offsetX, Turrets[i].Y + UTurret.HEIGHT/2 - offsetY); //Rotate the Stalk of the Turret Canvas.Rotate((Turrets[i].Angle) * PI / 180); //Restore the 0, 0 point back to 0, 0 Canvas.Translate(-(Turrets[i].X + UTurret.WIDTH/2 - offsetX), -(Turrets[i].Y + UTurret.HEIGHT/2 - offsetY)); Canvas.FillStyle := 'black'; Canvas.BeginPath; Canvas.FillRectF(Turrets[i].X + UTurret.WIDTH/2 - UBullet.HEIGHT/2 - offsetX, Turrets[i].Y + UTurret.HEIGHT/2 - offsetY, UBullet.HEIGHT, -(UTurret.HEIGHT/3) * 2); Canvas.ClosePath; Canvas.Fill; //Set 0, 0 point to the centre of the Turret Canvas.Translate(Turrets[i].X + UTurret.WIDTH/2 - offsetX, Turrets[i].Y + UTurret.HEIGHT/2 - offsetY); //Rotate back to normal Canvas.Rotate(-((Turrets[i].Angle) * PI / 180)); //Restore the 0, 0 point back to 0, 0 Canvas.Translate(-(Turrets[i].X + UTurret.WIDTH/2 - offsetX), -(Turrets[i].Y + UTurret.HEIGHT/2 - offsetY)); end; end; end; function OnScreen(x, y, x2, y2 : float) : boolean; begin if (x - offsetX <= screenWidth) or (x2 - offsetX >= 0) then //checks if the x is on screen begin if (y - offsetY <= screenHeight) or (y2 - offsetY >= 0) then //checks if the y is on screen Exit(true); //if both succeed, return true end; Exit(false); //else it is not on screen so return false end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { Implements FBO support. Original author of the unit is Riz. } unit VXS.FBORenderer; interface {$I VXScene.inc} uses System.Classes, System.SysUtils, FMX.Dialogs, VXS.OpenGL, VXS.PersistentClasses, VXS.VectorGeometry, VXS.Scene, VXS.Texture, VXS.Context, VXS.FBO, VXS.Color, VXS.Material, VXS.RenderContextInfo, VXS.State, VXS.PipelineTransformation, VXS.TextureFormat, VXS.VectorTypes, VXS.MultisampleImage; type TVXEnabledRenderBuffer = (erbDepth, erbStencil); TVXEnabledRenderBuffers = set of TVXEnabledRenderBuffer; TVXFBOTargetVisibility = (tvDefault, tvFBOOnly); TVXFBOClearOption = (coColorBufferClear, coDepthBufferClear, coStencilBufferClear, coUseBufferBackground); TVXFBOClearOptions = set of TVXFBOClearOption; TVXTextureArray = array of TVXTexture; TSetTextureTargetsEvent = procedure(Sender: TObject; var colorTexs: TVXTextureArray) of object; TVXFBORenderer = class(TVXBaseSceneObject, IVXMaterialLibrarySupported) private FFbo: TVXFrameBuffer; FDepthRBO: TVXDepthRBO; FStencilRBO: TVXStencilRBO; FColorAttachment: Integer; FRendering: Boolean; FHasColor: Boolean; FHasDepth: Boolean; FHasStencil: Boolean; FMaterialLibrary: TVXMaterialLibrary; FColorTextureName: TVXLibMaterialName; FDepthTextureName: TVXLibMaterialName; FWidth: Integer; FHeight: Integer; FForceTextureDimensions: Boolean; FStencilPrecision: TVXStencilPrecision; FRootObject: TVXBaseSceneObject; FRootVisible: Boolean; FCamera: TVXCamera; FEnabledRenderBuffers: TVXEnabledRenderBuffers; FTargetVisibility: TVXFBOTargetVisibility; FBeforeRender: TDirectRenderEvent; FPostInitialize: TNotifyEvent; FAfterRender: TDirectRenderEvent; FPreInitialize: TNotifyEvent; FBackgroundColor: TVXColor; FClearOptions: TVXFBOClearOptions; FAspect: Single; FSceneScaleFactor: Single; FUseLibraryAsMultiTarget: Boolean; FPostGenerateMipmap: Boolean; FMaxSize: Integer; FMaxAttachment: Integer; FStoreCamera: array [0 .. 2] of TVector; FOnSetTextureTargets: TSetTextureTargetsEvent; // implementing IGLMaterialLibrarySupported function GetMaterialLibrary: TVXAbstractMaterialLibrary; procedure SetMaterialLibrary(const Value: TVXAbstractMaterialLibrary); procedure SetDepthTextureName(const Value: TVXLibMaterialName); procedure SetColorTextureName(const Value: TVXLibMaterialName); procedure SetForceTextureDimentions(const Value: Boolean); procedure SetHeight(Value: Integer); procedure SetWidth(Value: Integer); procedure SetLayer(const Value: Integer); function GetLayer: Integer; procedure SetLevel(const Value: Integer); function GetLevel: Integer; procedure SetStencilPrecision(const Value: TVXStencilPrecision); procedure SetRootObject(const Value: TVXBaseSceneObject); function GetViewport: TRectangle; procedure SetCamera(const Value: TVXCamera); procedure SetEnabledRenderBuffers(const Value: TVXEnabledRenderBuffers); procedure SetTargetVisibility(const Value: TVXFBOTargetVisibility); procedure SetBackgroundColor(const Value: TVXColor); function StoreSceneScaleFactor: Boolean; function StoreAspect: Boolean; procedure SetUseLibraryAsMultiTarget(Value: Boolean); procedure SetPostGenerateMipmap(const Value: Boolean); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure Initialize; procedure ForceDimensions(Texture: TVXTexture); procedure RenderToFBO(var ARci: TVXRenderContextInfo); procedure ApplyCamera(var ARci: TVXRenderContextInfo); procedure UnApplyCamera(var ARci: TVXRenderContextInfo); procedure DoBeforeRender(var ARci: TVXRenderContextInfo); procedure DoAfterRender(var ARci: TVXRenderContextInfo); procedure DoPreInitialize; procedure DoPostInitialize; property HasColor: Boolean read FHasColor; property HasDepth: Boolean read FHasDepth; property HasStencil: Boolean read FHasStencil; property Viewport: TRectangle read GetViewport; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure DoRender(var ARci: TVXRenderContextInfo; ARenderSelf: Boolean; ARenderChildren: Boolean); override; { Layer (also cube map face) is activated only on the volume textures, texture array and cube map. You can select the layer during the drawing to. } property Layer: Integer read GetLayer write SetLayer; { Mipmap Level where will be rendering } property Level: Integer read GetLevel write SetLevel; published property Active: Boolean read GetVisible write SetVisible default True; property PickableTarget: Boolean read GetPickable write SetPickable default False; { force texture dimensions when initializing only works with TVXBlankImage and GLfloatDataImage, otherwise does nothing } property ForceTextureDimensions: Boolean read FForceTextureDimensions write SetForceTextureDimentions default True; property Width: Integer read FWidth write SetWidth default 256; property Height: Integer read FHeight write SetHeight default 256; property Aspect: Single read FAspect write FAspect stored StoreAspect; property ColorTextureName: TVXLibMaterialName read FColorTextureName write SetColorTextureName; property DepthTextureName: TVXLibMaterialName read FDepthTextureName write SetDepthTextureName; property MaterialLibrary: TVXAbstractMaterialLibrary read GetMaterialLibrary write SetMaterialLibrary; property BackgroundColor: TVXColor read FBackgroundColor write SetBackgroundColor; property ClearOptions: TVXFBOClearOptions read FClearOptions write FClearOptions; { camera used for rendering to the FBO if not assigned, use the active view's camera } property Camera: TVXCamera read FCamera write SetCamera; { adjust the scene scale of the camera so that the rendering becomes independent of the width of the fbo renderer 0 = disabled } property SceneScaleFactor: Single read FSceneScaleFactor write FSceneScaleFactor stored StoreSceneScaleFactor; { root object used when rendering to the FBO if not assigned, uses itself as root and renders the child objects to the FBO } property RootObject: TVXBaseSceneObject read FRootObject write SetRootObject; { determines if target is rendered to FBO only or rendered normally in FBO only mode, if RootObject is assigned, the RootObject's Visible flag is modified in default mode, if RootObject is not assigned, children are rendered normally after being rendered to the FBO } property TargetVisibility: TVXFBOTargetVisibility read FTargetVisibility write SetTargetVisibility default tvDefault; { Enables the use of a render buffer if a texture is not assigned } property EnabledRenderBuffers: TVXEnabledRenderBuffers read FEnabledRenderBuffers write SetEnabledRenderBuffers; { use stencil buffer } property StencilPrecision: TVXStencilPrecision read FStencilPrecision write SetStencilPrecision default spDefault; { called before rendering to the FBO } property BeforeRender: TDirectRenderEvent read FBeforeRender write FBeforeRender; { called after the rendering to the FBO } property AfterRender: TDirectRenderEvent read FAfterRender write FAfterRender; { Called before the FBO is initialized the FBO is bound before calling this event } property PreInitialize: TNotifyEvent read FPreInitialize write FPreInitialize; { Called after the FBO is initialized, but before any rendering the FBO is bound before calling this event } property PostInitialize: TNotifyEvent read FPostInitialize write FPostInitialize; property UseLibraryAsMultiTarget: Boolean read FUseLibraryAsMultiTarget write SetUseLibraryAsMultiTarget default False; { Control mipmap generation after rendering texture must have MinFilter with mipmaping } property PostGenerateMipmap: Boolean read FPostGenerateMipmap write SetPostGenerateMipmap default True; { Allows multiTargeting to different texture sources instead of all coming from one single MatLib with UseLibraryAsMultiTarget. OnSetTextureTargets overrides the other method of setting target textures via the MaterialLibrary, ColorTextureName and DepthTextureName propertes } property OnSetTextureTargets: TSetTextureTargetsEvent read FOnSetTextureTargets write FOnSetTextureTargets; end; //------------------------------------------------------------------------------ implementation //------------------------------------------------------------------------------ { TVXFBORenderer } procedure TVXFBORenderer.ApplyCamera(var ARci: TVXRenderContextInfo); var sc: Single; begin with ARci.PipelineTransformation do begin Push; if Assigned(Camera) then begin FStoreCamera[0] := ARci.cameraPosition; FStoreCamera[1] := ARci.cameraDirection; FStoreCamera[2] := ARci.cameraUp; IdentityAll; sc := FCamera.SceneScale; if FSceneScaleFactor > 0 then FCamera.SceneScale := Width / FSceneScaleFactor; FCamera.ApplyPerspective(Viewport, Width, Height, 96); // 96 is default dpi FCamera.SceneScale := sc; SetViewMatrix(CreateScaleMatrix(Vector3fMake(1.0 / FAspect, 1.0, 1.0))); FCamera.Apply; end else begin SetViewMatrix(MatrixMultiply(ViewMatrix^, CreateScaleMatrix(Vector3fMake(1.0 / FAspect, 1.0, 1.0)))); end; end; end; procedure TVXFBORenderer.UnApplyCamera(var ARci: TVXRenderContextInfo); begin ARci.cameraPosition := FStoreCamera[0]; ARci.cameraDirection := FStoreCamera[1]; ARci.cameraUp := FStoreCamera[2]; ARci.PipelineTransformation.Pop; end; constructor TVXFBORenderer.Create(AOwner: TComponent); begin inherited; ObjectStyle := [osDirectDraw, osNoVisibilityCulling]; FFbo := TVXFrameBuffer.Create; FBackgroundColor := TVXColor.Create(Self); FUseLibraryAsMultiTarget := False; FForceTextureDimensions := True; FWidth := 256; FHeight := 256; FEnabledRenderBuffers := [erbDepth]; FClearOptions := [coColorBufferClear, coDepthBufferClear, coStencilBufferClear, coUseBufferBackground]; PickableTarget := False; FAspect := 1.0; FSceneScaleFactor := 0.0; FPostGenerateMipmap := True; StructureChanged; end; destructor TVXFBORenderer.Destroy; begin FFbo.Free; FDepthRBO.Free; FStencilRBO.Free; FBackgroundColor.Free; inherited; end; procedure TVXFBORenderer.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (AComponent = FRootObject) and (Operation = opRemove) then FRootObject := nil; end; procedure TVXFBORenderer.DoAfterRender(var ARci: TVXRenderContextInfo); begin if Assigned(FAfterRender) then FAfterRender(Self, ARci); end; procedure TVXFBORenderer.DoBeforeRender(var ARci: TVXRenderContextInfo); begin if Assigned(FBeforeRender) then FBeforeRender(Self, ARci); end; procedure TVXFBORenderer.DoPostInitialize; begin if Assigned(FPostInitialize) then FPostInitialize(Self); end; procedure TVXFBORenderer.DoPreInitialize; begin if Assigned(FPreInitialize) then FPreInitialize(Self); end; procedure TVXFBORenderer.DoRender(var ARci: TVXRenderContextInfo; ARenderSelf, ARenderChildren: Boolean); begin if not(csDesigning in ComponentState) then RenderToFBO(ARci); if (not Assigned(FRootObject)) and (TargetVisibility = tvDefault) and ARenderChildren then RenderChildren(0, Count - 1, ARci); end; procedure TVXFBORenderer.ForceDimensions(Texture: TVXTexture); var bi: TVXBlankImage; mi: TVXMultisampleImage; begin if Texture.Image is TVXBlankImage then begin bi := TVXBlankImage(Texture.Image); bi.Width := Width; bi.Height := Height; end else if Texture.Image is TVXMultisampleImage then begin mi := TVXMultisampleImage(Texture.Image); mi.Width := Width; mi.Height := Height; end; end; function TVXFBORenderer.GetViewport: TRectangle; begin Result.Left := 0; Result.Top := 0; Result.Width := Width; Result.Height := Height; end; procedure TVXFBORenderer.Initialize; procedure AddOneMultiTarget(colorTex: TVXTexture); begin if ForceTextureDimensions then ForceDimensions(colorTex); if FColorAttachment >= FMaxAttachment then begin ShowMessage('Number of color attachments out of GL_MAX_COLOR_ATTACHMENTS'); Visible := False; Abort; end; FFbo.AttachTexture(FColorAttachment, colorTex); Inc(FColorAttachment); end; const cDrawBuffers: array [0 .. 15] of GLenum = (GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3, GL_COLOR_ATTACHMENT4, GL_COLOR_ATTACHMENT5, GL_COLOR_ATTACHMENT6, GL_COLOR_ATTACHMENT7, GL_COLOR_ATTACHMENT8, GL_COLOR_ATTACHMENT9, GL_COLOR_ATTACHMENT10, GL_COLOR_ATTACHMENT11, GL_COLOR_ATTACHMENT12, GL_COLOR_ATTACHMENT13, GL_COLOR_ATTACHMENT14, GL_COLOR_ATTACHMENT15); var colorTex: TVXTexture; depthTex: TVXTexture; I: Integer; MulTexture: TVXTextureArray; begin for I := 0 to MaxColorAttachments - 1 do FFbo.DetachTexture(I); if FMaxSize = 0 then glGetIntegerv(GL_MAX_RENDERBUFFER_SIZE, @FMaxSize); if Width > FMaxSize then begin FWidth := FMaxSize; ShowMessage(Format('%s.Width out of GL_MAX_RENDERBUFFER_SIZE', [Name])); end; if Height > FMaxSize then begin FHeight := FMaxSize; ShowMessage(Format('%s.Height out of GL_MAX_RENDERBUFFER_SIZE', [Name])); end; FFbo.Width := Width; FFbo.Height := Height; FFbo.Bind; DoPreInitialize; FFbo.Unbind; if Assigned(FMaterialLibrary) then begin colorTex := FMaterialLibrary.TextureByName(ColorTextureName); depthTex := FMaterialLibrary.TextureByName(DepthTextureName); end else begin colorTex := nil; depthTex := nil; end; FHasColor := False; FHasDepth := False; FHasStencil := False; FColorAttachment := 0; if FUseLibraryAsMultiTarget or Assigned(FOnSetTextureTargets) then begin if FMaxAttachment = 0 then glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, @FMaxAttachment); if Assigned(FOnSetTextureTargets) then begin FOnSetTextureTargets(Self, MulTexture); for I := 0 to High(MulTexture) do begin colorTex := MulTexture[I]; // Skip depth texture if colorTex = depthTex then Continue; AddOneMultiTarget(colorTex); end; end else // Multicolor attachments for I := 0 to FMaterialLibrary.Materials.Count - 1 do begin colorTex := FMaterialLibrary.Materials[I].Material.Texture; // Skip depth texture if colorTex = depthTex then Continue; AddOneMultiTarget(colorTex); end; FHasColor := FColorAttachment > 0; end else begin // One color attachment if Assigned(colorTex) then begin if ForceTextureDimensions then ForceDimensions(colorTex); FFbo.AttachTexture(0, colorTex); Inc(FColorAttachment); FHasColor := True; end; end; if Assigned(depthTex) then begin if ForceTextureDimensions then ForceDimensions(depthTex); FFbo.AttachDepthTexture(depthTex); FDepthRBO.Free; FDepthRBO := nil; FHasDepth := True; FHasStencil := depthTex.TextureFormatEx = tfDEPTH24_STENCIL8; end else if erbDepth in EnabledRenderBuffers then begin if not Assigned(FDepthRBO) then FDepthRBO := TVXDepthRBO.Create; FDepthRBO.Width := Width; FDepthRBO.Height := Height; FFbo.AttachDepthBuffer(FDepthRBO); FHasDepth := True; end else begin FFbo.DetachDepthBuffer; if Assigned(FDepthRBO) then begin FDepthRBO.Free; FDepthRBO := nil; end; end; if erbStencil in EnabledRenderBuffers then begin if not Assigned(FStencilRBO) then FStencilRBO := TVXStencilRBO.Create; FStencilRBO.StencilPrecision := FStencilPrecision; FStencilRBO.Width := Width; FStencilRBO.Height := Height; FFbo.AttachStencilBuffer(FStencilRBO); FHasStencil := True; end else begin if not FHasStencil then FFbo.DetachStencilBuffer; if Assigned(FStencilRBO) then begin FStencilRBO.Free; FStencilRBO := nil; end; end; FFbo.Bind; if FColorAttachment = 0 then begin glDrawBuffer(GL_NONE); glReadBuffer(GL_NONE); end else glDrawBuffers(FColorAttachment, @cDrawBuffers); DoPostInitialize; FFbo.Unbind; /// CheckOpenGLError; ClearStructureChanged; end; procedure TVXFBORenderer.RenderToFBO(var ARci: TVXRenderContextInfo); function GetClearBits: cardinal; begin Result := 0; if HasColor and (coColorBufferClear in FClearOptions) then Result := Result or GL_COLOR_BUFFER_BIT; if HasDepth and (coDepthBufferClear in FClearOptions) then Result := Result or GL_DEPTH_BUFFER_BIT; if HasStencil and (coStencilBufferClear in FClearOptions) then Result := Result or GL_STENCIL_BUFFER_BIT; end; type TVXStoredStates = record ColorClearValue: TColorVector; ColorWriteMask: TVXColorMask; Tests: TVXStates; end; function StoreStates: TVXStoredStates; begin Result.ColorClearValue := ARci.VXStates.ColorClearValue; Result.ColorWriteMask := ARci.VXStates.ColorWriteMask[0]; Result.Tests := [stDepthTest, stStencilTest] * ARci.VXStates.States; end; procedure RestoreStates(const aStates: TVXStoredStates); begin ARci.VXStates.ColorClearValue := aStates.ColorClearValue; ARci.VXStates.SetColorMask(aStates.ColorWriteMask); if stDepthTest in aStates.Tests then ARci.VXStates.Enable(stDepthTest) else ARci.VXStates.Disable(stDepthTest); if stStencilTest in aStates.Tests then ARci.VXStates.Enable(stStencilTest) else ARci.VXStates.Disable(stStencilTest); end; var backColor: TColorVector; buffer: TVXSceneBuffer; savedStates: TVXStoredStates; w, h: Integer; s: string; begin if (ARci.drawState = dsPicking) and not PickableTarget then exit; if TVXFramebufferHandle.IsSupported = True then begin ShowMessage('Framebuffer not supported - deactivated'); Active := False; exit; end; // prevent recursion if FRendering then exit; FRendering := True; if (ocStructure in Changes) or Assigned(FOnSetTextureTargets) then begin Initialize; if not Active then exit; end; ApplyCamera(ARci); try savedStates := StoreStates; FFbo.Bind; if FFbo.GetStringStatus(s) <> fsComplete then begin ShowMessage(Format('Framebuffer error: %s. Deactivated', [s])); Active := False; exit; end; DoBeforeRender(ARci); if Assigned(Camera) then Camera.Scene.SetupLights(ARci.VXStates.MaxLights); w := Width; h := Height; if FFbo.Level > 0 then begin w := w shr FFbo.Level; h := h shr FFbo.Level; if w = 0 then w := 1; if h = 0 then h := 1; end; ARci.VXStates.Viewport := Vector4iMake(0, 0, w, h); buffer := ARci.buffer as TVXSceneBuffer; if HasColor then ARci.VXStates.SetColorMask(cAllColorComponents) else ARci.VXStates.SetColorMask([]); ARci.VXStates.DepthWriteMask := HasDepth; if HasStencil then ARci.VXStates.Enable(stStencilTest) else ARci.VXStates.Disable(stStencilTest); if coUseBufferBackground in FClearOptions then begin backColor := ConvertWinColor(buffer.BackgroundColor); backColor.w := buffer.BackgroundAlpha; ARci.VXStates.ColorClearValue := backColor; end else begin ARci.VXStates.ColorClearValue := FBackgroundColor.Color; end; glClear(GetClearBits); FFbo.PreRender; // render to fbo if Assigned(RootObject) then begin // if object should only be rendered to the fbo // ensure it's visible before rendering to fbo if TargetVisibility = tvFBOOnly then RootObject.Visible := True; RootObject.Render(ARci); // then make it invisible afterwards if TargetVisibility = tvFBOOnly then RootObject.Visible := False; end else if (Count > 0) then RenderChildren(0, Count - 1, ARci); FFbo.PostRender(FPostGenerateMipmap); RestoreStates(savedStates); ARci.VXStates.Viewport := Vector4iMake(0, 0, ARci.viewPortSize.cx, ARci.viewPortSize.cy); finally FFbo.Unbind; FRendering := False; DoAfterRender(ARci); UnApplyCamera(ARci); if Assigned(Camera) then Camera.Scene.SetupLights(ARci.VXStates.MaxLights); end; end; procedure TVXFBORenderer.SetBackgroundColor(const Value: TVXColor); begin FBackgroundColor.Assign(Value); end; procedure TVXFBORenderer.SetCamera(const Value: TVXCamera); begin if FCamera <> Value then begin FCamera := Value; StructureChanged; end; end; procedure TVXFBORenderer.SetColorTextureName(const Value: TVXLibMaterialName); begin if FColorTextureName <> Value then begin FColorTextureName := Value; StructureChanged; end; end; procedure TVXFBORenderer.SetDepthTextureName(const Value: TVXLibMaterialName); begin if FDepthTextureName <> Value then begin FDepthTextureName := Value; StructureChanged; end; end; procedure TVXFBORenderer.SetEnabledRenderBuffers(const Value: TVXEnabledRenderBuffers); begin if FEnabledRenderBuffers <> Value then begin FEnabledRenderBuffers := Value; StructureChanged; end; end; procedure TVXFBORenderer.SetForceTextureDimentions(const Value: Boolean); begin if FForceTextureDimensions <> Value then begin FForceTextureDimensions := Value; StructureChanged; end; end; function TVXFBORenderer.GetMaterialLibrary: TVXAbstractMaterialLibrary; begin Result := FMaterialLibrary; end; procedure TVXFBORenderer.SetMaterialLibrary(const Value: TVXAbstractMaterialLibrary); begin if FMaterialLibrary <> Value then begin if Value is TVXMaterialLibrary then begin FMaterialLibrary := TVXMaterialLibrary(Value); StructureChanged; end; end; end; procedure TVXFBORenderer.SetUseLibraryAsMultiTarget(Value: Boolean); begin if FUseLibraryAsMultiTarget <> Value then begin FUseLibraryAsMultiTarget := Value; StructureChanged; end; end; procedure TVXFBORenderer.SetPostGenerateMipmap(const Value: Boolean); begin if FPostGenerateMipmap <> Value then FPostGenerateMipmap := Value; end; procedure TVXFBORenderer.SetRootObject(const Value: TVXBaseSceneObject); begin if FRootObject <> Value then begin if Assigned(FRootObject) then FRootObject.RemoveFreeNotification(Self); FRootObject := Value; if Assigned(FRootObject) then FRootObject.FreeNotification(Self); StructureChanged; end; end; procedure TVXFBORenderer.SetStencilPrecision(const Value: TVXStencilPrecision); begin if FStencilPrecision <> Value then begin FStencilPrecision := Value; StructureChanged; end; end; procedure TVXFBORenderer.SetTargetVisibility(const Value: TVXFBOTargetVisibility); begin if FTargetVisibility <> Value then begin if Assigned(RootObject) then begin if (TargetVisibility = tvFBOOnly) then begin // we went from fbo only, restore root's old visibility RootObject.Visible := FRootVisible; end else begin // we're going to fbo only, save root visibility for later FRootVisible := RootObject.Visible; end; end; FTargetVisibility := Value; StructureChanged; end; end; function TVXFBORenderer.StoreSceneScaleFactor: Boolean; begin Result := (FSceneScaleFactor <> 0.0); end; function TVXFBORenderer.StoreAspect: Boolean; begin Result := (FAspect <> 1.0); end; procedure TVXFBORenderer.SetWidth(Value: Integer); begin if FWidth <> Value then begin FWidth := Value; StructureChanged; end; end; procedure TVXFBORenderer.SetHeight(Value: Integer); begin if FHeight <> Value then begin FHeight := Value; StructureChanged; end; end; procedure TVXFBORenderer.SetLayer(const Value: Integer); begin if Value <> FFbo.Layer then begin if FRendering or (ocStructure in Changes) then FFbo.Layer := Value else begin FFbo.Bind; FFbo.Layer := Value; FFbo.Unbind; end; end; end; function TVXFBORenderer.GetLayer: Integer; begin Result := FFbo.Layer; end; procedure TVXFBORenderer.SetLevel(const Value: Integer); var w, h: Integer; begin if Value <> FFbo.Level then begin if FRendering or (ocStructure in Changes) then begin FFbo.Level := Value; w := Width; h := Height; if FFbo.Level > 0 then begin w := w shr FFbo.Level; h := h shr FFbo.Level; if w = 0 then w := 1; if h = 0 then h := 1; CurrentVXContext.VXStates.Viewport := Vector4iMake(0, 0, w, h); end; end else begin FFbo.Bind; FFbo.Level := Value; FFbo.Unbind; end; end; end; function TVXFBORenderer.GetLevel: Integer; begin Result := FFbo.Level; end; //------------------------------------------------------------------- initialization //------------------------------------------------------------------- RegisterClasses([TVXFBORenderer]); end.
{ ---------------------------------------------------------------- File - PRINT_STRUCT.PAS Copyright (c) 2003 Jungo Ltd. http://www.jungo.com ---------------------------------------------------------------- } unit Print_Struct; interface uses Windows, SysUtils, windrvr; function StringToInt (str : STRING) : INTEGER; function HexToInt(hex : STRING) : INTEGER; procedure WD_CARD_print(pCard : PWD_CARD; pcPrefix : PCHAR); implementation function StringToInt(str : STRING) : INTEGER; var i : INTEGER; res : INTEGER; begin res := 0; for i:=1 to Length(str) do if (str[i]>='0') and (str[i]<='9') then res := res * 10 + Ord(str[i]) - Ord('0') else begin Writeln('Illegal number value'); StringToInt := 0; Exit; end; StringToInt := res; end; function HexToInt(hex : STRING) : INTEGER; var i : INTEGER; res : INTEGER; begin hex := UpperCase(hex); res := 0; for i:=1 to Length(hex) do begin if (hex[i]>='0') and (hex[i]<='9') then res := res * 16 + Ord(hex[i]) - Ord('0') else if (hex[i]>='A') and (hex[i]<='F') then res := res * 16 + Ord(hex[i]) - Ord('A') + 10 else begin Writeln('Illegal Hex value'); HexToInt := 0; Exit; end; end; HexToInt := res; end; procedure WD_CARD_print(pCard : PWD_CARD; pcPrefix : PCHAR); var i : DWORD; item : WD_ITEMS; begin for i:=1 to pCard^.dwItems do begin item := pCard^.Item[i-1]; Write(STRING(pcPrefix), 'Item '); case item.item of ITEM_MEMORY: Write('Memory: range ', IntToHex(item.Memory.dwPhysicalAddr, 8), '-', IntToHex(item.Memory.dwPhysicalAddr+item.Memory.dwMBytes-1, 8)); ITEM_IO: Write('IO: range $', IntToHex(item.IO.dwAddr, 4), '-$', IntToHex(item.IO.dwAddr+item.IO.dwBytes-1, 4)); ITEM_INTERRUPT: Write('Interrupt: irq ', item.Interrupt.dwInterrupt); ITEM_BUS: Write('Bus: type ', item.Bus.dwBusType, ' bus number ', item.Bus.dwBusNum, ' slot/func $', IntToHex(item.Bus.dwSlotFunc, 1)); else Write('Invalid item type'); end; Writeln(''); end; end; end.
unit ideSHEditorOptions; interface uses Windows, SysUtils, Classes, Graphics, StdCtrls, DesignIntf, TypInfo, SHDesignIntf, SHOptionsIntf; type // E D I T O R G E N E R A L ===============================================> TSHEditorOptions = class; TSHEditorGeneralOptions = class(TSHComponentOptions, ISHEditorGeneralOptions) private FHideSelection: Boolean; FInsertCaret: TSHEditorCaretType; FInsertMode: Boolean; FMaxLineWidth: Integer; FMaxUndo: Integer; FOpenLink: TSHEditorLinkOption; FOptions: TSHEditorOptions; FOverwriteCaret: TSHEditorCaretType; FScrollHintFormat: TSHEditorScrollHintFormat; FScrollBars: TScrollStyle; FSelectionMode: TSHEditorSelectionMode; FTabWidth: Integer; FUseHighlight: Boolean; FWantReturns: Boolean; FWantTabs: Boolean; FWordWrap: Boolean; { Invisible } FOpenedFilesHistory: TStrings; FFindTextHistory: TStrings; FReplaceTextHistory: TStrings; FLineNumberHistory: TStrings; FDemoLines: TStrings; FPromtOnReplace: Boolean; // -> ISHEditorGeneralOptions function GetHideSelection: Boolean; procedure SetHideSelection(Value: Boolean); function GetUseHighlight: Boolean; procedure SetUseHighlight(Value: Boolean); function GetInsertCaret: TSHEditorCaretType; procedure SetInsertCaret(Value: TSHEditorCaretType); function GetInsertMode: Boolean; procedure SetInsertMode(Value: Boolean); function GetMaxLineWidth: Integer; procedure SetMaxLineWidth(Value: Integer); function GetMaxUndo: Integer; procedure SetMaxUndo(Value: Integer); function GetOpenLink: TSHEditorLinkOption; procedure SetOpenLink(Value: TSHEditorLinkOption); function GetOptions: ISHEditorOptions; function GetOverwriteCaret: TSHEditorCaretType; procedure SetOverwriteCaret(Value: TSHEditorCaretType); function GetScrollHintFormat: TSHEditorScrollHintFormat; procedure SetScrollHintFormat(Value: TSHEditorScrollHintFormat); function GetScrollBars: TScrollStyle; procedure SetScrollBars(Value: TScrollStyle); function GetSelectionMode: TSHEditorSelectionMode; procedure SetSelectionMode(Value: TSHEditorSelectionMode); function GetTabWidth: Integer; procedure SetTabWidth(Value: Integer); function GetWantReturns: Boolean; procedure SetWantReturns(Value: Boolean); function GetWantTabs: Boolean; procedure SetWantTabs(Value: Boolean); function GetWordWrap: Boolean; procedure SetWordWrap(Value: Boolean); function GetOpenedFilesHistory: TStrings; function GetFindTextHistory: TStrings; function GetReplaceTextHistory: TStrings; function GetLineNumberHistory: TStrings; function GetDemoLines: TStrings; function GetPromtOnReplace: Boolean; procedure SetPromtOnReplace(Value: Boolean); protected function GetCategory: string; override; procedure RestoreDefaults; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property HideSelection: Boolean read FHideSelection write FHideSelection; property InsertCaret: TSHEditorCaretType read FInsertCaret write FInsertCaret; property InsertMode: Boolean read FInsertMode write FInsertMode; property MaxLineWidth: Integer read FMaxLineWidth write FMaxLineWidth; property MaxUndo: Integer read FMaxUndo write FMaxUndo; property OpenLink: TSHEditorLinkOption read FOpenLink write FOpenLink; property Options: TSHEditorOptions read FOptions write FOptions; property OverwriteCaret: TSHEditorCaretType read FOverwriteCaret write FOverwriteCaret; property ScrollHintFormat: TSHEditorScrollHintFormat read FScrollHintFormat write FScrollHintFormat; property ScrollBars: TScrollStyle read FScrollBars write FScrollBars; property SelectionMode: TSHEditorSelectionMode read FSelectionMode write FSelectionMode; property TabWidth: Integer read FTabWidth write FTabWidth; property UseHighlight: Boolean read FUseHighlight write FUseHighlight; property WantReturns: Boolean read FWantReturns write FWantReturns; property WantTabs: Boolean read FWantTabs write FWantTabs; property WordWrap: Boolean read FWordWrap write FWordWrap; { Invisible } property OpenedFilesHistory: TStrings read FOpenedFilesHistory write FOpenedFilesHistory; property FindTextHistory: TStrings read FFindTextHistory write FFindTextHistory; property ReplaceTextHistory: TStrings read FReplaceTextHistory write FReplaceTextHistory; property LineNumberHistory: TStrings read FLineNumberHistory write FLineNumberHistory; property DemoLines: TStrings read FDemoLines write FDemoLines; property PromtOnReplace: Boolean read FPromtOnReplace write FPromtOnReplace; end; TSHEditorOptions = class(TSHInterfacedPersistent, ISHEditorOptions) private FAltSetsColumnMode: Boolean; FAutoIndent: Boolean; FAutoSizeMaxLeftChar: Boolean; FDisableScrollArrows: Boolean; FDragDropEditing: Boolean; FEnhanceHomeKey: Boolean; FGroupUndo: Boolean; FHalfPageScroll: Boolean; FHideShowScrollbars: Boolean; FKeepCaretX: Boolean; FNoCaret: Boolean; FNoSelection: Boolean; FScrollByOneLess: Boolean; FScrollHintFollows: Boolean; FScrollPastEof: Boolean; FScrollPastEol: Boolean; FShowScrollHint: Boolean; FSmartTabDelete: Boolean; FSmartTabs: Boolean; FTabIndent: Boolean; FTabsToSpaces: Boolean; FTrimTrailingSpaces: Boolean; // -> ISHEditorOptions function GetAltSetsColumnMode: Boolean; procedure SetAltSetsColumnMode(Value: Boolean); function GetAutoIndent: Boolean; procedure SetAutoIndent(Value: Boolean); function GetAutoSizeMaxLeftChar: Boolean; procedure SetAutoSizeMaxLeftChar(Value: Boolean); function GetDisableScrollArrows: Boolean; procedure SetDisableScrollArrows(Value: Boolean); function GetDragDropEditing: Boolean; procedure SetDragDropEditing(Value: Boolean); function GetEnhanceHomeKey: Boolean; procedure SetEnhanceHomeKey(Value: Boolean); function GetGroupUndo: Boolean; procedure SetGroupUndo(Value: Boolean); function GetHalfPageScroll: Boolean; procedure SetHalfPageScroll(Value: Boolean); function GetHideShowScrollbars: Boolean; procedure SetHideShowScrollbars(Value: Boolean); function GetKeepCaretX: Boolean; procedure SetKeepCaretX(Value: Boolean); function GetNoCaret: Boolean; procedure SetNoCaret(Value: Boolean); function GetNoSelection: Boolean; procedure SetNoSelection(Value: Boolean); function GetScrollByOneLess: Boolean; procedure SetScrollByOneLess(Value: Boolean); function GetScrollHintFollows: Boolean; procedure SetScrollHintFollows(Value: Boolean); function GetScrollPastEof: Boolean; procedure SetScrollPastEof(Value: Boolean); function GetScrollPastEol: Boolean; procedure SetScrollPastEol(Value: Boolean); function GetShowScrollHint: Boolean; procedure SetShowScrollHint(Value: Boolean); function GetSmartTabDelete: Boolean; procedure SetSmartTabDelete(Value: Boolean); function GetSmartTabs: Boolean; procedure SetSmartTabs(Value: Boolean); function GetTabIndent: Boolean; procedure SetTabIndent(Value: Boolean); function GetTabsToSpaces: Boolean; procedure SetTabsToSpaces(Value: Boolean); function GetTrimTrailingSpaces: Boolean; procedure SetTrimTrailingSpaces(Value: Boolean); published property AltSetsColumnMode: Boolean read FAltSetsColumnMode write FAltSetsColumnMode; property AutoIndent: Boolean read FAutoIndent write FAutoIndent; property AutoSizeMaxLeftChar: Boolean read FAutoSizeMaxLeftChar write FAutoSizeMaxLeftChar; property DisableScrollArrows: Boolean read FDisableScrollArrows write FDisableScrollArrows; property DragDropEditing: Boolean read FDragDropEditing write FDragDropEditing; property EnhanceHomeKey: Boolean read FEnhanceHomeKey write FEnhanceHomeKey; property GroupUndo: Boolean read FGroupUndo write FGroupUndo; property HalfPageScroll: Boolean read FHalfPageScroll write FHalfPageScroll; property HideShowScrollbars: Boolean read FHideShowScrollbars write FHideShowScrollbars; property KeepCaretX: Boolean read FKeepCaretX write FKeepCaretX; property NoCaret: Boolean read FNoCaret write FNoCaret; property NoSelection: Boolean read FNoSelection write FNoSelection; property ScrollByOneLess: Boolean read FScrollByOneLess write FScrollByOneLess; property ScrollHintFollows: Boolean read FScrollHintFollows write FScrollHintFollows; property ScrollPastEof: Boolean read FScrollPastEof write FScrollPastEof; property ScrollPastEol: Boolean read FScrollPastEol write FScrollPastEol; property ShowScrollHint: Boolean read FShowScrollHint write FShowScrollHint; property SmartTabDelete: Boolean read FSmartTabDelete write FSmartTabDelete; property SmartTabs: Boolean read FSmartTabs write FSmartTabs; property TabIndent: Boolean read FTabIndent write FTabIndent; property TabsToSpaces: Boolean read FTabsToSpaces write FTabsToSpaces; property TrimTrailingSpaces: Boolean read FTrimTrailingSpaces write FTrimTrailingSpaces; end; // E D I T O R D I S P L A Y ===============================================> TSHEditorGutter = class; TSHEditorMargin = class; TSHEditorDisplayOptions = class(TSHComponentOptions, ISHEditorDisplayOptions) private FFont: TFont; FGutter: TSHEditorGutter; FMargin: TSHEditorMargin; procedure SetFont(Value: TFont); // -> ISHEditorDisplayOptions function GetFont: TFont; //procedure SetFont(Value: TFont); function GetGutter: ISHEditorGutter; function GetMargin: ISHEditorMargin; protected function GetParentCategory: string; override; function GetCategory: string; override; procedure RestoreDefaults; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Font: TFont read FFont write SetFont; property Gutter: TSHEditorGutter read FGutter write FGutter; property Margin: TSHEditorMargin read FMargin write FMargin; end; TSHEditorGutter = class(TSHInterfacedPersistent, ISHEditorGutter) private FAutoSize: Boolean; FDigitCount: Integer; FFont: TFont; FLeadingZeros: Boolean; FLeftOffset: Integer; FRightOffset: Integer; FShowLineNumbers: Boolean; FUseFontStyle: Boolean; FVisible: Boolean; FWidth: Integer; FZeroStart: Boolean; procedure SetFont(Value: TFont); // -> ISHEditorGutter function GetAutoSize: Boolean; procedure SetAutoSize(Value: Boolean); function GetDigitCount: Integer; procedure SetDigitCount(Value: Integer); function GetFont: TFont; //procedure SetFont(Value: TFont); function GetLeadingZeros: Boolean; procedure SetLeadingZeros(Value: Boolean); function GetLeftOffset: Integer; procedure SetLeftOffset(Value: Integer); function GetRightOffset: Integer; procedure SetRightOffset(Value: Integer); function GetShowLineNumbers: Boolean; procedure SetShowLineNumbers(Value: Boolean); function GetUseFontStyle: Boolean; procedure SetUseFontStyle(Value: Boolean); function GetVisible: Boolean; procedure SetVisible(Value: Boolean); function GetWidth: Integer; procedure SetWidth(Value: Integer); function GetZeroStart: Boolean; procedure SetZeroStart(Value: Boolean); public constructor Create; destructor Destroy; override; published property AutoSize: Boolean read FAutoSize write FAutoSize; property DigitCount: Integer read FDigitCount write FDigitCount; property Font: TFont read FFont write SetFont; property LeadingZeros: Boolean read FLeadingZeros write FLeadingZeros; property LeftOffset: Integer read FLeftOffset write FLeftOffset; property RightOffset: Integer read FRightOffset write FRightOffset; property ShowLineNumbers: Boolean read FShowLineNumbers write FShowLineNumbers; property UseFontStyle: Boolean read FUseFontStyle write FUseFontStyle; property Visible: Boolean read FVisible write FVisible; property Width: Integer read FWidth write FWidth; property ZeroStart: Boolean read FZeroStart write FZeroStart; end; TSHEditorMargin = class(TSHInterfacedPersistent, ISHEditorMargin) private FRightEdgeVisible: Boolean; FRightEdgeWidth: Integer; FBottomEdgeVisible: Boolean; // -> ISHEditorMargin function GetRightEdgeVisible: Boolean; procedure SetRightEdgeVisible(Value: Boolean); function GetRightEdgeWidth: Integer; procedure SetRightEdgeWidth(Value: Integer); function GetBottomEdgeVisible: Boolean; procedure SetBottomEdgeVisible(Value: Boolean); published property RightEdgeVisible: Boolean read FRightEdgeVisible write FRightEdgeVisible; property RightEdgeWidth: Integer read FRightEdgeWidth write FRightEdgeWidth; property BottomEdgeVisible: Boolean read FBottomEdgeVisible write FBottomEdgeVisible; end; // E D I T O R C O L O R ===================================================> TSHEditorColor = class; TSHEditorColorAttr = class; TSHEditorColorOptions = class(TSHComponentOptions, ISHEditorColorOptions) private FBackground: TColor; FGutter: TColor; FRightEdge: TColor; FBottomEdge: TColor; FCurrentLine: TColor; FErrorLine: TColor; FScrollHint: TColor; FSelected: TSHEditorColor; FCommentAttr: TSHEditorColorAttr; FCustomStringAttr: TSHEditorColorAttr; FDataTypeAttr: TSHEditorColorAttr; FIdentifierAttr: TSHEditorColorAttr; FFunctionAttr: TSHEditorColorAttr; FLinkAttr: TSHEditorColorAttr; FNumberAttr: TSHEditorColorAttr; FSQLKeywordAttr: TSHEditorColorAttr; FStringAttr: TSHEditorColorAttr; FStringDblQuotedAttr: TSHEditorColorAttr; FSymbolAttr: TSHEditorColorAttr; FVariableAttr: TSHEditorColorAttr; FWrongSymbolAttr: TSHEditorColorAttr; // -> ISHEditorColorOptions function GetBackground: TColor; procedure SetBackground(Value: TColor); function GetGutter: TColor; procedure SetGutter(Value: TColor); function GetRightEdge: TColor; procedure SetRightEdge(Value: TColor); function GetBottomEdge: TColor; procedure SetBottomEdge(Value: TColor); function GetCurrentLine: TColor; procedure SetCurrentLine(Value: TColor); function GetErrorLine: TColor; procedure SetErrorLine(Value: TColor); function GetScrollHint: TColor; procedure SetScrollHint(Value: TColor); function GetSelected: ISHEditorColor; function GetCommentAttr: ISHEditorColorAttr; function GetCustomStringAttr: ISHEditorColorAttr; function GetDataTypeAttr: ISHEditorColorAttr; function GetIdentifierAttr: ISHEditorColorAttr; function GetFunctionAttr: ISHEditorColorAttr; function GetLinkAttr: ISHEditorColorAttr; function GetNumberAttr: ISHEditorColorAttr; function GetSQLKeywordAttr: ISHEditorColorAttr; function GetStringAttr: ISHEditorColorAttr; function GetStringDblQuotedAttr: ISHEditorColorAttr; function GetSymbolAttr: ISHEditorColorAttr; function GetVariableAttr: ISHEditorColorAttr; function GetWrongSymbolAttr: ISHEditorColorAttr; protected function GetParentCategory: string; override; function GetCategory: string; override; procedure RestoreDefaults; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Background: TColor read FBackground write FBackground; property Gutter: TColor read FGutter write FGutter; property RightEdge: TColor read FRightEdge write FRightEdge; property BottomEdge: TColor read FBottomEdge write FBottomEdge; property CurrentLine: TColor read FCurrentLine write FCurrentLine; property ErrorLine: TColor read FErrorLine write FErrorLine; property ScrollHint: TColor read FScrollHint write FScrollHint; property Selected: TSHEditorColor read FSelected write FSelected; property CommentAttr: TSHEditorColorAttr read FCommentAttr write FCommentAttr; property CustomStringAttr: TSHEditorColorAttr read FCustomStringAttr write FCustomStringAttr; property DataTypeAttr: TSHEditorColorAttr read FDataTypeAttr write FDataTypeAttr; property IdentifierAttr: TSHEditorColorAttr read FIdentifierAttr write FIdentifierAttr; property FunctionAttr: TSHEditorColorAttr read FFunctionAttr write FFunctionAttr; property LinkAttr: TSHEditorColorAttr read FLinkAttr write FLinkAttr; property NumberAttr: TSHEditorColorAttr read FNumberAttr write FNumberAttr; property SQLKeywordAttr: TSHEditorColorAttr read FSQLKeywordAttr write FSQLKeywordAttr; property StringAttr: TSHEditorColorAttr read FStringAttr write FStringAttr; property StringDblQuotedAttr: TSHEditorColorAttr read FStringDblQuotedAttr write FStringDblQuotedAttr; property SymbolAttr: TSHEditorColorAttr read FSymbolAttr write FSymbolAttr; property VariableAttr: TSHEditorColorAttr read FVariableAttr write FVariableAttr; property WrongSymbolAttr: TSHEditorColorAttr read FWrongSymbolAttr write FWrongSymbolAttr; end; TSHEditorColor = class(TSHInterfacedPersistent, ISHEditorColor) private FForeground: TColor; FBackground: TColor; protected // -> ISHEditorColor function GetForeground: TColor; procedure SetForeground(Value: TColor); function GetBackground: TColor; procedure SetBackground(Value: TColor); published property Foreground: TColor read FForeground write FForeground; property Background: TColor read FBackground write FBackground; end; TSHEditorColorAttr = class(TSHEditorColor, ISHEditorColorAttr) private FStyle: TFontStyles; // -> ISHEditorColorAttr function GetStyle: TFontStyles; procedure SetStyle(Value: TFontStyles); published property Style: TFontStyles read FStyle write FStyle; end; // E D I T O R C O D E I N S I G H T =======================================> TSHEditorCodeInsightOptions = class(TSHComponentOptions, ISHEditorCodeInsightOptions, IEditorCodeInsightOptionsExt ) private FCodeCompletion: Boolean; FCodeParameters: Boolean; FCaseCode: TSHEditorCaseCode; FCaseSQLKeywords: TSHEditorCaseCode; FCustomStrings: TStrings; FDelay: Integer; { Invisible } FWindowLineCount: Integer; FWindowWidth: Integer; //Buzz FShowBeginEndRegions:boolean; // -> ISHEditorCodeInsightOptions function GetCodeCompletion: Boolean; procedure SetCodeCompletion(Value: Boolean); function GetCodeParameters: Boolean; procedure SetCodeParameters(Value: Boolean); function GetCaseCode: TSHEditorCaseCode; procedure SetCaseCode(Value: TSHEditorCaseCode); function GetCaseSQLKeywords: TSHEditorCaseCode; procedure SetCaseSQLKeywords(Value: TSHEditorCaseCode); function GetCustomStrings: TStrings; function GetDelay: Integer; procedure SetDelay(Value: Integer); function GetWindowLineCount: Integer; procedure SetWindowLineCount(Value: Integer); function GetWindowWidth: Integer; procedure SetWindowWidth(Value: Integer); procedure SetCustomStrings(const Value: TStrings); function GetShowBeginEndRegions:boolean; procedure SetShowBeginEndRegions(const Value:boolean); protected function GetParentCategory: string; override; function GetCategory: string; override; procedure RestoreDefaults; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property CodeCompletion: Boolean read FCodeCompletion write FCodeCompletion; property CodeParameters: Boolean read FCodeParameters write FCodeParameters; property CaseCode: TSHEditorCaseCode read FCaseCode write FCaseCode; property CaseSQLKeywords: TSHEditorCaseCode read FCaseSQLKeywords write FCaseSQLKeywords; property CustomStrings: TStrings read FCustomStrings write SetCustomStrings; property Delay: Integer read FDelay write FDelay; property ShowBeginEndRegions:boolean read FShowBeginEndRegions write FShowBeginEndRegions default True; { Invisible } property WindowLineCount: Integer read FWindowLineCount write FWindowLineCount; property WindowWidth: Integer read FWindowWidth write FWindowWidth ; end; procedure Register; implementation procedure Register; begin SHRegisterComponents([ TSHEditorGeneralOptions, TSHEditorDisplayOptions, TSHEditorColorOptions, TSHEditorCodeInsightOptions]); end; { TSHEditorGeneralOptions } constructor TSHEditorGeneralOptions.Create(AOwner: TComponent); begin FOptions := TSHEditorOptions.Create; { Invisible } FOpenedFilesHistory := TStringList.Create; FFindTextHistory := TStringList.Create; FReplaceTextHistory := TStringList.Create; FLineNumberHistory := TStringList.Create; FDemoLines := TStringList.Create; inherited Create(AOwner); // Expanded := False; MakePropertyInvisible('OpenedFilesHistory'); MakePropertyInvisible('FindTextHistory'); MakePropertyInvisible('ReplaceTextHistory'); MakePropertyInvisible('LineNumberHistory'); MakePropertyInvisible('DemoLines'); MakePropertyInvisible('PromtOnReplace'); end; destructor TSHEditorGeneralOptions.Destroy; begin FOptions.Free; { Invisible } FOpenedFilesHistory.Free; FFindTextHistory.Free; FReplaceTextHistory.Free; FLineNumberHistory.Free; FDemoLines.Free; inherited Destroy; end; function TSHEditorGeneralOptions.GetCategory: string; begin Result := Format('%s', ['Editor']); end; procedure TSHEditorGeneralOptions.RestoreDefaults; begin HideSelection := False; InsertCaret := VerticalLine; InsertMode := True; MaxLineWidth := 1000; MaxUndo := 50; OpenLink := DblClick; Options.AltSetsColumnMode := False; Options.AutoIndent := True; Options.AutoSizeMaxLeftChar := False; Options.DisableScrollArrows := False; Options.DragDropEditing := True; Options.EnhanceHomeKey := False; Options.GroupUndo := True; Options.HalfPageScroll := False; Options.HideShowScrollbars := False; Options.KeepCaretX := False; Options.NoCaret := False; Options.NoSelection := False; Options.ScrollByOneLess := False; Options.ScrollHintFollows := False; Options.ScrollPastEof := False; Options.ScrollPastEol := True; Options.ShowScrollHint := False; Options.SmartTabDelete := False; Options.SmartTabs := False; Options.TabIndent := False; Options.TabsToSpaces := True; Options.TrimTrailingSpaces := True; OverwriteCaret := Block; ScrollHintFormat := TopLineOnly; ScrollBars := ssBoth; SelectionMode := Normal; TabWidth := 2; UseHighlight := True; WantReturns := True; WantTabs := True; end; function TSHEditorGeneralOptions.GetHideSelection: Boolean; begin Result := HideSelection; end; procedure TSHEditorGeneralOptions.SetHideSelection(Value: Boolean); begin HideSelection := Value; end; function TSHEditorGeneralOptions.GetUseHighlight: Boolean; begin Result := UseHighlight; end; procedure TSHEditorGeneralOptions.SetUseHighlight(Value: Boolean); begin UseHighlight := Value; end; function TSHEditorGeneralOptions.GetInsertCaret: TSHEditorCaretType; begin Result := InsertCaret; end; procedure TSHEditorGeneralOptions.SetInsertCaret(Value: TSHEditorCaretType); begin InsertCaret := Value; end; function TSHEditorGeneralOptions.GetInsertMode: Boolean; begin Result := InsertMode; end; procedure TSHEditorGeneralOptions.SetInsertMode(Value: Boolean); begin InsertMode := Value; end; function TSHEditorGeneralOptions.GetMaxLineWidth: Integer; begin Result := MaxLineWidth; end; procedure TSHEditorGeneralOptions.SetMaxLineWidth(Value: Integer); begin MaxLineWidth := Value; end; function TSHEditorGeneralOptions.GetMaxUndo: Integer; begin Result := MaxUndo; end; procedure TSHEditorGeneralOptions.SetMaxUndo(Value: Integer); begin MaxUndo := Value; end; function TSHEditorGeneralOptions.GetOpenLink: TSHEditorLinkOption; begin Result := OpenLink; end; procedure TSHEditorGeneralOptions.SetOpenLink(Value: TSHEditorLinkOption); begin OpenLink := Value; end; function TSHEditorGeneralOptions.GetOptions: ISHEditorOptions; begin Supports(Options, ISHEditorOptions, Result); end; function TSHEditorGeneralOptions.GetOverwriteCaret: TSHEditorCaretType; begin Result := OverwriteCaret; end; procedure TSHEditorGeneralOptions.SetOverwriteCaret(Value: TSHEditorCaretType); begin OverwriteCaret := Value; end; function TSHEditorGeneralOptions.GetScrollHintFormat: TSHEditorScrollHintFormat; begin Result := ScrollHintFormat; end; procedure TSHEditorGeneralOptions.SetScrollHintFormat(Value: TSHEditorScrollHintFormat); begin ScrollHintFormat := Value; end; function TSHEditorGeneralOptions.GetScrollBars: TScrollStyle; begin Result := ScrollBars; end; procedure TSHEditorGeneralOptions.SetScrollBars(Value: TScrollStyle); begin ScrollBars := Value; end; function TSHEditorGeneralOptions.GetSelectionMode: TSHEditorSelectionMode; begin Result := SelectionMode; end; procedure TSHEditorGeneralOptions.SetSelectionMode(Value: TSHEditorSelectionMode); begin SelectionMode := Value; end; function TSHEditorGeneralOptions.GetTabWidth: Integer; begin Result := TabWidth; end; procedure TSHEditorGeneralOptions.SetTabWidth(Value: Integer); begin TabWidth := Value; end; function TSHEditorGeneralOptions.GetWantReturns: Boolean; begin Result := WantReturns; end; procedure TSHEditorGeneralOptions.SetWantReturns(Value: Boolean); begin WantReturns := Value; end; function TSHEditorGeneralOptions.GetWantTabs: Boolean; begin Result := WantTabs; end; procedure TSHEditorGeneralOptions.SetWantTabs(Value: Boolean); begin WantTabs := Value; end; function TSHEditorGeneralOptions.GetWordWrap: Boolean; begin Result := WordWrap; end; procedure TSHEditorGeneralOptions.SetWordWrap(Value: Boolean); begin WordWrap := Value; end; function TSHEditorGeneralOptions.GetOpenedFilesHistory: TStrings; begin Result := OpenedFilesHistory; end; function TSHEditorGeneralOptions.GetFindTextHistory: TStrings; begin Result := FindTextHistory; end; function TSHEditorGeneralOptions.GetReplaceTextHistory: TStrings; begin Result := ReplaceTextHistory; end; function TSHEditorGeneralOptions.GetLineNumberHistory: TStrings; begin Result := LineNumberHistory; end; function TSHEditorGeneralOptions.GetDemoLines: TStrings; begin Result := DemoLines; end; function TSHEditorGeneralOptions.GetPromtOnReplace: Boolean; begin Result := PromtOnReplace; end; procedure TSHEditorGeneralOptions.SetPromtOnReplace(Value: Boolean); begin PromtOnReplace := Value; end; { TSHEditorOptions } function TSHEditorOptions.GetAltSetsColumnMode: Boolean; begin Result := AltSetsColumnMode; end; procedure TSHEditorOptions.SetAltSetsColumnMode(Value: Boolean); begin AltSetsColumnMode := Value; end; function TSHEditorOptions.GetAutoIndent: Boolean; begin Result := AutoIndent; end; procedure TSHEditorOptions.SetAutoIndent(Value: Boolean); begin AutoIndent := Value; end; function TSHEditorOptions.GetAutoSizeMaxLeftChar: Boolean; begin Result := AutoSizeMaxLeftChar; end; procedure TSHEditorOptions.SetAutoSizeMaxLeftChar(Value: Boolean); begin AutoSizeMaxLeftChar := Value; end; function TSHEditorOptions.GetDisableScrollArrows: Boolean; begin Result := DisableScrollArrows; end; procedure TSHEditorOptions.SetDisableScrollArrows(Value: Boolean); begin DisableScrollArrows := Value; end; function TSHEditorOptions.GetDragDropEditing: Boolean; begin Result := DragDropEditing; end; procedure TSHEditorOptions.SetDragDropEditing(Value: Boolean); begin DragDropEditing := Value; end; function TSHEditorOptions.GetEnhanceHomeKey: Boolean; begin Result := EnhanceHomeKey; end; procedure TSHEditorOptions.SetEnhanceHomeKey(Value: Boolean); begin EnhanceHomeKey := Value; end; function TSHEditorOptions.GetGroupUndo: Boolean; begin Result := GroupUndo; end; procedure TSHEditorOptions.SetGroupUndo(Value: Boolean); begin GroupUndo := Value; end; function TSHEditorOptions.GetHalfPageScroll: Boolean; begin Result := HalfPageScroll; end; procedure TSHEditorOptions.SetHalfPageScroll(Value: Boolean); begin HalfPageScroll := Value; end; function TSHEditorOptions.GetHideShowScrollbars: Boolean; begin Result := HideShowScrollbars; end; procedure TSHEditorOptions.SetHideShowScrollbars(Value: Boolean); begin HideShowScrollbars := Value; end; function TSHEditorOptions.GetKeepCaretX: Boolean; begin Result := KeepCaretX; end; procedure TSHEditorOptions.SetKeepCaretX(Value: Boolean); begin KeepCaretX := Value; end; function TSHEditorOptions.GetNoCaret: Boolean; begin Result := NoCaret; end; procedure TSHEditorOptions.SetNoCaret(Value: Boolean); begin NoCaret := Value; end; function TSHEditorOptions.GetNoSelection: Boolean; begin Result := NoSelection; end; procedure TSHEditorOptions.SetNoSelection(Value: Boolean); begin NoSelection := Value; end; function TSHEditorOptions.GetScrollByOneLess: Boolean; begin Result := ScrollByOneLess; end; procedure TSHEditorOptions.SetScrollByOneLess(Value: Boolean); begin ScrollByOneLess := Value; end; function TSHEditorOptions.GetScrollHintFollows: Boolean; begin Result := ScrollHintFollows; end; procedure TSHEditorOptions.SetScrollHintFollows(Value: Boolean); begin ScrollHintFollows := Value; end; function TSHEditorOptions.GetScrollPastEof: Boolean; begin Result := ScrollPastEof; end; procedure TSHEditorOptions.SetScrollPastEof(Value: Boolean); begin ScrollPastEof := Value; end; function TSHEditorOptions.GetScrollPastEol: Boolean; begin Result := ScrollPastEol; end; procedure TSHEditorOptions.SetScrollPastEol(Value: Boolean); begin ScrollPastEol := Value; end; function TSHEditorOptions.GetShowScrollHint: Boolean; begin Result := ShowScrollHint; end; procedure TSHEditorOptions.SetShowScrollHint(Value: Boolean); begin ShowScrollHint := Value; end; function TSHEditorOptions.GetSmartTabDelete: Boolean; begin Result := SmartTabDelete; end; procedure TSHEditorOptions.SetSmartTabDelete(Value: Boolean); begin SmartTabDelete := Value; end; function TSHEditorOptions.GetSmartTabs: Boolean; begin Result := SmartTabs; end; procedure TSHEditorOptions.SetSmartTabs(Value: Boolean); begin SmartTabs := Value; end; function TSHEditorOptions.GetTabIndent: Boolean; begin Result := TabIndent; end; procedure TSHEditorOptions.SetTabIndent(Value: Boolean); begin TabIndent := Value; end; function TSHEditorOptions.GetTabsToSpaces: Boolean; begin Result := TabsToSpaces; end; procedure TSHEditorOptions.SetTabsToSpaces(Value: Boolean); begin TabsToSpaces := Value; end; function TSHEditorOptions.GetTrimTrailingSpaces: Boolean; begin Result := TrimTrailingSpaces; end; procedure TSHEditorOptions.SetTrimTrailingSpaces(Value: Boolean); begin TrimTrailingSpaces := Value; end; { TSHEditorDisplayOptions } constructor TSHEditorDisplayOptions.Create(AOwner: TComponent); begin FFont := TFont.Create; FGutter := TSHEditorGutter.Create; FMargin := TSHEditorMargin.Create; inherited Create(AOwner); end; destructor TSHEditorDisplayOptions.Destroy; begin FFont.Free; FGutter.Free; FMargin.Free; inherited Destroy; end; function TSHEditorDisplayOptions.GetParentCategory: string; begin Result := Format('%s', ['Editor']); end; function TSHEditorDisplayOptions.GetCategory: string; begin Result := Format('%s', ['Display']); end; procedure TSHEditorDisplayOptions.RestoreDefaults; begin Font.Charset := 1; Font.Color := clWindowText; Font.Height := -13; Font.Name := 'Courier New'; Font.Pitch := fpDefault; Font.Size := 10; Font.Style := []; Gutter.AutoSize := False; Gutter.DigitCount := 4; Gutter.Font.Charset := 1; Gutter.Font.Color := clWindowText; Gutter.Font.Height := -11; Gutter.Font.Name := 'Tahoma'; Gutter.Font.Pitch := fpDefault; Gutter.Font.Size := 8; Gutter.Font.Style := []; Gutter.LeadingZeros := False; Gutter.LeftOffset := 16; Gutter.RightOffset := 2; Gutter.ShowLineNumbers := False; Gutter.UseFontStyle := True; Gutter.Visible := True; Gutter.Width := 30; Gutter.ZeroStart := False; Margin.BottomEdgeVisible := True; Margin.RightEdgeVisible := True; Margin.RightEdgeWidth := 80; end; procedure TSHEditorDisplayOptions.SetFont(Value: TFont); begin FFont.Assign(Value); end; function TSHEditorDisplayOptions.GetFont: TFont; begin Result := Font; end; //procedure SetFont(Value: TFont); function TSHEditorDisplayOptions.GetGutter: ISHEditorGutter; begin Supports(Gutter, ISHEditorGutter, Result); end; function TSHEditorDisplayOptions.GetMargin: ISHEditorMargin; begin Supports(Margin, ISHEditorMargin, Result); end; { TSHEditorGutter } constructor TSHEditorGutter.Create; begin inherited Create; FFont := TFont.Create; end; destructor TSHEditorGutter.Destroy; begin FFont.Free; inherited Destroy; end; procedure TSHEditorGutter.SetFont(Value: TFont); begin FFont.Assign(Value); end; function TSHEditorGutter.GetAutoSize: Boolean; begin Result := AutoSize; end; procedure TSHEditorGutter.SetAutoSize(Value: Boolean); begin AutoSize := Value; end; function TSHEditorGutter.GetDigitCount: Integer; begin Result := DigitCount; end; procedure TSHEditorGutter.SetDigitCount(Value: Integer); begin DigitCount := Value; end; function TSHEditorGutter.GetFont: TFont; begin Result := Font; end; //procedure SetFont(Value: TFont); function TSHEditorGutter.GetLeadingZeros: Boolean; begin Result := LeadingZeros; end; procedure TSHEditorGutter.SetLeadingZeros(Value: Boolean); begin LeadingZeros := Value; end; function TSHEditorGutter.GetLeftOffset: Integer; begin Result := LeftOffset; end; procedure TSHEditorGutter.SetLeftOffset(Value: Integer); begin LeftOffset := Value; end; function TSHEditorGutter.GetRightOffset: Integer; begin Result := RightOffset; end; procedure TSHEditorGutter.SetRightOffset(Value: Integer); begin RightOffset := Value; end; function TSHEditorGutter.GetShowLineNumbers: Boolean; begin Result := ShowLineNumbers; end; procedure TSHEditorGutter.SetShowLineNumbers(Value: Boolean); begin ShowLineNumbers := Value; end; function TSHEditorGutter.GetUseFontStyle: Boolean; begin Result := UseFontStyle; end; procedure TSHEditorGutter.SetUseFontStyle(Value: Boolean); begin UseFontStyle := Value; end; function TSHEditorGutter.GetVisible: Boolean; begin Result := Visible; end; procedure TSHEditorGutter.SetVisible(Value: Boolean); begin Visible := Value; end; function TSHEditorGutter.GetWidth: Integer; begin Result := Width; end; procedure TSHEditorGutter.SetWidth(Value: Integer); begin Width := Value; end; function TSHEditorGutter.GetZeroStart: Boolean; begin Result := ZeroStart; end; procedure TSHEditorGutter.SetZeroStart(Value: Boolean); begin ZeroStart := Value; end; { TSHEditorMargin } function TSHEditorMargin.GetRightEdgeVisible: Boolean; begin Result := RightEdgeVisible; end; procedure TSHEditorMargin.SetRightEdgeVisible(Value: Boolean); begin RightEdgeVisible := Value; end; function TSHEditorMargin.GetRightEdgeWidth: Integer; begin Result := RightEdgeWidth; end; procedure TSHEditorMargin.SetRightEdgeWidth(Value: Integer); begin RightEdgeWidth := Value; end; function TSHEditorMargin.GetBottomEdgeVisible: Boolean; begin Result := BottomEdgeVisible; end; procedure TSHEditorMargin.SetBottomEdgeVisible(Value: Boolean); begin BottomEdgeVisible := Value; end; { TSHEditorColorOptions } constructor TSHEditorColorOptions.Create(AOwner: TComponent); begin FSelected := TSHEditorColor.Create; FCommentAttr := TSHEditorColorAttr.Create; FCustomStringAttr := TSHEditorColorAttr.Create; FDataTypeAttr := TSHEditorColorAttr.Create; FIdentifierAttr := TSHEditorColorAttr.Create; FFunctionAttr := TSHEditorColorAttr.Create; FLinkAttr := TSHEditorColorAttr.Create; FNumberAttr := TSHEditorColorAttr.Create; FSQLKeywordAttr := TSHEditorColorAttr.Create; FStringAttr := TSHEditorColorAttr.Create; FStringDblQuotedAttr := TSHEditorColorAttr.Create; FSymbolAttr := TSHEditorColorAttr.Create; FVariableAttr := TSHEditorColorAttr.Create; FWrongSymbolAttr := TSHEditorColorAttr.Create; inherited Create(AOwner); end; destructor TSHEditorColorOptions.Destroy; begin FSelected.Free; FCommentAttr.Free; FCustomStringAttr.Free; FDataTypeAttr.Free; FIdentifierAttr.Free; FFunctionAttr.Free; FLinkAttr.Free; FNumberAttr.Free; FSQLKeywordAttr.Free; FStringAttr.Free; FStringDblQuotedAttr.Free; FSymbolAttr.Free; FVariableAttr.Free; FWrongSymbolAttr.Free; inherited Destroy; end; function TSHEditorColorOptions.GetParentCategory: string; begin Result := Format('%s', ['Editor']); end; function TSHEditorColorOptions.GetCategory: string; begin Result := Format('%s', ['Color and Style']); end; procedure TSHEditorColorOptions.RestoreDefaults; begin Background := clWindow; Gutter := clBtnFace; RightEdge := clSilver; BottomEdge := clSilver; CurrentLine := RGB(250, 255, 230); //clNone; ErrorLine := clMaroon; ScrollHint := clInfoBk; Selected.Foreground := clHighLightText; Selected.Background := RGB(132, 145, 180); //clHighLight; CommentAttr.Foreground := clSilver; CommentAttr.Background := clNone; CommentAttr.Style := [fsBold]; CustomStringAttr.Foreground := clBtnFace; CustomStringAttr.Background := clNone; CustomStringAttr.Style := [fsBold]; DataTypeAttr.Foreground := clBlack; DataTypeAttr.Background := clNone; DataTypeAttr.Style := [fsBold]; IdentifierAttr.Foreground := clBlue; IdentifierAttr.Background := clNone; IdentifierAttr.Style := [fsBold]; FunctionAttr.Foreground := clBlack; FunctionAttr.Background := clNone; FunctionAttr.Style := [fsBold]; LinkAttr.Foreground := clGreen; LinkAttr.Background := clNone; LinkAttr.Style := [fsBold, fsUnderline]; NumberAttr.Foreground := clTeal; NumberAttr.Background := clNone; NumberAttr.Style := [fsBold]; SQLKeywordAttr.Foreground := clBlack; SQLKeywordAttr.Background := clNone; SQLKeywordAttr.Style := [fsBold]; StringAttr.Foreground := clPurple; StringAttr.Background := clNone; StringAttr.Style := [fsBold]; StringDblQuotedAttr.Foreground := clPurple; StringDblQuotedAttr.Background := clNone; StringDblQuotedAttr.Style := [fsBold]; SymbolAttr.Foreground := clBlack; SymbolAttr.Background := clNone; SymbolAttr.Style := [fsBold]; VariableAttr.Foreground := clBackground; VariableAttr.Background := clNone; VariableAttr.Style := [fsBold]; WrongSymbolAttr.Foreground := clYellow; WrongSymbolAttr.Background := clRed; WrongSymbolAttr.Style := [fsBold]; end; function TSHEditorColorOptions.GetBackground: TColor; begin Result := Background; end; procedure TSHEditorColorOptions.SetBackground(Value: TColor); begin Background := Value; end; function TSHEditorColorOptions.GetGutter: TColor; begin Result := Gutter; end; procedure TSHEditorColorOptions.SetGutter(Value: TColor); begin Gutter := Value; end; function TSHEditorColorOptions.GetRightEdge: TColor; begin Result := RightEdge; end; procedure TSHEditorColorOptions.SetRightEdge(Value: TColor); begin RightEdge := Value; end; function TSHEditorColorOptions.GetBottomEdge: TColor; begin Result := BottomEdge; end; procedure TSHEditorColorOptions.SetBottomEdge(Value: TColor); begin BottomEdge := Value; end; function TSHEditorColorOptions.GetCurrentLine: TColor; begin Result := CurrentLine; end; procedure TSHEditorColorOptions.SetCurrentLine(Value: TColor); begin CurrentLine := Value; end; function TSHEditorColorOptions.GetErrorLine: TColor; begin Result := ErrorLine; end; procedure TSHEditorColorOptions.SetErrorLine(Value: TColor); begin ErrorLine := Value; end; function TSHEditorColorOptions.GetScrollHint: TColor; begin Result := ScrollHint; end; procedure TSHEditorColorOptions.SetScrollHint(Value: TColor); begin ScrollHint := Value; end; function TSHEditorColorOptions.GetSelected: ISHEditorColor; begin Supports(Selected, ISHEditorColor, Result); end; function TSHEditorColorOptions.GetCommentAttr: ISHEditorColorAttr; begin Supports(CommentAttr, ISHEditorColorAttr, Result); end; function TSHEditorColorOptions.GetCustomStringAttr: ISHEditorColorAttr; begin Supports(CustomStringAttr, ISHEditorColorAttr, Result); end; function TSHEditorColorOptions.GetDataTypeAttr: ISHEditorColorAttr; begin Supports(DataTypeAttr, ISHEditorColorAttr, Result); end; function TSHEditorColorOptions.GetIdentifierAttr: ISHEditorColorAttr; begin Supports(IdentifierAttr, ISHEditorColorAttr, Result); end; function TSHEditorColorOptions.GetFunctionAttr: ISHEditorColorAttr; begin Supports(FunctionAttr, ISHEditorColorAttr, Result); end; function TSHEditorColorOptions.GetLinkAttr: ISHEditorColorAttr; begin Supports(LinkAttr, ISHEditorColorAttr, Result); end; function TSHEditorColorOptions.GetNumberAttr: ISHEditorColorAttr; begin Supports(NumberAttr, ISHEditorColorAttr, Result); end; function TSHEditorColorOptions.GetSQLKeywordAttr: ISHEditorColorAttr; begin Supports(SQLKeywordAttr, ISHEditorColorAttr, Result); end; function TSHEditorColorOptions.GetStringAttr: ISHEditorColorAttr; begin Supports(StringAttr, ISHEditorColorAttr, Result); end; function TSHEditorColorOptions.GetStringDblQuotedAttr: ISHEditorColorAttr; begin Supports(StringDblQuotedAttr, ISHEditorColorAttr, Result); end; function TSHEditorColorOptions.GetSymbolAttr: ISHEditorColorAttr; begin Supports(SymbolAttr, ISHEditorColorAttr, Result); end; function TSHEditorColorOptions.GetVariableAttr: ISHEditorColorAttr; begin Supports(VariableAttr, ISHEditorColorAttr, Result); end; function TSHEditorColorOptions.GetWrongSymbolAttr: ISHEditorColorAttr; begin Supports(WrongSymbolAttr, ISHEditorColorAttr, Result); end; { TSHEditorColor } function TSHEditorColor.GetForeground: TColor; begin Result := Foreground; end; procedure TSHEditorColor.SetForeground(Value: TColor); begin Foreground := Value; end; function TSHEditorColor.GetBackground: TColor; begin Result := Background; end; procedure TSHEditorColor.SetBackground(Value: TColor); begin Background := Value; end; { TSHEditorColorAttr } function TSHEditorColorAttr.GetStyle: TFontStyles; begin Result := Style; end; procedure TSHEditorColorAttr.SetStyle(Value: TFontStyles); begin Style := Value; end; { TSHEditorCodeInsightOptions } constructor TSHEditorCodeInsightOptions.Create(AOwner: TComponent); begin FCustomStrings := TStringList.Create; TStringList(FCustomStrings).Sorted := True; inherited Create(AOwner); FShowBeginEndRegions:=True; MakePropertyInvisible('WindowLineCount'); MakePropertyInvisible('WindowWidth'); end; destructor TSHEditorCodeInsightOptions.Destroy; begin FCustomStrings.Free; inherited Destroy; end; function TSHEditorCodeInsightOptions.GetParentCategory: string; begin Result := Format('%s', ['Editor']); end; function TSHEditorCodeInsightOptions.GetCategory: string; begin Result := Format('%s', ['Code Insight']); end; procedure TSHEditorCodeInsightOptions.RestoreDefaults; begin CodeCompletion := True; CodeParameters := True; CaseCode := Upper; CaseSQLKeywords := Upper; Delay := 1000; WindowLineCount := 12; WindowWidth := 300; FShowBeginEndRegions:=True; end; function TSHEditorCodeInsightOptions.GetCodeCompletion: Boolean; begin Result := CodeCompletion; end; procedure TSHEditorCodeInsightOptions.SetCodeCompletion(Value: Boolean); begin CodeCompletion := Value; end; function TSHEditorCodeInsightOptions.GetCodeParameters: Boolean; begin Result := CodeParameters; end; procedure TSHEditorCodeInsightOptions.SetCodeParameters(Value: Boolean); begin CodeParameters := Value; end; function TSHEditorCodeInsightOptions.GetCaseCode: TSHEditorCaseCode; begin Result := CaseCode; end; procedure TSHEditorCodeInsightOptions.SetCaseCode(Value: TSHEditorCaseCode); begin CaseCode := Value; end; function TSHEditorCodeInsightOptions.GetCaseSQLKeywords: TSHEditorCaseCode; begin Result := CaseSQLKeywords; end; procedure TSHEditorCodeInsightOptions.SetCaseSQLKeywords(Value: TSHEditorCaseCode); begin CaseSQLKeywords := Value; end; function TSHEditorCodeInsightOptions.GetCustomStrings: TStrings; begin Result := CustomStrings; end; function TSHEditorCodeInsightOptions.GetDelay: Integer; begin Result := Delay; end; procedure TSHEditorCodeInsightOptions.SetDelay(Value: Integer); begin Delay := Value; end; function TSHEditorCodeInsightOptions.GetWindowLineCount: Integer; begin Result := WindowLineCount; end; procedure TSHEditorCodeInsightOptions.SetWindowLineCount(Value: Integer); begin WindowLineCount := Value; end; function TSHEditorCodeInsightOptions.GetWindowWidth: Integer; begin Result := WindowWidth; end; procedure TSHEditorCodeInsightOptions.SetWindowWidth(Value: Integer); begin WindowWidth := Value; end; procedure TSHEditorCodeInsightOptions.SetCustomStrings( const Value: TStrings); begin FCustomStrings.Assign(Value); end; function TSHEditorCodeInsightOptions.GetShowBeginEndRegions: boolean; begin Result:=FShowBeginEndRegions end; procedure TSHEditorCodeInsightOptions.SetShowBeginEndRegions( const Value: boolean); begin FShowBeginEndRegions:=Value end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, VirtualTrees, VirtualExplorerTree, VirtualExplorerListviewEx, VirtualShellUtilities; type TForm1 = class(TForm) LVEx: TVirtualExplorerListviewEx; StatusBar1: TStatusBar; ProgressBar1: TProgressBar; Memo1: TMemo; Splitter1: TSplitter; Memo2: TMemo; procedure FormShow(Sender: TObject); procedure LVExEnumFolder(Sender: TCustomVirtualExplorerTree; Namespace: TNamespace; var AllowAsChild: Boolean); procedure FormCreate(Sender: TObject); procedure LVExRootChanging(Sender: TCustomVirtualExplorerTree; const NewValue: TRootFolder; const CurrentNamespace, Namespace: TNamespace; var Allow: Boolean); private { Private declarations } procedure FormOnIdle(Sender: TObject; var Done: Boolean); public { Public declarations } T: Cardinal; end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormShow(Sender: TObject); begin // Disable the Shell extraction LVEx.ThumbsOptions.UseShellExtraction := False; // Load all the thumbs at once LVEx.ThumbsOptions.LoadAllAtOnce := True; // For maximum extraction speed don't compress the cache LVEx.ThumbsOptions.CacheOptions.Compressed := False; LVEx.ViewStyle := vsxThumbs; LVEx.Active := True; end; procedure TForm1.LVExRootChanging(Sender: TCustomVirtualExplorerTree; const NewValue: TRootFolder; const CurrentNamespace, Namespace: TNamespace; var Allow: Boolean); begin ProgressBar1.Max := 0; T := GetTickCount; StatusBar1.Panels[1].Text := 'Elapsed Time: ...'; end; procedure TForm1.LVExEnumFolder(Sender: TCustomVirtualExplorerTree; Namespace: TNamespace; var AllowAsChild: Boolean); begin if LVEx.ThumbsOptions.LoadAllAtOnce then if Namespace.FileSystem and not Namespace.Folder then if LVEx.IsImageFile(Namespace.NameForParsingInFolder) then ProgressBar1.Max := ProgressBar1.Max + 1; end; procedure TForm1.FormOnIdle(Sender: TObject; var Done: Boolean); begin if T = 0 then Exit; //The ThumbsCache gets updated frequently ProgressBar1.Position := LVEx.ThumbsOptions.CacheOptions.ThumbsCount; if ProgressBar1.Position = ProgressBar1.Max then begin StatusBar1.Panels[1].Text := Format('Elapsed Time: %f sec', [(GetTickCount - T)/1000]); T := 0; end; StatusBar1.Panels[2].Text := Format('%d/%d image files', [ProgressBar1.Position, ProgressBar1.Max]); end; procedure TForm1.FormCreate(Sender: TObject); var I: integer; S: string; begin Memo1.Lines.Clear; Case LVEx.ImageLibrary of timNone: S := 'None'; timGraphicEx: S := 'GraphicEx'; timImageEn: S := 'ImageEn'; timEnvision: S := 'Envision'; timImageMagick: S := 'ImageMagick'; end; Memo1.Lines.Add('Image library: ' + S); Memo1.Lines.Add('Supported formats: '); for I := 0 to LVEx.ExtensionsList.Count - 1 do Memo1.Lines.Add(LVEx.ExtensionsList[I]); Application.OnIdle := FormOnIdle; end; end.
unit uI2XMemMap; interface uses Windows, SysUtils, JclStrings, Classes, uFileDir, uStrUtil, SyncObjs, uHashTable, MapStream, uI2XConstants; type TI2XMemoryMapManager = class(TObject) private FList : THashTable; FTokenFilePath : string; FWriteFileToken : boolean; FDebugMessage : string; FFileDir : CFileDir; FStrUtil : CStrUtil; FTokenFileName : string; FLogFileName : string; function GetItem(Index: TIndex): TMapStream; procedure SetItem(Index: TIndex; const Value: TMapStream); function GetCount: Cardinal; function Add( const MapLabel : string; const ItemToAdd : TMapStream ) : TMapStream; function GetTokenFilePath: string; procedure SetTokenFilePath(const Value: string); function GenTokenFileName( const MapLabel : string ) : string; function IncTokenFile( const MapLabel : string ) : bool; function DecTokenFile( const MapLabel : string; const ForceDelete : boolean = false ) : bool; procedure Debug(const Value: string); published //Notice that sometimes that map name can be different but point to the same map // This condition is encountered when the same map is called in different threads //function Add( const ItemToAdd : TMapStream ) : TMapStream; overload; //procedure Remove( MapToRemove : string ); property Count : Cardinal read GetCount; function Exists( const MapStreamName : string ) : boolean; public procedure Flush(); procedure Delete( MapToDelete : string ); overload; property Items[ Index: TIndex ]: TMapStream read GetItem write SetItem; default; property TokenFilePath : string read GetTokenFilePath write SetTokenFilePath; property DebugMessageText : string read FDebugMessage write FDebugMessage; function Stream( const AName: String; ASize:Cardinal; ATimeOut:Integer ): TMapStream; overload; function Stream( const AName: String; ASize:Cardinal ): TMapStream; overload; function Stream( const AName: String ): TMapStream; overload; function Write( var MapName : string; ObjectToStreamFrom : TObject ) : boolean; function Read( const MapName : string; ObjectToStreamTo : TObject; ReleaseAfterRead : boolean = true ) : boolean; function OpenMapsAsString() : string ; constructor Create(); destructor Destroy; override; end; var I2XMMManager : TI2XMemoryMapManager; implementation uses Graphics, uDWImage, uI2XOCR, GR32; { TI2XMemoryMapManager } function TI2XMemoryMapManager.Add(const MapLabel : string; const ItemToAdd: TMapStream): TMapStream; begin if ( Length( MapLabel ) = 0 ) then raise Exception.Create('You must specify an image source'); FList.Add( MapLabel, ItemToAdd ); if ( self.FWriteFileToken ) then self.IncTokenFile( MapLabel ); Result := ItemToAdd; end; {* function TI2XMemoryMapManager.Add(const ItemToAdd: TMapStream): TMapStream; begin if ( Length( ItemToAdd.Name ) = 0 ) then raise Exception.Create('You must specify an image source'); ItemToAdd.Parent := TObject( self ); FList.Add( ItemToAdd.Name, ItemToAdd ); Result := ItemToAdd; end; *} constructor TI2XMemoryMapManager.Create; begin FList := THashTable.Create; FFileDir := CFileDir.Create; FStrUtil := CStrUtil.Create; self.TokenFilePath := 'C:\Users\Administrator\AppData\Local\Temp\i2x\'; end; function TI2XMemoryMapManager.DecTokenFile(const MapLabel: string; const ForceDelete : boolean = false): bool; var sTokenFileName, sTokenFileContents : string; nTokenMapCount : integer; begin sTokenFileName := GenTokenFileName( MapLabel ); if ( FileExists( sTokenFileName ) ) then begin sTokenFileContents := FFileDir.TextFileToString( sTokenFileName ); nTokenMapCount := FStrUtil.ExtractInt( sTokenFileContents ); Dec( nTokenMapCount ); if ( ForceDelete ) then nTokenMapCount := 0; if ( nTokenMapCount = 0 ) then begin DeleteFile( sTokenFileName ); Debug('CLOSE:' + MapLabel + ' ' + self.FDebugMessage ); FDebugMessage := ''; end else begin FFileDir.WriteString( IntToStr( nTokenMapCount ), sTokenFileName ); Debug('DEC [' + IntToStr(nTokenMapCount) + ']:' + MapLabel + ' ' + self.FDebugMessage ); FDebugMessage := ''; end; end else begin //FFileDir.WriteString( sTokenFileName, '1' ); end; end; procedure TI2XMemoryMapManager.Delete( MapToDelete : string ); begin FList.Delete( MapToDelete ); if ( self.FWriteFileToken ) then self.DecTokenFile( MapToDelete ); end; destructor TI2XMemoryMapManager.Destroy; var kl : TKeyList; i : integer; begin kl := self.FList.Keys; for i := 0 to Length( kl ) - 1 do begin self.Delete( kl[i] ); end; FList.FreeObjectsOnDestroy := false; FreeAndNil( FList ); FreeAndNil( FFileDir ); FreeAndNil( FStrUtil ); inherited; end; function TI2XMemoryMapManager.Exists(const MapStreamName: string): boolean; begin Result := FList.ContainsKey( MapStreamName ); end; procedure TI2XMemoryMapManager.Flush; var kl : TKeyList; i : integer; begin kl := self.FList.Keys; for i := 0 to Length( kl ) - 1 do begin self.Delete( kl[i] ); end; end; function TI2XMemoryMapManager.GenTokenFileName(const MapLabel : string ): string; begin Result := FFileDir.Slash( FTokenFilePath ) + MapLabel + '._map'; end; function TI2XMemoryMapManager.GetCount: Cardinal; begin Result := FList.Count; end; function TI2XMemoryMapManager.GetItem(Index: TIndex): TMapStream; begin if ( Index.DataType = idtString ) then begin if ( FList.ContainsKey( Index.StringValue ) ) then Result := TMapStream( FList.Items[ Index ] ) else begin Result := TMapStream.Create( Index.StringValue ); FList.Add( Index.StringValue, Result ); end; end else begin Result := TMapStream( FList.Items[ Index ] ); end; end; function TI2XMemoryMapManager.GetTokenFilePath: string; begin Result := self.FTokenFilePath; end; function TI2XMemoryMapManager.IncTokenFile(const MapLabel: string): bool; var sTokenFileName, sTokenFileContents : string; nTokenMapCount : integer; begin sTokenFileName := GenTokenFileName( MapLabel ); if ( FileExists( sTokenFileName ) ) then begin sTokenFileContents := FFileDir.TextFileToString( sTokenFileName ); nTokenMapCount := FStrUtil.ExtractInt( sTokenFileContents ); Inc( nTokenMapCount ); FFileDir.WriteString( IntToStr( nTokenMapCount ), sTokenFileName ); Debug('INC [' + IntToStr(nTokenMapCount) + ']:' + MapLabel + ' ' + self.FDebugMessage ); FDebugMessage := ''; end else begin FFileDir.WriteString( '1', sTokenFileName ); Debug('OPEN:' + MapLabel + ' ' + self.FDebugMessage ); FDebugMessage := ''; end; end; function TI2XMemoryMapManager.OpenMapsAsString: string; var sb : TStringBuilder; i : integer; kl : TKeyList; Begin try sb := TStringBuilder.Create(); kl := self.FList.Keys; for i := 0 to Length( kl ) - 1 do begin sb.Append( kl[i] + #13); end; Result := sb.ToString(); finally FreeAndNil( sb ); end; End; function TI2XMemoryMapManager.Read(const MapName: string; ObjectToStreamTo: TObject; ReleaseAfterRead : boolean ): boolean; var DWImageToStream : TDWImage; Bitmap32ToStream : TBitmap32; BitmapToStream : TBitmap; OCRResultsToStream : TI2XOCRResults; FMemoryMap : TMapStream; ms : TMemoryStreamPlus; FLastStreamSize, FInitialSize : integer; bmp : TBitmap; begin try Result := false; //FMemoryMap := self.Items[ MapName ]; //try ms := TMemoryStreamPlus.Create(); if ( ObjectToStreamTo.ClassName = 'TDWImage' ) then begin FMemoryMap := self.Stream( MapName, IMAGE_MEMMAP_INIT_SIZE ); DWImageToStream := TDWImage(ObjectToStreamTo); DWImageToStream.Bitmap.FreeImage; if ( not FMemoryMap.Read( ms ) ) then raise Exception.Create('Error while copying BITMAP to Memory Map'); DWImageToStream.Bitmap.LoadFromStream( ms ); FLastStreamSize := ms.Size; DWImageToStream.BMPHeaderUpdate; Result := true; end else if ( ObjectToStreamTo.ClassName = 'TBitmap32' ) then begin FMemoryMap := self.Stream( MapName, IMAGE_MEMMAP_INIT_SIZE ); Bitmap32ToStream := TBitmap32( ObjectToStreamTo ); //if ( not FMemoryMap.Read( ms ) ) then // raise Exception.Create('Error while copying BITMAP to Memory Map'); try bmp := TBitmap.Create; if ( not FMemoryMap.Read( ms ) ) then raise Exception.Create('Error while copying BITMAP from Memory Map'); bmp.LoadFromStream( ms ); Bitmap32ToStream.Assign( bmp ); finally FreeAndNil( bmp ); end; Result := true; end else if ( ObjectToStreamTo.ClassName = 'TBitmap' ) then begin FMemoryMap := self.Stream( MapName, IMAGE_MEMMAP_INIT_SIZE ); BitmapToStream := TBitmap( ObjectToStreamTo ); if ( not FMemoryMap.Read( ms ) ) then raise Exception.Create('Error while copying BITMAP from Memory Map'); BitmapToStream.LoadFromStream( ms ); Result := true; end else if ( ObjectToStreamTo.ClassName = 'TI2XOCRResults' ) then begin FMemoryMap := self.Stream( MapName, OCR_MEMMAP_INIT_SIZE ); OCRResultsToStream := TI2XOCRResults( ObjectToStreamTo ); if ( not FMemoryMap.Read( ms ) ) then raise Exception.Create('Error while copying OCR Results from Memory Map'); OCRResultsToStream.LoadXML( ms.Read().StringValue ); Result := true; end else raise Exception.Create('Memory Map Manager does not know how to read an object of type "' + ObjectToStreamTo.ClassName + '" yet.'); if ( ReleaseAfterRead ) then self.Delete( MapName ); //except // raise; // on E : Exception do begin // raise; // end; //end; finally if ( ms <> nil ) then FreeAndNil( ms ); end; end; //procedure TI2XMemoryMapManager.Remove( MapToRemove : string ); //begin // FList.Remove( MapToRemove ); //end; procedure TI2XMemoryMapManager.SetItem(Index: TIndex; const Value: TMapStream); begin FList.Items[ Index ] := TObject( Value ); end; procedure TI2XMemoryMapManager.Debug(const Value: string); Begin if ( Length(FLogFileName) > 0 ) then begin self.FFileDir.WriteString( Value + #13, FLogFileName, true ); end; End; procedure TI2XMemoryMapManager.SetTokenFilePath(const Value: string); begin self.FTokenFilePath := Value; self.FWriteFileToken := ( Length( FTokenFilePath ) > 0 ); if ( FWriteFileToken ) then FLogFileName := FFileDir.Slash( FTokenFilePath ) + 'I2XMemoryManager.log' else FLogFileName := ''; end; function TI2XMemoryMapManager.Stream( const AName: String; ASize: Cardinal; ATimeOut: Integer): TMapStream; var ms : TMapStream; begin if ( FList.ContainsKey( AName ) ) then Result := TMapStream( FList.Items[ AName ] ) else begin Result := TMapStream.Create( AName, ASize, ATimeOut ); FList.Add( AName, Result ); if ( self.FWriteFileToken ) then self.IncTokenFile( AName ); end; end; function TI2XMemoryMapManager.Stream( const AName: String; ASize: Cardinal): TMapStream; var ms : TMapStream; begin if ( FList.ContainsKey( AName ) ) then Result := TMapStream( FList.Items[ AName ] ) else begin ms := TMapStream.Create( AName, ASize ); FList.Add( AName, ms ); if ( self.FWriteFileToken ) then self.IncTokenFile( AName ); Result := ms; end; end; function TI2XMemoryMapManager.Stream( const AName: String): TMapStream; var ms : TMapStream; begin if ( FList.ContainsKey( AName ) ) then Result := TMapStream( FList.Items[ AName ] ) else begin Result := TMapStream.Create( AName ); if ( self.FWriteFileToken ) then self.IncTokenFile( AName ); FList.Add( AName, Result ); end; end; function TI2XMemoryMapManager.Write(var MapName: string; ObjectToStreamFrom: TObject): boolean; var DWImageToStream : TDWImage; Bitmap32ToStream : TBitmap32; BitmapToStream : TBitmap; OCRResultsToStream : TI2XOCRResults; FMemoryMap : TMapStream; ms : TMemoryStreamPlus; FLastStreamSize, FInitialSize : integer; bmp : TBitmap; begin result := false; try if ( ObjectToStreamFrom.ClassName = 'TDWImage' ) then begin DWImageToStream := TDWImage(ObjectToStreamFrom); if ( Length(MapName) = 0 ) then MapName := IMAGE_MEMMAP_HEADER + IntToStr( Integer(Pointer(ObjectToStreamFrom)) ); FInitialSize := IMAGE_MEMMAP_INIT_SIZE; ms := TMemoryStreamPlus.Create(); DWImageToStream.BITMAP.SaveToStream( ms ); end else if ( ObjectToStreamFrom.ClassName = 'TBitmap32' ) then begin Bitmap32ToStream := TBitmap32( ObjectToStreamFrom ); if ( Length(MapName) = 0 ) then MapName := IMAGE_MEMMAP_HEADER + IntToStr( Integer(Pointer(ObjectToStreamFrom)) ); FInitialSize := IMAGE_MEMMAP_INIT_SIZE; ms := TMemoryStreamPlus.Create(); try bmp := TBitmap.Create; bmp.Assign( Bitmap32ToStream ); bmp.SaveToStream( ms ); finally FreeAndNil( bmp ); end; end else if ( ObjectToStreamFrom.ClassName = 'TBitmap' ) then begin BitmapToStream := TBitmap( ObjectToStreamFrom ); if ( Length(MapName) = 0 ) then MapName := IMAGE_MEMMAP_HEADER + IntToStr( Integer(Pointer(ObjectToStreamFrom)) ); FInitialSize := IMAGE_MEMMAP_INIT_SIZE; ms := TMemoryStreamPlus.Create(); BitmapToStream.SaveToStream( ms ); end else if ( ObjectToStreamFrom.ClassName = 'TI2XOCRResults' ) then begin OCRResultsToStream := TI2XOCRResults( ObjectToStreamFrom ); if ( Length(MapName) = 0 ) then MapName := OCR_MEMMAP_HEADER + IntToStr( Integer(Pointer(ObjectToStreamFrom)) ); FInitialSize := OCR_MEMMAP_INIT_SIZE; ms := TMemoryStreamPlus.Create( OCRResultsToStream.AsXML() ); end else raise Exception.Create('Memory Map Manager does not know how to write an object of type "' + ObjectToStreamFrom.ClassName + '" yet.'); FMemoryMap := self.Stream( MapName, FInitialSize ); if ( not FMemoryMap.Write( ms ) ) then raise Exception.Create('Error while copying stream to Memory Map'); result := true; finally if ( ms <> nil ) then FreeAndNil( ms ); end; end; initialization finalization END.
(* Category: SWAG Title: MATH ROUTINES Original name: 0027.PAS Description: Prime Numbers Author: MICHAEL BYRNE Date: 08-27-93 21:45 *) { MICHAEL M. BYRNE > the way, it took about 20 mins. on my 386/40 to get prime numbers > through 20000. I tried to come up With code to do the same With > Turbo but it continues to elude me. Could anybody explain > how to Write such a routine in Pascal? Here is a simple Boolean Function For you to work With. } Function Prime(N : Integer) : Boolean; {Returns True if N is a prime; otherwise returns False. Precondition: N > 0.} Var I : Integer; begin if N = 1 then Prime := False else if N = 2 then Prime := True else begin { N > 2 } Prime := True; {tentatively} For I := 2 to N - 1 do if (N mod I = 0) then Prime := False; end; { N > 2 } end; begin if Prime(34) then WriteLn('34 is prime'); if Prime(37) then WriteLn('37 is prime'); end.
{ Copyright (c) 2020 Adrian Siekierka Based on a reconstruction of code from ZZT, Copyright 1991 Epic MegaGames, used with permission. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. } {$I-} unit ZVideo; interface type TVideoLine = string[80]; { Was 160 in ZZT 3.2. } TScreenCopyLine = string[100]; TVideoWriteTextProc = procedure(x, y, color: byte; text: TVideoLine); const PORT_CGA_MODE = $03D8; PORT_CGA_PALETTE = $03D9; var VideoWriteText: TVideoWriteTextProc; VideoMonochrome: boolean; VideoColumns: integer; VideoTextSegment: word; VideoEGAInstalled: boolean; VideoMDAInstalled: boolean; VideoLastMode: word; function VideoConfigure: boolean; procedure VideoInstall(borderColor: integer); procedure VideoUninstall; procedure VideoShowCursor; procedure VideoHideCursor; procedure VideoSetBorderColor(value: integer); procedure VideoSetBlink(value: boolean); procedure VideoMove(x, y, chars: integer; data: pointer; toVideo: boolean); procedure VideoInvert(x1, y1, x2, y2: integer); implementation uses Crt, Dos; {$F+} {$IFNDEF FPC} procedure VideoWriteTextCGA(x, y, color: byte; text: TVideoLine); begin inline( $8B/$06/VideoTextSegment/{ MOV AX, VideoTextSegment } $8E/$C0/ { MOV ES, AX } $8A/$86/y/ { MOV AL, byte ptr [BP + y] } $F6/$26/VideoColumns/{ MUL VideoColumns } $31/$C9/ { XOR CX, CX } $89/$CE/ { MOV SI, CX } $8A/$8E/x/ { MOV CL, byte ptr [BP + x] } $01/$C8/ { ADD AX, CX } $D1/$E0/ { SHL AX, 1 } $8B/$F8/ { MOV DI, AX } $8A/$BE/color/ { MOV BH, byte ptr [BP + color] } $8A/$8E/text/ { MOV CL, byte ptr [BP + text] } $BA/$03DA/ { MOV DX, 0x03DA } $22/$C9/ { AND CL, CL } $74/$1A/ { JZ finish } $FA/ { CLI } { next_char: } $46/ { INC SI } $8A/$9A/text/ { MOV BL, byte ptr [BP + SI + text] } { cga_snow: } $EC/ { IN AL, DX } $A8/$08/ { TEST AL, 8 } $75/$09/ { JNZ write_char } $D0/$E8/ { SHR AL, 1 } $72/$F7/ { JC cga_snow } { cga_snow2: } $EC/ { IN AL, DX } $D0/$E8/ { SHR AL, 1 } $73/$FB/ { JNC cga_snow2 } { write_char: } $89/$D8/ { MOV AX, BX } $AB/ { STOSW } $E2/$E8/ { LOOP next_char } $FB { STI } { finish: } ); end; procedure VideoWriteTextFast(x, y, color: byte; text: TVideoLine); begin inline( $8B/$06/VideoTextSegment/{ MOV AX, VideoTextSegment } $8E/$C0/ { MOV ES, AX } $8A/$86/y/ { MOV AL, byte ptr [BP + y] } $F6/$26/VideoColumns/{ MUL VideoColumns } $31/$C9/ { XOR CX, CX } $89/$CE/ { MOV SI, CX } $8A/$8E/x/ { MOV CL, byte ptr [BP + x] } $01/$C8/ { ADD AX, CX } $D1/$E0/ { SHL AX, 1 } $8B/$F8/ { MOV DI, AX } $8A/$A6/color/ { MOV AH, byte ptr [BP + color] } $8A/$8E/text/ { MOV CL, byte ptr [BP + text] } $22/$C9/ { AND CL, CL } $74/$0A/ { JZ finish } $FA/ { CLI } { next_char: } $46/ { INC SI } $8A/$82/text/ { MOV AL, byte ptr [BP + SI + text] } $AB/ { STOSW } $E2/$F8/ { LOOP next_char } $FB { STI } { finish: } ); end; {$ELSE} procedure VideoWriteTextCGA(x, y, color: byte; text: TVideoLine); assembler; label next_char; label cga_snow; label cga_snow2; label write_char; label finish; asm push es mov ax, VideoTextSegment mov es, ax mov al, y mul VideoColumns xor cx, cx mov cl, x add ax, cx shl ax, 1 mov di, ax mov bh, color mov dx, 03DAh push ds lds si, [text] mov cl, [si] and cl, cl jz finish cli next_char: inc si mov bl, [si] cga_snow: in al, dx test al, 8 jnz write_char shr al, 1 jc cga_snow cga_snow2: in al, dx shr al, 1 jnc cga_snow2 write_char: mov ax, bx stosw loop next_char sti finish: pop ds pop es end ['ax', 'bx', 'cx', 'dx', 'si', 'di']; procedure VideoWriteTextFast(x, y, color: byte; text: TVideoLine); assembler; label next_char; label finish; asm push es mov ax, VideoTextSegment mov es, ax mov al, y mul VideoColumns xor cx, cx mov cl, x add ax, cx shl ax, 1 mov di, ax mov ah, color mov dx, 03DAh push ds lds si, [text] mov cl, [si] and cl, cl jz finish cli next_char: inc si mov al, [si] stosw loop next_char sti finish: pop ds pop es end ['ax', 'cx', 'dx', 'si', 'di']; {$ENDIF} {$F-} function ColorToBW(color: byte): byte; begin { FIX: Special handling of blinking solids } if (color and $80) = $80 then if ((color shr 4) and $07) = (color and $0F) then color := (color and $7F); if (color and $09) = $09 then color := (color and $F0) or $0F else if (color and $07) <> 0 then color := (color and $F0) or $07; if (color and $0F) = $00 then begin if (color and $70) = $00 then color := (color and $8F) else color := (color and $8F) or $70; end else if (color and $70) <> $70 then color := color and $8F; ColorToBW := color; end; {$F+} procedure VideoWriteTextCGABW(x, y, color: byte; text: TVideoLine); begin VideoWriteTextCGA(x, y, ColorToBW(color), text); end; procedure VideoWriteTextFastBW(x, y, color: byte; text: TVideoLine); begin VideoWriteTextFast(x, y, ColorToBW(color), text); end; {$F-} function VideoConfigure: boolean; var charTyped: Char; begin charTyped := ' '; if VideoLastMode = 7 then begin VideoWriteText := VideoWriteTextFastBW; VideoMonochrome := true; end else begin Writeln; Write(' Video mode: C)olor, M)onochrome? '); repeat repeat until KeyPressed; charTyped := UpCase(ReadKey); until charTyped in [#27, 'C', 'M']; case charTyped of 'C', #27: VideoMonochrome := false; 'M': VideoMonochrome := true; { #27: false if (VideoLastMode = 7);, checked above } end; end; VideoConfigure := charTyped <> #27; end; procedure VideoInstall(borderColor: integer); var regs: Registers; begin regs.AH := $12; regs.BX := $FF10; Intr($10, regs); VideoEGAInstalled := regs.BH <> $FF; VideoMDAInstalled := VideoLastMode = 7; if VideoEGAInstalled then begin regs.AX := $1201; regs.BL := $30; Intr($10, regs); end; VideoColumns := 80; if VideoMonochrome then begin if VideoEGAInstalled or VideoMDAInstalled then VideoWriteText := VideoWriteTextFastBW else VideoWriteText := VideoWriteTextCGABW; if (VideoLastMode and $FFFC) = 0 {>= 0, <= 3} then begin TextMode(BW80); end else begin TextMode(7); end; end else begin if VideoEGAInstalled then VideoWriteText := VideoWriteTextFast else VideoWriteText := VideoWriteTextCGA; TextMode(CO80); TextBackground(borderColor); VideoSetBorderColor(borderColor); end; ClrScr; VideoHideCursor; end; procedure VideoUninstall; var regs: Registers; begin if VideoEGAInstalled then begin regs.AX := $1201; regs.BL := $30; Intr($10, regs); end; TextBackground(0); VideoColumns := 80; TextMode(VideoLastMode); VideoSetBorderColor(0); ClrScr; end; procedure VideoSetCursorShape(value: integer); var regs: Registers; begin regs.AH := $01; regs.CX := value; Intr($10, regs); end; procedure VideoShowCursor; begin VideoSetCursorShape($0607); end; procedure VideoHideCursor; begin VideoSetCursorShape($2000); end; procedure VideoSetBorderColor(value: integer); begin Port[PORT_CGA_PALETTE] := value; end; procedure VideoSetBlink(value: boolean); var regs: Registers; begin { CGA route } if value then Port[PORT_CGA_MODE] := Port[PORT_CGA_MODE] or $20 else Port[PORT_CGA_MODE] := Port[PORT_CGA_MODE] and $DF; { EGA/VGA route } regs.AX := $1003; regs.BH := 0; regs.BL := Byte(value); Intr($10, regs); end; procedure VideoMove(x, y, chars: integer; data: pointer; toVideo: boolean); var offset: integer; begin offset := (y * VideoColumns + x) * 2; if toVideo then Move(data^, Ptr(VideoTextSegment, offset)^, chars * 2) else Move(Ptr(VideoTextSegment, offset)^, data^, chars * 2); end; procedure VideoInvert(x1, y1, x2, y2: integer); var ix, iy, offset: integer; begin if x2 < x1 then begin ix := x1; x1 := x2; x2 := ix; end; if y2 < y1 then begin ix := y1; y1 := y2; y2 := ix; end; for iy := y1 to y2 do begin offset := (((iy * VideoColumns) + x1) shl 1) + 1; for ix := x1 to x2 do begin Mem[VideoTextSegment:offset] := Mem[VideoTextSegment:offset] xor $7F; Inc(offset, 2); end; end; end; begin VideoColumns := 80; VideoWriteText := VideoWriteTextCGA; VideoLastMode := LastMode; if VideoLastMode = 7 then begin VideoTextSegment := $B000; VideoMonochrome := true; end else begin VideoTextSegment := $B800; VideoMonochrome := false; end; end.
namespace TsmPluginFx.Manager; uses GisdkAPI, System.Reflection, System.IO, System.Collections.Generic; type TsmPluginModuleManager = public class (IGisdkExtension) private fModules: not nullable List<TsmPluginModule> := new List<TsmPluginModule>; fConfigFilePath: String; method ConfigFilePath: String; begin if not String.IsNullOrEmpty(fConfigFilePath) then exit fConfigFilePath; var lCodeBase := &Assembly.GetExecutingAssembly.CodeBase; var lUri := new UriBuilder(lCodeBase); fConfigFilePath := Uri.UnescapeDataString(lUri.Path) + '.config'; exit fConfigFilePath; ensure File.Exists(fConfigFilePath); end; method LoadConfig; begin var lConfigXmlDoc := RemObjects.Elements.RTL.XmlDocument.FromFile(ConfigFilePath); var lActive: Boolean; var lPath: String; for each el in lConfigXmlDoc.Root.Elements do begin lActive := Convert.ToBoolean(el.Attribute['enabled'].Value); lPath := el.Attribute['path'].Value; fModules.Add(new TsmPluginModule(lPath, lActive)); end; end; method SaveConfig; begin var lConfigXmlDoc := RemObjects.Elements.RTL.XmlDocument.FromFile(ConfigFilePath); for each p in fModules do begin for each el in lConfigXmlDoc.Root.Elements do if el.Attribute['path'].Value.Equals(p.Path) then el.Attribute['enabled'].Value := p.Enabled.ToString; end; lConfigXmlDoc.SaveToFile(ConfigFilePath) end; method ShowUI; begin SaveConfig; end; public constructor; begin LoadConfig; end; method Load(app: IGisdkEngine); begin ShowUI; end; property Title: String read begin exit 'TransModeler Plugin Manager'; end; end; end.
unit GTINTests; interface uses TestFramework, GTIN; type TGTINTests = class(TTestCase) private FGTIN: TGTIN; procedure AssertValid; procedure CheckIfGTINIsValid(const aGTIN: array of string); published procedure TestGTINIsValid; procedure TestGTINAssertValid; procedure TestGTIN8IsValid; procedure TestGTIN12IsValid; procedure TestGTIN13IsValid; procedure TestGTIN14IsValid; procedure TestInvalidCheckDigit; procedure TestInvalidDataStructure; end; implementation const VALID_GTIN: array[1..20] of string = ('20013776', '20012984', '20007331', '48297943', '80496373', '789822986142', '789300005969', '789300768727', '789300488953', '789300030206', '7897158700011', '7898951405073', '7892970020019', '7898386722677', '7899638306768', '47891164132185', '47891164132772', '87891164132534', '47891164133038', '47891164133267'); { TGTINTests } procedure TGTINTests.AssertValid; begin GTINAssertValid(FGTIN); end; procedure TGTINTests.CheckIfGTINIsValid(const aGTIN: array of string); var GTIN: string; begin for GTIN in aGTIN do begin FGTIN := GTIN; CheckTrue(FGTIN.IsValid, GTIN + ' should be a valid GTIN'); end; end; procedure TGTINTests.TestGTIN12IsValid; const VALID_GTIN: array[1..10] of string = ( '700083132369', '700083132239', '742832426107', '789733701292', '789300768307', '751320009548', '789300081581', '341224116000', '789300005945', '761318111894'); begin CheckIfGTINIsValid(VALID_GTIN); end; procedure TGTINTests.TestGTIN13IsValid; const VALID_GTIN: array[1..10] of string = ( '7898387630018', '7898419081504', '7890000182249','7898302290877', '7898494840027', '7891515852108', '7891515898106', '7892970020118', '7898929528865', '9788524304460'); begin CheckIfGTINIsValid(VALID_GTIN); end; procedure TGTINTests.TestGTIN14IsValid; const VALID_GTIN: array[1..10] of string = ( '78972929000182', '47891164020406', '17894904996473', '17894904996480', '27893000516834', '78915158781507', '47891164132284', '47891164132352', '47891164132673', '47891164132383'); begin CheckIfGTINIsValid(VALID_GTIN); end; procedure TGTINTests.TestGTIN8IsValid; const VALID_GTIN: array[1..10] of string = ('20006693', '78911017', '45584411' , '20001773', '20010379', '20006532', '20006143', '20005658', '20005818', '10011812'); begin CheckIfGTINIsValid(VALID_GTIN); end; procedure TGTINTests.TestGTINAssertValid; var GTIN: string; begin for GTIN in VALID_GTIN do begin FGTIN := GTIN; AssertValid; end; end; procedure TGTINTests.TestGTINIsValid; var GTIN: string; begin for GTIN in VALID_GTIN do CheckTrue(GTINIsValid(GTIN), GTIN + ' should be a valid GTIN'); end; procedure TGTINTests.TestInvalidCheckDigit; const INVALID_GTIN: array[1..20] of string = ('20013771', '20012982', '20007333', '48297944', '80496375', '789822986146', '789300005967', '789300768728', '789300488959', '789300030200', '7897158700012', '7898951405074', '7892970020015', '7898386722676', '7899638306767', '47891164132188', '47891164132779', '87891164132530', '47891164133031', '47891164133262'); var GTIN: string; begin for GTIN in INVALID_GTIN do begin FGTIN := GTIN; CheckException(FGTIN.AssertValid, GTINException, 'Check digit of GTIN ' + GTIN + ' should be invalid'); CheckException(AssertValid, GTINException, 'GTINAssertValid should throw exception for Check digit invalid of GTIN ' + GTIN); end; end; procedure TGTINTests.TestInvalidDataStructure; const INVALID_GTIN: array[1..5] of string = ('1234567', '123456789', '1234567890', '12345678901', '123456789012345'); var GTIN: string; begin for GTIN in INVALID_GTIN do begin FGTIN := GTIN; CheckException(FGTIN.AssertValid, GTINException, 'GTIN ' + GTIN + ' should throw exception for data structure'); CheckException(AssertValid, GTINException, 'GTINAssertValid of GTIN ' + GTIN + ' should throw exception for data structure'); end; end; initialization RegisterTest(TGTINTests.Suite); end.
{$B-,I-,Q-,R-,S-} {$M 16384,0,655360} { 97¦ Paseo Vespertino. México 2006 ---------------------------------------------------------------------- Como todos sabemos, a las vacas les gustan las novedades. Por lo tanto muchas veces somos llamados para ayudarles a evitar duplicación de esfuerzos o escenarios. Otra pregunta importante ha aparecido. Betsy está feliz pasteando en un campo de R (1 <= R <= 20) filas por C (1 <= C <= 30) columnas de lotes de pasteo (denotados por '.') y lotes rocosos (denotados por 'R'). El lote (1, 1) está en la esquina superior izquierda de esta cuadrícula. El sol se está ocultando, por lo tanto es tiempo de devolverse al establo, el cual está al sur y al este de Betsy. Betsy quiere usar una ruta nueva al establo cada noche. Ella no puede caminar sobre los lotes rocosos y solo se desplazará hacia el sur y hacia el este hacia el establo, nunca al norte ni al oeste. Por favor calcule cuantas tardes puede ella deambular en una nueva ruta antes que ella tenga que repetir una ruta usada anteriormente. Como ejemplo, considere esta distribución para la zona de pasteo de Besty: B . . . B = Betsy . = lote para caminar R . . . R = Rocas . . . B B = Establo Aquí están las seis maneras en que ella puede caminar al establo: B## . . B## . . B#### . B## . . B###### B#### . R # . . R ### . R . # . R ##### R . . # R . ### . ####B . . ##B . . ##B . . . B . . . B . . . B NOMBRE DEL PROBLEMA: stroll FORMATO DE ENTRADA: - Línea 1: Dos enteros separados por espacio, respectivamente: R y C - Líneas 2..R+1: La línea i+1 representa la fila i y contiene C elementos separados por espacios que representan lotes en el campo. El primer elemento es el elemento en la columna 1 o fila 1. Cada elemento es una 'B', 'R', o '.'. Las 'B's no son ambiguas. ENTRADA EJEMPLO (archivo STROLL.IN): 3 4 B . . . R . . . . . . B FORMATO DE SALIDA: - Línea 1: Un solo entero que es el número de caminos únicos de Betsy al establo. La respuesta no excederá 2,000,000,000. SALIDA EJEMPLO (archivo STROLL.OUT): 6 } const mov : array[1..2,1..2] of shortint =((1,0),(0,1)); var fe,fs : text; r,c : byte; sol : longint; posi : array[1..2,1..2] of byte; mtx : array[1..30,1..40] of longint; m : array[1..30,1..40] of boolean; procedure open; var i,j,t : byte; x : string[1]; begin assign(fe,'stroll.in'); reset(fe); assign(fs,'stroll.out'); rewrite(fs); readln(fe,r,c); t:=0; for i:=1 to r do begin for j:=1 to c do begin read(fe,x); if (x = 'B') then begin inc(t); posi[t,1]:=i; posi[t,2]:=j; end; if (x='.') then mtx[i,j]:=0; if (x='R') then mtx[i,j]:=-1; read(fe,x); end; readln(fe); end; close(fe); end; function valid(x,y : byte) : boolean; begin valid:=false; if (x>0) and (x<=r) and (y>0) and (y<=c) and (mtx[x,y] <> -1) then valid:=true; end; procedure bfs; var cp,ch,x,y,i,j : integer; sav : array[boolean,1..601,1..2] of integer; s : boolean; begin s:=true; cp:=1; ch:=0; sol:=0; mtx[posi[1,1],posi[1,2]]:=1; sav[s,1,1]:=posi[1,1]; sav[s,1,2]:=posi[1,2]; r:=posi[2,1]; c:=posi[2,2]; while cp > 0 do begin fillchar(m,sizeof(m),false); for i:=1 to cp do for j:=1 to 2 do begin x:=sav[s,i,1] + mov[j,1]; y:=sav[s,i,2] + mov[j,2]; if valid(x,y) then begin mtx[x,y]:=mtx[x,y]+mtx[sav[s,i,1],sav[s,i,2]]; if not m[x,y] then begin inc(ch); sav[not s,ch,1]:=x; sav[not s,ch,2]:=y; m[x,y]:=true; end; end; end; cp:=ch; ch:=0; s:=not s; end; end; procedure closer; begin writeln(fs,mtx[posi[2,1],posi[2,2]]); close(fs); end; begin open; bfs; closer; end.
unit UBrwTaxCategory; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, PaiDeBrowses, BrowseConfig, Mask, DateBox, Menus, Db, DBTables, Grids, PanelRights, LblEffct, ExtCtrls, StdCtrls, Buttons, ImgList, ADODB, RCADOQuery, PowerADOQuery, siComp, siLangRT, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGrid, dxPSGlbl, dxPSUtl, dxPSEngn, dxPrnPg, dxBkgnd, dxWrap, dxPrnDev, dxPSCompsProvider, dxPSFillPatterns, dxPSEdgePatterns, dxPSCore, dxPScxGridLnk, cxGridCustomPopupMenu, cxGridPopupMenu; type TBrwTaxCategory = class(TbrwParent) quBrowseIDTaxCategory: TIntegerField; quBrowseTaxCategory: TStringField; quBrowseTax: TFloatField; grdBrowseDBIDTaxCategory: TcxGridDBColumn; grdBrowseDBTaxCategory: TcxGridDBColumn; grdBrowseDBTax: TcxGridDBColumn; Label2: TLabel; cbxTaxType: TComboBox; Label1: TLabel; cbxSaleType: TComboBox; procedure FormCreate(Sender: TObject); procedure btnExecClick(Sender: TObject); procedure cbxTaxTypeChange(Sender: TObject); procedure cbxSaleTypeChange(Sender: TObject); private { Private declarations } fOperationType, fSaleTaxType : Integer; public { Public declarations } end; implementation uses uFchTaxCategory, uDM, uDMGlobal, uSystemConst; {$R *.DFM} procedure TBrwTaxCategory.FormCreate(Sender: TObject); begin inherited; brwForm := TFchTaxCategory.Create(Self); end; procedure TBrwTaxCategory.btnExecClick(Sender: TObject); var fParam : String; begin inherited; case cbxTaxType.ItemIndex of 0 : begin aWhereBasicFilters[1] := 'T.OperationType='+IntToStr(TAX_OP_TYPE_SALE); fParam := 'OPType='+IntToStr(TAX_OP_TYPE_SALE)+';'; case cbxSaleType.ItemIndex of 0 : begin aWhereBasicFilters[2] := 'T.SaleTaxType='+IntToStr(SALE_TAX_TYPE_CHARGE); fParam := fParam + 'STType='+IntToStr(SALE_TAX_TYPE_CHARGE)+ ';'; end; 1 : begin aWhereBasicFilters[2] := 'T.SaleTaxType='+IntToStr(SALE_TAX_TYPE_GOV); fParam := fParam + 'STType='+IntToStr(SALE_TAX_TYPE_GOV)+ ';'; end; end; end; 1 : begin aWhereBasicFilters[1] := 'T.OperationType='+IntToStr(TAX_OP_TYPE_PURCHASE); aWhereBasicFilters[2] := ''; fParam := 'OPType='+IntToStr(TAX_OP_TYPE_PURCHASE)+';'; end; end; ExecBrowseSQL(True); //Desliga o pisca do pnlGo! DesativaAviso; //Passo os params para a ficha TFchTaxCategory(brwForm).sParam := fParam; end; procedure TBrwTaxCategory.cbxTaxTypeChange(Sender: TObject); begin inherited; Label1.Visible := (TComboBox(Sender).ItemIndex = 0); cbxSaleType.Visible := Label1.Visible; AtivaAviso; end; procedure TBrwTaxCategory.cbxSaleTypeChange(Sender: TObject); begin inherited; AtivaAviso; end; end.
unit SDUFilenameEdit_U; interface uses Classes, Controls, Dialogs, Forms, Graphics, Messages, SDUDialogs, SDUFrames, StdCtrls, SysUtils, Variants, Windows; type TSDUFilenamEditType = (fetOpen, fetSave); TSDUFilenameEdit = class (TSDUFrame) edFilename: TEdit; pbBrowse: TButton; OpenDialog1: TSDUOpenDialog; SaveDialog1: TSDUSaveDialog; procedure pbBrowseClick(Sender: TObject); procedure FrameEnter(Sender: TObject); procedure edFilenameChange(Sender: TObject); procedure FrameResize(Sender: TObject); PRIVATE FFilenameEditType: TSDUFilenamEditType; FInitialDir: String; FFilter: String; FFilterIndex: Integer; FDefaultExt: String; FOnChange: TNotifyEvent; procedure TweakControlsLayout(); PROTECTED { function GetInitialDir(): string; procedure SetInitialDir(value: string); function GetFilter(): string; procedure SetFilter(value: string); function GetFilterIndex(): integer; procedure SetFilterIndex(value: integer); function GetDefaultExt(): string; procedure SetDefaultExt(value: string); } function GetFilename(): String; procedure SetFilename(Value: String); procedure SetFilenameEditType(Value: TSDUFilenamEditType); procedure SetEnabled(Value: Boolean); OVERRIDE; procedure Resizing(State: TWindowState); OVERRIDE; procedure DesigningSummary(); procedure BrowseDialogOpen(); procedure BrowseDialogSave(); procedure DoOnChange(); PUBLIC constructor Create(AOwner: TComponent); OVERRIDE; destructor Destroy(); OVERRIDE; PUBLISHED property TabStop DEFAULT True; // Change default to TRUE property FilenameEditType: TSDUFilenamEditType Read FFilenameEditType Write SetFilenameEditType DEFAULT fetOpen; property InitialDir: String Read FInitialDir Write FInitialDir; property Filter: String Read FFilter Write FFilter; property FilterIndex: Integer Read FFilterIndex Write FFilterIndex DEFAULT 1; property DefaultExt: String Read FDefaultExt Write FDefaultExt; { property InitialDir: string read GetInitialDir write SetInitialDir; property Filter: string read GetFilter write SetFilter; property FilterIndex: integer read GetFilterIndex write SetFilterIndex; property DefaultExt: string read GetDefaultExt write SetDefaultExt; } property Filename: String Read GetFilename Write SetFilename; property OpenDialog: TSDUOpenDialog Read OpenDialog1; property SaveDialog: TSDUSaveDialog Read SaveDialog1; property OnChange: TNotifyEvent Read FOnChange Write FOnChange; end; procedure Register; implementation {$R *.dfm} uses SDUGeneral; const // The space between the two controls CONTROL_MARGIN = 5; procedure Register; begin RegisterComponents('SDeanUtils', [TSDUFilenameEdit]); end; constructor TSDUFilenameEdit.Create(AOwner: TComponent); begin inherited; DesigningSummary(); edFilename.Text := ''; self.Height := edFilename.Height; TweakControlsLayout(); edFilename.Anchors := [akLeft, akRight, akTop]; pbBrowse.Anchors := [akRight, akTop]; self.Constraints.MinHeight := edFilename.Height; self.Constraints.MaxHeight := edFilename.Height; end; destructor TSDUFilenameEdit.Destroy(); begin inherited; end; procedure TSDUFilenameEdit.TweakControlsLayout(); begin pbBrowse.Height := edFilename.Height; pbBrowse.Width := pbBrowse.Height; edFilename.Top := 0; edFilename.left := 0; edFilename.Width := self.Width - (pbBrowse.Width + CONTROL_MARGIN); pbBrowse.Top := 0; pbBrowse.left := edFilename.Width + CONTROL_MARGIN; end; { function TSDUFilenameEdit.GetInitialDir(): string; begin Result := OpenDialog1.InitialDir; end; procedure TSDUFilenameEdit.SetInitialDir(value: string); begin OpenDialog1.InitialDir := value; SaveDialog1.InitialDir := value; end; function TSDUFilenameEdit.GetFilter(): string; begin Result := OpenDialog1.Filter; end; procedure TSDUFilenameEdit.SetFilter(value: string); begin OpenDialog1.Filter := value; SaveDialog1.Filter := value; end; function TSDUFilenameEdit.GetFilterIndex(): integer; begin Result := OpenDialog1.FilterIndex; end; procedure TSDUFilenameEdit.SetFilterIndex(value: integer); begin OpenDialog1.FilterIndex := value; SaveDialog1.FilterIndex := value; end; function TSDUFilenameEdit.GetDefaultExt(): string; begin Result := OpenDialog1.DefaultExt; end; procedure TSDUFilenameEdit.SetDefaultExt(value: string); begin OpenDialog1.DefaultExt := value; SaveDialog1.DefaultExt := value; end; } procedure TSDUFilenameEdit.edFilenameChange(Sender: TObject); begin inherited; DoOnChange(); end; procedure TSDUFilenameEdit.DoOnChange(); begin if Assigned(FOnChange) then begin FOnChange(self); end; end; procedure TSDUFilenameEdit.FrameEnter(Sender: TObject); begin inherited; // If the frame gets the focus, set it to the filename TEdit // This allows other controls (e.g. TLabel) to have their "FocusControl" // property to this component, and the right control will get the focus when // the user presses that control's accelerator key/gives it the focus // Need to check if the browse button has the focus first - otherwise, if the // user clicks on the button, the TEdit will get the focus! if not (pbBrowse.Focused) then begin edFilename.SetFocus(); end; end; procedure TSDUFilenameEdit.pbBrowseClick(Sender: TObject); begin if (FilenameEditType = fetSave) then begin BrowseDialogSave(); end else begin BrowseDialogOpen(); end; end; procedure TSDUFilenameEdit.BrowseDialogOpen(); var dlg: TSDUOpenDialog; cwd: String; begin inherited; // Store and restore the CWD; the dialog changes it cwd := SDUGetCWD(); try dlg := OpenDialog; dlg.InitialDir := InitialDir; dlg.Filter := Filter; dlg.FilterIndex := FilterIndex; dlg.DefaultExt := DefaultExt; SDUOpenSaveDialogSetup(dlg, Filename); if dlg.Execute() then begin Filename := dlg.Filename; end; finally SDUSetCWD(cwd); end; end; procedure TSDUFilenameEdit.BrowseDialogSave(); var dlg: TSDUSaveDialog; cwd: String; begin inherited; // Store and restore the CWD; the dialog changes it cwd := SDUGetCWD(); try dlg := SaveDialog; dlg.InitialDir := InitialDir; dlg.Filter := Filter; dlg.FilterIndex := FilterIndex; dlg.DefaultExt := DefaultExt; SDUOpenSaveDialogSetup(dlg, Filename); if dlg.Execute() then begin Filename := dlg.Filename; end; finally SDUSetCWD(cwd); end; end; function TSDUFilenameEdit.GetFilename(): String; begin Result := edFilename.Text; end; procedure TSDUFilenameEdit.SetFilename(Value: String); begin edFilename.Text := Value; end; procedure TSDUFilenameEdit.SetEnabled(Value: Boolean); begin inherited; SDUEnableControl(edFilename, Value); SDUEnableControl(pbBrowse, Value); end; // Change the button's caption to reflect the open/save type - but only at // design time. // This makes it easier to see what type of filename edit it is. At runtime, // the button's caption will revert to "..." procedure TSDUFilenameEdit.DesigningSummary(); begin if (csDesigning in ComponentState) then begin pbBrowse.Font.Style := [fsBold]; pbBrowse.Caption := 'O'; if (FilenameEditType = fetSave) then begin pbBrowse.Caption := 'S'; end; end; end; procedure TSDUFilenameEdit.Resizing(State: TWindowState); begin inherited; DesigningSummary(); end; procedure TSDUFilenameEdit.SetFilenameEditType(Value: TSDUFilenamEditType); begin FFilenameEditType := Value; DesigningSummary(); end; procedure TSDUFilenameEdit.FrameResize(Sender: TObject); begin inherited; TweakControlsLayout(); end; end.
unit ASUP_LoaderPrintDocs_Types; interface uses IBase,Classes,SysUtils; type TESavedItem = class(Exception); Type TSavedItem = record Id:integer; Kod:string; Text:string; end; Type TIndexSavedItem = 0..5; Type TSavedItems = class protected PArraySavedItems : array[1..5] of TSavedItem; PCount:TIndexSavedItem; private function GetSavedItem(Index:TIndexSavedItem):TSavedItem; public constructor Create;reintroduce; procedure AddSavedItem(ASavedItem:TSavedItem);overload; procedure AddSavedItem(ASavedItem:string);overload; function IndexByKodAndText(KodAndText:String):TIndexSavedItem; function IndexById(Id:Integer):TIndexSavedItem; property SavedItem[Index: TIndexSavedItem]:TSavedItem read GetSavedItem; property Count:TIndexSavedItem read PCount; end; Type TSavedItemsForSave = class(TSavedItems) public procedure AddSavedItem(ASavedItem:string);reintroduce; function StringForSave:String; end; Type TSimpleParam = class(TObject) public DB_Handle:TISC_DB_HANDLE; Owner:TComponent; end; Type TSimpleParamWithType = class(TSimpleParam) public IdType:Variant; end; implementation //********************* TSavedItems *********************************// constructor TSavedItems.Create; begin inherited Create; PCount:=0; end; function TSavedItems.IndexById(Id:Integer):TIndexSavedItem; var i:TIndexSavedItem; begin for i:=1 to PCount do if PArraySavedItems[i].Id=Id then begin Result:=i; Exit; end; Result:=0; end; function TSavedItems.IndexByKodAndText(KodAndText:String):TIndexSavedItem; var i:TIndexSavedItem; begin for i:=1 to PCount do if Trim(PArraySavedItems[i].Kod+' - '+PArraySavedItems[i].Text)=Trim(KodAndText) then begin Result:=i; Exit; end; Result:=0; end; procedure TSavedItems.AddSavedItem(ASavedItem:String); var PSavedItem:TSavedItem; Str:String; PStrSaveItem:string; begin PStrSaveItem:= ASavedItem; Str:=copy(PStrSaveItem,1,pos('%',PStrSaveItem)-1); if Str='' then raise TESavedItem.Create('Id not found!'); PSavedItem.Id:=StrToInt(Str); delete(PStrSaveItem,1,pos('%',PStrSaveItem)); Str:=copy(PStrSaveItem,1,pos('%',PStrSaveItem)-1); PSavedItem.Kod:=Str; delete(PStrSaveItem,1,pos('%',PStrSaveItem)); PSavedItem.Text:=PStrSaveItem; AddSavedItem(PSavedItem); end; procedure TSavedItems.AddSavedItem(ASavedItem:TSavedItem); var i:integer; begin for i:=High(TIndexSavedItem) downto 2 do PArraySavedItems[i]:=PArraySavedItems[i-1]; PArraySavedItems[1]:=ASavedItem; if PCount<>5 then Inc(PCount); end; function TSavedItems.GetSavedItem(Index: TIndexSavedItem):TSavedItem; begin Result:=PArraySavedItems[Index]; end; //********************* TSavedItemsForSave *********************************// procedure TSavedItemsForSave.AddSavedItem(ASavedItem:string); var PSavedItem:TSavedItem; Str:String; PStrSaveItem:string; i,index:TIndexSavedItem; begin PStrSaveItem:= ASavedItem; Str:=copy(PStrSaveItem,1,pos('%',PStrSaveItem)-1); if Str='' then raise TESavedItem.Create('Id not found!'); PSavedItem.Id:=StrToInt(Str); delete(PStrSaveItem,1,pos('%',PStrSaveItem)); Str:=copy(PStrSaveItem,1,pos('%',PStrSaveItem)-1); PSavedItem.Kod:=Str; delete(PStrSaveItem,1,pos('%',PStrSaveItem)); PSavedItem.Text:=PStrSaveItem; index := IndexById(PSavedItem.Id); if index<>0 then begin for i:=index to High(TIndexSavedItem)-1 do PArraySavedItems[i]:=PArraySavedItems[i+1]; dec(PCount); end; inherited AddSavedItem(PSavedItem); end; function TSavedItemsForSave.StringForSave:String; var i:TIndexSavedItem; begin for i:=1 to PCount do if Result<>'' then Result:=Result+'@@@'+IntToStr(PArraySavedItems[i].Id)+'%'+PArraySavedItems[i].Kod+'%'+PArraySavedItems[i].Text else Result:= IntToStr(PArraySavedItems[i].Id)+'%'+PArraySavedItems[i].Kod+'%'+PArraySavedItems[i].Text; end; end.
unit RadioButtonAll; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, stdctrls, SuperComboADO; type TRadioButtonAll = class(TRadioButton) private { Private declarations } FLinkedSuperCombo : TSuperComboADO; FTextAll : String; protected { Protected declarations } procedure Click; override; constructor Create( AOwner: TComponent ); override; public { Public declarations } published { Published declarations } property TextAll : String read FTextAll write FTextAll; property LinkedSuperCombo : TSuperComboADO read FLinkedSuperCombo write FLinkedSuperCombo; end; procedure Register; implementation uses PowerParam; constructor TRadioButtonAll.Create( AOwner: TComponent ); begin inherited Create( AOwner); if Language = laPortuguese then FTextAll := '<Todos>' else FTextAll := '<ALL>'; end; procedure TRadioButtonAll.Click; begin if Checked then begin // Seta o SuperCombo associado para <ALL> e LookUpValue = '' if Assigned(LinkedSuperCombo) then begin with LinkedSuperCombo do begin LookUpValue := ''; Text := FTextAll; end; end; end; inherited Click; end; procedure Register; begin RegisterComponents('NewPower', [TRadioButtonAll]); end; end.
unit translation; {$mode objfpc}{$H+} interface uses Classes, SysUtils; resourcestring //Master form rs0001 = 'TimeOut reading from slot: %s'; rs0002 = 'Error Reading lines from slot: %s'; rs0003 = 'Receiving headers'; rs0004 = 'Error Receiving headers from %s (%s)'; rs0005 = 'Headers file received: %s'; rs0006 = 'Receiving blocks'; rs0007 = 'Error Receiving blocks from %s (%s)'; rs0008 = 'Error sending outgoing message: %s'; rs0009 = 'ERROR: Deleting OutGoingMessage-> %s'; rs0010 = 'Auto restart enabled'; rs0011 = 'BAT file created'; rs0012 = 'Crash info file created'; rs0013 = 'Data restart file created'; rs0014 = 'All forms closed'; rs0015 = 'Outgoing connections closed'; rs0016 = 'Node server closed'; rs0017 = 'Closing pool server...'; rs0018 = 'Pool server closed'; rs0019 = 'Pool members file saved'; rs0020 = 'Noso launcher executed'; rs0021 = 'Blocks received up to %s'; rs0022 = '✓ Data directory ok'; rs0023 = '✓ GUI initialized'; rs0024 = '✓ My data updated'; rs0025 = '✓ Miner configuration set'; rs0026 = '✓ %s languages available'; rs0027 = 'Node %s%s'; rs0028 = '✓ %s CPUs found'; rs0029 = 'Noso session started'; rs0030 = 'Closing wallet'; rs0031 = 'POOL: Error trying close a pool client connection (%s)'; rs0032 = 'POOL: Error sending message to miner (%s)'; rs0033 = 'POOL: Rejected not registered user'; rs0034 = 'Pool: Error registering a ping-> %s'; rs0035 = 'Pool solution verified!'; rs0036 = 'Pool solution FAILED at step %s'; rs0038 = 'POOL: Unexpected command from: %s -> %s'; rs0039 = 'POOL: Status requested from %s'; rs0040 = 'Pool: closed incoming %s (%s)'; rs0041 = 'Pool: Error inside MinerJoin (%s) -> %s'; rs0042 = 'SERVER: Error trying close a server client connection (%s)'; rs0043 = 'SERVER: Received a line from a client without and assigned slot: %s'; rs0044 = 'SERVER: Timeout reading line from connection'; rs0045 = 'SERVER: Can not read line from connection %s (%s)'; rs0046 = 'SERVER: Server error receiving headers file (%s)'; rs0047 = 'Headers file received: %s'; rs0048 = 'SERVER: Server error receiving block file (%s)'; rs0049 = 'SERVER: Error creating stream from headers: %s'; rs0050 = 'Headers file sent to: %s'; rs0051 = 'SERVER: Error sending headers file (%s)'; rs0052 = 'SERVER: BlockZip send to %s: %s'; rs0053 = 'SERVER: Error sending ZIP blocks file (%s)'; rs0054 = 'SERVER: Error adding received line (%s)'; rs0055 = 'SERVER: Got unexpected line: %s'; rs0056 = 'SERVER: Timeout reading line from new connection'; rs0057 = 'SERVER: Can not read line from new connection (%s)'; rs0058 = 'SERVER: Invalid client -> %s'; rs0059 = 'SERVER: Own connected'; rs0060 = 'SERVER: Duplicated connection -> %s'; rs0061 = 'New Connection from: %s'; rs0062 = 'SERVER: Closed unhandled incoming connection -> %s'; rs0063 = 'Stake size'; rs0064 = 'MNs earnings'; rs0065 = 'PoS earnings'; rs0066 = 'Rebuilding my transactions...'; rs0067 = '✓ My transactions rebuilded'; rs0068 = '✓ My transactions grid updated'; rs0069 = '✓ Launcher file deleted'; rs0070 = '✓ Restart file deleted'; rs0071 = 'Checking last release available...'; rs0072 = '✗ Failed connecting with project repo'; rs0073 = '✓ Running last release version'; rs0074 = '✗ New version available on project repo'; rs0075 = '✓ Running a development version'; rs0076 = 'Start server'; rs0077 = 'Stop server'; rs0078 = 'Connect'; rs0079 = 'Disconnect'; rs0080 = 'You can not test while server is active'; rs0081 = 'Invalid sign address'; rs0082 = 'Funds address do not owns enough coins'; rs0083 = 'You need update the wallet'; rs0084 = 'Not valid ASCII message received: %s'; rs0085 = 'Receiving summary file'; rs0086 = 'Error Receiving sumary from %s (%s)'; rs0087 = 'Sumary file received: %s'; rs0088 = '✓ My GVTs grid updated'; rs0089 = 'Receiving GVTs file'; rs0090 = 'Error Receiving GVTs from %s (%s)'; rs0091 = 'SERVER: Error creating stream from GVTs: %s'; //mpGUI rs0500 = 'Noso Launcher'; rs0501 = 'Destination'; rs0502 = 'Amount'; rs0503 = 'Reference'; rs0505 = 'Server'; rs0506 = 'Connections'; rs0507 = 'Headers'; rs0508 = 'Summary'; rs0509 = 'LastBlock'; rs0510 = 'Blocks'; rs0511 = 'Pending'; rs0512 = 'Invalid language: %s'; rs0513 = 'Wallet restart needed'; rs0514 = 'Address'; rs0515 = 'Balance'; rs0516 = 'Masternodes: (%d) %s'; rs0517 = '(%d) %d/%s'; //mpDisk rs1000 = 'Processing block %d (%d %%)'; rs1001 = '----- ERROR ----'+Slinebreak+'Block: %d'; rs1002 = 'Wrong block hash'+SlineBreak+'File: %s'+Slinebreak+'Headers: %s'; rs1003 = 'File not found: %s'; rs1004 = 'Wrong summary hash'+SlineBreak+'Summary: %s'+Slinebreak+'Headers: %s'; //mpParser rs1501 = 'Invalid address'; rs1502 = 'You can not do it while pool is active.'; rs1503 = 'Totals: %d connections, %d IPs'; rs1504 = 'Address do not exists in wallet.'; rs1505 = 'Keys pasted to clipboard.'; //mpred rs2000 = 'Sign address not valid'; rs2001 = 'Wallet not updated'; rs2002 = '*****CRITICAL*****'+Slinebreak+'Error inside VerifyConnectionStatus'+Slinebreak+'%s'+'*****CRITICAL*****'; rs2003 = 'Sumary file requested'; //mpcrypto rs2501 = '*****CRITICAL*****'+Slinebreak+'Error type 3 on crypto thread: %s'+Slinebreak+'*****CRITICAL*****'; rs2502 = '*****CRITICAL*****'+Slinebreak+'Error type 4 on crypto thread: %s'+Slinebreak+'*****CRITICAL*****'; rs2503 = '*****CRITICAL*****'+Slinebreak+'Error type 5 on crypto thread: %s'+Slinebreak+'*****CRITICAL*****'; rs2504 = '*****CRITICAL*****'+Slinebreak+'Error type 6 on crypto thread: %s'+Slinebreak+'*****CRITICAL*****'; rs2505 = '*****CRITICAL*****'+Slinebreak+'Error type 7 on crypto thread: %s'+Slinebreak+'*****CRITICAL*****'; { ConsoleLinesadd(format(rs,[])); } implementation END.
unit uProgramStatInfo; interface uses System.Classes, System.SysUtils, System.Math, uMemory, uSettings; const cStatisticsRegistryKey = 'Stat'; type TProgramStatInfo = class(TObject) private procedure UpdateProperty(PropertyAlias: string); public procedure ProgramStarted; //S procedure ProgramStartedDefault; //D procedure ProgramStartedViewer; //V procedure ImportUsed; //I procedure ShareUsed; //SH procedure GeoInfoReadUsed; //GR procedure GeoInfoSaveUsed; //GW procedure EncryptionImageUsed; //EI procedure DecryptionImageUsed; //DI procedure EncryptionFileUsed; //EF procedure DecryptionFileUsed; //DF procedure StegoUsed; //ST procedure DeStegoUsed; //DST procedure SearchDatabaseUsed; //SD procedure SearchImagesUsed; //SI procedure SearchFilesUsed; //SF procedure EditorUsed; //E procedure PrinterUsed; //P procedure FaceDetectionUsed; //F procedure ConverterUsed; //C procedure ShelfUsed; //SHE procedure PropertiesUsed; //PRO procedure ActionsUsed; //ACT procedure Image3dUsed; //DD procedure StyleUsed; //STY procedure PersonUsed; //PO procedure GroupUsed; //GO procedure PortableUsed; //PV procedure DBUsed; //DB procedure DuplicatesCleanUpUsed; //DC procedure PropertyLinksUsed; //PRL procedure MassRenameUsed; //RM procedure CDExportUsed; //CDE procedure CDMappingUsed; //CDM procedure QuickLinksUsed; //QL procedure WatermarkImageUsed; //WI procedure WatermarkTextUsed; //WT procedure FastShareUsed; //FS procedure OpenWithLinksUsed; //OW procedure CompactCollectionUsed; //CC function ToString: string; override; end; function ProgramStatistics: TProgramStatInfo; implementation var FProgramStatistics: TProgramStatInfo = nil; function ProgramStatistics: TProgramStatInfo; begin if FProgramStatistics = nil then FProgramStatistics := TProgramStatInfo.Create; Result := FProgramStatistics; end; { TFeatureStatInfo } procedure TProgramStatInfo.ActionsUsed; begin UpdateProperty('ACT'); end; procedure TProgramStatInfo.CDExportUsed; begin UpdateProperty('CDE'); end; procedure TProgramStatInfo.CDMappingUsed; begin UpdateProperty('CDM'); end; procedure TProgramStatInfo.CompactCollectionUsed; begin UpdateProperty('CC'); end; procedure TProgramStatInfo.ConverterUsed; begin UpdateProperty('C'); end; procedure TProgramStatInfo.DBUsed; begin UpdateProperty('DB'); end; procedure TProgramStatInfo.DecryptionFileUsed; begin UpdateProperty('DF'); end; procedure TProgramStatInfo.DecryptionImageUsed; begin UpdateProperty('DI'); end; procedure TProgramStatInfo.DeStegoUsed; begin UpdateProperty('DST'); end; procedure TProgramStatInfo.DuplicatesCleanUpUsed; begin UpdateProperty('DC'); end; procedure TProgramStatInfo.EditorUsed; begin UpdateProperty('E'); end; procedure TProgramStatInfo.EncryptionFileUsed; begin UpdateProperty('EF'); end; procedure TProgramStatInfo.EncryptionImageUsed; begin UpdateProperty('EI'); end; procedure TProgramStatInfo.FaceDetectionUsed; begin UpdateProperty('F'); end; procedure TProgramStatInfo.FastShareUsed; begin UpdateProperty('FS'); end; procedure TProgramStatInfo.GeoInfoReadUsed; begin UpdateProperty('GR'); end; procedure TProgramStatInfo.GeoInfoSaveUsed; begin UpdateProperty('GW'); end; procedure TProgramStatInfo.GroupUsed; begin UpdateProperty('GO'); end; procedure TProgramStatInfo.Image3dUsed; begin UpdateProperty('DD'); end; procedure TProgramStatInfo.ImportUsed; begin UpdateProperty('I'); end; procedure TProgramStatInfo.MassRenameUsed; begin UpdateProperty('RM'); end; procedure TProgramStatInfo.OpenWithLinksUsed; begin UpdateProperty('OW'); end; procedure TProgramStatInfo.PersonUsed; begin UpdateProperty('PO'); end; procedure TProgramStatInfo.PortableUsed; begin UpdateProperty('PV'); end; procedure TProgramStatInfo.PrinterUsed; begin UpdateProperty('P'); end; procedure TProgramStatInfo.ProgramStarted; begin UpdateProperty('S'); end; procedure TProgramStatInfo.ProgramStartedDefault; begin UpdateProperty('D'); end; procedure TProgramStatInfo.ProgramStartedViewer; begin UpdateProperty('V'); end; procedure TProgramStatInfo.PropertiesUsed; begin UpdateProperty('PRO'); end; procedure TProgramStatInfo.PropertyLinksUsed; begin UpdateProperty('PRL'); end; procedure TProgramStatInfo.QuickLinksUsed; begin UpdateProperty('QL'); end; procedure TProgramStatInfo.SearchDatabaseUsed; begin UpdateProperty('SD'); end; procedure TProgramStatInfo.SearchFilesUsed; begin UpdateProperty('SF'); end; procedure TProgramStatInfo.SearchImagesUsed; begin UpdateProperty('SI'); end; procedure TProgramStatInfo.ShareUsed; begin UpdateProperty('SH'); end; procedure TProgramStatInfo.ShelfUsed; begin UpdateProperty('SHE'); end; procedure TProgramStatInfo.StegoUsed; begin UpdateProperty('ST'); end; procedure TProgramStatInfo.StyleUsed; begin UpdateProperty('STY'); end; procedure TProgramStatInfo.WatermarkImageUsed; begin UpdateProperty('WI'); end; procedure TProgramStatInfo.WatermarkTextUsed; begin UpdateProperty('WT'); end; function ProcessCount(I: Integer): Integer; begin Result := Round(System.Math.Log2(I + 1)); end; function TProgramStatInfo.ToString: string; var Info: TStrings; Key: string; Value: Integer; begin //format: PROPNAME1(COUNT)PROPNAME2(COUNT) Info := AppSettings.ReadValues(cStatisticsRegistryKey); try Result := ''; for Key in Info do begin Value := AppSettings.ReadInteger(cStatisticsRegistryKey, Key, 0); if Value > 0 then begin Value := ProcessCount(Value); Result := Result + Key + IntToStr(Value); end; end; finally F(Info); end; end; procedure TProgramStatInfo.UpdateProperty(PropertyAlias: string); begin try AppSettings.IncrementInteger(cStatisticsRegistryKey, PropertyAlias); except //this is OK, this methoud should never affect program flow end; end; initialization finalization F(FProgramStatistics); end.
unit OpenSSL.HashUtilsTests; interface uses TestFramework, OpenSSL.Api_11, OpenSSL.HashUtils, System.SysUtils, System.Classes, OpenSSL.Core; type THashUtilTest = class(TTestCase) strict private FHashUtil: THashUtil; private procedure TestResult(const AIn, AOut: string); public procedure SetUp; override; procedure TearDown; override; published procedure TestMD4; procedure TestMD5; procedure TestSHA1; procedure TestSHA256; procedure TestSHA512; end; implementation const defTestData: string = 'https://zh-google-styleguide.readthedocs.io/en/latest/google-cpp-styleguide/contents/'; { THashUtilTest } procedure THashUtilTest.SetUp; begin inherited; FHashUtil := nil; end; procedure THashUtilTest.TearDown; begin inherited; FreeAndNil(FHashUtil); end; procedure THashUtilTest.TestMD4; begin FHashUtil := TMD4.Create; TestResult(defTestData, '6a42d290939305608ac610a57e8fd02c'); end; procedure THashUtilTest.TestMD5; begin FHashUtil := TMD5.Create; TestResult(defTestData, 'ba317f28c5430abc9023aadcee41dc2f'); end; procedure THashUtilTest.TestResult(const AIn, AOut: string); var InData, OutData: TBytes; S: string; begin InData := TEncoding.UTF8.GetBytes(AIn); FHashUtil.Init; FHashUtil.Update(Pointer(InData), Length(InData)); FHashUtil.Final(OutData); S := BytesToHex(OutData, True); CheckEquals(AOut, S); end; procedure THashUtilTest.TestSHA1; begin FHashUtil := TSHA1.Create; TestResult(defTestData, 'd300a933f34f921e7fbf560b5c89200002e1867d'); end; procedure THashUtilTest.TestSHA256; begin FHashUtil := TSHA256.Create; TestResult(defTestData, '72be0554c0e39ac9a8eca93c084a441c21e4abdaf055195026544c99b97c7e6a'); end; procedure THashUtilTest.TestSHA512; begin FHashUtil := TSHA512.Create; TestResult(defTestData, 'd7091dd17a10263572a561d1cf99f174e365bc8bbb515d10b0b678709dc2712bd843480be20215dee5e7c086c4406c4d4f2bb52d67eadf91013083025c448df4'); end; initialization // Register any test cases with the test runner RegisterTest(THashUtilTest.Suite); end.
(* Category: SWAG Title: TEXT FILE MANAGEMENT ROUTINES Original name: 0046.PAS Description: Text File Paginator Author: DAVID DANIEL ANDERSON Date: 02-28-95 10:04 *) PROGRAM PaginateTextFiles; CONST ProgData = 'PAGINATE- Free DOS utility: text file paginator.'; ProgDat2 = 'V1.00: July 14, 1993. (c) 1993 by David Daniel Anderson - Reign Ware.'; Usage = 'Usage: PAGINATE /i<infile> /o<outfile> /l##[:##] (lines per odd/even page)'; Example = 'Example: PAGINATE /iNOTPAGED.TXT /oPAGED.TXT /l55'; VAR IFL, OFL, LPP : String[80]; InFile, OutFile : Text; OddL,EvenL : Word; PROCEDURE InValidParms( ErrCode : Word ); VAR Message : String[80]; BEGIN WriteLn(Usage); WriteLn(Example); CASE ErrCode OF 1 : Message := 'Incorrect number of parameters on command line.'; 2 : Message := 'Invalid switch on command line.'; 3 : Message := 'Cannot open input file '+ IFL + '.'; 4 : Message := 'Cannot open NEW output file '+ OFL + '.'; 5 : Message := 'Non-numeric '+ LPP + ' specified for lines per page.'; ELSE Message := 'Unknown error.'; END; Writeln(Message); Halt; END; PROCEDURE ParseComLine; CONST Bad = ''; {An invalid filename character & invalid integer.} VAR SwStr : String[1]; SwChar : Char; ic : Byte; ArgText : String[80]; BEGIN IF ParamCount <> 3 THEN InValidParms(1); IFL := Bad; OFL := Bad; LPP := Bad; FOR ic := 1 to 3 DO BEGIN SwStr := Copy(ParamStr(ic),1,1); SwChar := UpCase(SwStr[1]); IF (SwChar <> '/') THEN InValidParms(2); SwStr := Copy(ParamStr(ic),2,1); SwChar := UpCase(SwStr[1]); ArgText := Copy(ParamStr(ic),3,(Length(ParamStr(ic))-2)); CASE SwChar OF 'I' : IFL := ArgText; 'O' : OFL := ArgText; 'L' : LPP := ArgText; END; END; END; PROCEDURE Open_I_O_Files; BEGIN Assign(InFile,IFL); {$I-} Reset(InFile); {$I+} IF IOResult <> 0 THEN InValidParms(3); Assign(OutFile,OFL); {$I-} Rewrite(OutFile); {$I+} IF IOResult <> 0 THEN InValidParms(4); END; PROCEDURE GetEvenOdd ( lpp_param : string; var oddnum, evennum : Word); { determine page length for odd/ even pages } VAR odds, evens, { string of odd/ even lines per page } lstr : string[5]; { entire string containing numbers needed } vlppo,vlppe, { numeric of lines per page odd/even } lval : byte; { numeric of string containing numbers needed } pcode : integer; { error code, will be non-zero if strings are not numbers } BEGIN lstr := lpp_param; IF ((pos(':',lstr)) <> 0) THEN BEGIN { determine position of } odds := copy(lstr,1,((pos(':',lstr))-1)); { any colon, and divide } evens := copy(lstr,((pos(':',lstr))+1),length(lstr)); { at that point } val(odds,vlppo,pcode); { convert first part of string } IF (pcode <> 0) THEN { into numeric } InValidParms(5); { show help if any errors } val(evens,vlppe,pcode); { convert first part of string } IF (pcode <> 0) THEN { into numeric } InValidParms(5); { show help if any errors } END ELSE BEGIN { if colon not present, lines/pg should be entire parameter } val(lstr,lval,pcode); { convert entire of string } IF (pcode <> 0) THEN { into numeric } InValidParms(5); { show help if any errors } vlppo := lval; vlppe := lval; END; oddnum := vlppo; evennum := vlppe; END; PROCEDURE InsertFF( OddLines, EvenLines : Word); CONST FF = ' '; VAR LinesCopied, LinesPerPage, PageCopying : Word; ALine : String; BEGIN LinesCopied := 0; LinesPerPage := OddLines; PageCopying := 1; WHILE (NOT Eof(InFile)) DO BEGIN ReadLn(InFile,ALine); IF (LinesCopied = LinesPerPage) THEN BEGIN ALine := FF + ALine; LinesCopied := 0; PageCopying := Succ(PageCopying); IF ((PageCopying MOD 2) = 0) THEN LinesPerPage := EvenLines ELSE LinesPerPage := OddLines; END; WriteLn(OutFile,ALine); LinesCopied := Succ(LinesCopied); END; END; BEGIN { main } Writeln(ProgData); Writeln(ProgDat2); Writeln; ParseComLine; Open_I_O_Files; GetEvenOdd(LPP,OddL,EvenL); Writeln('Input file: ',IFL,' - Output file: ',OFL,'.'); Writeln('Lines per odd / even page: ',Oddl,' / ',EvenL,'.'); InsertFF(OddL,EvenL); Close(InFile); Close(OutFile); Writeln('Done!'); END.
unit M_regist; interface uses WinTypes, WinProcs, Classes, Graphics, Forms, Controls, Buttons, StdCtrls, M_Global, Dialogs; type TRegisterWindow = class(TForm) OKBtn: TBitBtn; CancelBtn: TBitBtn; Memo1: TMemo; Label1: TLabel; Label15: TLabel; EDEmail: TEdit; EDName: TEdit; Label2: TLabel; EDReg: TEdit; LabelINFO: TLabel; procedure OKBtnClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var RegisterWindow: TRegisterWindow; implementation uses Mapper; {$R *.DFM} procedure TRegisterWindow.OKBtnClick(Sender: TObject); begin USERname := EDName.Text; USERemail := EDEmail.Text; USERreg := EDReg.Text; Ini.WriteString('REGISTRATION', 'Name', USERname); Ini.WriteString('REGISTRATION', 'email', USERemail); Ini.WriteString('REGISTRATION', 'Reg', USERreg); if IsRegistered then begin Application.MessageBox('Registration Accepted. Thanks again !', 'WDFUSE - Register Dialog', mb_Ok or mb_IconInformation); RegisterWindow.ModalResult := mrOk; end else begin Application.MessageBox('Invalid Registration #', 'WDFUSE - Register Dialog', mb_Ok or mb_IconExclamation); end; end; end.
(* Category: SWAG Title: POINTERS, LINKING, LISTS, TREES Original name: 0014.PAS Description: Linked List of Text Author: KEN BURROWS Date: 02-03-94 16:08 *) { From: KEN BURROWS Subj: Linked List Problem --------------------------------------------------------------------------- Here is a short Linked List example. It loads a file, and lets you traverse the list in two directions. It's as simple as it gets. You may also want to look into the TCollection objects associated with the Objects unit of Borlands version 6 and 7. } Program LinkedListOfText; {tested} Uses Dos,CRT; Type TextListPtr = ^TextList; TextList = Record line : string; next, prev : TextListPtr; end; Const first : TextListPtr = nil; last : TextListPtr = nil; Procedure FreeTheList(p:TextListPtr); var hold:TextListPtr; begin while p <> Nil do begin hold := p; p := p^.next; dispose(hold); end; end; Procedure ViewForward(p:TextListPtr); begin clrscr; while p <> nil do begin writeln(p^.line); p := p^.next; end; end; Procedure ViewReverse(p:TextListPtr); begin clrscr; while p <> nil do begin writeln(p^.line); p := p^.prev; end; end; Procedure Doit(fname:string); var f :Text; s :string; curr, hold : TextListPtr; stop : boolean; begin assign(f,fname); reset(f); if ioresult <> 0 then exit; curr := nil; hold := nil; while (not eof(f)) {and (maxavail > SizeOf(TextList))} do begin {load the list forward and link the prev fields} readln(f,s); new(curr); curr^.prev := hold; curr^.next := nil; curr^.line := s; hold := curr; end; close(f); while curr^.prev <> nil do {traverse the list backwards} begin {and link the next fields} hold := curr; curr := curr^.prev; curr^.next := hold; end; first := curr; {set the first and last records} while curr^.next <> Nil do curr := curr^.next; last := curr; Repeat {test it} clrscr; writeln(' [F]orward view : '); writeln(' [R]everse view : '); writeln(' [S]top : '); write('enter a command : '); readln(s); stop := (s = '') or (upcase(s[1]) = 'S'); if not stop then case upcase(s[1]) of 'F' : ViewForward(first); 'R' : ViewReverse(last); end; Until Stop; FreeTheList(First); end; {var m:longint;} Begin if paramcount > 0 then doit(paramstr(1)) else writeln('you need to supply a filename'); End.
unit Dmitry.Graphics.LayeredBitmap; interface uses System.Classes, System.SysUtils, System.Math, Winapi.Windows, Winapi.CommCtrl, Vcl.Controls, Vcl.Graphics, Vcl.ImgList, Dmitry.Memory, Dmitry.Graphics.Types; type TLayeredBitmap = class(TBitmap) private FIsLayered: Boolean; FHightliteArray: array[0..255] of Byte; procedure SetIsLayered(const Value: Boolean); public constructor Create; override; destructor Destroy; override; procedure LoadFromBitmap(Bitmap: TBitmap); procedure InvertLayeredChannel; procedure SaveToBitmap(Bitmap: TBitmap); procedure LoadLayered(Bitmap: TBitmap; Mode: Integer); procedure DoDraw(X, Y: Integer; Bitmap: TBitmap; IsHightLite: Boolean = False); procedure DoDrawGrayscale(X, Y: Integer; Bitmap: TBitmap); procedure DoLayeredDraw(X, Y: Integer; Layered: Byte; Bitmap: TBitmap); procedure DoStreachDraw(X, Y, NewWidth, NewHeight: Integer; Bitmap: TBitmap); procedure DoStreachDrawGrayscale(X, Y, Newwidth, Newheight: Integer; Bitmap: TBitmap); procedure LoadFromHIcon(Icon: HIcon; FWidth: Integer = 0; FHeight: Integer = 0; Background: TColor = clBlack); procedure Load(Image: TLayeredBitmap); procedure GrayScale; property IsLayered: Boolean read FIsLayered write SetIsLayered; end; implementation constructor TLayeredBitmap.Create; var I: Integer; begin inherited; FIsLayered := False; PixelFormat := pf32Bit; for I := 0 to 255 do FHightliteArray[I] := Round(255 * Power(I / 255, 0.8)); end; destructor TLayeredBitmap.Destroy; begin inherited; end; procedure TLayeredBitmap.DoDraw(X, Y: Integer; Bitmap: TBitmap; IsHightLite: Boolean = False); var I, J, H, W, X1: Integer; BeginY, EndY, BeginX, EndX: Integer; PD: PARGB; PS: PARGB32; CL, LI: Integer; R, G, B: Byte; begin HandleNeeded; Bitmap.PixelFormat := pf24bit; H := Bitmap.Height; W := Bitmap.Width; BeginX := Max(0, X); BeginY := Max(0, Y); EndX := Min(W, X + Width) - 1; EndY := Min(H, Y + Height) - 1; for I := BeginY to EndY do begin PD := Bitmap.ScanLine[I]; PS := Scanline[I - Y]; if IsHightLite and FIsLayered then begin for J := BeginX to EndX do begin X1 := J - X; R := PS[X1].R; G := PS[X1].G; B := PS[X1].B; R := FHightliteArray[R]; G := FHightliteArray[G]; B := FHightliteArray[B]; CL := PS[X1].L; LI := 255 - CL; PD[J].R := (PD[J].R * LI + R * CL + 127) div 255; PD[J].G := (PD[J].G * LI + G * CL + 127) div 255; PD[J].B := (PD[J].B * LI + B * CL + 127) div 255; end; end else if IsHightLite and not FIsLayered then begin for J := BeginX to EndX do begin X1 := J - X; R := PS[X1].R; G := PS[X1].G; B := PS[X1].B; R := FHightliteArray[R]; G := FHightliteArray[G]; B := FHightliteArray[B]; PD[J].R := R; PD[J].G := G; PD[J].B := B; end; end else if not IsHightLite and FIsLayered then begin for J := BeginX to EndX do begin X1 := J - X; R := PS[X1].R; G := PS[X1].G; B := PS[X1].B; CL := PS[X1].L; LI := 255 - CL; PD[J].R := (PD[J].R * LI + R * CL + 127) div 255; PD[J].G := (PD[J].G * LI + G * CL + 127) div 255; PD[J].B := (PD[J].B * LI + B * CL + 127) div 255; end; end else begin for J := BeginX to EndX do begin X1 := J - X; R := PS[X1].R; G := PS[X1].G; B := PS[X1].B; PD[J].R := R; PD[J].G := G; PD[J].B := B; end; end; end; end; procedure TLayeredBitmap.DoDrawGrayscale(X, Y: Integer; Bitmap: TBitmap); var I, J, H, W, X1: Integer; BeginY, EndY, BeginX, EndX: Integer; PD: PARGB; PS: PARGB32; C, CL, LI: Integer; begin HandleNeeded; Bitmap.PixelFormat := pf24bit; H := Bitmap.Height; W := Bitmap.Width; BeginX := Max(0, X); BeginY := Max(0, Y); EndX := Min(W, X + Width) - 1; EndY := Min(H, Y + Height) - 1; for I := BeginY to EndY do begin PD := Bitmap.ScanLine[I]; PS := Scanline[I - Y]; if FIsLayered then begin for J := BeginX to EndX do begin X1 := J - X; CL := PS[X1].L; LI := 255 - CL; C := (PS[X1].R * 77 + PS[X1].G * 151 + PS[X1].B * 28) shr 8; PD[J].R := (PD[J].R * LI + C * CL + 127) div 255; PD[J].G := (PD[J].G * LI + C * CL + 127) div 255; PD[J].B := (PD[J].B * LI + C * CL + 127) div 255; end; end else begin for J := BeginX to EndX do begin X1 := J - X; PD[J].R := PS[X1].R; PD[J].G := PS[X1].G; PD[J].B := PS[X1].B; end; end; end; end; procedure TLayeredBitmap.DoLayeredDraw(X, Y: Integer; Layered: Byte; Bitmap: TBitmap); var I, J, H, W, X1: Integer; BeginY, EndY, BeginX, EndX: Integer; PD: PARGB; PS: PARGB32; CL, LI: Integer; begin HandleNeeded; Bitmap.PixelFormat := pf24bit; H := Bitmap.Height; W := Bitmap.Width; BeginX := Max(0, X); BeginY := Max(0, Y); EndX := Min(W, X + Width) - 1; EndY := Min(H, Y + Height) - 1; for I := BeginY to EndY do begin PD := Bitmap.ScanLine[I]; PS := Scanline[I - Y]; if FIsLayered then begin for J := BeginX to EndX do begin X1 := J - X; LI := PS[X1].L * Layered div 255; CL := 255 - LI; PD[J].R := (PD[J].R * CL + PS[X1].R * LI + 127) div 255; PD[J].G := (PD[J].G * CL + PS[X1].G * LI + 127) div 255; PD[J].B := (PD[J].B * CL + PS[X1].B * LI + 127) div 255; end end else begin for J := BeginX to EndX do begin X1 := J - X; PD[J].R := PS[X1].R; PD[J].G := PS[X1].G; PD[J].B := PS[X1].B; end; end; end; end; procedure TLayeredBitmap.DoStreachDraw(X, Y, NewWidth, NewHeight: Integer; Bitmap: TBitmap); var I, J, H, W: Integer; BeginY, EndY, BeginX, EndX: Integer; PS: array of PARGB32; PD: PARGB; Ccw, Cch: Integer; ScaleX, ScaleY: Extended; Cr, Cg, Cb, Cl, Ccc: Integer; DX, DY: Integer; LI: Byte; begin if (Height = 0) or (Width = 0) then Exit; HandleNeeded; if (NewWidth = Width) and (NewHeight = Height) then begin DoDraw(X, Y, Bitmap); Exit; end; SetLength(PS, Height); for I := 0 to Height - 1 do PS[I] := ScanLine[I]; Bitmap.PixelFormat := pf24bit; H := Bitmap.Height; W := Bitmap.Width; ScaleX := NewWidth / Width; ScaleY := NewHeight / Height; if ScaleX > 1 then DX := 0 else DX := 1; if ScaleY > 1 then DY := 0 else DY := 1; BeginY := Max(0, Y); BeginX := Max(0, X); EndY := Min(H, Y + NewHeight) - 1; EndX := Min(W, X + NewWidth) - 1; for I := BeginY to EndY do begin PD := Bitmap.ScanLine[I]; for J := BeginX to EndX do begin CCC := 0; CR := 0; CG := 0; CB := 0; CL := 0; for cch := Round(((I - Y) / ScaleY)) to Min(Round(((I - Y + 1) / ScaleY)) - DY, Height - 1) do for ccw := Round(((J - X) / ScaleX)) to Min(Round(((J - X + 1) / ScaleX)) - DY, Width - 1) do begin Inc(CCC); Inc(CR, PS[cch][ccw].R); Inc(CG, PS[cch][ccw].G); Inc(CB, PS[cch][ccw].B); Inc(CL, PS[cch][ccw].L); end; if ccc = 0 then Continue; CR := CR div ccc; CG := CG div ccc; CB := CB div ccc; CL := CL div ccc; if FIsLayered then begin LI := 255 - CL; PD[J].R := (PD[J].R * LI + CR * CL + 127) div 255; PD[J].G := (PD[J].G * LI + CG * CL + 127) div 255; PD[J].B := (PD[J].B * LI + CB * CL + 127) div 255; end else begin PD[J].R := CR; PD[J].G := CG; PD[J].B := CB; end; end; end; end; procedure TLayeredBitmap.DoStreachDrawGrayscale(X, Y, NewWidth, NewHeight: integer; Bitmap: TBitmap); var I, J, H, W, C: Integer; BeginY, EndY, BeginX, EndX: Integer; PS: array of PARGB32; PD: PARGB; CCW, CCH: Integer; ScaleX, ScaleY: Extended; CR, CG, CB, CL, CCC: Integer; DX, DY: Integer; LI: Byte; begin if (Height = 0) or (Width = 0) then Exit; HandleNeeded; if (NewWidth = Width) and (NewHeight = Height) then begin DoDrawGrayscale(X, Y, Bitmap); Exit; end; SetLength(PS, Height); for I := 0 to Height - 1 do PS[I] := ScanLine[I]; Bitmap.PixelFormat := pf24bit; H := Bitmap.Height; W := Bitmap.Width; ScaleX := NewWidth / Width; ScaleY := NewHeight / Height; if ScaleX > 1 then DX := 0 else DX := 1; if ScaleY > 1 then DY := 0 else DY := 1; BeginY := Max(0, Y); BeginX := Max(0, X); EndY := Min(H, Y + NewHeight) - 1; EndX := Min(W, X + NewWidth) - 1; for I := BeginY to EndY do begin PD := Bitmap.ScanLine[I]; for J := BeginX to EndX do begin CCC := 0; CR := 0; CG := 0; CB := 0; CL := 0; for CCH := Round(((I - Y) / ScaleY)) to Min(Round(((I - X + 1) / ScaleY)) - DY, Height - 1) do for CCW := Round(((J - X) / ScaleX)) to Min(Round(((I - X + 1) / ScaleX)) - DY, Width - 1) do begin Inc(CCC); Inc(CR, PS[CCH][CCW].R); Inc(CG, PS[CCH][CCW].G); Inc(CB, PS[CCH][CCW].B); Inc(CL, PS[CCH][CCW].L); end; if CCC = 0 then Continue; CR := CR div CCC; CG := CG div CCC; CB := CB div CCC; CL := CL div CCC; C := (CR * 77 + CG * 151 + CB * 28) shr 8; if FIsLayered then begin LI := 255 - CL; PD[J].R := (PD[J].R * CL + C * LI + 127) div 255; PD[J].G := (PD[J].G * CL + C * LI + 127) div 255; PD[J].B := (PD[J].B * CL + C * LI + 127) div 255; end else begin PD[J].R := C; PD[J].G := C; PD[J].B := C; end; end; end; end; procedure TLayeredBitmap.GrayScale; var P: PARGB32; I, J, C: Integer; begin HandleNeeded; for I := 0 to Height - 1 do begin P := ScanLine[I]; for J := 0 to Width - 1 do begin C := (P[J].R * 77 + P[J].G * 151 + P[J].B * 28) shr 8; P[J].R := C; P[J].G := C; P[J].B := C; end; end; end; procedure TLayeredBitmap.InvertLayeredChannel; var P: PARGB32; I, J: Integer; begin HandleNeeded; for I := 0 to Height - 1 do begin P := ScanLine[I]; for J := 0 to Width - 1 do P[J].L := 255 - P[J].L; end; end; procedure TLayeredBitmap.Load(Image: TLayeredBitmap); var I, J: Integer; PS, PD: PARGB32; begin if Image = nil then Exit; HandleNeeded; SetSize(Image.Width, Image.Height); IsLayered := Image.IsLayered; if (Height = 0) or (Width = 0) then Exit; for I := 0 to Height - 1 do begin PS := Image.ScanLine[I]; PD := ScanLine[I]; for J := 0 to Width - 1 do PD[J] := PS[J]; end; end; procedure TLayeredBitmap.LoadFromBitmap(Bitmap: TBitmap); var I, J: Integer; PS: PARGB; PD, PS32: PARGB32; begin HandleNeeded; SetSize(Bitmap.Width, Bitmap.Height); if Bitmap.PixelFormat = pf24Bit then begin for I := 0 to Height - 1 do begin PS := Bitmap.ScanLine[I]; PD := ScanLine[I]; for J := 0 to Width - 1 do begin PD[J].R := PS[J].R; PD[J].G := PS[J].G; PD[J].B := PS[J].B; PD[J].L := 255; end; end; end else begin for I := 0 to Height - 1 do begin PS32 := Bitmap.ScanLine[I]; PD := ScanLine[I]; for J := 0 to Width - 1 do PD[J] := PS32[J]; end; end; end; procedure TLayeredBitmap.LoadFromHIcon(Icon: HIcon; FWidth: Integer = 0; FHeight: Integer = 0; Background: TColor = clBlack); var BMask1, BMask2: TBitmap; PMask1, PMask2: PARGB; PD: PARGB32; I, J: Integer; piconinfo: TIconInfo; DIB: TDIBSection; begin HandleNeeded; IsLayered := True; if FHeight = 0 then begin FWidth := 16; FHeight := 16; SetSize(FWidth, 16); end; if GetIconInfo(Icon, piconinfo) then begin try GetObject(piconinfo.hbmColor, SizeOf(DIB), @DIB); if (DIB.dsBm.bmWidth = FWidth) and (DIB.dsBm.bmHeight = FHeight) then begin Handle := piconinfo.hbmColor; MaskHandle := piconinfo.hbmMask; PixelFormat := pf32Bit; AlphaFormat := afDefined; Exit; end; finally DeleteObject(piconinfo.hbmMask); DeleteObject(piconinfo.hbmColor); end; end; BMask1 := TBitmap.Create; BMask2 := TBitmap.Create; try BMask1.PixelFormat := pf24bit; BMask1.Canvas.Brush.Color := clWhite; BMask1.Canvas.Pen.Color := clWhite; BMask2.PixelFormat := pf24bit; BMask2.Canvas.Brush.Color := clBlack; BMask2.Canvas.Pen.Color := clBlack; Canvas.Brush.Color := Background; Canvas.Pen.Color := Background; Canvas.Rectangle(0, 0, Width, Height); SetSize(FWidth, FHeight); BMask1.Width := Width; BMask1.Height := Height; BMask1.Canvas.Rectangle(0, 0, Width, Height); BMask2.Width := Width; BMask2.Height := Height; BMask2.Canvas.Rectangle(0, 0, Width, Height); DrawIconEx(Canvas.Handle, 0, 0, Icon, FWidth, FHeight, 0, 0, DI_NORMAL); DrawIconEx(BMask1.Canvas.Handle, 0, 0, Icon, FWidth, FHeight, 0, 0, DI_NORMAL); DrawIconEx(BMask2.Canvas.Handle, 0, 0, Icon, FWidth, FHeight, 0, 0, DI_NORMAL); for I := 0 to Height - 1 do begin PD := ScanLine[I]; PMask1 := BMask1.ScanLine[I]; PMask2 := BMask2.ScanLine[I]; for J := 0 to Width - 1 do PD[J].L := 255 - ((PMask1[J].R + PMask1[J].G + PMask1[J].B) div 3 - (PMask2[J].R + PMask2[J].G + PMask2[J].B) div 3); end; finally F(BMask1); F(BMask2); end; end; procedure TLayeredBitmap.LoadLayered(Bitmap: TBitmap; Mode: integer); var I, J: Integer; PD: PARGB32; PS: PARGB; begin HandleNeeded; Bitmap.PixelFormat := pf24bit; SetSize(Bitmap.Width, Bitmap.Height); for I := 0 to Height - 1 do begin PS := Bitmap.ScanLine[I]; PD := ScanLine[I]; for J := 0 to Width - 1 do PD[J].L := 255 - (PS[J].R + PS[J].G + PS[J].B) div 3; end; end; procedure TLayeredBitmap.SaveToBitmap(Bitmap: TBitmap); var I, J: Integer; PS: PARGB32; PD: PARGB; begin HandleNeeded; SetSize(Bitmap.Width, Bitmap.Height); for I := 0 to Height - 1 do begin PD := Bitmap.ScanLine[I]; PS := ScanLine[I]; for J := 0 to Width - 1 do begin PD[J].R := PS[J].R; PD[J].G := PS[J].G; PD[J].B := PS[J].B; end; end; end; procedure TLayeredBitmap.SetIsLayered(const Value: boolean); begin FIsLayered := Value; end; end.
unit uLinkListEditorUpdateDirectories; interface uses Generics.Collections, Winapi.Windows, System.SysUtils, System.Classes, System.StrUtils, Vcl.Controls, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Forms, Vcl.Graphics, Vcl.Imaging.PngImage, Dmitry.Utils.System, Dmitry.Imaging.JngImage, Dmitry.Controls.WatermarkedEdit, Dmitry.Controls.WebLink, Dmitry.PathProviders, UnitDBDeclare, uMemory, uConstants, uDBForm, uTranslate, uFormInterfaces, uResources, uShellIntegration, uCollectionUtils, uLinkListEditorFolders, uDatabaseDirectoriesUpdater, uVCLHelpers, uDBManager, uCollectionEvents, uIconUtils; type TLinkListEditorUpdateDirectories = class(TInterfacedObject, ILinkEditor) private FForm: IFormLinkItemEditorData; function L(StringToTranslate: string): string; procedure LoadIconForLink(Link: TWebLink; Path: string); procedure OnChangePlaceClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); public constructor Create; procedure SetForm(Form: IFormLinkItemEditorData); virtual; procedure CreateNewItem(Sender: ILinkItemSelectForm; var Data: TDataObject; Verb: string; Elements: TListElements); procedure CreateEditorForItem(Sender: ILinkItemSelectForm; Data: TDataObject; EditorData: IFormLinkItemEditorData); procedure UpdateItemFromEditor(Sender: ILinkItemSelectForm; Data: TDataObject; EditorData: IFormLinkItemEditorData); procedure FillActions(Sender: ILinkItemSelectForm; AddActionProc: TAddActionProcedure); function OnDelete(Sender: ILinkItemSelectForm; Data: TDataObject; Editor: TPanel): Boolean; function OnApply(Sender: ILinkItemSelectForm): Boolean; end; implementation uses uFormLinkItemSelector; const CHANGE_DIRECTORY_ICON = 1; CHANGE_DIRECTORY_EDIT = 2; CHANGE_DIRECTORY_CHANGE_PATH = 3; CHANGE_DIRECTORY_INFO = 4; { TLinkListEditorUpdateDirectories } constructor TLinkListEditorUpdateDirectories.Create(); begin end; procedure TLinkListEditorUpdateDirectories.CreateEditorForItem(Sender: ILinkItemSelectForm; Data: TDataObject; EditorData: IFormLinkItemEditorData); var DD: TDatabaseDirectory; WlIcon: TWebLink; WlChangeLocation: TWebLink; WedCaption: TWatermarkedEdit; LbInfo: TLabel; Editor: TPanel; begin Editor := EditorData.EditorPanel; DD := TDatabaseDirectory(Data); WlIcon := Editor.FindChildByTag<TWebLink>(CHANGE_DIRECTORY_ICON); WedCaption := Editor.FindChildByTag<TWatermarkedEdit>(CHANGE_DIRECTORY_EDIT); WlChangeLocation := Editor.FindChildByTag<TWebLink>(CHANGE_DIRECTORY_CHANGE_PATH); LbInfo := Editor.FindChildByTag<TLabel>(CHANGE_DIRECTORY_INFO); if WedCaption = nil then begin WedCaption := TWatermarkedEdit.Create(Editor); WedCaption.Parent := Editor; WedCaption.Tag := CHANGE_DIRECTORY_EDIT; WedCaption.Top := 8; WedCaption.Left := 35; WedCaption.Width := 200; WedCaption.OnKeyDown := FormKeyDown; end; if WlIcon = nil then begin WlIcon := TWebLink.Create(Editor); WlIcon.Parent := Editor; WlIcon.Tag := CHANGE_DIRECTORY_ICON; WlIcon.Width := 16; WlIcon.Height := 16; WlIcon.Left := 8; WlIcon.Top := 8 + WedCaption.Height div 2 - WlIcon.Height div 2; WlIcon.CanClick := False; end; if WlChangeLocation = nil then begin WlChangeLocation := TWebLink.Create(Editor); WlChangeLocation.Parent := Editor; WlChangeLocation.Tag := CHANGE_DIRECTORY_CHANGE_PATH; WlChangeLocation.Height := 26; WlChangeLocation.Text := L('Change location'); WlChangeLocation.RefreshBuffer(True); WlChangeLocation.Top := 8 + WedCaption.Height div 2 - WlChangeLocation.Height div 2; WlChangeLocation.Left := 240; WlChangeLocation.LoadFromResource('NAVIGATE'); WlChangeLocation.OnClick := OnChangePlaceClick; end; if LbInfo = nil then begin LbInfo := TLabel.Create(Editor); LbInfo.Parent := Editor; LbInfo.Tag := CHANGE_DIRECTORY_INFO; LbInfo.Left := 35; LbInfo.Top := 35; end; LoadIconForLink(WlIcon, DD.Path); WedCaption.Text := DD.Name; LbInfo.Caption := DD.Path; end; procedure TLinkListEditorUpdateDirectories.CreateNewItem(Sender: ILinkItemSelectForm; var Data: TDataObject; Verb: string; Elements: TListElements); var DD: TDatabaseDirectory; PI: TPathItem; Link: TWebLink; Info: TLabel; I: Integer; begin if Data = nil then begin if Verb = 'Refresh' then begin ClearUpdaterCache(DBManager.DBContext); RecheckUserDirectories; MessageBoxDB(0, L('The cache was cleared and scanning process has been started!'), L('Info'), TD_BUTTON_OK, TD_ICON_INFORMATION); Exit; end; PI := nil; try if SelectLocationForm.Execute(L('Select a directory'), '', PI, False) then begin for I := 0 to Sender.DataList.Count - 1 do begin DD := TDatabaseDirectory(Sender.DataList[I]); if StartsStr(AnsiLowerCase(DD.Path), AnsiLowerCase(PI.Path)) then begin MessageBoxDB(0, FormatEx(L('Location {0} is already in collection!'), [PI.Path]), L('Info'), TD_BUTTON_OK, TD_ICON_WARNING); Exit; end; end; Data := TDatabaseDirectory.Create(PI.Path, PI.DisplayName, 0); end; finally F(PI); end; Exit; end; DD := TDatabaseDirectory(Data); Link := TWebLink(Elements[leWebLink]); Info := TLabel(Elements[leInfoLabel]); Link.Text := DD.Name; Info.Caption := DD.Path; Info.EllipsisPosition := epPathEllipsis; LoadIconForLink(Link, DD.Path); end; procedure TLinkListEditorUpdateDirectories.FillActions(Sender: ILinkItemSelectForm; AddActionProc: TAddActionProcedure); begin AddActionProc(['Add', 'Refresh'], procedure(Action: string; WebLink: TWebLink) begin if Action = 'Add' then begin WebLink.Text := L('Add directory'); WebLink.LoadFromResource('SERIES_EXPAND'); end; if Action = 'Refresh' then begin WebLink.Text := L('Rescan'); WebLink.LoadFromResource('SYNC'); end; end ); end; procedure TLinkListEditorUpdateDirectories.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then FForm.ApplyChanges; end; function TLinkListEditorUpdateDirectories.L(StringToTranslate: string): string; begin Result := TA(StringToTranslate, 'CollectionSettings'); end; procedure TLinkListEditorUpdateDirectories.LoadIconForLink(Link: TWebLink; Path: string); var PI: TPathItem; begin PI := PathProviderManager.CreatePathItem(Path); try if (PI <> nil) and PI.LoadImage(PATH_LOAD_NORMAL or PATH_LOAD_FAST or PATH_LOAD_FOR_IMAGE_LIST, 16) and (PI.Image <> nil) then Link.LoadFromPathImage(PI.Image); finally F(PI); end; end; procedure TLinkListEditorUpdateDirectories.UpdateItemFromEditor( Sender: ILinkItemSelectForm; Data: TDataObject; EditorData: IFormLinkItemEditorData); var DD: TDatabaseDirectory; WedCaption: TWatermarkedEdit; begin DD := TDatabaseDirectory(Data); WedCaption := EditorData.EditorPanel.FindChildByTag<TWatermarkedEdit>(CHANGE_DIRECTORY_EDIT); DD.Assign(EditorData.EditorData); DD.Name := WedCaption.Text; end; function TLinkListEditorUpdateDirectories.OnApply(Sender: ILinkItemSelectForm): Boolean; begin Result := True; end; procedure TLinkListEditorUpdateDirectories.OnChangePlaceClick(Sender: TObject); var DD: TDatabaseDirectory; LbInfo: TLabel; Editor: TPanel; PI: TPathItem; begin Editor := TPanel(TControl(Sender).Parent); DD := TDatabaseDirectory(Editor.Tag); PI := nil; try if SelectLocationForm.Execute(L('Select a directory'), DD.Path, PI, False) then begin LbInfo := Editor.FindChildByTag<TLabel>(CHANGE_DIRECTORY_INFO); LbInfo.Caption := PI.Path; DD.Path := PI.Path; end; finally F(PI); end; end; function TLinkListEditorUpdateDirectories.OnDelete(Sender: ILinkItemSelectForm; Data: TDataObject; Editor: TPanel): Boolean; begin Result := True; end; procedure TLinkListEditorUpdateDirectories.SetForm(Form: IFormLinkItemEditorData); var TopPanel: TPanel; Image: TImage; LbInfo: TLabel; Png: TPngImage; begin FForm := Form; if FForm <> nil then begin TopPanel := Form.TopPanel; Image := TImage.Create(TopPanel); Image.Parent := TopPanel; Png := GetCollectionSyncImage; try Image.Picture.Graphic := Png; Image.Top := 8; Image.Left := 8; Image.Width := Png.Width; Image.Height := Png.Height; finally F(Png); end; LbInfo := TLabel.Create(TopPanel); LbInfo.Parent := TopPanel; LbInfo.Top := Image.Top + Image.Height + 8; LbInfo.Left := 8; LbInfo.Constraints.MaxWidth := Image.Width; LbInfo.Constraints.MinWidth := Image.Width; LbInfo.AutoSize := True; LbInfo.WordWrap := True; LbInfo.Caption := ' ' + L('Choose directories to synchronize with collection. All images in these directories will be automatically included to collection.'); TopPanel.Height := LbInfo.Top + LbInfo.Height + 8; end; end; end.
unit utils; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, ExtCtrls, StdCtrls, Buttons, OleCtrls, SHDocVw, stdActns, ShellAPI, ShlObj; function PastaProcurar(const Title: string; const Flag: integer): string; procedure MsgErr(Error: String); Function LocalDoExe: String; procedure PastaCriar(Nome: String); Function StrNumeros(Str: String): String; procedure MsgInf(Messagem: String); function PathSystem: String; implementation function PathSystem: String; var strTmp: array[0..MAX_PATH] of char; DirWindows: String; const SYS_64 = 'SysWOW64'; SYS_32 = 'System32'; begin Result := ''; if Windows.GetWindowsDirectory(strTmp, MAX_PATH) > 0 then begin DirWindows := Trim(StrPas(strTmp)); DirWindows := IncludeTrailingPathDelimiter(DirWindows); if DirectoryExists(DirWindows + SYS_64) then Result := DirWindows + SYS_64 else if DirectoryExists(DirWindows + SYS_32) then Result := DirWindows + SYS_32 else raise Exception.Create('Diretório de sistema não encontrado.'); end else raise Exception.Create('Ocorreu um erro ao tentar obter o diretório do windows.'); end; procedure MsgInf(Messagem: String); begin Application.MessageBox(PChar(Messagem),PChar(Application.Title), Mb_IconInformation); end; Function StrPermanece(Str,Permanece: String): String; var i, v: Integer; S: String; begin for I := 1 to Length(Str) do for v := 1 to Length(Permanece) do if Str[i] = Permanece[v] then S:= S+Str[i]; Result:= S; end; Function StrNumeros(Str: String): String; begin Result:= StrPermanece(Str, '0123456789'); end; procedure PastaCriar(Nome: String); begin if not DirectoryExists(Nome) then ForceDirectories(Nome) end; Function LocalDoExe: String; begin Result:= ExtractFilePath(ParamStr(0)); end; procedure MsgErr(Error: String); begin Application.MessageBox(PChar(Error),PChar(Application.Title), Mb_IconError); end; function BrowseDialogCallBack (Wnd: HWND; uMsg: UINT; lParam, lpData: LPARAM): integer stdcall; var wa, rect : TRect; dialogPT : TPoint; begin //center in work area if uMsg = BFFM_INITIALIZED then begin wa := Screen.WorkAreaRect; GetWindowRect(Wnd, Rect); dialogPT.X := ((wa.Right-wa.Left) div 2) - ((rect.Right-rect.Left) div 2); dialogPT.Y := ((wa.Bottom-wa.Top) div 2) - ((rect.Bottom-rect.Top) div 2); MoveWindow(Wnd, dialogPT.X, dialogPT.Y, Rect.Right - Rect.Left, Rect.Bottom - Rect.Top, True); end; Result := 0; end; (*BrowseDialogCallBack*) function PastaProcurar(const Title: string; const Flag: integer): string; var lpItemID : PItemIDList; BrowseInfo : TBrowseInfo; DisplayName : array[0..MAX_PATH] of char; TempPath : array[0..MAX_PATH] of char; begin Result:=''; FillChar(BrowseInfo, sizeof(TBrowseInfo), #0); with BrowseInfo do begin hwndOwner := Application.Handle; pszDisplayName := @DisplayName; lpszTitle := PChar(Title); ulFlags := Flag; lpfn := BrowseDialogCallBack; end; lpItemID := SHBrowseForFolder(BrowseInfo); if lpItemId <> nil then begin SHGetPathFromIDList(lpItemID, TempPath); Result := TempPath; GlobalFreePtr(lpItemID); end; end; end.
unit EanHtml; interface procedure CreateHtml_AllCodes(Root:Boolean; Dir:String); implementation uses Classes, SysUtils, EanSpecs, EanKod; const Html_Template='<HTML><HEAD>%s<STYLE TYPE="text/css">@import url(../styles.css);</STYLE></HEAD><BODY>%s</BODY></HTML>'; function YesNo(B:Boolean):String; begin if B then Result :='Yes' else Result :='No'; end; procedure CreateHtml_AllCodes(Root:Boolean; Dir:String); const anchor='<A HREF="%s" alt="%s">%s</A><BR>'; table_row='<TR><TD WIDTH="30%%">%s</TD><TD WIDTH="70%%">%s</TD></TR>'; img_tag ='<img src="%s" width=%d height=%d border=0 vspace=20>'; var i:Integer; LI:TStringList; BI:TBarCodeInfo; T :TTypBarcode; s,header,pom :String; ext,fn :String; E :TEan; begin LI:=TStringList.Create; try E:=TEan.Create(nil); try s := ExtractFileDir(dir); ext := GrExtensions[gtJPeg]; if Root then begin for T:=Low(TTypBarcode) to High(TTypBarcode) do begin BI:=BarcodeInfo(T); LI.Add(format(anchor,['barcode_'+IntToStr(Integer(T))+'.html',BI.LongName,BI.LongName])); end; LI.Text := Format(html_template,['',LI.Text]); LI.saveToFile(Dir); end; for T:=Low(TTypBarcode) to High(TTypBarcode) do begin E.TypBarCode := T; E.Height := 100; E.Width := 2*E.MinWidth; E.SaveToFile(Lowercase(s+'\'+E.BarcodeTypeName+ext)); LI.Clear; BI:=BarcodeInfo(T); LI.Add('<TABLE WIDTH="100%">'); LI.Add('<TH COLSPAN=2>'+BI.LongName+'</TH>'); LI.Add(Format(table_row,['Barcode type', BI.Name ])); LI.Add(Format(table_row,['Barcode family', BI.LongName ])); LI.Add(Format(table_row,['Number of available char', IntToStr(Length(BI.Chars)) ])); LI.Add(Format(table_row,['Set of chars', BI.Chars ])); LI.Add(Format(table_row,['Year', IntToStr(BI.Year) ])); LI.Add(Format(table_row,['Country', BI.Country ])); LI.Add(Format(table_row,['Supplement digits', YesNo(BI.EnabledAdd) ])); LI.Add(Format(table_row,['Optimal char width in mm', FloatToStr(BI.OptCharWidthMM)+' mm'])); LI.Add(Format(table_row,[ Format(img_tag,[lowercase(E.BarcodeTypeName+ext), E.Width, E.Height]), ''])); if BI.EnabledAdd then begin pom:=E.barcode; fn :=lowercase(E.BarcodeTypeName+'_2'+ext); E.Barcode := pom+' 12'; E.Width := 2*E.MinWidth; E.SaveToFile(Lowercase(s+'\'+fn)); LI.Add(Format(table_row,[ Format(img_tag,[lowercase(fn), E.Width, E.Height]), ''])); fn:=lowercase(E.BarcodeTypeName+'_5'+ext); E.Barcode := pom+' 12345'; E.Width := 2*E.MinWidth; E.SaveToFile(Lowercase(s+'\'+fn)); LI.Add(Format(table_row,[ Format(img_tag,[lowercase(fn), E.Width, E.Height]), ''])); end; LI.Add('</TABLE>'); Header := '<META NAME=DESCRIPTION CONTENT="'+BI.LongName+'">' + '<META NAME=KEYWORDS CONTENT="barcode,delphi,component,print,vcl,'+BI.LongName+'">' + '<TITLE>PSOFT Barcode library : '+BI.LongName+'</TITLE>'; LI.Text := Format(html_template,[header,LI.Text]); LI.saveToFile(s+'\barcode_'+IntToStr(Integer(T))+'.html'); end; finally E.Free; end; finally LI.Free; end; end; end.
unit uFindString; interface uses Winapi.Windows, System.SysUtils, System.Classes, SynCobjs, uFormats; type /// <summary>Потік пошуку входження рядка в файл</summary> TFindStrThread = class(TThread) private ThreadListP: TThreadList; SearchText : TSearchAll; FileName : string; Text : string; public procedure AddToFindList; procedure Execute; override; constructor Create(AThreadList: TThreadList); destructor Destroy; override; end; /// <summary>Клас пошуку входження рядка в множину файлів</summary> TFindsString = class const NOT_FIND = 'Задана строка не знайдена в жодному з файлів'; Maska = '*.*'; TIMER_ITERATION = 1000; private class var ReturnList: TStrings; class var TimerID : UINT; class var FindList : TStrings; class var ThreadList: TThreadList; class procedure TimerProc(Wnd:HWND; uMsg:DWORD; idEvent:PDWORD; dwTime:DWORD); stdcall; static; /// <remarks>Виведення результату роботи пошуку</remarks> class procedure Return; class procedure CloseThread; private FileList: TStrings; public constructor Create; destructor Destroy; override; /// <param name="AFolder">Папка в якій буде пошук рядка</param> function GetFiles(AFolder: string; const DisplayList: TStrings = nil): Boolean; /// <param name="AText">Рядок який будемо шукати</param> procedure StartSearch(const AText: string; const DisplayList: TStrings = nil); /// <remarks>Зупинка пошуку</remarks> procedure StopSearch; end; var cs: TCriticalSection; ThreadCounter: Integer = 0; implementation uses uProcedure, Dialogs {$IFDEF DEBUG},CodeSiteLogging{$ENDIF}; { ------------------------------------------ TFindsString -------------------------------------------------------------} class procedure TFindsString.TimerProc(Wnd:HWND; uMsg:DWORD; idEvent:PDWORD; dwTime:DWORD); begin // Очікуємо на останній закриття останнього потоку if ThreadCounter = 0 then begin KillTimer(0, TimerID); TFindsString.Return; CloseThread; end; end; class procedure TFindsString.CloseThread; var I: integer; begin with ThreadList.LockList do try if Count > 0 then begin for I := 0 to Count-1 do if Assigned(TFindStrThread(Items[i])) then begin TFindStrThread(Items[i]).Terminate; // TFindStrThread(Items[i]).WaitFor; // TFindStrThread(Items[i]).Free; end; ThreadList.Clear; end; finally ThreadList.UnlockList; end; end; constructor TFindsString.Create; begin cs := TCriticalSection.Create; FileList := TStringList.Create; FindList := TStringList.Create; ReturnList:= nil; //Зберігаємо список потоків для їх закриття ThreadList:= TThreadList.Create; //Забороняємо дублікати TStringList(FindList).Duplicates := dupIgnore; end; destructor TFindsString.Destroy; begin FreeAndNil( FileList ); FreeAndNil( FindList ); FreeAndNil( ThreadList ); FreeAndNil( cs ); KillTimer(0, TimerID); inherited; end; class procedure TFindsString.Return; var tmp: string; i,j: Integer; begin // Якщо нічого не знайдено виходимо (-: if FindList.Count = 0 then begin ShowMessage( NOT_FIND ); Exit; end; // Виводимо результат у вигляді списку файлів for i := 0 to FindList.Count-1 do begin j := ReturnList.IndexOf( FindList[i] ); if j > -1 then ReturnList[ j ] := Format('[%s] %s', [Chr($221A), ReturnList[ j ]]); end; end; procedure TFindsString.StartSearch(const AText: string; const DisplayList: TStrings); var tmp: string; begin {$IFDEF DEBUG} CodeSite.EnterMethod('TFindsString.StartSearch'); {$ENDIF} if Assigned(DisplayList) then ReturnList := DisplayList; FindList.Clear; // Проходисося по всім знайденим файлам в списку for tmp in FileList do begin { TODO : Для прискорення потрібно: Файл бється на поток, кожна частина файла обробляється своїм потоком, без обриву текстового рядка} // Для кожного файлу запускаємо окремий потік на пошук тексту with TFindStrThread.Create( ThreadList ) do begin FileName := tmp; Text := AText; Start; end; end; // Запускаємо таймер для виведення результату TimerID := SetTimer(0, 0, TIMER_ITERATION, @TimerProc); end; procedure TFindsString.StopSearch; begin CloseThread; {$IFDEF DEBUG} CodeSite.ExitMethod('TFindsString.StopSearch'); CodeSite.AddSeparator; {$ENDIF} end; // Завантаження списку для роботи function TFindsString.GetFiles(AFolder: string; const DisplayList: TStrings): Boolean; begin Result := False; FileList.Clear; FindFiles(AFolder, Maska, FileList); Result := FileList.Count > 0; if Assigned(DisplayList) then begin DisplayList.Clear; DisplayList.AddStrings( FileList ); end; end; { ------------------------------------------ TFindStrThread ---------------------------------------------------------- } procedure TFindStrThread.AddToFindList; begin cs.Enter; try TFindsString.FindList.Add( FileName ); finally cs.Leave; end; end; constructor TFindStrThread.Create(AThreadList: TThreadList); begin inherited Create( true ); FreeOnTerminate := True; ThreadListP := AThreadList; ThreadListP.Add( Self ); InterlockedIncrement( ThreadCounter ); {$IFDEF DEBUG} CodeSite.SendFmtMsg('Create: %d',[Self.Handle]); {$ENDIF} end; destructor TFindStrThread.Destroy; begin InterlockedDecrement( ThreadCounter ); cs.Enter; try ThreadListP.Remove( Self ); finally cs.Leave; end; {$IFDEF DEBUG} CodeSite.SendFmtMsg('Destroy: %d',[Self.Handle]); {$ENDIF} inherited; end; // Пошук входження тексту procedure TFindStrThread.Execute; var isFind: Boolean; begin SearchText := TSearchAll.Create( FileName ); try SearchText.Thread := Self; isFind := SearchText.Search( Text ); if isFind then AddToFindList; finally FreeAndNil( SearchText ); end; end; end.
unit InspectorView; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, Grids, dcgen, dcedit, dcpedit, oinspect, JsInspector; type TInspectorForm = class(TForm) Bevel1: TBevel; CompList: TCompList; Bevel2: TBevel; InspectorTabs: TTabControl; ObjectInspector: TObjectInspector; procedure FormCreate(Sender: TObject); procedure CompListChange(Sender: TObject); procedure InspectorTabsChange(Sender: TObject); procedure ObjectInspectorShowProperty(Sender: TObject; const PropEdit: TDCDsgnProperty; var show: Boolean); procedure ObjectInspectorChangedPropValue(Sender: TObject; const PropEdit: TDCDsgnProperty; var newval: String); private { Private declarations } FDefaultComponent: TComponent; FOnPropChanged: TNotifyEvent; FOnSelect: TNotifyEvent; FOnSelect2: TNotifyEvent; FRoot: TComponent; CompListLocked: Boolean; JsEventInspector: TJsInspector; protected function GetSelected: TPersistent; procedure SetDefaultComponent(const Value: TComponent); procedure SetRoot(const Value: TComponent); protected procedure UpdateInspectorComponent(inComponent: TComponent); procedure UpdateInspectorList(inComponents: TList); public { Public declarations } procedure InspectComponents(inComponents: TList); procedure InspectPersistent(inObject: TPersistent); property DefaultComponent: TComponent read FDefaultComponent write SetDefaultComponent; property OnPropChanged: TNotifyEvent read FOnPropChanged write FOnPropChanged; property OnSelect: TNotifyEvent read FOnSelect write FOnSelect; property OnSelect2: TNotifyEvent read FOnSelect2 write FOnSelect2; property Root: TComponent read FRoot write SetRoot; property Selected: TPersistent read GetSelected; end; var InspectorForm: TInspectorForm; implementation uses LrUtils, ThPanel; {$R *.dfm} procedure TInspectorForm.FormCreate(Sender: TObject); begin //InspectorTabs.DoubleBuffered := true; JsEventInspector := TJsInspector.Create(Self); JsEventInspector.Parent := InspectorTabs; JsEventInspector.BorderStyle := bsNone; JsEventInspector.Align := alClient; JsEventInspector.Visible := false; JsEventInspector.FixedColWidth := 100; end; procedure TInspectorForm.SetDefaultComponent(const Value: TComponent); begin FDefaultComponent := Value; end; procedure TInspectorForm.SetRoot(const Value: TComponent); begin FRoot := Value; CompListLocked := true; try CompList.OwnerComponent := Root; finally CompListLocked := false; end; end; procedure TInspectorForm.InspectComponents(inComponents: TList); begin if (inComponents <> nil) and (inComponents.Count < 1) and (DefaultComponent <> nil) then UpdateInspectorComponent(DefaultComponent) else UpdateInspectorList(inComponents); end; procedure TInspectorForm.UpdateInspectorList(inComponents: TList); begin ObjectInspector.CurrentControls := inComponents; JsEventInspector.CurrentControls := inComponents; CompListLocked := true; try CompList.SelectedComponents := inComponents; finally CompListLocked := false; end; end; procedure TInspectorForm.UpdateInspectorComponent(inComponent: TComponent); var list: TList; begin list := TList.Create; try list.Add(inComponent); UpdateInspectorList(list); finally list.Free; end; end; procedure TInspectorForm.InspectPersistent(inObject: TPersistent); begin ObjectInspector.CurrentControl := inObject; end; procedure TInspectorForm.CompListChange(Sender: TObject); begin if not CompListLocked and not (csDestroying in ComponentState) {and not (csFreeNotification in CompList.ComponentState)} then if ObjectInspector.CanFocus then begin ObjectInspector.SetFocus; if Assigned(OnSelect) then OnSelect(Self); if Assigned(OnSelect2) then OnSelect2(Self); end; end; function TInspectorForm.GetSelected: TPersistent; begin if CompList.SelectedComponents.Count > 0 then Result := CompList.SelectedComponents[0] else Result := nil; end; procedure TInspectorForm.ObjectInspectorShowProperty(Sender: TObject; const PropEdit: TDCDsgnProperty; var show: Boolean); begin show := Copy(PropEdit.GetName, 1, 2) = 'On'; if InspectorTabs.TabIndex = 0 then show := not show; end; procedure TInspectorForm.InspectorTabsChange(Sender: TObject); begin ObjectInspector.Visible := (InspectorTabs.TabIndex <= 1); JsEventInspector.Visible := (InspectorTabs.TabIndex = 2); if ObjectInspector.Visible then ObjectInspector.Rescan; if JsEventInspector.Visible then JsEventInspector.Rescan; end; procedure TInspectorForm.ObjectInspectorChangedPropValue(Sender: TObject; const PropEdit: TDCDsgnProperty; var newval: String); begin if Assigned(OnPropChanged) then OnPropChanged(Self); end; end.
unit uAddMinZP; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uLogicCheck, ActnList, uInvisControl, uFControl, uLabeledFControl, uDateControl, StdCtrls, Buttons, uFormControl, uCharControl, uFloatControl, uSimpleCheck, uMinZPData; type TfmAddMinZP = class(TForm) FormControl: TqFFormControl; OkButton: TBitBtn; CancelButton: TBitBtn; Date_Beg: TqFDateControl; Date_End: TqFDateControl; CutPrev: TqFInvisControl; ActionList1: TActionList; OkAction: TAction; qFLogicCheck1: TqFLogicCheck; Value_Min_ZP: TqFFloatControl; DateCheck: TqFSimpleCheck; procedure OkActionExecute(Sender: TObject); procedure FormControlNewRecordAfterPrepare(Sender: TObject); procedure qFLogicCheck1Check(Sender: TObject; var Error: String); private { Private declarations } public DM: TdmMinZP; end; var fmAddMinZP: TfmAddMinZP; implementation {$R *.dfm} uses DateUtils, qFTools; procedure TfmAddMinZP.OkActionExecute(Sender: TObject); begin FormControl.Ok; end; procedure TfmAddMinZP.FormControlNewRecordAfterPrepare(Sender: TObject); begin Date_Beg.Value := EncodeDate(YearOf(Date), 1, 1); Date_End.Value := EncodeDate(9999, 12, 31); end; procedure TfmAddMinZP.qFLogicCheck1Check(Sender: TObject; var Error: String); begin CutPrev.Value := 0; if FormControl.Mode = fmAdd then begin DM.CheckZP.Close; DM.CheckZP.ParamByName('Date_Beg').AsDate := Date_Beg.Value; DM.CheckZP.ParamByName('Date_End').AsDate := Date_End.Value; DM.CheckZP.Open; if not DM.CheckZP.IsEmpty then begin if qFConfirm('Вже є запис на цей період! Бажаєте закрити старий запис?') then begin CutPrev.Value := 1; Error := ''; end else Error := 'Неможливо додати запис через перетин періодів!'; end else Error := ''; end; end; initialization RegisterClass(TfmAddMinZP); end.
unit UpDefSignersFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, uFormControl, cxDataStorage, cxEdit, DB, cxDBData, FIBQuery, pFIBQuery, FIBDataSet, pFIBDataSet, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, Buttons, ExtCtrls, ImgList, ComCtrls, ToolWin, StdCtrls, pFibStoredProc, FIBDatabase, pFIBDatabase, Ibase; type TUP_DefSignersFrame = class(TFrame) SignersGrid: TcxGrid; View: TcxGridDBTableView; cxGridDBColumn2: TcxGridDBColumn; ViewDBColumn1: TcxGridDBColumn; cxGridLevel2: TcxGridLevel; pFIBDS_Signers: TpFIBDataSet; DS_Signers: TDataSource; pFIBDS_AddSigner: TpFIBDataSet; pFIBQ_DelSigner: TpFIBQuery; ToolBar1: TToolBar; AddSignerButton: TToolButton; DeleteSignerButton: TToolButton; StyleRepository: TcxStyleRepository; stBackground: TcxStyle; stContent: TcxStyle; stContentEven: TcxStyle; stContentOdd: TcxStyle; stFilterBox: TcxStyle; stFooter: TcxStyle; stGroup: TcxStyle; stGroupByBox: TcxStyle; stHeader: TcxStyle; stInactive: TcxStyle; stIncSearch: TcxStyle; stIndicator: TcxStyle; stPreview: TcxStyle; stSelection: TcxStyle; stHotTrack: TcxStyle; qizzStyle: TcxGridTableViewStyleSheet; Panel1: TPanel; CheckBox1: TCheckBox; CheckBox2: TCheckBox; cxStyleRepository1: TcxStyleRepository; cxStyle1: TcxStyle; cxStyle2: TcxStyle; cxStyle3: TcxStyle; cxStyle4: TcxStyle; cxStyle5: TcxStyle; cxStyle6: TcxStyle; cxStyle7: TcxStyle; cxStyle8: TcxStyle; cxStyle9: TcxStyle; cxStyle10: TcxStyle; cxStyle11: TcxStyle; cxStyle12: TcxStyle; cxStyle13: TcxStyle; cxStyle14: TcxStyle; cxStyle15: TcxStyle; cxGridTableViewStyleSheet1: TcxGridTableViewStyleSheet; ToolButton2: TToolButton; ToolButton3: TToolButton; ViewDBColumn2: TcxGridDBColumn; WorkDatabase: TpFIBDatabase; ReadTransaction: TpFIBTransaction; WriteTransaction: TpFIBTransaction; IL_Orders: TImageList; procedure AddSignerButtonClick(Sender: TObject); procedure DeleteSignerButtonClick(Sender: TObject); procedure CheckBox1Click(Sender: TObject); procedure CheckBox2Click(Sender: TObject); procedure ToolButton2Click(Sender: TObject); procedure ToolButton3Click(Sender: TObject); private id_signers_type: Int64; id_type: Integer; public FMode: TFormMode; constructor Create(aOwner: TComponent; aId_type: Int64; dbHandle: TIsc_DB_HANDLE); reintroduce; end; implementation uses uUnivSprav, RxMemDS, BaseTypes; {$R *.dfm} constructor TUP_DefSignersFrame.Create(aOwner: TComponent; aId_type: Int64; DbHandle: TISC_DB_HANDLE); begin inherited Create(aOwner); id_signers_type := aId_type; WorkDatabase.Handle := dbHandle; pFIBDS_AddSigner.Database := WorkDatabase; pFIBDS_AddSigner.Transaction := WriteTransaction; pFIBQ_DelSigner.Database := WorkDatabase; pFIBQ_DelSigner.Transaction := WriteTransaction; pFIBDS_Signers.Database := WorkDatabase; pFIBDS_Signers.Transaction := ReadTransaction; pFIBDS_Signers.SelectSQL.Text := 'select * from UP_DT_ORDER_DEF_SIGNERS_SEL(' + IntTOStr(aid_type) + ')'; pFIBDS_Signers.Open; pFIBDS_AddSigner.ParamByName('id_sign_type').AsInt64 := id_signers_type; self.id_type := id_signers_type; end; procedure TUP_DefSignersFrame.AddSignerButtonClick(Sender: TObject); var Params: TUnivParams; OutPut: TRxMemoryData; id_signer: Int64; begin Params.FormCaption := 'Додати візу до наказу'; Params.ShowMode := fsmSelect; Params.ShowButtons := [fbExit]; Params.TableName := 'up_get_text_shablon(6)'; Params.Fields := 'text1,text2,id_shablon'; Params.FieldsName := 'ПІП/б,Посада'; Params.KeyField := 'ID_shablon'; Params.ReturnFields := 'text1,text2'; Params.DBHandle := Integer(pFIBDS_AddSigner.Database.Handle); OutPut := TRxMemoryData.Create(self); if GetUnivSprav(Params, OutPut) then begin pFIBDS_AddSigner.ParamByName('signer_fio').AsString := VarToStr(output['text1']); pFIBDS_AddSigner.ParamByName('signer_post').AsString := VarToStr(output['text2']); try pFIBDS_AddSigner.Transaction.StartTransaction; pFIBDS_AddSigner.Open; id_signer := pFIBDS_AddSigner['ID_SIGNER']; pFIBDS_AddSigner.Close; pFIBDS_AddSigner.Transaction.Commit; pFIBDS_Signers.CloseOpen(true); pFIBDS_Signers.Locate('ID_SIGNER', ID_SIGNER, []); except on e: Exception do begin MessageDlg('Помилка : ' + e.Message, mtError, [mbYes], -1); pFIBDS_AddSigner.Transaction.Rollback; end; end; end; end; procedure TUP_DefSignersFrame.DeleteSignerButtonClick(Sender: TObject); begin if (pFIBDS_Signers.IsEmpty) then begin agShowMessage('Помилка : немає записів для вилучення! '); Exit; end; if (agMessageDlg('Увага!', 'Ви впевнені що хочете вилучити запис?', mtConfirmation, [mbYes, mbNo]) = mrYes) then begin try pFIBQ_DelSigner.ParamByName('id_signer').AsInt64 := pFIBDS_Signers['ID_SIGNER']; WriteTransaction.StartTransaction; pFIBQ_DelSigner.ExecProc; pFIBDS_Signers.CacheDelete; WriteTransaction.Commit; except on e: Exception do begin agShowMessage('Помилка : ' + e.Message); pFIBDS_AddSigner.Transaction.Rollback; end; end; end; end; procedure TUP_DefSignersFrame.CheckBox1Click(Sender: TObject); var I: Integer; begin for i := 0 to View.ColumnCount - 1 do begin View.Columns[i].Options.Filtering := CheckBox1.Checked; end; end; procedure TUP_DefSignersFrame.CheckBox2Click(Sender: TObject); begin View.OptionsView.GroupByBox := CheckBox2.Checked; end; procedure TUP_DefSignersFrame.ToolButton2Click(Sender: TObject); var UpdateSP: TpFibStoredProc; id: Int64; begin //необходимо повысить запись в порядке if (pFIBDS_Signers.RecordCount > 0) then begin UpdateSP := TpFibStoredProc.Create(self); UpdateSP.Database := WorkDatabase; UpdateSP.Transaction := WriteTransaction; WriteTransaction.StartTransaction; UpdateSP.StoredProcName := 'UP_DT_ORDER_DEF_SIGNERS_UPD_TOP'; UpdateSP.Prepare; id := StrToInt64(pFIBDS_Signers.FieldByName('ID_SIGNER').asString); UpdateSP.ParamByName('ID_SIGNER').AsInt64 := StrToInt64(pFIBDS_Signers.FieldByName('ID_SIGNER').asString); UpdateSP.ParamByName('PRINT_ORDER').Value := pFIBDS_Signers.FieldByName('PRINT_ORDER').Value; UpdateSP.ParamByName('ID_TYPE_SIGNER').Value := id_type; UpdateSP.ExecProc; WriteTransaction.Commit; pFIBDS_Signers.CloseOpen(true); pFIBDS_Signers.Locate('ID_SIGNER', id, []); UpdateSP.Close; UpdateSP.Free; end; end; procedure TUP_DefSignersFrame.ToolButton3Click(Sender: TObject); var UpdateSP: TpFibStoredProc; id: Int64; begin //необходимо понизить запись в порядке if (pFIBDS_Signers.RecordCount > 0) then begin UpdateSP := TpFibStoredProc.Create(self); UpdateSP.Database := WorkDatabase; UpdateSP.Transaction := WriteTransaction; WriteTransaction.StartTransaction; UpdateSP.StoredProcName := 'UP_DT_ORDER_DE_SIGNERS_UPD_DOWN'; UpdateSP.Prepare; id := StrToInt64(pFIBDS_Signers.FieldByName('ID_SIGNER').asString); UpdateSP.ParamByName('ID_SIGNER').AsInt64 := StrToInt64(pFIBDS_Signers.FieldByName('ID_SIGNER').asString); UpdateSP.ParamByName('PRINT_ORDER').Value := pFIBDS_Signers.FieldByName('PRINT_ORDER').Value; UpdateSP.ParamByName('ID_TYPE_SIGNER').Value := id_type; UpdateSP.ExecProc; WriteTransaction.Commit; pFIBDS_Signers.CloseOpen(true); pFIBDS_Signers.Locate('ID_SIGNER', id, []); UpdateSP.Close; UpdateSP.Free; end; end; end.
unit uSubripFile; { Subrip file (srt) decoder and encoder. Copyright (C) 2017 Mohammadreza Bahrami m.audio91@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 with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1335, USA. } {$mode objfpc}{$H+} interface uses Classes, SysUtils, CommonStrUtils, CommonGenericLists, uTimeSlice, uGenericSubtitleFile; type { TCustomSubripFile } TCustomSubripFile = specialize TGenericSubtitleFile<TPlainSubtitleEvent>; { TSubripFile } TSubripFile = class(TCustomSubripFile) public procedure LoadFromString(const AContents: String); override; procedure SaveToString(out AContents: String); override; constructor Create; override; end; const SubripTimeSliceSep = ' --> '; function DefaultSubripTimeSliceFormat: TTimeSliceFormatSettings; implementation function DefaultSubripTimeSliceFormat: TTimeSliceFormatSettings; begin with Result do begin TimeCodes.MillisecondPrecision := 3; TimeCodes.MajorSep := ':'; TimeCodes.MinorSep := ','; TimeCodes.SourceFPS := 25; TimeCodes.HasFrame := False; TimeCodes.IsFrame := False; SliceSep := SubripTimeSliceSep; end; end; { TSubripFile } procedure TSubripFile.LoadFromString(const AContents: String); var il: TIntegerList; sl: TStringList; Dlg: TPlainSubtitleEvent; i,j: Integer; begin Clear; if IsEmptyStr(AContents) or (AContents.IndexOf(SubripTimeSliceSep)<0) then Exit; il := TIntegerList.Create; sl := TStringList.Create; Dlg.TimeSlice.Initialize(TimeSlice.TimeSliceFormat); try sl.Text := AContents.TrimLeft; if sl.Count < 3 then Exit; il.Capacity := sl.Count div 3; Events.Capacity := sl.Count div 3; for i:=0 to sl.Count-1 do begin if sl[i].Contains(SubripTimeSliceSep) then begin Dlg.TimeSlice.ValueAsString := sl[i]; if Dlg.TimeSlice.Valid then il.Add(i); end; end; for i:=0 to il.Count-2 do begin if (il[i+1]-1)-il[i]>1 then begin Dlg.TimeSlice.ValueAsString := sl[il[i]]; Dlg.Text := EmptyStr; for j:=il[i]+1 to il[i+1]-2 do Dlg.Text := Dlg.Text + sl[j] +LineEnding; Events.Add(Dlg); end; end; Dlg.TimeSlice.ValueAsString := sl[il[il.Count-1]]; Dlg.Text := EmptyStr; for j:=il[il.Count-1]+1 to sl.Count-1 do Dlg.Text := Dlg.Text + sl[j] +LineEnding; Events.Add(Dlg); finally il.Free; sl.Free; end; end; procedure TSubripFile.SaveToString(out AContents: String); var i: Integer; begin AContents := EmptyStr; for i := 0 to Events.Count-1 do begin AContents := AContents +(i+1).ToString +LineEnding +Events[i].TimeSlice.ValueAsString +LineEnding +Events[i].Text; end; end; constructor TSubripFile.Create; begin inherited Create; TimeSlice.Initialize(DefaultSubripTimeSliceFormat); end; end.
unit uIDivider; {$I ..\Include\IntXLib.inc} interface uses uEnums, uIntX, uIntXLibTypes; type /// <summary> /// Divider class interface. /// </summary> IIDivider = interface(IInterface) ['{1DE44B6B-BCC7-47EF-B03E-1E289CBDA4B9}'] /// <summary> /// Divides one <see cref="TIntX" /> by another. /// </summary> /// <param name="int1">First big integer.</param> /// <param name="int2">Second big integer.</param> /// <param name="modRes">Remainder big integer.</param> /// <param name="resultFlags">Which operation results to return.</param> /// <returns>Divident big integer.</returns> function DivMod(int1: TIntX; int2: TIntX; out modRes: TIntX; resultFlags: TDivModResultFlags): TIntX; overload; /// <summary> /// Divides two big integers. /// Also modifies <paramref name="digits1" /> and <paramref name="length1"/> (it will contain remainder). /// </summary> /// <param name="digits1">First big integer digits.</param> /// <param name="digitsBuffer1">Buffer for first big integer digits. May also contain remainder. Can be null - in this case it's created if necessary.</param> /// <param name="length1">First big integer length.</param> /// <param name="digits2">Second big integer digits.</param> /// <param name="digitsBuffer2">Buffer for second big integer digits. Only temporarily used. Can be null - in this case it's created if necessary.</param> /// <param name="length2">Second big integer length.</param> /// <param name="digitsRes">Resulting big integer digits.</param> /// <param name="resultFlags">Which operation results to return.</param> /// <param name="cmpResult">Big integers comparison result (pass -2 if omitted).</param> /// <returns>Resulting big integer length.</returns> function DivMod(digits1: TIntXLibUInt32Array; digitsBuffer1: TIntXLibUInt32Array; var length1: UInt32; digits2: TIntXLibUInt32Array; digitsBuffer2: TIntXLibUInt32Array; length2: UInt32; digitsRes: TIntXLibUInt32Array; resultFlags: TDivModResultFlags; cmpResult: Integer): UInt32; overload; /// <summary> /// Divides two big integers. /// Also modifies <paramref name="digitsPtr1" /> and <paramref name="length1"/> (it will contain remainder). /// </summary> /// <param name="digitsPtr1">First big integer digits.</param> /// <param name="digitsBufferPtr1">Buffer for first big integer digits. May also contain remainder.</param> /// <param name="length1">First big integer length.</param> /// <param name="digitsPtr2">Second big integer digits.</param> /// <param name="digitsBufferPtr2">Buffer for second big integer digits. Only temporarily used.</param> /// <param name="length2">Second big integer length.</param> /// <param name="digitsResPtr">Resulting big integer digits.</param> /// <param name="resultFlags">Which operation results to return.</param> /// <param name="cmpResult">Big integers comparison result (pass -2 if omitted).</param> /// <returns>Resulting big integer length.</returns> function DivMod(digitsPtr1: PCardinal; digitsBufferPtr1: PCardinal; var length1: UInt32; digitsPtr2: PCardinal; digitsBufferPtr2: PCardinal; length2: UInt32; digitsResPtr: PCardinal; resultFlags: TDivModResultFlags; cmpResult: Integer): UInt32; overload; end; implementation end.
unit InflatablesList_SimpleBitmap; {$INCLUDE '.\InflatablesList_defs.inc'} interface uses AuxTypes, AuxClasses, Windows, Classes, Graphics; type TILRGBAQuad = packed record R,G,B,A: Byte; end; PILRGBAQuad = ^TILRGBAQuad; TILRGBAQuadArray = array[0..$FFFF] of TILRGBAQuad; PILRGBAQuadArray = ^TILRGBAQuadArray; Function RGBAToColor(RGBA: TILRGBAQuad): TColor; Function ColorToRGBA(Color: TColor): TILRGBAQuad; Function RGBAToWinRGBA(RGBA: TILRGBAQuad): TRGBQuad; Function WinRGBAToRGBA(WinRGBA: TRGBQuad): TILRGBAQuad; Function RGBAToWinRGB(RGBA: TILRGBAQuad): TRGBTriple; Function WinRGBToRGBA(WinRGB: TRGBTriple): TILRGBAQuad; type TRGBTripleArray = array[0..$FFFF] of TRGBTriple; PRGBTripleArray = ^TRGBTripleArray; //============================================================================== const IL_SIMPLE_BITMAP_SIGNATURE = UInt32($42534C49); // ILSB type TILSimpleBitmap = class(TCustomObject) private fMemory: Pointer; fSize: TMemSize; fWidth: UInt32; fHeight: UInt32; Function GetPixel(X,Y: UInt32): TILRGBAQuad; procedure SetPixel(X,Y: UInt32; Value: TILRGBAQuad); procedure SetWidth(Value: UInt32); procedure SetHeight(Value: UInt32); protected procedure Reallocate(NewSize: TMemSize); public constructor Create; constructor CreateFrom(Bitmap: TBitmap); overload; virtual; constructor CreateFrom(SimpleBitmap: TILSimpleBitmap); overload; virtual; destructor Destroy; override; Function ScanLine(Y: UInt32): Pointer; virtual; procedure AssignTo(Bitmap: TBitmap); virtual; procedure AssignFrom(Bitmap: TBitmap); overload; virtual; procedure AssignFrom(SimpleBitmap: TILSimpleBitmap); overload; virtual; procedure LoadFromStream(Stream: TStream); virtual; procedure SaveToStream(Stream: TStream); virtual; procedure DrawTo(Bitmap: TBitmap; AtX,AtY,Left,Top,Right,Bottom: Integer); overload; virtual; procedure DrawTo(Bitmap: TBitmap; AtX,AtY,Width,Height: Integer); overload; virtual; procedure DrawTo(Bitmap: TBitmap; AtX,AtY: Integer); overload; virtual; property Memory: Pointer read fMemory; property Size: TMemSize read fSize; property Pixels[X,Y: UInt32]: TILRGBAQuad read GetPixel write SetPixel; default; property Width: UInt32 read fWidth write SetWidth; property Height: UInt32 read fHeight write SetHeight; end; implementation uses SysUtils, Math, BinaryStreaming; Function RGBAToColor(RGBA: TILRGBAQuad): TColor; begin { TILRGBAQuad and TColor has the same memory layout. First byte is red channel, second byte id green channel and third byte is blue channel. Fourth byte (alpha) is masked-out and set to 0 in the result. } Result := TColor(RGBA) and $00FFFFFF; end; //------------------------------------------------------------------------------ Function ColorToRGBA(Color: TColor): TILRGBAQuad; begin // alpha is set to 255 (fully opaque) Result := TILRGBAQuad(Color or TColor($FF000000)); end; //------------------------------------------------------------------------------ Function RGBAToWinRGBA(RGBA: TILRGBAQuad): TRGBQuad; begin Result.rgbBlue := RGBA.B; Result.rgbGreen := RGBA.G; Result.rgbRed := RGBA.R; Result.rgbReserved := RGBA.A; end; //------------------------------------------------------------------------------ Function WinRGBAToRGBA(WinRGBA: TRGBQuad): TILRGBAQuad; begin Result.R := WinRGBA.rgbRed; Result.G := WinRGBA.rgbGreen; Result.B := WinRGBA.rgbBlue; Result.A := WinRGBA.rgbReserved; end; //------------------------------------------------------------------------------ Function RGBAToWinRGB(RGBA: TILRGBAQuad): TRGBTriple; begin Result.rgbtBlue := RGBA.B; Result.rgbtGreen := RGBA.G; Result.rgbtRed := RGBA.R; // alpha is ignored end; //------------------------------------------------------------------------------ Function WinRGBToRGBA(WinRGB: TRGBTriple): TILRGBAQuad; begin Result.R := WinRGB.rgbtRed; Result.G := WinRGB.rgbtGreen; Result.B := WinRGB.rgbtBlue; Result.A := 255; // alpha is set to fully opaque end; //============================================================================== //------------------------------------------------------------------------------ //============================================================================== Function TILSimpleBitmap.GetPixel(X,Y: UInt32): TILRGBAQuad; begin If (Y < fHeight) and (X < fWidth) then Result := PILRGBAQuad(PtrUInt(fMemory) + (((PtrUInt(fWidth) * PtrUInt(Y)) + PtrUInt(X)) * SizeOf(TILRGBAQuad)))^ else raise Exception.CreateFmt('TILSimpleBitmap.GetPixel: Invalid coordinates [%d,%d].',[X,Y]); end; //------------------------------------------------------------------------------ procedure TILSimpleBitmap.SetPixel(X,Y: UInt32; Value: TILRGBAQuad); begin If (Y < fHeight) and (X < fWidth) then PILRGBAQuad(PtrUInt(fMemory) + (((PtrUInt(fWidth) * PtrUInt(Y)) + PtrUInt(X)) * SizeOf(TILRGBAQuad)))^ := Value else raise Exception.CreateFmt('TILSimpleBitmap.SetPixel: Invalid coordinates [%d,%d].',[X,Y]); end; //------------------------------------------------------------------------------ procedure TILSimpleBitmap.SetWidth(Value: UInt32); var NewSize: TMemSize; begin If Value <> fWidth then begin NewSize := TMemSize(Value) * TMemSize(fHeight) * SizeOf(TILRGBAQuad); Reallocate(NewSize); fWidth := Value; end; end; //------------------------------------------------------------------------------ procedure TILSimpleBitmap.SetHeight(Value: UInt32); var NewSize: TMemSize; begin If Value <> fHeight then begin NewSize := TMemSize(fWidth) * TMemSize(Value) * SizeOf(TILRGBAQuad); Reallocate(NewSize); fHeight := Value; end; end; //============================================================================== procedure TILSimpleBitmap.Reallocate(NewSize: TMemSize); begin If NewSize <> fSize then begin If NewSize > 0 then ReallocMem(fMemory,NewSize) else FreeMem(fMemory,NewSize); fSize := NewSize; end; end; //============================================================================== constructor TILSimpleBitmap.Create; begin inherited Create; fMemory := nil; fSize := 0; fWidth := 0; fHeight := 0; end; //------------------------------------------------------------------------------ constructor TILSimpleBitmap.CreateFrom(Bitmap: TBitmap); begin Create; AssignFrom(Bitmap); end; //------------------------------------------------------------------------------ constructor TILSimpleBitmap.CreateFrom(SimpleBitmap: TILSimpleBitmap); begin Create; AssignFrom(SimpleBitmap); end; //------------------------------------------------------------------------------ destructor TILSimpleBitmap.Destroy; begin If Assigned(fMemory) and (fSize > 0) then FreeMem(fMemory,fSize); inherited; end; //------------------------------------------------------------------------------ Function TILSimpleBitmap.ScanLine(Y: UInt32): Pointer; begin Result := Pointer(PtrUInt(fMemory) + ((PtrUInt(fWidth) * PtrUInt(Y)) * SizeOf(TILRGBAQuad))); end; //------------------------------------------------------------------------------ procedure TILSimpleBitmap.AssignTo(Bitmap: TBitmap); var SrcScanLine: Pointer; DstScanLine: Pointer; X,Y: Integer; begin // prepare destination bitmap Bitmap.PixelFormat := pf24bit; Bitmap.Width := fWidth; Bitmap.Height := fHeight; For Y := 0 to Pred(fHeight) do begin SrcScanLine := ScanLine(Y); DstScanLine := Bitmap.ScanLine[Y]; For X := 0 to Pred(fWidth) do PRGBTripleArray(DstScanLine)^[X] := RGBAToWinRGB(PILRGBAQuadArray(SrcScanLine)^[X]); end; end; //------------------------------------------------------------------------------ procedure TILSimpleBitmap.AssignFrom(Bitmap: TBitmap); var SrcScanLine: Pointer; DstScanLine: Pointer; X,Y: Integer; begin If Bitmap.PixelFormat = pf24Bit then begin Width := Bitmap.Width; Height := Bitmap.Height; For Y := 0 to Pred(fHeight) do begin SrcScanLine := Bitmap.ScanLine[Y]; DstScanLine := ScanLine(Y); For X := 0 to Pred(fWidth) do PILRGBAQuadArray(DstScanLine)^[X] := WinRGBToRGBA(PRGBTripleArray(SrcScanLine)^[X]); end; end else raise Exception.CreateFmt('TILSimpleBitmap.AssignFrom: Unsupported pixel format (%d).',[Ord(Bitmap.PixelFormat)]); end; //------------------------------------------------------------------------------ procedure TILSimpleBitmap.AssignFrom(SimpleBitmap: TILSimpleBitmap); begin fWidth := SimpleBitmap.Width; fHeight := SimpleBitmap.Height; Reallocate(SimpleBitmap.Size); Move(SimpleBitmap.Memory^,fMemory^,fSize); end; //------------------------------------------------------------------------------ procedure TILSimpleBitmap.LoadFromStream(Stream: TStream); begin If Stream_ReadUInt32(Stream) = IL_SIMPLE_BITMAP_SIGNATURE then begin Stream_ReadUInt32(Stream); // drop this value Width := Stream_ReadUInt32(Stream); Height := Stream_ReadUInt32(Stream); // setting width and height has allocated the memory Stream_ReadBuffer(Stream,fMemory^,fSize); end else raise Exception.Create('TILSimpleBitmap.LoadFromStream: Invalid signature.'); end; //------------------------------------------------------------------------------ procedure TILSimpleBitmap.SaveToStream(Stream: TStream); begin Stream_WriteUInt32(Stream,IL_SIMPLE_BITMAP_SIGNATURE); Stream_WriteUInt32(Stream,0); // reserved for future use Stream_WriteUInt32(Stream,fWidth); Stream_WriteUInt32(Stream,fHeight); Stream_WriteBuffer(Stream,fMemory^,fSize); end; //------------------------------------------------------------------------------ procedure TILSimpleBitmap.DrawTo(Bitmap: TBitmap; AtX,AtY,Left,Top,Right,Bottom: Integer); var SrcScanLine: Pointer; DstScanLine: Pointer; X,Y: Integer; begin If Bitmap.PixelFormat = pf24Bit then begin // rectify coordinates If Left < 0 then Left := 0; If Right >= Integer(fWidth) then Right := Pred(fWidth); If Top < 0 then Top := 0; If Bottom >= Integer(fHeight) then Bottom := Pred(fHeight); // traversing For Y := Top to Bottom do If ((Y + AtY - Top) >= 0) and ((Y + AtY - Top) < Bitmap.Height) then begin SrcScanLine := ScanLine(Y); DstScanLine := Bitmap.ScanLine[Y + AtY - Top]; For X := Left to Right do If ((X + AtX - Left) >= 0) and ((X + AtX - Left) < Bitmap.Width) then PRGBTripleArray(DstScanLine)^[X + AtX - Left] := RGBAToWinRGB(PILRGBAQuadArray(SrcScanLine)^[X]); end; end else raise Exception.CreateFmt('TILSimpleBitmap.DrawTo: Unsupported pixel format (%d).',[Ord(Bitmap.PixelFormat)]); end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - procedure TILSimpleBitmap.DrawTo(Bitmap: TBitmap; AtX,AtY,Width,Height: Integer); begin DrawTo(Bitmap,AtX,AtY,0,0,Pred(Width),Pred(Height)); end; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - procedure TILSimpleBitmap.DrawTo(Bitmap: TBitmap; AtX,AtY: Integer); begin DrawTo(Bitmap,AtX,AtY,0,0,Pred(fWidth),Pred(fHeight)); end; end.
{ ****************************************************************************** } { * geometry Rotation imp writen by QQ 600585@qq.com * } { * https://zpascal.net * } { * https://github.com/PassByYou888/zAI * } { * https://github.com/PassByYou888/ZServer4D * } { * https://github.com/PassByYou888/PascalString * } { * https://github.com/PassByYou888/zRasterization * } { * https://github.com/PassByYou888/CoreCipher * } { * https://github.com/PassByYou888/zSound * } { * https://github.com/PassByYou888/zChinese * } { * https://github.com/PassByYou888/zExpression * } { * https://github.com/PassByYou888/zGameWare * } { * https://github.com/PassByYou888/zAnalysis * } { * https://github.com/PassByYou888/FFMPEG-Header * } { * https://github.com/PassByYou888/zTranslate * } { * https://github.com/PassByYou888/InfiniteIoT * } { * https://github.com/PassByYou888/FastMD5 * } { ****************************************************************************** } unit GeometryRotationUnit; {$INCLUDE zDefine.inc} { create by,passbyyou } interface uses GeometryLib; procedure NormalizeMat(var M: TMatrix); procedure MulRMat(var M: TMatrix; const ScaleXYZ: TAffineVector); procedure DecodeOrderAngle(lvec, uvec, dvec: TAffineVector; var p, t, r: Single); overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} procedure DecodeOrderAngle(lvec, uvec, dvec: TVector; var p, t, r: Single); overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} procedure DecodeOrderAngle(uvec, dvec: TVector; var p, t, r: Single); overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} procedure DecodeOrderAngle(M: TMatrix; var p, t, r: Single); overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} function ComputePitch(uvec, dvec: TAffineVector): Single; overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} function ComputePitch(uvec, dvec: TVector): Single; overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} function ComputePitch(M: TMatrix): Single; overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} function ComputeTurn(uvec, dvec: TAffineVector): Single; overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} function ComputeTurn(uvec, dvec: TVector): Single; overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} function ComputeTurn(M: TMatrix): Single; overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} function ComputeRoll(uvec, dvec: TAffineVector): Single; overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} function ComputeRoll(uvec, dvec: TVector): Single; overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} function ComputeRoll(M: TMatrix): Single; overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} procedure StepPitch(var uvec, dvec: TVector; angle: Single); overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} procedure StepPitch(uvec, dvec: TVector; angle: Single; var p, t, r: Single); overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} procedure StepPitch(M: TMatrix; angle: Single; var p, t, r: Single); overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} procedure StepPitch(var M: TMatrix; ScaleXYZ: TAffineVector; angle: Single); overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} procedure StepTurn(var uvec, dvec: TVector; angle: Single); overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} procedure StepTurn(uvec, dvec: TVector; angle: Single; var p, t, r: Single); overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} procedure StepTurn(M: TMatrix; angle: Single; var p, t, r: Single); overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} procedure StepTurn(var M: TMatrix; ScaleXYZ: TAffineVector; angle: Single); overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} procedure StepRoll(var uvec, dvec: TVector; angle: Single); overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} procedure StepRoll(uvec, dvec: TVector; angle: Single; var p, t, r: Single); overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} procedure StepRoll(M: TMatrix; angle: Single; var p, t, r: Single); overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} procedure StepRoll(var M: TMatrix; ScaleXYZ: TAffineVector; angle: Single); overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} procedure SetPitch(var uvec, dvec: TAffineVector; angle: Single); overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} procedure SetPitch(var uvec, dvec: TVector; angle: Single); overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} procedure SetPitch(var M: TMatrix; ScaleXYZ: TAffineVector; angle: Single); overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} procedure SetTurn(var uvec, dvec: TAffineVector; angle: Single); overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} procedure SetTurn(var uvec, dvec: TVector; angle: Single); overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} procedure SetTurn(var M: TMatrix; ScaleXYZ: TAffineVector; angle: Single); overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} procedure SetRoll(var uvec, dvec: TAffineVector; angle: Single); overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} procedure SetRoll(var uvec, dvec: TVector; angle: Single); overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} procedure SetRoll(var M: TMatrix; ScaleXYZ: TAffineVector; angle: Single); overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} implementation procedure NormalizeMat(var M: TMatrix); begin NormalizeVector(M[0]); NormalizeVector(M[1]); NormalizeVector(M[2]); end; procedure MulRMat(var M: TMatrix; const ScaleXYZ: TAffineVector); begin M[0][0] := M[0][0] * ScaleXYZ[0]; M[0][0] := M[0][1] * ScaleXYZ[0]; M[0][0] := M[0][2] * ScaleXYZ[0]; M[0][0] := M[0][3] * ScaleXYZ[0]; M[1][0] := M[1][0] * ScaleXYZ[1]; M[1][0] := M[1][1] * ScaleXYZ[1]; M[1][0] := M[1][2] * ScaleXYZ[1]; M[1][0] := M[1][3] * ScaleXYZ[1]; M[2][0] := M[2][0] * ScaleXYZ[2]; M[2][0] := M[2][1] * ScaleXYZ[2]; M[2][0] := M[2][2] * ScaleXYZ[2]; M[2][0] := M[2][3] * ScaleXYZ[2]; end; procedure DecodeOrderAngle(lvec, uvec, dvec: TAffineVector; var p, t, r: Single); var sinTurn, cosTurn, sinPitch, cosPitch, sinRoll, cosRoll: Single; begin sinTurn := -dvec[0]; cosTurn := Sqrt(1 - sinTurn * sinTurn); if (Abs(cosTurn) > Epsilon) then begin sinPitch := dvec[1] / cosTurn; cosPitch := dvec[2] / cosTurn; sinRoll := uvec[0] / cosTurn; cosRoll := lvec[0] / cosTurn; end else begin sinPitch := -uvec[2]; cosPitch := uvec[1]; sinRoll := 0; cosRoll := 1; end; p := RadToDeg(ArcTan2(sinPitch, cosPitch)); t := -RadToDeg(ArcTan2(sinTurn, cosTurn)); r := -RadToDeg(ArcTan2(sinRoll, cosRoll)); end; procedure DecodeOrderAngle(lvec, uvec, dvec: TVector; var p, t, r: Single); begin DecodeOrderAngle(PAffineVector(@lvec)^, PAffineVector(@uvec)^, PAffineVector(@dvec)^, p, t, r); end; procedure DecodeOrderAngle(uvec, dvec: TVector; var p, t, r: Single); var lvec: TVector; begin lvec := VectorCrossProduct(uvec, dvec); NormalizeVector(lvec); DecodeOrderAngle(lvec, uvec, dvec, p, t, r); end; procedure DecodeOrderAngle(M: TMatrix; var p, t, r: Single); begin DecodeOrderAngle(M[0], M[1], M[2], p, t, r); end; function ComputePitch(uvec, dvec: TAffineVector): Single; overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} var sinTurn, cosTurn, sinPitch, cosPitch: Single; begin sinTurn := -dvec[0]; cosTurn := Sqrt(1 - sinTurn * sinTurn); sinPitch := dvec[1] / cosTurn; cosPitch := dvec[2] / cosTurn; Result := RadToDeg(ArcTan2(sinPitch, cosPitch)); end; function ComputePitch(uvec, dvec: TVector): Single; overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} begin Result := ComputePitch(PAffineVector(@uvec)^, PAffineVector(@dvec)^); end; function ComputePitch(M: TMatrix): Single; overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} begin Result := ComputePitch(M[1], M[2]); end; function ComputeTurn(uvec, dvec: TAffineVector): Single; overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} var sinTurn, cosTurn: Single; begin sinTurn := -dvec[0]; cosTurn := Sqrt(1 - sinTurn * sinTurn); Result := -RadToDeg(ArcTan2(sinTurn, cosTurn)); end; function ComputeTurn(uvec, dvec: TVector): Single; overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} begin Result := ComputeTurn(PAffineVector(@uvec)^, PAffineVector(@dvec)^); end; function ComputeTurn(M: TMatrix): Single; overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} begin Result := ComputeTurn(M[1], M[2]); end; function ComputeRoll(uvec, dvec: TAffineVector): Single; overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} var lvec: TAffineVector; sinTurn, cosTurn, sinRoll, cosRoll: Single; begin lvec := VectorCrossProduct(uvec, dvec); sinTurn := -dvec[0]; cosTurn := Sqrt(1 - sinTurn * sinTurn); sinRoll := uvec[0] / cosTurn; cosRoll := lvec[0] / cosTurn; Result := -RadToDeg(ArcTan2(sinRoll, cosRoll)); end; function ComputeRoll(uvec, dvec: TVector): Single; overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} begin Result := ComputeRoll(PAffineVector(@uvec)^, PAffineVector(@dvec)^); end; function ComputeRoll(M: TMatrix): Single; overload; {$IFDEF INLINE_ASM} inline; {$ENDIF} begin Result := ComputeRoll(M[1], M[2]); end; procedure StepPitch(var uvec, dvec: TVector; angle: Single); var rvec: TVector; begin angle := -DegToRad(angle); rvec := VectorCrossProduct(dvec, uvec); RotateVector(uvec, rvec, angle); NormalizeVector(uvec); RotateVector(dvec, rvec, angle); NormalizeVector(dvec); end; procedure StepPitch(uvec, dvec: TVector; angle: Single; var p, t, r: Single); begin StepPitch(uvec, dvec, angle); DecodeOrderAngle(uvec, dvec, p, t, r); end; procedure StepPitch(M: TMatrix; angle: Single; var p, t, r: Single); begin StepPitch(M, XYZVector, angle); DecodeOrderAngle(M, p, t, r); end; procedure StepPitch(var M: TMatrix; ScaleXYZ: TAffineVector; angle: Single); begin NormalizeMat(M); StepPitch(M[1], M[2], angle); // change left vector M[0] := VectorCrossProduct(M[1], M[2]); MulRMat(M, ScaleXYZ); end; procedure StepTurn(var uvec, dvec: TVector; angle: Single); var uvec2: TAffineVector; begin angle := -DegToRad(angle); uvec2 := AffineVectorMake(uvec); RotateVector(uvec, uvec2, angle); NormalizeVector(uvec); RotateVector(dvec, uvec2, angle); NormalizeVector(dvec); end; procedure StepTurn(uvec, dvec: TVector; angle: Single; var p, t, r: Single); begin StepTurn(uvec, dvec, angle); DecodeOrderAngle(uvec, dvec, p, t, r); end; procedure StepTurn(M: TMatrix; angle: Single; var p, t, r: Single); begin StepTurn(M, XYZVector, angle); DecodeOrderAngle(M, p, t, r); end; procedure StepTurn(var M: TMatrix; ScaleXYZ: TAffineVector; angle: Single); begin NormalizeMat(M); StepTurn(M[1], M[2], angle); // change left vector M[0] := VectorCrossProduct(M[1], M[2]); MulRMat(M, ScaleXYZ); end; procedure StepRoll(var uvec, dvec: TVector; angle: Single); var dvec2: TVector; begin angle := -DegToRad(angle); dvec2 := dvec; RotateVector(uvec, dvec2, angle); NormalizeVector(uvec); RotateVector(dvec, dvec2, angle); NormalizeVector(dvec); end; procedure StepRoll(uvec, dvec: TVector; angle: Single; var p, t, r: Single); begin StepRoll(uvec, dvec, angle); DecodeOrderAngle(uvec, dvec, p, t, r); end; procedure StepRoll(M: TMatrix; angle: Single; var p, t, r: Single); begin StepRoll(M, XYZVector, angle); DecodeOrderAngle(M, p, t, r); end; procedure StepRoll(var M: TMatrix; ScaleXYZ: TAffineVector; angle: Single); begin NormalizeMat(M); StepRoll(M[1], M[2], angle); // change left vector M[0] := VectorCrossProduct(M[1], M[2]); MulRMat(M, ScaleXYZ); end; procedure SetPitch(var uvec, dvec: TAffineVector; angle: Single); var rvec: TAffineVector; Diff: Single; rotMatrix: TMatrix; begin rvec := VectorCrossProduct(dvec, uvec); Diff := DegToRad(ComputePitch(uvec, dvec) - angle); rotMatrix := CreateRotationMatrix(rvec, Diff); uvec := VectorTransform(uvec, rotMatrix); NormalizeVector(uvec); dvec := VectorTransform(dvec, rotMatrix); NormalizeVector(dvec); end; procedure SetPitch(var uvec, dvec: TVector; angle: Single); begin SetPitch(PAffineVector(@uvec)^, PAffineVector(@dvec)^, angle); end; procedure SetPitch(var M: TMatrix; ScaleXYZ: TAffineVector; angle: Single); begin NormalizeMat(M); SetPitch(M[1], M[2], angle); // change left vector M[0] := VectorCrossProduct(M[1], M[2]); MulRMat(M, ScaleXYZ); end; procedure SetTurn(var uvec, dvec: TAffineVector; angle: Single); var rvec: TAffineVector; Diff: Single; rotMatrix: TMatrix; begin rvec := VectorCrossProduct(dvec, uvec); Diff := DegToRad(ComputeTurn(uvec, dvec) - angle); rotMatrix := CreateRotationMatrix(uvec, Diff); uvec := VectorTransform(uvec, rotMatrix); NormalizeVector(uvec); dvec := VectorTransform(dvec, rotMatrix); NormalizeVector(dvec); end; procedure SetTurn(var uvec, dvec: TVector; angle: Single); begin SetTurn(PAffineVector(@uvec)^, PAffineVector(@dvec)^, angle); end; procedure SetTurn(var M: TMatrix; ScaleXYZ: TAffineVector; angle: Single); begin NormalizeMat(M); SetTurn(M[1], M[2], angle); // change left vector M[0] := VectorCrossProduct(M[1], M[2]); MulRMat(M, ScaleXYZ); end; procedure SetRoll(var uvec, dvec: TAffineVector; angle: Single); var rvec: TAffineVector; Diff: Single; rotMatrix: TMatrix; begin rvec := VectorCrossProduct(dvec, uvec); Diff := DegToRad(ComputeRoll(uvec, dvec) - angle); rotMatrix := CreateRotationMatrix(dvec, Diff); uvec := VectorTransform(uvec, rotMatrix); NormalizeVector(uvec); dvec := VectorTransform(dvec, rotMatrix); NormalizeVector(dvec); end; procedure SetRoll(var uvec, dvec: TVector; angle: Single); begin SetRoll(PAffineVector(@uvec)^, PAffineVector(@dvec)^, angle); end; procedure SetRoll(var M: TMatrix; ScaleXYZ: TAffineVector; angle: Single); begin NormalizeMat(M); SetRoll(M[1], M[2], angle); // change left vector M[0] := VectorCrossProduct(M[1], M[2]); MulRMat(M, ScaleXYZ); end; end.
library Streams; uses SysUtils, Classes, svm in '..\svm.pas'; {STREAM} type TStreamContainer = class public stream: TStream; constructor Create(s: TStream); end; constructor TStreamContainer.Create(s: TStream); begin self.stream := s; end; procedure _Stream_Destructor(pStreamContainer: pointer); stdcall; var sct: TStreamContainer; begin sct := TStreamContainer(pStreamContainer); sct.stream.Free; sct.Free; end; procedure _Stream_Create(pctx: pointer); stdcall; begin __Return_Ref(pctx, TStreamContainer.Create(TStream.Create), @_Stream_Destructor); end; procedure _Stream_Seek(pctx: pointer); stdcall; var St:TStream; P: Cardinal; begin St := TStream(TStreamContainer(__Next_Ref(pctx)).stream); P := __Next_Word(pctx); St.Seek(P, TSeekOrigin(__Next_Word(pctx))); end; procedure _Stream_GetCaretPos(pctx: pointer); stdcall; begin __Return_Word(pctx, TStreamContainer(__Next_Ref(pctx)).stream.Position); end; procedure _Stream_WriteFromMemoryStream(pctx: pointer); stdcall; var Dest:TStream; Src:TMemoryStream; begin Dest := TStreamContainer(__Next_Ref(pctx)).stream; Src := TMemoryStream(TStreamContainer(__Next_Ref(pctx)).stream); Dest.Write(PByte(Cardinal(Src.Memory) + Src.Position)^, __Next_Word(pctx)); end; procedure _Stream_ReadFromMemoryStream(pctx: pointer); stdcall; var Dest:TStream; Src:TMemoryStream; begin Dest := TStreamContainer(__Next_Ref(pctx)).stream; Src := TMemoryStream(TStreamContainer(__Next_Ref(pctx)).stream); Dest.Read(PByte(Cardinal(Src.Memory) + Src.Position)^, __Next_Word(pctx)); end; procedure _Stream_CopyFromStream(pctx: pointer); stdcall; var St, From: TStream; begin St := TStreamContainer(__Next_Ref(pctx)).stream; From := TStreamContainer(__Next_Ref(pctx)).stream; St.CopyFrom(From, __Next_Word(pctx)); end; procedure _Stream_WriteByte(pctx: pointer); stdcall; var Dest:TStream; begin Dest := TStreamContainer(__Next_Ref(pctx)).stream; Dest.WriteByte(__Next_Word(pctx)); end; procedure _Stream_WriteWord(pctx: pointer); stdcall; var Dest:TStream; Val:Cardinal; begin Dest := TStreamContainer(__Next_Ref(pctx)).stream; Val := __Next_Word(pctx); Dest.Write(Val, SizeOf(Val)); end; procedure _Stream_WriteInt(pctx: pointer); stdcall; var Dest:TStream; Val:Int64; begin Dest := TStreamContainer(__Next_Ref(pctx)).stream; Val := __Next_Int(pctx); Dest.Write(Val, SizeOf(Val)); end; procedure _Stream_WriteFloat(pctx: pointer); stdcall; var Dest:TStream; Val:Double; begin Dest := TStreamContainer(__Next_Ref(pctx)).stream; Val := __Next_Float(pctx); Dest.Write(Val, SizeOf(Val)); end; procedure _Stream_WriteStr(pctx: pointer); stdcall; var Dest:TStream; Val:String; begin Dest := TStreamContainer(__Next_Ref(pctx)).stream; Val := ''; __Next_String(pctx, @Val); Dest.Write(Val[1], Length(Val)); end; procedure _Stream_ReadByte(pctx: pointer); stdcall; var Dest:TStream; begin Dest := TStreamContainer(__Next_Ref(pctx)).stream; __Return_Word(pctx, Dest.ReadByte); end; procedure _Stream_ReadWord(pctx: pointer); stdcall; var Dest:TStream; Val:Cardinal; begin Dest := TStreamContainer(__Next_Ref(pctx)).stream; Val := 0; Dest.Read(Val, SizeOf(Val)); __Return_Word(pctx, Val); end; procedure _Stream_ReadInt(pctx: pointer); stdcall; var Dest:TStream; Val:Int64; begin Dest := TStreamContainer(__Next_Ref(pctx)).stream; Val := 0; Dest.Read(Val, SizeOf(Val)); __Return_Int(pctx, Val); end; procedure _Stream_ReadFloat(pctx: pointer); stdcall; var Dest:TStream; Val:Double; begin Dest := TStreamContainer(__Next_Ref(pctx)).stream; Val := 0; Dest.Read(Val, SizeOf(Val)); __Return_Float(pctx, Val); end; procedure _Stream_ReadStr(pctx: pointer); stdcall; var Dest:TStream; Val:Pointer; Len:Cardinal; S:String; begin Dest := TStreamContainer(__Next_Ref(pctx)).stream; Len := __Next_Word(pctx); SetLength(S, Len); Dest.Read(S[1], Len); __Return_StringA(pctx, S); end; procedure _Stream_CopyBuffer(pctx: pointer); stdcall; var From, Dest:TStream; Buf:TBytes; Len:Cardinal; S:String; begin From := TStreamContainer(__Next_Ref(pctx)).stream; Dest := TStreamContainer(__Next_Ref(pctx)).stream; Len := __Next_Word(pctx); try SetLength(Buf, Len); From.Read(Buf, Len); Dest.Write(Buf, Len); __Return_Bool(pctx, true); except __Return_Bool(pctx, false); end; SetLength(Buf, 0); end; procedure _Stream_GetSize(pctx: pointer); stdcall; begin __Return_Word(pctx, TStreamContainer(__Next_Ref(pctx)).stream.Size); end; procedure _Stream_Clear(pctx: pointer); stdcall; begin TStreamContainer(__Next_Ref(pctx)).stream.Size := 0; end; procedure _Stream_UnPack(pctx: pointer); stdcall; begin __Return_Ref(pctx, TStreamContainer(__Next_Ref(pctx)).stream, nil); end; {MEMORYSTREAM} procedure _MemoryStream_Destructor(pStreamContainer: pointer); stdcall; var sct: TStreamContainer; begin sct := TStreamContainer(pStreamContainer); TMemoryStream(sct.stream).Free; sct.Free; end; procedure _MemoryStream_Create(pctx: pointer); stdcall; begin __Return_Ref(pctx, TStreamContainer.Create(TMemoryStream.Create), @_MemoryStream_Destructor); end; procedure _MemoryStream_LoadFromResource(pctx: pointer); stdcall; var Ms: TMemoryStream; begin Ms := TMemoryStream(TStreamContainer(__Next_Ref(pctx)).stream); Ms.LoadFromStream(TStream(__Next_Ref(pctx))); end; procedure _MemoryStream_LoadFromStream(pctx: pointer); stdcall; var Ms: TMemoryStream; begin Ms := TMemoryStream(TStreamContainer(__Next_Ref(pctx)).stream); Ms.LoadFromStream(TStreamContainer(__Next_Ref(pctx)).stream); end; procedure _MemoryStream_StoreToStream(pctx: pointer); stdcall; var Ms: TMemoryStream; begin Ms := TMemoryStream(TStreamContainer(__Next_Ref(pctx)).stream); Ms.SaveToStream(TStreamContainer(__Next_Ref(pctx)).stream); end; procedure _MemoryStream_LoadFromFile(pctx: pointer); stdcall; var fp: string; begin try fp := __Next_StringA(pctx); if not (Pos(':', fp) > 0) then fp := ExtractFilePath(ParamStr(1)) + fp; TMemoryStream(TStreamContainer(__Next_Ref(pctx)).stream).LoadFromFile(fp); __Return_Bool(pctx, true); except __Return_Bool(pctx, false); end; end; procedure _MemoryStream_SaveToFile(pctx: pointer); stdcall; var fp: string; begin try fp := __Next_StringA(pctx); if not (Pos(':', fp) > 0) then fp := ExtractFilePath(ParamStr(1)) + fp; TMemoryStream(TStreamContainer(__Next_Ref(pctx)).stream).SaveToFile(fp); __Return_Bool(pctx, true); except __Return_Bool(pctx, false); end; end; {FILESTREAM} procedure _FileStream_Destructor(pStreamContainer: pointer); stdcall; var sct: TStreamContainer; begin sct := TStreamContainer(pStreamContainer); if sct.stream <> nil then TFileStream(sct.stream).Free; sct.Free; end; procedure _FileStream_Create(pctx: pointer); stdcall; var fp: string; begin try fp := __Next_StringA(pctx); if not (Pos(':', fp) > 0) then fp := ExtractFilePath(ParamStr(1)) + fp; __Return_Ref(pctx, TStreamContainer.Create(TFileStream.Create(fp, __Next_Word(pctx))), @_FileStream_Destructor); except __Return_Null(pctx); end; end; procedure _FileStream_Close(pctx: pointer); stdcall; var sct: TStreamContainer; begin sct := TStreamContainer(__Next_Ref(pctx)); TFileStream(sct.stream).Free; sct.stream := nil; end; {EXPORTS DB} exports _Stream_Create name '_Stream_Create'; exports _Stream_Seek name '_Stream_Seek'; exports _Stream_GetCaretPos name '_Stream_GetCaretPos'; exports _Stream_WriteFromMemoryStream name '_Stream_WriteFromMemoryStream'; exports _Stream_ReadFromMemoryStream name '_Stream_ReadFromMemoryStream'; exports _Stream_CopyFromStream name '_Stream_CopyFromStream'; exports _Stream_WriteByte name '_Stream_WriteByte'; exports _Stream_WriteWord name '_Stream_WriteWord'; exports _Stream_WriteInt name '_Stream_WriteInt'; exports _Stream_WriteFloat name '_Stream_WriteFloat'; exports _Stream_WriteStr name '_Stream_WriteStr'; exports _Stream_ReadByte name '_Stream_ReadByte'; exports _Stream_ReadWord name '_Stream_ReadWord'; exports _Stream_ReadInt name '_Stream_ReadInt'; exports _Stream_ReadFloat name '_Stream_ReadFloat'; exports _Stream_ReadStr name '_Stream_ReadStr'; exports _Stream_CopyBuffer name '_Stream_CopyBuffer'; exports _Stream_GetSize name '_Stream_GetSize'; exports _Stream_Clear name '_Stream_Clear'; exports _Stream_UnPack name '_Stream_UnPack'; exports _MemoryStream_Create name '_MemoryStream_Create'; exports _MemoryStream_LoadFromResource name '_MemoryStream_LoadFromResource'; exports _MemoryStream_LoadFromStream name '_MemoryStream_LoadFromStream'; exports _MemoryStream_StoreToStream name '_MemoryStream_StoreToStream'; exports _MemoryStream_LoadFromFile name '_MemoryStream_LoadFromFile'; exports _MemoryStream_SaveToFile name '_MemoryStream_SaveToFile'; exports _FileStream_Create name '_FileStream_Create'; exports _FileStream_Close name '_FileStream_Close'; begin end.
unit DiscSpec_EditForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ActnList, dxBar, dxBarExtItems, ImgList, cxGraphics, cxCustomData, cxStyles, cxTL, cxControls, cxInplaceContainer, cxTLData, cxDBTL, cxLabel, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxButtonEdit, ExtCtrls, FIBDatabase, pFIBDatabase, FIBQuery, pFIBQuery, pFIBStoredProc, DB, FIBDataSet, pFIBDataSet, IBase, DiscSpec_dmCommonStyles; type TfEditForm = class(TForm) ImageList: TImageList; BarManager1: TdxBarManager; RefresBtn: TdxBarLargeButton; SaveBtn: TdxBarLargeButton; ExitBtn: TdxBarLargeButton; ActionList: TActionList; RefreshA: TAction; SaveA: TAction; ExitA: TAction; MainTreeList: TcxDBTreeList; DiscSpecPanel: TPanel; SpecBE: TcxButtonEdit; DiscBE: TcxButtonEdit; SpecLabel: TcxLabel; DiscLabel: TcxLabel; DB: TpFIBDatabase; Transaction: TpFIBTransaction; WriteTransaction: TpFIBTransaction; DSet: TpFIBDataSet; StoredProc: TpFIBStoredProc; DSource: TDataSource; cmnTEXT: TcxDBTreeListColumn; cmnPERCENT: TcxDBTreeListColumn; cmnID: TcxDBTreeListColumn; cmnID_PARENT: TcxDBTreeListColumn; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure RefreshAExecute(Sender: TObject); private { Private declarations } pStylesDM:TStylesDM; pID_DISC_SPEC:Int64; public { Public declarations } constructor Create(AOwner:TComponent;ADB_HANDLE:TISC_DB_HANDLE;AID:Int64);reintroduce; end; implementation {$R *.dfm} constructor TfEditForm.Create(AOwner:TComponent;ADB_HANDLE:TISC_DB_HANDLE;AID:Int64); begin inherited Create(AOwner); pID_DISC_SPEC:=AID; //****************************************************************************** DB.Handle:=ADB_HANDLE; Transaction.Active:=True; //****************************************************************************** pStylesDM:=TStylesDM.Create(Self); MainTreeList.Styles.StyleSheet:=pStylesDM.TreeListStyleSheetDevExpress; //****************************************************************************** RefreshAExecute(Self); end; procedure TfEditForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Transaction.Active:=False; end; procedure TfEditForm.RefreshAExecute(Sender: TObject); begin if DSet.Active then DSet.Close; DSet.SQLs.SelectSQL.Text:='SELECT * FROM UO_SP_DISC_SPEC_DISTRIB_S('+IntToStr(pID_DISC_SPEC)+')'; DSet.Open; end; end.
unit Demo.ProcessLine; { ProcessLines example from the the Duktape guide (http://duktape.org/guide.html) } interface uses Duktape, Demo; type TDemoProcessLine = class(TDemo) public procedure Run; override; end; implementation { TDemoProcessLine } procedure TDemoProcessLine.Run; const LINE = 'Escape HTML: <Test>, Make *bold*.'; begin PushResource('PROCESS'); if (Duktape.ProtectedEval <> 0) then begin Log('Error: ' + String(Duktape.SafeToString(-1))); Exit; end; Duktape.Pop; // Ignore result Duktape.PushGlobalObject; Duktape.GetProp(-1, 'processLine'); Duktape.PushString(LINE); if (Duktape.ProtectedCall(1) <> 0) then Log('Error: ' + String(Duktape.SafeToString(-1))) else Log(LINE + ' -> ' + String(Duktape.SafeToString(-1))); Duktape.Pop; end; initialization TDemo.Register('Process Line', TDemoProcessLine); end.
// // This unit is part of the GLScene Project, http://glscene.org // {: GLFileQ3BSP<p> Support-code to load Q3BSP Files into TGLFreeForm-Components in GLScene.<p> Note that you must manually add this unit to one of your project's uses to enable support for OBJ & OBJF at run-time.<p> <b>History : </b><font size=-1><ul> <li>22/01/10 - Yar - Added GLTextureFormat to uses <li>31/03/07 - DaStr - Added $I GLScene.inc <li>31/01/03 - EG - Materials support <li>30/01/03 - EG - Creation </ul><p> } unit GLFileQ3BSP; interface {$I GLScene.inc} uses Classes, GLVectorFileObjects, ApplicationFileIO; type // TGLQ3BSPVectorFile // {: The Q3BSP vector file (Quake III BSP).<p> } TGLQ3BSPVectorFile = class(TVectorFile) public { Public Declarations } class function Capabilities : TDataFileCapabilities; override; procedure LoadFromStream(aStream: TStream); override; end; var // Q3 lightmaps are quite dark, we brighten them a lot by default vQ3BSPLightmapGammaCorrection : Single = 2.5; vQ3BSPLightmapBrightness : Single = 2; // scaling factor, 1.0 = unchanged vGLFileQ3BSPLoadMaterials : boolean = True; // Mrqzzz : Flag to avoid loading materials (useful for IDE Extentions like GlaredX) // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ uses Q3BSP, GLVectorGeometry, GLVectorLists, SysUtils, GLBSP, GLTexture, GLGraphics, GLCrossPlatform, GLState, GLUtils, GLMaterial, GLTextureFormat; // ------------------ // ------------------ TGLSTLVectorFile ------------------ // ------------------ // Capabilities // class function TGLQ3BSPVectorFile.Capabilities : TDataFileCapabilities; begin Result:=[dfcRead]; end; // LoadFromStream // procedure TGLQ3BSPVectorFile.LoadFromStream(aStream : TStream); function LocateTextureFile(const texName : String) : String; begin if FileStreamExists(texName+'.bmp') then Result:=texName+'.bmp' else if FileStreamExists(texName+'.jpg') then Result:=texName+'.jpg' else if FileStreamExists(texName+'.tga') then Result:=texName+'.tga' else Result:=''; end; function GetOrAllocateMaterial(const matName : String) : String; var matLib : TGLMaterialLibrary; libMat : TGLLibMaterial; texName : String; begin if GetOwner is TGLBaseMesh then begin // got a linked material library? matLib:=TGLBaseMesh(GetOwner).MaterialLibrary; if Assigned(matLib) then begin Result:=matName; libMat:=matLib.Materials.GetLibMaterialByName(matName); if not Assigned(libMat) then begin if Pos('.', matName)<1 then begin texName:=LocateTextureFile(matName); if texName='' then texName:=LocateTextureFile(Copy(matName, LastDelimiter('\/', matName)+1, MaxInt)); end else texName:=matName; with matLib.AddTextureMaterial(matName, texName) do begin Material.Texture.TextureMode:=tmModulate; end; end; end else Result:=''; end else Result:=''; end; var bsp : TQ3BSP; mo : TBSPMeshObject; fg, lastfg : TFGBSPNode; i, j, n, y : Integer; facePtr : PBSPFace; lightmapLib : TGLMaterialLibrary; lightmapBmp : TGLBitmap; libMat : TGLLibMaterial; bspLightMap : PBSPLightmap; plane : THmgPlane; begin bsp:=TQ3BSP.Create(aStream); try mo:=TBSPMeshObject.CreateOwned(Owner.MeshObjects); // import all materials if vGLFileQ3BSPLoadMaterials then begin for i:=0 to High(bsp.Textures) do begin GetOrAllocateMaterial(Trim(StrPas(bsp.Textures[i].TextureName))); end; end; // import all lightmaps lightmapLib:=Owner.LightmapLibrary; if Assigned(lightmapLib) and vGLFileQ3BSPLoadMaterials then begin // import lightmaps n:=bsp.NumOfLightmaps; lightmapBmp:=TGLBitmap.Create; try lightmapBmp.PixelFormat:=glpf24bit; lightmapBmp.Width:=128; lightmapBmp.Height:=128; for i:=0 to n-1 do begin bspLightMap:=@bsp.Lightmaps[i]; // apply brightness correction if ant if vQ3BSPLightmapBrightness<>1 then BrightenRGBArray(@bspLightMap.imageBits[0], 128*128, vQ3BSPLightmapBrightness); // apply gamma correction if any if vQ3BSPLightmapGammaCorrection<>1 then GammaCorrectRGBArray(@bspLightMap.imageBits[0], 128*128, vQ3BSPLightmapGammaCorrection); // convert RAW RGB to BMP {$WARNING crossbuilder: disabled call to BGR24ToRGB24. Please enable! } {for y:=0 to 127 do BGR24ToRGB24(@bspLightMap.imageBits[y*128*3], lightmapBmp.ScanLine[127-y], 128);} // spawn lightmap libMat:=lightmapLib.AddTextureMaterial(IntToStr(i), lightmapBmp); with libMat.Material.Texture do begin MinFilter:=miLinear; TextureWrap:=twNone; TextureFormat:=tfRGB; end; end; finally lightmapBmp.Free; end; end; // import all geometry mo.Vertices.AdjustCapacityToAtLeast(bsp.NumOfVerts); mo.Normals.AdjustCapacityToAtLeast(bsp.NumOfVerts); mo.TexCoords.AdjustCapacityToAtLeast(bsp.NumOfVerts); for i:=0 to bsp.NumOfVerts-1 do begin mo.Vertices.Add(bsp.Vertices[i].Position); mo.Normals.Add(bsp.Vertices[i].Normal); mo.TexCoords.Add(bsp.Vertices[i].TextureCoord); if Assigned(lightMapLib) and vGLFileQ3BSPLoadMaterials then mo.LightMapTexCoords.Add(bsp.Vertices[i].LightmapCoord) end; mo.TexCoords.Scale(AffineVectorMake(1, -1, 0)); mo.TexCoords.Translate(YVector); mo.RenderSort:=rsBackToFront; // Q3 BSP separates tree nodes from leafy nodes, we don't, // so we place nodes first, then all leafs afterwards for i:=0 to bsp.NumOfNodes-1 do begin fg:=TFGBSPNode.CreateOwned(mo.FaceGroups); plane:=bsp.Planes[bsp.Nodes[i].plane]; plane:=VectorMake(plane[0], plane[1], plane[2], plane[3]); fg.SplitPlane:=plane; fg.PositiveSubNodeIndex:=bsp.Nodes[i].Children[0]; if fg.PositiveSubNodeIndex<0 then fg.PositiveSubNodeIndex:=bsp.NumOfNodes-fg.PositiveSubNodeIndex-1; Assert(fg.PositiveSubNodeIndex<bsp.NumOfNodes+bsp.NumOfLeaves); Assert(fg.PositiveSubNodeIndex>0); fg.NegativeSubNodeIndex:=bsp.Nodes[i].Children[1]; if fg.NegativeSubNodeIndex<0 then fg.NegativeSubNodeIndex:=bsp.NumOfNodes-fg.NegativeSubNodeIndex-1; Assert(fg.NegativeSubNodeIndex<bsp.NumOfNodes+bsp.NumOfLeaves); Assert(fg.NegativeSubNodeIndex>0); end; // import all leaves for i:=0 to bsp.NumOfLeaves-1 do TFGBSPNode.CreateOwned(mo.FaceGroups); // import all faces into leaves & subnodes for i:=0 to bsp.NumOfLeaves-1 do begin lastfg:=nil; for j:=0 to bsp.Leaves[i].NumFaces-1 do begin n:=bsp.Leaves[i].FirstFace+j; if n>=bsp.NumOfFaces then Break; // corrupted BSP? facePtr:=@bsp.Faces[n]; if facePtr.FaceType=FACE_POLYGON then begin if lastfg=nil then fg:=TFGBSPNode(mo.FaceGroups[i+bsp.NumOfNodes]) else begin lastfg.PositiveSubNodeIndex:=mo.FaceGroups.Count; fg:=TFGBSPNode.CreateOwned(mo.FaceGroups); end; // check for BSP corruption if Cardinal(facePtr.textureID)<=Cardinal(bsp.NumOfTextures) then fg.MaterialName:=Trim(StrPas(bsp.Textures[facePtr.textureID].TextureName)); if Assigned(lightmapLib) and vGLFileQ3BSPLoadMaterials then fg.LightMapIndex:=facePtr.lightmapID; lastfg:=fg; // Q3 Polygon Faces are actually fans, but winded the other way around! fg.Mode:=fgmmTriangleFan; fg.VertexIndices.Add(facePtr.startVertIndex); fg.VertexIndices.AddSerie(facePtr.startVertIndex+facePtr.numOfVerts-1, -1, facePtr.numOfVerts-1); // there are also per-leaf mesh references... dunno what they // are for, did not encounter them so far... If you have a BSP // that has some, and if you know how to make use of them, shout! // Copy the cluster index, used for visibility determination fg.Cluster:=bsp.Leaves[i].Cluster; end; end; end; // Copy the visibility data if bsp.VisData.numOfClusters>0 then mo.ClusterVisibility.SetData( @bsp.VisData.bitSets[0], bsp.VisData.numOfClusters); finally bsp.Free; end; // Some BSP end up with empty nodes/leaves (information unused, incorrept BSP...) // This call takes care of cleaning up all the empty nodes mo.CleanupUnusedNodes; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ RegisterVectorFileFormat('q3bsp', 'Quake3 BSP files', TGLQ3BSPVectorFile); // registering this extension too might be a little abusive right now... RegisterVectorFileFormat('bsp', 'BSP files', TGLQ3BSPVectorFile); end.
unit Odontologia.Modelo.Entidades.Agenda; interface uses SimpleAttributes; type [Tabela('DAGENDA')] TDAGENDA = class private FAGE_PACIENTE : integer; FAGE_CODIGO : integer; FAGE_FECHA : String; FAGE_MEDICO : integer; FAGE_COD_ESTADO_CITA : integer; FAGE_HORA : TTime; procedure SetAGE_COD_ESTADO_CITA(const Value: integer); procedure SetAGE_CODIGO(const Value: integer); procedure SetAGE_FECHA(const Value: String); procedure SetAGE_HORA(const Value: TTime); procedure SetAGE_MEDICO(const Value: integer); procedure SetAGE_PACIENTE(const Value: integer); published [Campo('AGE_CODIGO'), Pk, AutoInc] property AGE_CODIGO : integer read FAGE_CODIGO write SetAGE_CODIGO; [Campo('AGE_FECHA')] property AGE_FECHA : String read FAGE_FECHA write SetAGE_FECHA; [Campo('AGE_HORA')] property AGE_HORA : TTime read FAGE_HORA write SetAGE_HORA; [Campo('AGE_PACIENTE')] property AGE_PACIENTE : integer read FAGE_PACIENTE write SetAGE_PACIENTE; [Campo('AGE_MEDICO')] property AGE_MEDICO : integer read FAGE_MEDICO write SetAGE_MEDICO; [Campo('AGE_COD_ESTADO_CITA')] property AGE_COD_ESTADO_CITA : integer read FAGE_COD_ESTADO_CITA write SetAGE_COD_ESTADO_CITA; end; implementation { TDAGENDA } procedure TDAGENDA.SetAGE_CODIGO(const Value: integer); begin FAGE_CODIGO := Value; end; procedure TDAGENDA.SetAGE_COD_ESTADO_CITA(const Value: integer); begin FAGE_COD_ESTADO_CITA := Value; end; procedure TDAGENDA.SetAGE_FECHA(const Value: String); begin FAGE_FECHA := Value; end; procedure TDAGENDA.SetAGE_HORA(const Value: TTime); begin FAGE_HORA := Value; end; procedure TDAGENDA.SetAGE_MEDICO(const Value: integer); begin FAGE_MEDICO := Value; end; procedure TDAGENDA.SetAGE_PACIENTE(const Value: integer); begin FAGE_PACIENTE := Value; end; end.
unit uSearchQuery; interface uses System.Classes, System.DateUtils, Dmitry.Utils.System, uMemory, uConstants, uDBConnection, uDBEntities, uStringUtils; type TSearchQuery = class(TObject) private FPictureSize: Integer; FGroups: TStringList; FGroupsAnd: Boolean; FPersons: TStringList; FPersonsAnd: Boolean; FColors: TStringList; function GetGroupsWhere: string; function GetPersonsWhereOr: string; function GetColorsWhere: string; public Query: string; RatingFrom: Integer; RatingTo: Integer; ShowPrivate: Boolean; DateFrom: TDateTime; DateTo: TDateTime; SortMethod: Integer; SortDecrement: Boolean; IsEstimate: Boolean; ShowAllImages: Boolean; function EqualsTo(AQuery: TSearchQuery): Boolean; constructor Create(PictureSize: Integer = 0); destructor Destroy; override; property PictureSize: Integer read FPictureSize; property Groups: TStringList read FGroups; property GroupsAnd: Boolean read FGroupsAnd write FGroupsAnd; property GroupsWhere: string read GetGroupsWhere; property Persons: TStringList read FPersons; property PersonsAnd: Boolean read FPersonsAnd write FPersonsAnd; property PersonsWhereOr: string read GetPersonsWhereOr; property Colors: TStringList read FColors; property ColorsWhere: string read GetColorsWhere; end; implementation { TSearchQuery } constructor TSearchQuery.Create(PictureSize: Integer); begin FPictureSize := PictureSize; FGroups := TStringList.Create; FPersons := TStringList.Create; FColors := TStringList.Create; GroupsAnd := False; PersonsAnd := False; RatingFrom := 0; RatingTo := 10; DateFrom := EncodeDateTime(1900, 1, 1, 0, 0, 0, 0); DateTo := EncodeDateTime(2100, 1, 1, 0, 0, 0, 0); SortMethod := SM_DATE_TIME; SortDecrement := False; IsEstimate := False; ShowPrivate := False; ShowAllImages := False; end; destructor TSearchQuery.Destroy; begin F(FGroups); F(FPersons); F(FColors); end; function TSearchQuery.EqualsTo(AQuery: TSearchQuery): Boolean; begin Result := (AQuery.RatingFrom = RatingFrom) and (AQuery.RatingTo = RatingTo) and (AQuery.DateFrom = DateFrom) and (AQuery.DateTo = DateTo) and AQuery.Groups.Equals(Groups) and (AQuery.Query = Query) and (AQuery.SortMethod = SortMethod) and (AQuery.SortDecrement = SortDecrement); end; function TSearchQuery.GetColorsWhere: string; var I: Integer; SList: TStringList; begin Result := ''; if Colors.Count > 0 then begin SList := TStringList.Create; try for I := 0 to Colors.Count - 1 do if Colors[I] <> '' then SList.Add(FormatEx('Colors like {0}', [NormalizeDBString(NormalizeDBStringLike('%' + Colors[I] + '%'))])); Result := SList.Join(' AND '); finally F(SList); end; end; end; function TSearchQuery.GetGroupsWhere: string; var I: Integer; SList: TStringList; begin Result := ''; if Groups.Count > 0 then begin SList := TStringList.Create; try for I := 0 to Groups.Count - 1 do if Groups[I] <> '' then SList.Add(FormatEx('Groups like {0}', [NormalizeDBString(NormalizeDBStringLike(TGroup.GroupSearchByGroupName(Groups[I])))])); Result := SList.Join(IIF(GroupsAnd, ' AND ', ' OR ')); finally F(SList); end; end; end; function TSearchQuery.GetPersonsWhereOr: string; var I: Integer; SList: TStringList; begin Result := ''; if Persons.Count > 0 then begin SList := TStringList.Create; try for I := 0 to Persons.Count - 1 do if Persons[I] <> '' then SList.Add(FormatEx('trim(P.ObjectName) like {0}', [NormalizeDBString(NormalizeDBStringLike(Persons[I]))])); Result := SList.Join(' OR '); finally F(SList); end; end; end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, ADODB, StdCtrls, cxLookAndFeelPainters, cxButtons, cxMemo, cxTextEdit, cxControls, cxContainer, cxEdit, cxMaskEdit, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox; type TForm1 = class(TForm) ADOConn: TADOConnection; qryColumns: TADOQuery; qryColumnsColumnName: TWideStringField; qryColumnsColumnType: TWideStringField; qryValues: TADOQuery; Label1: TLabel; Label2: TLabel; Label3: TLabel; qryLuTable: TADOQuery; qryLuTableName: TWideStringField; qryLuTableid: TIntegerField; edtTable: TcxLookupComboBox; edtFilter: TcxTextEdit; mmInsert: TcxMemo; btnScript: TcxButton; dsLuTable: TDataSource; procedure btnScriptClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private function GetInsertSQL(AColumns: String): String; end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.btnScriptClick(Sender: TObject); var sColumns: String; begin with qryColumns do try if Active then Close; Parameters.ParamByName('TableName').Value := edtTable.Text; Open; while not Eof do begin if sColumns <> '' then sColumns := sColumns + ', '; sColumns := sColumns + FieldByName('ColumnName').AsString; Next; end; mmInsert.Text := 'ALTER TABLE ' + edtTable.Text + ' DISABLE TRIGGER ALL' + #13#13; mmInsert.Text := mmInsert.Text + GetInsertSQL(sColumns); mmInsert.Text := mmInsert.Text + 'ALTER TABLE ' + edtTable.Text + ' ENABLE TRIGGER ALL'; finally Close; end; end; function TForm1.GetInsertSQL(AColumns: String): String; var i: Integer; sValues, sColumns, sColumn: String; aSelectColumns: array of String; begin sColumns := AColumns; AColumns := StringReplace(sColumns, ' ', '', [rfReplaceAll]); while AColumns <> '' do begin if Pos(',', AColumns) > 0 then begin sColumn := Copy(AColumns, 1, Pos(',', AColumns) - 1); AColumns := Copy(AColumns, Pos(',', AColumns) + 1, Length(AColumns)); end else begin sColumn := AColumns; AColumns := ''; end; SetLength(aSelectColumns, Length(aSelectColumns) + 1); aSelectColumns[Length(aSelectColumns) - 1] := sColumn; end; with qryValues do try if qryValues.Active then qryValues.Close; qryValues.SQL.Text := 'SELECT ' + sColumns + ' FROM ' + edtTable.Text + ' WHERE ' + edtFilter.Text;; qryValues.Open; while not qryValues.Eof do begin for i := 0 to Pred(Length(aSelectColumns)) do begin if sValues <> '' then sValues := sValues + ', '; if qryValues.FieldByName(aSelectColumns[i]).Value = NULL then sValues := sValues + 'NULL' else if qryValues.FieldByName(aSelectColumns[i]).DataType = ftBoolean then sValues := sValues + BoolToStr(qryValues.FieldByName(aSelectColumns[i]).AsBoolean) else if (qryValues.FieldByName(aSelectColumns[i]).DataType = ftDateTime) or (qryValues.FieldByName(aSelectColumns[i]).DataType = ftTimeStamp) then sValues := sValues + QuotedStr(FormatDateTime('yyyy-mm-dd hh:nn:ss', qryValues.FieldByName(aSelectColumns[i]).AsDateTime)) else if (qryValues.FieldByName(aSelectColumns[i]).DataType = ftString) or (qryValues.FieldByName(aSelectColumns[i]).DataType = ftMemo) then sValues := sValues + QuotedStr(qryValues.FieldByName(aSelectColumns[i]).Value) else if (qryValues.FieldByName(aSelectColumns[i]).DataType = ftBCD) or (qryValues.FieldByName(aSelectColumns[i]).DataType = ftCurrency) or (qryValues.FieldByName(aSelectColumns[i]).DataType = ftFloat) then sValues := sValues + StringReplace(FormatFloat('0.00', qryValues.FieldByName(aSelectColumns[i]).Value), ',', '.', [rfReplaceAll]) else sValues := sValues + VarToStr(qryValues.FieldByName(aSelectColumns[i]).Value); end; Result := Result + 'INSERT INTO ' + edtTable.Text + ' (' + sColumns + ') VALUES (' + sValues + ')' + #13#13; sValues := ''; qryValues.Next; end; finally qryValues.Close; end; end; procedure TForm1.FormShow(Sender: TObject); begin ADOConn.Open; qryLuTable.Open; end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin qryLuTable.Close; ADOConn.Close; end; end.
unit TestULeituraGasVO; interface uses TestFramework, SysUtils, Atributos, ULeituraGasVO, UCondominioVO, Generics.Collections, UGenericVO, Classes, Constantes, UitensLeituraGasVO; type TestTLeituraGasVO = class(TTestCase) strict private FLeituraGasVO: TLeituraGasVO; public procedure SetUp; override; procedure TearDown; override; published procedure TestValidarCamposObrigatorios; procedure TestValidarCamposObrigatoriosNaoEncontrado; end; implementation procedure TestTLeituraGasVO.SetUp; begin FLeituraGasVO := TLeituraGasVO.Create; end; procedure TestTLeituraGasVO.TearDown; begin FLeituraGasVO.Free; FLeituraGasVO := nil; end; procedure TestTLeituraGasVO.TestValidarCamposObrigatorios; var Leitura : TLeituraGasVO; begin Leitura := TLeituraGasVO.Create; Leitura.dtLeitura := StrToDate('01/01/2016'); Leitura.idLeituraGas := 1; try Leitura.ValidarCamposObrigatorios; Check(True,'Sucesso!') except on E: Exception do Check(False,'Erro!'); end; end; procedure TestTLeituraGasVO.TestValidarCamposObrigatoriosNaoEncontrado; var Leitura : TLeituraGasVO; begin Leitura := TLeituraGasVO.Create; Leitura.dtLeitura := StrToDate('01/01/2016'); Leitura.idLeituraGas := 0; try Leitura.ValidarCamposObrigatorios; Check(false,'Erro!') except on E: Exception do Check(true,'Sucesso!'); end; end; initialization // Register any test cases with the test runner RegisterTest(TestTLeituraGasVO.Suite); end.
unit uGenericDAO; interface Uses Db, Rtti, uCustomAttributesEntity, TypInfo, SysUtils; type TGenericDAO = class private class function GetTableName<T: class>(Obj: T): String; public //procedimentos para o crud class function Insert<T: class>(AObject: T):boolean; class function GetAll<T: class>(AObject: T): TDataSet; end; implementation class function TGenericDAO.GetTableName<T>(Obj: T): String; var Contexto: TRttiContext; TypObj: TRttiType; Atributo: TCustomAttribute; strTable: String; begin Contexto := TRttiContext.Create; TypObj := Contexto.GetType(TObject(Obj).ClassInfo); for Atributo in TypObj.GetAttributes do begin if Atributo is TableName then Exit(TableName(Atributo).Name); end; end; //funções para manipular as entidades class function TGenericDAO.Insert<T>(AObject: T):boolean; var LContexto: TRttiContext; LTypeObject: TRttiType; LProperty: TRttiProperty; LInsert, LFields, LValues: String; LAtributo: TCustomAttribute; begin LInsert := ''; LFields := ''; LValues := ''; LInsert := 'INSERT INTO ' + GetTableName(AObject); LContexto := TRttiContext.Create; LTypeObject := LContexto.GetType(TObject(AObject).ClassInfo); for LProperty in LTypeObject.GetProperties do begin for LAtributo in LProperty.GetAttributes do begin if LAtributo is FieldName then begin LFields := LFields + FieldName(LAtributo).Name + ','; case LProperty.GetValue(TObject(AObject)).Kind of tkWChar, tkLString, tkWString, tkString, tkChar, tkUString: LValues := LValues + QuotedStr(LProperty.GetValue(TObject(AObject)).AsString) + ','; tkInteger, tkInt64: LValues := LValues + IntToStr(LProperty.GetValue(TObject(AObject)).AsInteger) + ','; tkFloat: LValues := LValues + FloatToStr(LProperty.GetValue(TObject(AObject)).AsExtended) + ','; else raise Exception.Create('Tipo não suportado'); end; end; end; end; LFields := Copy(LFields, 1, Length(LFields) - 1); LValues := Copy(LValues, 1, Length(LValues) - 1); LInsert := LInsert + ' ( ' + LFields + ' ) VALUES ( ' + LValues + ' )'; Result := DSServerModuleBaseDados.execSql(LInsert); end; class function TGenericDAO.GetAll<T>(AObject: T): TDataSet; begin Result := DSServerModuleBaseDados.getDataSet('SELECT T1.* FROM ' + GetTableName(AObject) + ' T1' ); end; end.
{* ***** BEGIN LICENSE BLOCK ***** Copyright 2010 Sean B. Durkin This file is part of TurboPower LockBox 3. TurboPower LockBox 3 is free software being offered under a dual licensing scheme: LGPL3 or MPL1.1. The contents of this file are subject to the Mozilla Public License (MPL) Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/ Alternatively, you may redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. You should have received a copy of the Lesser GNU General Public License along with TurboPower LockBox 3. If not, see <http://www.gnu.org/licenses/>. TurboPower LockBox 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. In relation to LGPL, see the GNU Lesser General Public License for more details. In relation to MPL, see the MPL License for the specific language governing rights and limitations under the License. The Initial Developer of the Original Code for TurboPower LockBox version 2 and earlier was TurboPower Software. * ***** END LICENSE BLOCK ***** *} unit uTPLb_MemoryStreamPool; interface uses Classes; type IMemoryStreamPool = interface ['{ADB2D4BA-40F6-4249-923E-201D4719609B}'] function BayCount: integer; procedure GetUsage( Size: integer; var Current, Peak: integer); function GetSize( Idx: Integer): integer; function NewMemoryStream( InitSize: integer): TMemoryStream; end; TPooledMemoryStream = class( TMemoryStream) protected FPool: IMemoryStreamPool; FCoVector: integer; function Realloc( var NewCapacity: Longint): Pointer; override; public constructor Create( const Pool1: IMemoryStreamPool); end; function NewPool: IMemoryStreamPool; implementation uses RTLConsts, SysUtils, Generics.Collections, uTPLb_PointerArithmetic; const iNullCoVector = -1; MemoryDelta = $200; // Copy from implementation section of Classes. CacheSegmentSize = MemoryDelta * 2; // Should be the same or a multiple of MemoryDelta. AnticipatedPeakUsage = 30; type IMemoryStreamPoolEx = interface ['{0F24C5E3-3331-4A47-8342-CF50DBAFF4FF}'] function NullCoVector: integer; procedure GetMem1 ( var p: pointer; var CoVector: integer; Size: Integer); procedure FreeMem1 ( P: Pointer; CoVector: integer; Size: Integer); procedure ReallocMem1( var p: Pointer; var CoVector: integer; OldSize, Size: Integer); function CanManageSize( Size: integer): boolean; end; {$IF CompilerVersion > 15} TMemoryStreamPool = class( TInterfacedObject, IMemoryStreamPool, IMemoryStreamPoolEx) private {$ENDIF} type IAllocationRecordList = interface ['{ECDAD2EC-C47E-4D24-B583-F36E62D3FDBB}'] function GetSize( Idx: integer): integer; procedure RecordUsage( Size: integer); procedure RecordReturn( Size: integer); procedure GetUsage( Size: integer; var Current, Peak: integer); function Count: integer; property Sizes[ Idx: Integer]: integer read GetSize; end; {$IF CompilerVersion <= 15} TMemoryStreamPool = class( TInterfacedObject, IMemoryStreamPool, IMemoryStreamPoolEx) {$ENDIF} private FAllocRecords: IAllocationRecordList; FCache: pointer; FCacheSegmentInUse: TBits; FCachedCount: integer; protected procedure GetMem1 ( var p: pointer; var CoVector: integer; Size: Integer); virtual; procedure FreeMem1 ( P: Pointer; CoVector: integer; Size: Integer); virtual; procedure ReallocMem1( var p: Pointer; var CoVector: integer; OldSize, Size: Integer); virtual; function NullCoVector: integer; virtual; function CanManageSize( Size: integer): boolean; virtual; public function BayCount: integer; procedure GetUsage( Size: integer; var Current, Peak: integer); function GetSize( Idx: Integer): integer; function NewMemoryStream( InitSize: integer): TMemoryStream; virtual; constructor Create; destructor Destroy; override; end; function NewPool: IMemoryStreamPool; begin result := TMemoryStreamPool.Create end; type PAllocationRecord = ^TAllocationRecord; TAllocationRecord = record FSize: integer; FCurrentUsage: integer; FPeakUsage: integer; end; {$IF CompilerVersion > 15} TAllocationRecordListObj = class( TInterfacedObject, TMemoryStreamPool.IAllocationRecordList) {$ELSE} TAllocationRecordListObj = class( TInterfacedObject, IAllocationRecordList) {$ENDIF} private FAllocRecs: TList<PAllocationRecord>; // of AllocationRecord function GetSize( Idx: integer): integer; procedure RecordUsage( Size: integer); procedure RecordReturn( Size: integer); procedure GetUsage( Size: integer; var Current, Peak: integer); function Count: integer; public constructor Create; destructor Destroy; override; end; { TMemoryStreamPool } function TMemoryStreamPool.NewMemoryStream( InitSize: integer): TMemoryStream; begin result := TPooledMemoryStream.Create( self); if InitSize > 0 then result.Size := InitSize end; function TMemoryStreamPool.NullCoVector: integer; begin result := iNullCoVector end; { TPooledMemoryStream } constructor TPooledMemoryStream.Create( const Pool1: IMemoryStreamPool); var Ex: IMemoryStreamPoolEx; begin FPool := Pool1; if Supports( FPool, IMemoryStreamPoolEx, Ex) then FCoVector := Ex.NullCoVector; inherited Create end; function TPooledMemoryStream.Realloc( var NewCapacity: Integer): Pointer; // Fragments of this method were copied from the Classes unit and modified. var Ex: IMemoryStreamPoolEx; begin if (NewCapacity > 0) and (NewCapacity <> Size) then NewCapacity := (NewCapacity + (MemoryDelta - 1)) and not (MemoryDelta - 1); result := Memory; if NewCapacity <> Capacity then begin if NewCapacity = 0 then begin if Supports( FPool, IMemoryStreamPoolEx, Ex) then begin Ex.FreeMem1( Memory, FCoVector, Capacity); FCoVector := Ex.NullCoVector end else FreeMem( Memory); result := nil end else begin if Capacity = 0 then begin if Supports( FPool, IMemoryStreamPoolEx, Ex) then Ex.GetMem1( result, FCoVector, NewCapacity) else GetMem( result, NewCapacity); end else begin if Supports( FPool, IMemoryStreamPoolEx, Ex) then Ex.ReallocMem1( result, FCoVector, Capacity, NewCapacity) else ReallocMem( result, NewCapacity); end; if Result = nil then raise EStreamError.CreateRes( @SMemoryStreamError) end end end; function TMemoryStreamPool.BayCount: integer; begin result := FAllocRecords.Count end; function TMemoryStreamPool.CanManageSize( Size: integer): boolean; begin result := (Size <= CacheSegmentSize) and (FCachedCount < AnticipatedPeakUsage) end; constructor TMemoryStreamPool.Create; begin FAllocRecords := TAllocationRecordListObj.Create; GetMem( FCache, CacheSegmentSize * AnticipatedPeakUsage); FCacheSegmentInUse := TBits.Create; FCacheSegmentInUse.Size := AnticipatedPeakUsage; FCachedCount := 0 end; destructor TMemoryStreamPool.Destroy; begin FAllocRecords := nil; FCacheSegmentInUse.Free; FreeMem( FCache); inherited end; procedure TMemoryStreamPool.FreeMem1( P: Pointer; CoVector: integer; Size: integer); // Note: Size = -1 means size unknown. begin if CoVector = iNullCoVector then FreeMem( P) else begin if (CoVector >= 0) and (CoVector < FCacheSegmentInUse.Size) then FCacheSegmentInUse[ CoVector] := False; if FCachedCount > 0 then Dec( FCachedCount) end; FAllocRecords.RecordReturn( Size) end; procedure TMemoryStreamPool.GetMem1( var p: pointer; var CoVector: integer; Size: Integer); var j, Idx: integer; begin Idx := -1; if CanManageSize( Size) then for j := 0 to AnticipatedPeakUsage - 1 do begin if j >= FCacheSegmentInUse.Size then break; if FCacheSegmentInUse[j] then continue; Idx := j; break end; if Idx <> -1 then begin p := Offset( FCache, Idx * CacheSegmentSize); CoVector := Idx; FCacheSegmentInUse[ Idx] := True; Inc( FCachedCount) end else begin GetMem( p, Size); CoVector := iNullCoVector end; FAllocRecords.RecordUsage( Size); end; function TMemoryStreamPool.GetSize( Idx: Integer): integer; begin result := FAllocRecords.Sizes[ Idx] end; procedure TMemoryStreamPool.GetUsage( Size: integer; var Current, Peak: integer); begin FAllocRecords.GetUsage( Size, Current, Peak) end; procedure TMemoryStreamPool.ReallocMem1( var p: Pointer; var CoVector: integer; OldSize, Size: Integer); var isNewManaged: boolean; begin isNewManaged := CanManageSize( Size); // TO DO: Override and implement efficient caching. if (CoVector <> iNullCoVector) and isNewManaged then begin // Old AND new managed // Do nothing. Old and New both fit in the same physical space. end else if (CoVector = iNullCoVector) and (not isNewManaged) then begin // neither Old NOR New new managed ReallocMem( P, Size); // CoVector = iNullCoVector end else begin // Old, new mixed managed FreeMem1( P, CoVector, OldSize); // -1 means old size not given. GetMem1( p, CoVector, Size) end end; { TAllocationRecordListObj } function TAllocationRecordListObj.Count: integer; begin result := FAllocRecs.Count end; constructor TAllocationRecordListObj.Create; begin inherited Create; FAllocRecs := TList<PAllocationRecord>.Create; end; destructor TAllocationRecordListObj.Destroy; var j: integer; P: pointer; begin for j := 0 to FAllocRecs.Count - 1 do begin P := FAllocRecs[j]; FreeMem( P) end; FAllocRecs.Free; inherited; end; function TAllocationRecordListObj.GetSize( Idx: integer): integer; begin result := PAllocationRecord( FAllocRecs[ Idx])^.FSize end; procedure TAllocationRecordListObj.GetUsage( Size: integer; var Current, Peak: integer); var j: integer; P: PAllocationRecord; begin Current := 0; Peak := 0; for j := 0 to FAllocRecs.Count - 1 do begin P := PAllocationRecord( FAllocRecs[j]); if P^.FSize <> Size then continue; Current := P^.FCurrentUsage; Peak := P^.FPeakUsage; break end end; procedure TAllocationRecordListObj.RecordReturn( Size: integer); var j: integer; P: PAllocationRecord; Current: integer; begin P := nil; Current := 0; for j := 0 to FAllocRecs.Count - 1 do begin P := PAllocationRecord( FAllocRecs[j]); if P^.FSize <> Size then continue; Current := P^.FCurrentUsage; break end; if Current > 0 then P^.FCurrentUsage := Current - 1 end; procedure TAllocationRecordListObj.RecordUsage( Size: integer); var j: integer; Pntr: pointer; P, Q: PAllocationRecord; Current, Peak: integer; //s: string; begin Current := 0; Peak := 0; P := nil; for j := 0 to FAllocRecs.Count - 1 do begin Q := PAllocationRecord( FAllocRecs[j]); if Q^.FSize <> Size then continue; Current := Q^.FCurrentUsage; Peak := Q^.FPeakUsage; P := Q; break end; if not assigned( P) then begin // New( P); GetMem( Pntr, SizeOf( TAllocationRecord)); P := PAllocationRecord( Pntr); P^.FSize := Size; FAllocRecs.Add( P) end; Inc( Current); if Current > Peak then Peak := Current; P^.FCurrentUsage := Current; P^.FPeakUsage := Peak end; end.
{------------------------------------------------------------------------------- Copyright 2012 Ethea S.r.l. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -------------------------------------------------------------------------------} unit Kitto.Ext.Utils; {$I Kitto.Defines.inc} interface uses SysUtils, Classes, Ext, ExtPascal, ExtPascalUtils, ExtMenu, ExtTree, EF.ObserverIntf, EF.Tree, Kitto.Ext.Base, Kitto.Ext.Controller, Kitto.Metadata.Views, Kitto.Ext.Session; type TKExtTreeTreeNode = class(TExtTreeTreeNode) private FView: TKView; procedure SetView(const AValue: TKView); public property View: TKView read FView write SetView; end; TKExtViewButton = class(TKExtButton) private FView: TKView; procedure SetView(const AValue: TKView); public property View: TKView read FView write SetView; end; TKExtMenuItem = class(TExtMenuItem) private FView: TKView; procedure SetView(const AValue: TKView); public property View: TKView read FView write SetView; end; /// <summary> /// Renders a tree view on a container in various ways: as a set of buttons /// with submenus, an Ext treeview control, etc. /// </summary> TKExtTreeViewRenderer = class private FOwner: TExtObject; FClickHandler: TExtProcedure; FAddedItems: Integer; FSession: TKExtSession; FTreeView: TKTreeView; procedure AddButton(const ANode: TKTreeViewNode; const ADisplayLabel: string; const AContainer: TExtContainer); procedure AddMenuItem(const ANode: TKTreeViewNode; const AMenu: TExtMenuMenu); procedure AddNode(const ANode: TKTreeViewNode; const ADisplayLabel: string; const AParent: TExtTreeTreeNode); function GetClickFunction(const AView: TKView): TExtFunction; /// <summary> /// Clones the specified tree view, filters all invisible items /// (including folders containing no visible items) and returns the /// clone. /// </summary> /// <remarks> /// The caller is responsible for freeing the returned object. /// </remarks> function CloneAndFilter(const ATreeView: TKTreeView): TKTreeView; procedure Filter(const ANode: TKTreeViewNode); public property Session: TKExtSession read FSession write FSession; /// <summary> /// Attaches to the container a set of buttons, one for each top-level /// element of the specified tree view. Each button has a submenu tree /// with the child views. Returns the total number of effectively added /// items. /// </summary> function RenderAsButtons(const ATreeView: TKTreeView; const AContainer: TExtContainer; const AOwner: TExtObject; const AClickHandler: TExtProcedure): Integer; /// <summary> /// Renders a tree under ARoot with all views in the tree view. Returns /// the total number of effectively added items. /// </summary> function RenderAsTree(const ATreeView: TKTreeView; const ARoot: TExtTreeTreeNode; const AOwner: TExtObject; const AClickHandler: TExtProcedure): Integer; /// <summary> /// Renders a tree by calling AProc for each top-level element in the tree view. /// </summary> function Render(const ATreeView: TKTreeView; const AProc: TProc<TKTreeViewNode, string>; const AOwner: TExtObject; const AClickHandler: TExtProcedure): Integer; end; function DelphiDateTimeFormatToJSDateTimeFormat(const ADateTimeFormat: string): string; function DelphiDateFormatToJSDateFormat(const ADateFormat: string): string; function DelphiTimeFormatToJSTimeFormat(const ATimeFormat: string): string; /// <summary> /// Adapts a standard number format string (with , as thousand /// separator and . as decimal separator) according to the /// specificed format settings for displaying to the user. /// </summary> function AdaptExtNumberFormat(const AFormat: string; const AFormatSettings: TFormatSettings): string; /// <summary> /// Computes and returns a display label based on the underlying view, /// if any, or the node itself (if no view is found). /// </summary> function GetDisplayLabelFromNode(const ANode: TKTreeViewNode; const AViews: TKViews): string; /// <summary> /// Invoke a method of a View that return a string using RTTI /// </summary> function CallViewControllerStringMethod(const AView: TKView; const AMethodName: string; const ADefaultValue: string): string; implementation uses Types, StrUtils, RTTI, EF.Macros, EF.SysUtils, EF.StrUtils, EF.Classes, EF.Localization, Kitto.AccessControl, Kitto.Utils, Kitto.Config; function CallViewControllerStringMethod(const AView: TKView; const AMethodName: string; const ADefaultValue: string): string; var LControllerClass: TClass; LContext: TRttiContext; LMethod: TRttiMethod; begin Assert(Assigned(AView)); Assert(AMethodName <> ''); LControllerClass := TKExtControllerRegistry.Instance.GetClass(AView.ControllerType); LMethod := LContext.GetType(LControllerClass).GetMethod(AMethodName); if Assigned(LMethod) then Result := LMethod.Invoke(LControllerClass, []).AsString else Result := ADefaultValue; end; function GetDisplayLabelFromNode(const ANode: TKTreeViewNode; const AViews: TKViews): string; var LView: TKView; begin Assert(Assigned(ANode)); LView := ANode.FindView(AViews); if Assigned(LView) then begin Result := _(LView.DisplayLabel); if Result = '' then Result := CallViewControllerStringMethod(LView, 'GetDefaultDisplayLabel', Result); end else begin Result := _(ANode.AsString); TEFMacroExpansionEngine.Instance.Expand(Result); end; Result := Result; end; function GetImageName(const ANode: TKTreeViewNode; const AView: TKView): string; begin Assert(Assigned(ANode)); Assert(Assigned(AView)); Result := ANode.GetString('ImageName'); if Result = '' then Result := CallViewControllerStringMethod(AView, 'GetDefaultImageName', ''); end; { TKExtTreeViewRenderer } function TKExtTreeViewRenderer.GetClickFunction( const AView: TKView): TExtFunction; begin Assert(Assigned(FOwner)); Assert(Assigned(FClickHandler)); if Assigned(AView) then begin if Session.StatusHost <> nil then Result := FOwner.Ajax(FClickHandler, ['View', Integer(AView), 'Dummy', Session.StatusHost.ShowBusy]) else Result := FOwner.Ajax(FClickHandler, ['View', Integer(AView)]); end else Result := nil; end; procedure TKExtTreeViewRenderer.AddMenuItem(const ANode: TKTreeViewNode; const AMenu: TExtMenuMenu); var I: Integer; LMenuItem: TKExtMenuItem; LSubMenu: TExtMenuMenu; LIsEnabled: Boolean; LView: TKView; LDisplayLabel: string; LNode: TKTreeViewNode; begin Assert(Assigned(ANode)); Assert(Assigned(AMenu)); for I := 0 to ANode.TreeViewNodeCount - 1 do begin LNode := ANode.TreeViewNodes[I]; LView := LNode.FindView(Session.Config.Views); if Assigned(LView) then LIsEnabled := LView.IsAccessGranted(ACM_RUN) else LIsEnabled := TKConfig.Instance.IsAccessGranted(ANode.GetACURI(FTreeView), ACM_RUN); LMenuItem := TKExtMenuItem.CreateAndAddTo(AMenu.Items); try Inc(FAddedItems); LMenuItem.Disabled := not LIsEnabled; LMenuItem.View := LView; if Assigned(LMenuItem.View) then begin LMenuItem.IconCls := Session.SetViewIconStyle(LMenuItem.View, GetImageName(LNode, LMenuItem.View)); LMenuItem.On('click', GetClickFunction(LMenuItem.View)); LDisplayLabel := _(LNode.GetString('DisplayLabel', LMenuItem.View.DisplayLabel)); if LDisplayLabel = '' then LDisplayLabel := CallViewControllerStringMethod(LView, 'GetDefaultDisplayLabel', ''); LMenuItem.Text := HTMLEncode(LDisplayLabel); // No tooltip here - could be done through javascript if needed. end else begin if ANode.TreeViewNodes[I].TreeViewNodeCount > 0 then begin LDisplayLabel := _(LNode.GetString('DisplayLabel', LNode.AsString)); LMenuItem.Text := HTMLEncode(LDisplayLabel); LMenuItem.IconCls := Session.SetIconStyle('Folder', LNode.GetString('ImageName')); LSubMenu := TExtMenuMenu.Create(AMenu.Items); LMenuItem.Menu := LSubMenu; AddMenuItem(ANode.TreeViewNodes[I], LSubMenu); end; end; except FreeAndNil(LMenuItem); raise; end; end; end; procedure TKExtTreeViewRenderer.AddButton(const ANode: TKTreeViewNode; const ADisplayLabel: string; const AContainer: TExtContainer); var LButton: TKExtViewButton; LMenu: TExtMenuMenu; LIsEnabled: Boolean; LView: TKView; begin Assert(Assigned(ANode)); Assert(Assigned(AContainer)); LView := ANode.FindView(Session.Config.Views); if Assigned(LView) then LIsEnabled := LView.IsAccessGranted(ACM_RUN) else LIsEnabled := TKConfig.Instance.IsAccessGranted(ANode.GetACURI(FTreeView), ACM_RUN); LButton := TKExtViewButton.CreateAndAddTo(AContainer.Items); try Inc(FAddedItems); LButton.View := LView; if Assigned(LButton.View) then begin LButton.IconCls := Session.SetViewIconStyle(LButton.View, GetImageName(ANode, LButton.View)); LButton.On('click', GetClickFunction(LButton.View)); LButton.Disabled := not LIsEnabled; end; LButton.Text := HTMLEncode(ADisplayLabel); if Session.TooltipsEnabled then LButton.Tooltip := LButton.Text; if ANode.ChildCount > 0 then begin LMenu := TExtMenuMenu.Create(AContainer); try LButton.Menu := LMenu; AddMenuItem(ANode, LMenu); except FreeAndNil(LMenu); raise; end; end; except FreeAndNil(LButton); raise; end; end; procedure TKExtTreeViewRenderer.AddNode(const ANode: TKTreeViewNode; const ADisplayLabel: string; const AParent: TExtTreeTreeNode); var LNode: TKExtTreeTreeNode; I: Integer; LIsEnabled: Boolean; LView: TKView; LSubNode: TKTreeViewNode; LDisplayLabel: string; begin Assert(Assigned(ANode)); Assert(Assigned(AParent)); LView := ANode.FindView(Session.Config.Views); if Assigned(LView) then LIsEnabled := LView.IsAccessGranted(ACM_RUN) else LIsEnabled := TKConfig.Instance.IsAccessGranted(ANode.GetACURI(FTreeView), ACM_RUN); LNode := TKExtTreeTreeNode.Create(AParent.ChildNodes); try Inc(FAddedItems); LNode.View := LView; if Assigned(LNode.View) then begin LNode.IconCls := Session.SetViewIconStyle(LNode.View, GetImageName(ANode, LNode.View)); LNode.On('click', GetClickFunction(LNode.View)); LNode.Disabled := not LIsEnabled; end; LNode.Text := HTMLEncode(ADisplayLabel); if Session.TooltipsEnabled then LNode.Qtip := LNode.Text; if ANode.TreeViewNodeCount > 0 then begin for I := 0 to ANode.TreeViewNodeCount - 1 do begin LSubNode := ANode.TreeViewNodes[I]; LDisplayLabel := _(LSubNode.GetString('DisplayLabel', GetDisplayLabelFromNode(LSubNode, Session.Config.Views))); AddNode(LSubNode, LDisplayLabel, LNode); end; LNode.Expandable := True; if ANode is TKTreeViewFolder then LNode.Expanded := not TKTreeViewFolder(ANode).IsInitiallyCollapsed else LNode.Expanded := True; LNode.Leaf := False; end; AParent.AppendChild(LNode); except FreeAndNil(LNode); raise; end; end; function TKExtTreeViewRenderer.CloneAndFilter(const ATreeView: TKTreeView): TKTreeView; var I: Integer; begin Assert(Assigned(ATreeView)); Result := TKTreeView.Clone(ATreeView, procedure (const ASource, ADestination: TEFNode) begin ADestination.SetObject('Sys/SourceNode', ASource); end ); for I := Result.TreeViewNodeCount - 1 downto 0 do Filter(Result.TreeViewNodes[I]); end; procedure TKExtTreeViewRenderer.Filter(const ANode: TKTreeViewNode); var LView: TKView; I: Integer; LIsVisible: Boolean; begin Assert(Assigned(ANode)); LView := ANode.FindView(Session.Config.Views); if Assigned(LView) then LIsVisible := LView.IsAccessGranted(ACM_VIEW) else LIsVisible := TKConfig.Instance.IsAccessGranted(ANode.GetACURI(FTreeView), ACM_VIEW); if not LIsVisible then ANode.Delete else begin for I := ANode.TreeViewNodeCount - 1 downto 0 do Filter(ANode.TreeViewNodes[I]); // Remove empty folders. if (ANode is TKTreeViewFolder) and (ANode.TreeViewNodeCount = 0) then ANode.Delete; end; end; function TKExtTreeViewRenderer.Render(const ATreeView: TKTreeView; const AProc: TProc<TKTreeViewNode, string>; const AOwner: TExtObject; const AClickHandler: TExtProcedure): Integer; var I: Integer; LNode: TKTreeViewNode; LTreeView: TKTreeView; begin Assert(Assigned(ATreeView)); Assert(Assigned(AProc)); Assert(Assigned(AOwner)); Assert(Assigned(AClickHandler)); FOwner := AOwner; FTreeView := ATreeView; FClickHandler := AClickHandler; FAddedItems := 0; LTreeView := CloneAndFilter(ATreeView); try for I := 0 to LTreeView.TreeViewNodeCount - 1 do begin LNode := LTreeView.TreeViewNodes[I]; AProc(LNode, GetDisplayLabelFromNode(LNode, Session.Config.Views)); end; finally FreeAndNil(LTreeView); end; Result := FAddedItems; end; function TKExtTreeViewRenderer.RenderAsButtons( const ATreeView: TKTreeView; const AContainer: TExtContainer; const AOwner: TExtObject; const AClickHandler: TExtProcedure): Integer; begin Assert(Assigned(AContainer)); Result := Render(ATreeView, procedure (ANode: TKTreeViewNode; ADisplayLabel: string) begin AddButton(ANode, ADisplayLabel, AContainer); end, AOwner, AClickHandler); end; function TKExtTreeViewRenderer.RenderAsTree( const ATreeView: TKTreeView; const ARoot: TExtTreeTreeNode; const AOwner: TExtObject; const AClickHandler: TExtProcedure): Integer; begin Assert(Assigned(ARoot)); Result := Render(ATreeView, procedure (ANode: TKTreeViewNode; ADisplayLabel: string) begin AddNode(ANode, ADisplayLabel, ARoot); end, AOwner, AClickHandler); end; function DelphiDateTimeFormatToJSDateTimeFormat(const ADateTimeFormat: string): string; var LFormats: TStringDynArray; begin LFormats := Split(ADateTimeFormat); Assert(Length(LFormats) = 2); Result := DelphiDateFormatToJSDateFormat(LFormats[0]) + ' ' + DelphiTimeFormatToJSTimeFormat(LFormats[1]); end; function DelphiDateFormatToJSDateFormat(const ADateFormat: string): string; begin Result := ReplaceText(ADateFormat, 'yyyy', 'Y'); Result := ReplaceText(Result, 'yy', 'y'); Result := ReplaceText(Result, 'dd', 'd'); Result := ReplaceText(Result, 'mm', 'm'); end; function DelphiTimeFormatToJSTimeFormat(const ATimeFormat: string): string; begin Result := ReplaceText(ATimeFormat, 'hh', 'H'); Result := ReplaceText(Result, 'mm', 'i'); Result := ReplaceText(Result, 'nn', 'i'); Result := ReplaceText(Result, 'ss', 's'); end; function AdaptExtNumberFormat(const AFormat: string; const AFormatSettings: TFormatSettings): string; var I: Integer; begin Result := AFormat; if AFormatSettings.DecimalSeparator = ',' then begin for I := 1 to Length(Result) do begin if Result[I] = '.' then Result[I] := ',' else if Result[I] = ',' then Result[I] := '.'; end; Result := Result + '/i'; end; end; { TKExtTreeTreeNode } procedure TKExtTreeTreeNode.SetView(const AValue: TKView); begin FView := AValue; if Assigned(FView) then begin Expandable := False; Expanded := False; Leaf := True; end; end; { TKExtViewButton } procedure TKExtViewButton.SetView(const AValue: TKView); begin FView := AValue; end; { TKExtMenuItem } procedure TKExtMenuItem.SetView(const AValue: TKView); begin FView := AValue; end; end.
unit Odontologia.Modelo.Entidades.Ciudad; interface uses SimpleAttributes; type [Tabela('DCIUDAD')] TDCIUDAD = class private FCIU_NOMBRE : String; FCIU_COD_DEPARTAMENTO : Integer; FCIU_CODIGO : Integer; procedure SetCIU_COD_DEPARTAMENTO (const Value: Integer); procedure SetCIU_CODIGO (const Value: Integer); procedure SetCIU_NOMBRE (const Value: String); published [Campo('CIU_CODIGO'), Pk, AutoInc] property CIU_CODIGO : Integer read FCIU_CODIGO write SetCIU_CODIGO; [Campo('CIU_NOMBRE')] property CIU_NOMBRE : String read FCIU_NOMBRE write SetCIU_NOMBRE; [Campo('CIU_COD_DEPARTAMENTO')] property CIU_COD_DEPARTAMENTO : Integer read FCIU_COD_DEPARTAMENTO write SetCIU_COD_DEPARTAMENTO; end; implementation { TDCIUDAD } procedure TDCIUDAD.SetCIU_CODIGO(const Value: Integer); begin FCIU_CODIGO := Value; end; procedure TDCIUDAD.SetCIU_COD_DEPARTAMENTO(const Value: Integer); begin FCIU_COD_DEPARTAMENTO := Value; end; procedure TDCIUDAD.SetCIU_NOMBRE(const Value: String); begin FCIU_NOMBRE := Value; end; end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, SynHighlighterPython, SynEdit, Forms, Controls, Graphics, Dialogs, ComCtrls, ExtCtrls, StdCtrls, Buttons, LCLIntf, Spin, ExtDlgs, EditBtn, Types, TypInfo, IniFiles, ucom; const NEOPIXEL16x16_MAX_TEXTWIDTH = 2048; NEOPIXEL16x16_MAX_IMAGEWIDTH = 64; VERSION = '1.0.0'; type { TfrmMain } TfrmMain = class(TForm) btnColorNeopixel_16x16: TColorButton; btnMakeNeopixel_16x16_Img: TSpeedButton; btnImageFontNeopixel_16x16: TSpeedButton; btnMakeNeopixel_strip: TSpeedButton; cbbPinNeopixel: TComboBox; dlgFont: TFontDialog; dlgFontTextNeopixel_16x16: TFontDialog; dlgSaveImg: TSavePictureDialog; EdtBrightnessNeopixel: TSpinEdit; edtMakeNeopixel_16x16_Img: TSynEdit; edtMakeNeopixel_strip: TSynEdit; edtTextNeopixel_16x16: TEdit; edtFileNameNeopixel_16x16_Img: TFileNameEdit; rbNeopixelStripEffect: TRadioGroup; Image1: TImage; Image2: TImage; imgNeopixel_16x16_Img: TImage; imgSrcNeopixel_16x16: TImage; imgNeopixel_16x16: TImage; ImageListToolBar: TImageList; dlgOpenImg: TOpenPictureDialog; imgSrcNeopixel_16x16_Img: TImage; lbWarnNeopixel_16x16_img: TLabel; lbLenNeopixel_16x16: TLabel; lbLenNeopixel_16x16_Img: TLabel; lbTPNeopixel_16x16: TListBox; lbTPNeopixel_16x16_Img: TListBox; Panel4: TPanel; Panel5: TPanel; pnlBrightnessNeopixel: TPanel; pnlPinNeopixel: TPanel; pnlCountNeopixel: TPanel; Panel3: TPanel; pgctMain: TPageControl; pgctNeopixel: TPageControl; ScrollBox1: TScrollBox; EdtCountNeopixel: TSpinEdit; edtMakeNeopixel_16x16: TSynEdit; btnTextFontNeopixel_16x16: TSpeedButton; btnMakeNeopixel_16x16: TSpeedButton; ScrollBox2: TScrollBox; SynPythonSyn: TSynPythonSyn; ToolButton5: TToolButton; TrackBarBrightnessNeopixel: TTrackBar; tsNeopixel_16x16_Img: TTabSheet; tmrInit: TTimer; ToolButton4: TToolButton; tsNeopixel: TTabSheet; tsNeopixel_16x16: TTabSheet; tsNeopixel_Strip: TTabSheet; TabSheet5: TTabSheet; TabSheet6: TTabSheet; TabSheet7: TTabSheet; TabSheet8: TTabSheet; TabSheet9: TTabSheet; tbNeopixel: TToolBar; ToolBar: TToolBar; ToolButton1: TToolButton; ToolButton2: TToolButton; ToolButton3: TToolButton; UpDown1: TUpDown; procedure btnColorNeopixel_16x16ColorChanged(Sender: TObject); procedure btnImageFontNeopixel_16x16Click(Sender: TObject); procedure btnMakeNeopixel_16x16Click(Sender: TObject); procedure btnMakeNeopixel_16x16_ImgClick(Sender: TObject); procedure btnMakeNeopixel_stripClick(Sender: TObject); procedure btnTextFontNeopixel_16x16Click(Sender: TObject); procedure EdtBrightnessNeopixelChange(Sender: TObject); procedure edtTextNeopixel_16x16Change(Sender: TObject); procedure edtFileNameNeopixel_16x16_ImgAcceptFileName(Sender: TObject; var Value: string); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormCreate(Sender: TObject); procedure imgNeopixel_16x16Click(Sender: TObject); procedure tmrInitTimer(Sender: TObject); procedure ToolButton3Click(Sender: TObject); procedure ToolButton5Click(Sender: TObject); procedure TrackBarBrightnessNeopixelChange(Sender: TObject); private procedure TextImageNoepixel_16x16(Sender: TObject); procedure redrawNeopixel_16x16(Sender: TObject); public end; { TIni } TIni = class(TIniFile) private function FontToStr(const F: TFont): string; function StrToFont(const FontStr: string; const Default: TFont): TFont; function StyleToStr(const Styles: TFontStyles): string; function StrToStyle(const StyleStr: string): TFontStyles; function PointToStr(const P: TPoint): string; function StrToPoint(const S: string; const Default: TPoint): TPoint; function RectToStr(const R: TRect): string; function StrToRect(const RectStr: string; const Default: TRect): TRect; public function ReadFont(const Section, Ident: string; const Default: TFont): TFont; procedure WriteFont(const Section, Ident: string; const Value: TFont); function ReadPoint(const Section, Ident: string; const Default: TPoint): TPoint; procedure WritePoint(const Section, Ident: string; const Value: TPoint); function ReadRect(const Section, Ident: string; const Default: TRect): TRect; procedure WriteRect(const Section, Ident: string; const Value: TRect); function ReadReal(const Section, Ident: string; Default: Extended): Extended; procedure WriteReal(const Section, Ident: string; Value: Extended); end; var frmMain: TfrmMain; ini: TIni; implementation {$R *.lfm} { TIni } function TIni.FontToStr(const F: TFont): string; begin with F do Result := Format('%s,%d,%s,%s,%d,%d', [Name, Size, StyleToStr(Style), ColorToString(Color), Ord(Pitch), Charset]); end; function TIni.StrToFont(const FontStr: string; const Default: TFont): TFont; var S: string; I: integer; begin Result := Default; S := FontStr; I := Pos(',', S); if I > 0 then begin Result.Name := Trim(Copy(S, 1, I - 1)); Delete(S, 1, I); I := Pos(',', S); if I > 0 then begin Result.Size := StrToIntDef(Trim(Copy(S, 1, I - 1)), Default.Size); Delete(S, 1, I); I := Pos(']', S); if I > 0 then begin Result.Style := StrToStyle(Trim(Copy(S, 1, I))); Delete(S, 1, I + 1); I := Pos(',', S); if I > 0 then begin Result.Color := StringToColor(Trim(Copy(S, 1, I - 1))); Delete(S, 1, I); I := Pos(',', S); if I > 0 then begin Result.Pitch := TFontPitch(StrToIntDef(Trim(Copy(S, 1, I - 1)), Ord(Default.Pitch))); Delete(S, 1, I); Result.CharSet := StrToIntDef(Trim(S), Default.CharSet); end; end; end; end; end; end; function TIni.StyleToStr(const Styles: TFontStyles): string; var Style: TFontStyle; begin Result := '['; for Style := Low(Style) to High(Style) do begin if Style in Styles then begin if Length(Result) > 1 then Result := Result + ','; Result := Result + GetEnumname(TypeInfo(TFontStyle), Ord(Style)); end; end; Result := Result + ']'; end; function TIni.StrToStyle(const StyleStr: string): TFontStyles; var I: integer; S: string; SL: TStringList; Style: TFontStyle; begin Result := []; S := StyleStr; if (Length(S) > 2) and (S[1] = '[') and (S[Length(S)] = ']') then S := Copy(S, 2, Length(S) - 2) else Exit; SL := TStringList.Create; try SL.CommaText := S; for I := 0 to SL.Count - 1 do try Style := TFontStyle(GetEnumValue(TypeInfo(TFontStyle), SL[I])); Include(Result, Style); except end; finally SL.Free; end; end; function TIni.PointToStr(const P: TPoint): string; begin with P do Result := Format('%d,%d', [X, Y]); end; function TIni.StrToPoint(const S: string; const Default: TPoint): TPoint; var I: integer; begin I := Pos(',', S); if I = 0 then // Assume only X is specified begin Result.X := StrToIntDef(S, Default.X); Result.Y := Default.Y; end else begin Result.X := StrToIntDef(Copy(S, 1, I - 1), Default.X); Result.Y := StrToIntDef(Copy(S, I + 1, 255), Default.Y); end; end; function TIni.RectToStr(const R: TRect): string; begin with R do Result := Format('%d,%d,%d,%d', [Left, Top, Right, Bottom]); end; function TIni.StrToRect(const RectStr: string; const Default: TRect): TRect; var S: string; I: integer; begin Result := Default; S := RectStr; I := Pos(',', S); if I > 0 then begin Result.Left := StrToIntDef(Trim(Copy(S, 1, I - 1)), Default.Left); Delete(S, 1, I); I := Pos(',', S); if I > 0 then begin Result.Top := StrToIntDef(Trim(Copy(S, 1, I - 1)), Default.Top); Delete(S, 1, I); I := Pos(',', S); if I > 0 then begin Result.Right := StrToIntDef(Trim(Copy(S, 1, I - 1)), Default.Right); Delete(S, 1, I); Result.Bottom := StrToIntDef(Trim(S), Default.Bottom); end; end; end; end; function TIni.ReadFont(const Section, Ident: string; const Default: TFont): TFont; begin Result := StrToFont(ReadString(Section, Ident, FontToStr(Default)), Default); end; procedure TIni.WriteFont(const Section, Ident: string; const Value: TFont); begin WriteString(Section, Ident, FontToStr(Value)); end; function TIni.ReadPoint(const Section, Ident: string; const Default: TPoint): TPoint; begin Result := StrToPoint(ReadString(Section, Ident, PointToStr(Default)), Default); end; procedure TIni.WritePoint(const Section, Ident: string; const Value: TPoint); begin WriteString(Section, Ident, PointToStr(Value)); end; function TIni.ReadRect(const Section, Ident: string; const Default: TRect): TRect; begin Result := StrToRect(ReadString(Section, Ident, RectToStr(Default)), Default); end; procedure TIni.WriteRect(const Section, Ident: string; const Value: TRect); begin WriteString(Section, Ident, RectToStr(Value)); end; function TIni.ReadReal(const Section, Ident: string; Default: Extended ): Extended; var TempStr: string; ResFloat: Extended; Error: Integer; begin Result := Default; TempStr := ReadString(Section, Ident, '?'); if TempStr <> '?' then begin Val(TempStr, ResFloat, Error); if Error = 0 then Result := ResFloat; end; end; procedure TIni.WriteReal(const Section, Ident: string; Value: Extended); begin WriteString(Section, Ident, FloatToStrF(Value, ffGeneral, 9, 0)); end; { TfrmMain } procedure TfrmMain.FormCreate(Sender: TObject); begin ini := TIni.Create(ChangeFileExt(Application.ExeName, '.ini')); BoundsRect:=ini.ReadRect('Last','Position',Rect(81,50,81+800,51+637)); end; procedure TfrmMain.imgNeopixel_16x16Click(Sender: TObject); begin if dlgSaveImg.Execute then imgSrcNeopixel_16x16.Picture.SaveToFile(dlgSaveImg.FileName); end; procedure TfrmMain.tmrInitTimer(Sender: TObject); begin tmrInit.Enabled := False; pgctMain.ActivePageIndex := ini.ReadInteger('Last', 'Page', 0); pgctNeopixel.ActivePageIndex := ini.ReadInteger('Neopixel', 'Page', 1); // Neopixel cbbPinNeopixel.ItemIndex := ini.ReadInteger('Neopixel', 'Pin', 1); EdtCountNeopixel.Value := ini.ReadInteger('Neopixel', 'Count', 8); EdtBrightnessNeopixel.Value := ini.ReadInteger('Neopixel', 'Brightness', 32); // NeoPixel 16x16 imgNeopixel_16x16.Width := NEOPIXEL16x16_MAX_TEXTWIDTH; imgNeopixel_16x16.Canvas.Brush.Color := 0; imgNeopixel_16x16.Canvas.Clear; dlgFontTextNeopixel_16x16.Font := ini.ReadFont('Neopixel', '16x16', dlgFontTextNeopixel_16x16.Font); edtTextNeopixel_16x16.Text := ini.ReadString('Neopixel', '16x16_Text', ''); imgSrcNeopixel_16x16.Width := NEOPIXEL16x16_MAX_TEXTWIDTH div 4; btnColorNeopixel_16x16.ButtonColor := dlgFontTextNeopixel_16x16.Font.Color; end; procedure TfrmMain.ToolButton3Click(Sender: TObject); begin OpenURL('http://microbit.site'); end; procedure TfrmMain.ToolButton5Click(Sender: TObject); begin OpenURL('http://www.micropython.org.cn'); end; procedure TfrmMain.TrackBarBrightnessNeopixelChange(Sender: TObject); begin EdtBrightnessNeopixel.Value := TrackBarBrightnessNeopixel.Position; end; procedure TfrmMain.TextImageNoepixel_16x16(Sender: TObject); begin imgSrcNeopixel_16x16.Canvas.Brush.Color := 0; imgSrcNeopixel_16x16.Canvas.Clear; imgSrcNeopixel_16x16.Canvas.Font := dlgFontTextNeopixel_16x16.Font; imgSrcNeopixel_16x16.Canvas.TextOut(0, 0, edtTextNeopixel_16x16.Text); end; procedure TfrmMain.redrawNeopixel_16x16(Sender: TObject); var i, j, w, h: integer; begin imgNeopixel_16x16.Canvas.Brush.Color := 0; imgNeopixel_16x16.Canvas.Clear; imgNeopixel_16x16.Canvas.Brush.Color := dlgFontTextNeopixel_16x16.Font.Color; w := 0; for i := 0 to imgSrcNeopixel_16x16.Width - 1 do for j := 0 to 15 do begin if imgSrcNeopixel_16x16.Canvas.Pixels[i, j] <> 0 then begin imgNeopixel_16x16.Canvas.FillRect(i * 4, j * 4, i * 4 + 4, j * 4 + 4); w := i; end; end; lbLenNeopixel_16x16.Tag := w; lbLenNeopixel_16x16.Caption := IntToStr(lbLenNeopixel_16x16.Tag) + ' x 16'; imgNeopixel_16x16.Canvas.Pen.Color := clGray; imgNeopixel_16x16.Canvas.Pen.Style := psSolid; imgNeopixel_16x16.Canvas.Pen.Width := 1; for i := 0 to (2048 div 4) do imgNeopixel_16x16.Canvas.Line(i * 4, 0, i * 4, 64); for i := 0 to (64 div 4) do imgNeopixel_16x16.Canvas.Line(0, i * 4, 2047, i * 4); end; procedure TfrmMain.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin try ini.WriteRect('Last','Position',BoundsRect); ini.WriteInteger('Last', 'Page', pgctMain.ActivePageIndex); ini.WriteInteger('Neopixel', 'Page', pgctNeopixel.ActivePageIndex); // Neopixel ini.WriteInteger('Neopixel', 'Pin', cbbPinNeopixel.ItemIndex); ini.WriteInteger('Neopixel', 'Count', EdtCountNeopixel.Value); ini.WriteInteger('Neopixel', 'Brightness', EdtBrightnessNeopixel.Value); // Neopixel 16x16 ini.WriteFont('Neopixel', '16x16', dlgFontTextNeopixel_16x16.Font); ini.WriteString('Neopixel', '16x16_Text', edtTextNeopixel_16x16.Text); finally ini.Free; end; end; // new input Text procedure TfrmMain.edtTextNeopixel_16x16Change(Sender: TObject); begin edtTextNeopixel_16x16.Tag := 0; TextImageNoepixel_16x16(Sender); redrawNeopixel_16x16(Sender); end; procedure TfrmMain.edtFileNameNeopixel_16x16_ImgAcceptFileName(Sender: TObject; var Value: string); var w, h: integer; begin try lbLenNeopixel_16x16_Img.Caption := ''; imgSrcNeopixel_16x16_Img.Stretch := False; imgSrcNeopixel_16x16_Img.Picture.LoadFromFile(Value); w := imgSrcNeopixel_16x16_Img.Picture.Width; h := imgSrcNeopixel_16x16_Img.Picture.Height; imgSrcNeopixel_16x16_Img.Stretch := True; imgSrcNeopixel_16x16_Img.Height := 16; imgSrcNeopixel_16x16_Img.Width := w * 16 div h; lbLenNeopixel_16x16_Img.Caption := Format('%d x 16', [imgSrcNeopixel_16x16_Img.Width]); lbLenNeopixel_16x16_Img.Tag := imgSrcNeopixel_16x16_Img.Width; imgNeopixel_16x16_Img.Width := imgSrcNeopixel_16x16_Img.Width * 4; imgNeopixel_16x16_Img.Picture := imgSrcNeopixel_16x16_Img.Picture; except end; end; // select display Font procedure TfrmMain.btnTextFontNeopixel_16x16Click(Sender: TObject); begin if dlgFontTextNeopixel_16x16.Execute then begin if edtTextNeopixel_16x16.Tag = 0 then TextImageNoepixel_16x16(Sender); redrawNeopixel_16x16(Sender); btnColorNeopixel_16x16.ButtonColor := dlgFontTextNeopixel_16x16.Font.Color; end; end; procedure TfrmMain.EdtBrightnessNeopixelChange(Sender: TObject); begin TrackBarBrightnessNeopixel.Position := EdtBrightnessNeopixel.Value; end; // create Text/image list procedure TfrmMain.btnMakeNeopixel_16x16Click(Sender: TObject); var i, j, w: integer; r, g, b: byte; n: word; s: string; begin if edtTextNeopixel_16x16.Text = '' then Exit; edtMakeNeopixel_16x16.Clear; edtMakeNeopixel_16x16.Lines := lbTPNeopixel_16x16.Items; edtMakeNeopixel_16x16.Lines.Append('npdat=['); w := lbLenNeopixel_16x16.Tag; s := ''; for i := 0 to w do begin n := 0; for j := 0 to 15 do begin if imgSrcNeopixel_16x16.Canvas.Pixels[i, j] <> 0 then n := n + (1 shl j); end; if (i mod 2) = 1 then n := ReverseWord(n); s := s + '0x' + IntToHex(n, 4) + ','; if (i mod 8) = 7 then begin edtMakeNeopixel_16x16.Lines.Append(s); s := ''; end; end; edtMakeNeopixel_16x16.Lines.Append(s + ']'); edtMakeNeopixel_16x16.Lines.Append(''); edtMakeNeopixel_16x16.Lines.Append('ne = neo16x16(' + cbbPinNeopixel.Text + ')'); ExtractRGB(dlgFontTextNeopixel_16x16.Font.Color, r, g, b); r := r * EdtBrightnessNeopixel.Value div 256; g := g * EdtBrightnessNeopixel.Value div 256; b := b * EdtBrightnessNeopixel.Value div 256; edtMakeNeopixel_16x16.Lines.Append('ne.setcolor((' + IntToStr(r) + ',' + IntToStr(g) + ',' + IntToStr(b) + '))'); if (w > 16) then begin edtMakeNeopixel_16x16.Lines.Append('n = 0'); edtMakeNeopixel_16x16.Lines.Append('while True:'); edtMakeNeopixel_16x16.Lines.Append(' ne.show(npdat, n)'); edtMakeNeopixel_16x16.Lines.Append(' n = (n+1)%' + IntToStr(w - 8)); edtMakeNeopixel_16x16.Lines.Append(' _delay(100)'); end else edtMakeNeopixel_16x16.Lines.Append('ne.show(npdat)'); edtMakeNeopixel_16x16.Lines.Append(''); edtMakeNeopixel_16x16.SelectAll; edtMakeNeopixel_16x16.CopyToClipboard; edtMakeNeopixel_16x16.SelEnd := 0; end; procedure TfrmMain.btnMakeNeopixel_16x16_ImgClick(Sender: TObject); var i, j: integer; r1, g1, b1: byte; r2, g2, b2: byte; c1, c2: TColor; s: string; begin if lbLenNeopixel_16x16_Img.Tag = 0 then Exit; edtMakeNeopixel_16x16_Img.Clear; edtMakeNeopixel_16x16_Img.Lines := lbTPNeopixel_16x16_Img.Items; edtMakeNeopixel_16x16_Img.Lines.Append('npdat=['); s := ''; for i := 0 to imgSrcNeopixel_16x16_Img.Width - 1 do begin for j := 0 to 7 do begin if (i mod 2) = 1 then begin c1 := imgSrcNeopixel_16x16_Img.Canvas.Pixels[i, j * 2]; c2 := imgSrcNeopixel_16x16_Img.Canvas.Pixels[i, j * 2 + 1]; end else begin c1 := imgSrcNeopixel_16x16_Img.Canvas.Pixels[i, 15 - j * 2]; c2 := imgSrcNeopixel_16x16_Img.Canvas.Pixels[i, 15 - j * 2 - 1]; end; ExtractRGB(c1, r1, g1, b1); r1 := r1 shr 4; g1 := g1 shr 4; b1 := b1 shr 4; ExtractRGB(c2, r2, g2, b2); r2 := r2 shr 4; g2 := g2 shr 4; b2 := b2 shr 4; s := s + Format('0x%.X%.X%.X%.X%.X%.X, ', [b2, g2, r2, b1, g1, r1]); if (j mod 4) = 3 then begin edtMakeNeopixel_16x16_Img.Lines.Append(s); s := ''; end; end; end; edtMakeNeopixel_16x16_Img.Lines.Append(']'); edtMakeNeopixel_16x16_Img.Lines.Append(''); edtMakeNeopixel_16x16_Img.Lines.Append('ne = neo16x16_img(' + cbbPinNeopixel.Text + ')'); if (imgSrcNeopixel_16x16_Img.Width > 16) then begin edtMakeNeopixel_16x16_Img.Lines.Append('n = 0'); edtMakeNeopixel_16x16_Img.Lines.Append('while True:'); edtMakeNeopixel_16x16_Img.Lines.Append(' ne.show(npdat, n)'); edtMakeNeopixel_16x16_Img.Lines.Append(' n = (n+16)%' + IntToStr(imgSrcNeopixel_16x16_Img.Width)); edtMakeNeopixel_16x16_Img.Lines.Append(' _delay(15000)'); end else edtMakeNeopixel_16x16_Img.Lines.Append('ne.show(npdat)'); edtMakeNeopixel_16x16_Img.Lines.Append(''); edtMakeNeopixel_16x16_Img.SelectAll; edtMakeNeopixel_16x16_Img.CopyToClipboard; edtMakeNeopixel_16x16_Img.SelEnd := 0; end; procedure TfrmMain.btnMakeNeopixel_stripClick(Sender: TObject); var s: string; r, g, b: byte; i, n: integer; begin edtMakeNeopixel_strip.Clear; edtMakeNeopixel_strip.Lines.Append('from microbit import *'); edtMakeNeopixel_strip.Lines.Append('import neopixel'); edtMakeNeopixel_strip.Lines.Append(''); edtMakeNeopixel_strip.Lines.Append('np = neopixel.NeoPixel(' + cbbPinNeopixel.Text + ' ,' + EdtCountNeopixel.Text + ')'); edtMakeNeopixel_strip.Lines.Append(''); s := ''; case rbNeopixelStripEffect.ItemIndex of 0://rainbow begin edtMakeNeopixel_strip.Lines.Append( 'def np_rainbow(np, num, bright=32, offset = 0):'); edtMakeNeopixel_strip.Lines.Append( ' rb = ((255,0,0), (255,127,0), (255,255,0), (0,255,0), (0,255,255),(0,0,255),(136,0,255), (255,0,0))'); edtMakeNeopixel_strip.Lines.Append(' for i in range(num):'); edtMakeNeopixel_strip.Lines.Append(' t = 7*i/num'); edtMakeNeopixel_strip.Lines.Append(' t0 = int(t)'); edtMakeNeopixel_strip.Lines.Append( ' r = round((rb[t0][0] + (t-t0)*(rb[t0+1][0]-rb[t0][0]))*bright)>>8'); edtMakeNeopixel_strip.Lines.Append( ' g = round((rb[t0][1] + (t-t0)*(rb[t0+1][1]-rb[t0][1]))*bright)>>8'); edtMakeNeopixel_strip.Lines.Append( ' b = round((rb[t0][2] + (t-t0)*(rb[t0+1][2]-rb[t0][2]))*bright)>>8'); edtMakeNeopixel_strip.Lines.Append(' np[(i+offset)%num] = (r, g, b)'); edtMakeNeopixel_strip.Lines.Append(''); edtMakeNeopixel_strip.Lines.Append('np_rainbow(np, ' + IntToStr( EdtCountNeopixel.Value) + ', bright=' + IntToStr(EdtBrightnessNeopixel.Value) + ', offset=0)'); edtMakeNeopixel_strip.Lines.Append('np.show()'); end; 1: begin end; 2: begin end; 3: begin end; 4: begin end; end; // copy to clipboard edtMakeNeopixel_strip.Lines.Append(''); edtMakeNeopixel_strip.SelectAll; edtMakeNeopixel_strip.CopyToClipboard; edtMakeNeopixel_strip.SelEnd := 0; end; procedure TfrmMain.btnColorNeopixel_16x16ColorChanged(Sender: TObject); begin dlgFontTextNeopixel_16x16.Font.Color := btnColorNeopixel_16x16.ButtonColor; redrawNeopixel_16x16(Sender); end; procedure TfrmMain.btnImageFontNeopixel_16x16Click(Sender: TObject); var w, h, i, j: integer; begin if dlgOpenImg.Execute then begin imgSrcNeopixel_16x16.Stretch := False; imgSrcNeopixel_16x16.Picture.LoadFromFile(dlgOpenImg.FileName); w := imgSrcNeopixel_16x16.Picture.Width; h := imgSrcNeopixel_16x16.Picture.Height; imgSrcNeopixel_16x16.Stretch := True; imgSrcNeopixel_16x16.Height := 16; imgSrcNeopixel_16x16.Width := w * 16 div h; redrawNeopixel_16x16(Sender); edtTextNeopixel_16x16.Tag := 1; end; end; end.
unit uGridFunc; { Создан 18.10.2004 года Должиковым Модуль предназначен для сортировки данных в гриде DbGridEh, прежде всгео в случае, когда источником данных грида является MemoryTable. Если у вас есть DbGridEh, и его источником данных является MemoryTable, то для того, чтобы можно было осуществлять сортировку с помощью щелканья по заголовку нужно сделать два действия: 1. При создании формы вызвать функцию InitGridToolButtons от этого грида (можно указать необязательным параметром поле, по которому грид будет отсортирован сразу, в противном случае грид будет отсортирован по первому полю) 2. На событие OnSortMarkingChange повесить вызов SortGridMemoryTable от грида } interface uses uCommonForm, Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Db, DBTables, MemTable, ExtCtrls, Ora, DbGridEh,uOilQuery,uOilStoredProc {$IFDEF VER150},Variants{$ENDIF}; procedure SortMemoryTable( p_MT: TMemoryTable; p_FieldName: string; p_Direction: integer; // 1 - прямое направление, -1 - обратное p_SortType: integer = 0 // 0 - обычная сортировка строк, 1 - продвинутая ); procedure InitGridToolButtons(p_Grid: TDbGridEh; p_FieldName: string=''); procedure SortGridMemoryTable(p_Grid: TDbGridEh); implementation //============================================================================== procedure SortMemoryTable( p_MT: TMemoryTable; p_FieldName: string; p_Direction: integer; // 1 - прямое направление, -1 - обратное p_SortType: integer = 0 // 0 - обычная сортировка строк, 1 - продвинутая ); type TRec = record Id: integer; Key: Variant; Moved: Boolean; end; var a: array of TRec; {i,}LastStart: integer; //s: string; buf1,buf2: array of variant; //**************************************************************************** procedure Log_(s: string); //var F: TextFile; begin {AssignFile(F,'d:\log.txt'); if FileExists('d:\log.txt') then Append(F) else Rewrite(F); writeln(F,s); CloseFile(F);} end; //**************************************************************************** procedure WriteLogA; var i: integer; s: string; begin s:=''; for i:=0 to High(a) do s:=s+Format('%d-%s; ',[a[i].id,a[i].Key ]); Log_(s); end; //**************************************************************************** procedure InitA; var i: integer; begin SetLength(a,p_MT.RecordCount); p_MT.First; i:=0; while not p_MT.Eof do begin a[i].Id:=i; a[i].Key:=p_MT.FieldByName(p_FieldName).Value; a[i].Moved:=FALSE; p_MT.Next; inc(i); end; end; //**************************************************************************** procedure Swap(i,j: integer); var vId: integer; vKey: variant; begin vId:=a[i].Id; vKey:=a[i].Key; a[i].Id:=a[j].Id; a[i].Key:=a[j].Key; a[j].Id:=vId; a[j].Key:=vKey; end; //**************************************************************************** function Compare(v1,v2: variant): integer; begin if VarType(v1)=varString then begin if p_SortType=0 then result:=AnsiCompareStr(v1,v2); end else if v1>v2 then result:=1 else if v1=v2 then result:=0 else result:=-1; if p_Direction=-1 then result:=-result; end; //**************************************************************************** procedure QuickSortA(p_First,p_Last: integer); var i,j,n: integer; vKey: variant; begin //Log('Вызов: '+IntToStr(p_First)+' - '+IntToStr(p_Last)); if p_First>=p_Last then exit; {if p_First+1=p_Last then begin if a[p_First].Key>a[p_Last].Key then swap(p_First,p_Last); exit; end;} n:=p_First+random(p_Last-p_First+1); //Log(' n='+IntToStr(n)); if n<>p_First then Swap(p_First,n); vKey:=a[p_First].Key; i:=p_First; j:=p_Last+1; while i<j do begin repeat inc(i) until (i>p_Last) or (Compare(a[i].Key,vKey)>=0); repeat dec(j) until Compare(a[j].Key,vKey)<=0; if i<j then swap(i,j); end; Swap(p_First,j); QuickSortA(p_First,j-1); QuickSortA(j+1,p_Last); end; //**************************************************************************** procedure SortMT; var i,j,iStart,nMoved,CurMtPosition: integer; log: string; //************************************************************************** procedure GotoPosition(p_NewPos: integer); begin p_MT.GotoRecord(p_NewPos+1);//MoveBy(p_NewPos-CurMtPosition); CurMtPosition:=p_NewPos; end; //************************************************************************** procedure PutToBuf1(p_Pos: integer); var i: integer; begin log:=log+'P1-'+IntToStr(p_Pos)+'; '; GotoPosition(p_Pos); for i:=0 to p_MT.Fields.Count-1 do buf1[i]:=p_MT.Fields[i].Value; end; //************************************************************************** procedure PutToBuf2(p_Pos: integer); var i: integer; begin log:=log+'P2-'+IntToStr(p_Pos)+'; '; GotoPosition(p_Pos); for i:=0 to p_MT.Fields.Count-1 do buf2[i]:=p_MT.Fields[i].Value; end; //************************************************************************** procedure GetFromBuf1(p_Pos: integer); var i: integer; begin log:=log+'G1-'+IntToStr(p_Pos)+'; '; GotoPosition(p_Pos); p_MT.Edit; for i:=0 to p_MT.Fields.Count-1 do p_MT.Fields[i].Value:=buf1[i]; p_MT.Post; inc(NMoved); a[p_Pos].Moved:=TRUE; end; //************************************************************************** procedure GetFromBuf2(p_Pos: integer); var i: integer; begin log:=log+'G2-'+IntToStr(p_Pos)+'; '; GotoPosition(p_Pos); p_MT.Edit; for i:=0 to p_MT.Fields.Count-1 do p_MT.Fields[i].Value:=buf2[i]; p_MT.Post; inc(NMoved); a[p_Pos].Moved:=TRUE; end; //************************************************************************** begin log:=''; Log_(TranslateText('Размер буферов ')+IntToStr(p_Mt.Fields.Count)); SetLength(buf1,p_MT.Fields.Count); SetLength(buf2,p_MT.Fields.Count); NMoved:=0; p_MT.First; CurMtPosition:=0; LastStart:=-1; Log_(Format('RecordCount=%d',[p_Mt.RecordCount])); while NMoved<p_MT.RecordCount do begin Log_(TranslateText('Новое начало while')); Log_(Format('NMoved=%d',[NMoved])); for i:=LastStart+1 to p_MT.RecordCount-1 do if not a[i].Moved then break; Log_(Format('i=%d',[i])); {while (a[i].Key=a[a[i].Id].Key) and not a[i].Moved do begin log_(Format('i->%d',[a[i].Id])); a[i].Moved:=TRUE; inc(NMoved); i:=a[i].Id; end;} Log_(Format('NMoved=%d',[NMoved])); if NMoved=p_MT.RecordCount then break; iStart:=i; LastStart:=iStart; Log_(Format('istart=%d',[iStart])); Log_(Format('LastStart=%d',[LastStart])); if a[i].Moved then continue; Log_(Format(TranslateText('Начало цепочки %d:%s'),[iStart,a[iStart].Key])); PutToBuf1(iStart); while TRUE do begin j:=a[i].Id; if j=iStart then break; Log_(Format('%d -> %d',[j,i])); PutToBuf2(j); GetFromBuf2(i); i:=j; end; Log_(Format(TranslateText('Конец цепочки %d:%s'),[i,a[i].Key])); GetFromBuf1(i); Log_(Format('NMoved=%d',[NMoved])); end; p_MT.First; Log_(log); end; //**************************************************************************** begin InitA; Log_('********************************************'); WriteLogA; QuickSortA(0,p_Mt.RecordCount-1); WriteLogA; SortMT; Log_('********************************************'); end; //============================================================================== procedure InitGridToolButtons(p_Grid: TDbGridEh; p_FieldName: string=''); var i: integer; begin p_Grid.OptionsEh:=p_Grid.OptionsEh+[dghAutoSortMarking]; if p_Grid.Columns.Count>0 then for i:=0 to p_Grid.Columns.Count-1 do begin if (p_FieldName='') and (i=0) or (p_Grid.Columns[i].FieldName=p_FieldName) then p_Grid.Columns[i].Title.SortMarker:=smDownEh else p_Grid.Columns[i].Title.SortMarker:=smNoneEh; p_Grid.Columns[i].Title.TitleButton:=TRUE; end; end; //============================================================================== procedure SortGridMemoryTable(p_Grid: TDbGridEh); var i,vDirection: integer; dset: TDataSet; begin vDirection := 0; for i:=0 to p_Grid.SortMarkedColumns.Count-1 do begin case p_Grid.SortMarkedColumns[i].Title.SortMarker of smNoneEh: continue; smDownEh: vDirection:=1; smUpEh: vDirection:=-1; end; break; end; if p_Grid.DataSource.DataSet.RecordCount=0 then exit; dset:=p_Grid.DataSource.DataSet; p_Grid.DataSource.DataSet:=nil; if vDirection <> 0 then SortMemoryTable(dset as TMemoryTable,p_Grid.SortMarkedColumns[i].FieldName,vDirection); p_Grid.DataSource.DataSet:=dset; end; //============================================================================== end.
unit GOBLFD; interface Uses Files, Classes, SysUtils; Type TGOBheader=packed record magic:array[0..3] of char; index_ofs:longint; end; TNEntries=longint; TGOBEntry=packed record offs:longint; size:longint; name:array[0..12] of char; end; TLFDentry=packed record tag:array[0..3] of char; name:array[0..7] of char; size:longint; end; TFInfo=TFileInfo; TGOBDirectory=class(TContainerFile) gh:TGobHeader; Procedure Refresh;override; Function GetContainerCreator(name:String):TContainerCreator;override; end; TFLDDirectory=class(TContainerFile) Procedure Refresh;override; Function GetContainerCreator(name:String):TContainerCreator;override; end; TGOBCreator=class(TContainerCreator) pes:TList; centry:integer; Procedure PrepareHeader(newfiles:TStringList);override; Procedure AddFile(F:TFile);override; Function ValidateName(name:String):String;override; Destructor Destroy;override; end; TLFDCreator=class(TContainerCreator) pes:TList; centry:integer; Procedure PrepareHeader(newfiles:TStringList);override; Procedure AddFile(F:TFile);override; Function ValidateName(name:String):String;override; Destructor Destroy;override; private Function ValidateExt(e:string):String; end; implementation Uses FileOperations; Procedure TGOBCreator.PrepareHeader(newfiles:TStringList); var i:Integer; pe:^TGOBEntry; aName:STring; begin pes:=TList.Create; cf.FSeek(sizeof(TGOBHeader)); for i:=0 to newfiles.count-1 do begin New(pe); aName:=ExtractName(Newfiles[i]); StrPCopy(Pe^.Name,ValidateName(aName)); pes.Add(pe); end; centry:=0; end; Procedure TGOBCreator.AddFile(F:TFile); begin with TgobEntry(pes[centry]^) do begin offs:=cf.Fpos; size:=f.Fsize; end; CopyFileData(F,CF,f.Fsize); inc(Centry); end; Function TGOBCreator.ValidateName(name:String):String; var n,ext:String; begin Ext:=ExtractExt(name); n:=Copy(Name,1,length(Name)-length(ext)); if length(Ext)>4 then SetLength(Ext,4); if length(N)>8 then SetLength(N,8); Result:=N+ext; end; Destructor TGOBCreator.Destroy; var i:integer; gh:TGobHeader; n:Longint; begin if pes<>nil then begin gh.magic:='GOB'#10; gh.index_ofs:=cf.Fpos; cf.Fseek(0); cf.FWrite(gh,sizeof(gh)); cf.FSeek(gh.index_ofs); n:=pes.count; cf.FWrite(n,sizeof(n)); for i:=0 to pes.count-1 do begin cf.FWrite(TGOBEntry(pes[i]^),sizeof(TGOBEntry)); Dispose(pes[i]); end; pes.Free; end; Inherited Destroy; end; Procedure TGOBDirectory.Refresh; var Fi:TFInfo; i:integer; ge:TGobEntry; gn:TNEntries; s:string; f:TFile; begin ClearIndex; f:=OpenFileRead(name,0); Try F.FRead(gh,sizeof(gh)); if gh.magic<>'GOB'#10 then raise Exception.Create(Name+' is not a GOB file'); F.FSeek(gh.index_ofs); F.FRead(gn,sizeof(gn)); for i:=0 to gn-1 do begin F.FRead(ge,sizeof(ge)); fi:=TFInfo.Create; fi.offs:=ge.offs; fi.size:=ge.size; Files.AddObject(ge.name,fi); end; Finally F.FClose; end; end; Function TGOBDirectory.GetContainerCreator(name:String):TContainerCreator; begin Result:=TGOBCreator.Create(Name); end; {Procedure TDirectoryFile.RenameFile(Fname,newname:TFileName); var i:integer; begin i:=Files.IndexOf(Fname); if i=-1 then exit; Files.Strings[i]:=NewName; end;} Procedure TFLDDirectory.Refresh; var Le:TLFDEntry; N:array[0..12] of char; E:array[0..5] of char; fi:TFInfo; f:TFile; pos:Longint; begin ClearIndex; F:=OpenFileRead(Name,0); Try While (F.FPos<F.FSize) do begin F.FRead(le,sizeof(le)); StrLCopy(n,le.name,sizeof(le.name)); StrLCopy(e,le.tag,sizeof(le.tag)); fi:=TFInfo.Create; Fi.offs:=F.FPos; fi.size:=le.size; Fi.offs:=F.Fpos; Files.AddObject(Concat(n,'.',e),fi); F.Fseek(F.Fpos+le.size); end; Finally F.FClose; end; end; Function TFLDDirectory.GetContainerCreator(name:String):TContainerCreator; begin Result:=TLFDCreator.Create(Name); end; Procedure TLFDCreator.PrepareHeader(newfiles:TStringList); var i:Integer; pe:^TLFDEntry; name,ext,s:string; begin pes:=TList.Create; cf.FSeek(sizeof(TLFDEntry)*newfiles.count+sizeof(TLFDEntry)); for i:=0 to newfiles.count-1 do begin New(pe); name:=ValidateName(ExtractName(Newfiles[i])); {always 4 letter extension} ext:=ExtractExt(name); Delete(Ext,1,1); SetLength(Name,length(Name)-5); StrMove(Pe^.Name,Pchar(Name),8); StrMove(pe^.tag,Pchar(Ext),4); pe^.size:=0; pes.Add(pe); end; centry:=0; end; Procedure TLFDCreator.AddFile(F:TFile); begin TLFDEntry(Pes[centry]^).size:=f.Fsize; cf.FWrite(TLFDEntry(Pes[centry]^),sizeof(TLFDEntry)); CopyFileData(f,cf,f.Fsize); inc(centry); end; Function TLFDCreator.ValidateName(name:String):String; var n,ext:String; begin Ext:=ExtractExt(name); n:=Copy(name,1,length(Name)-length(ext)); Ext:=ValidateExt(ext); n:=LowerCase(n); if length(n)>8 then SetLength(n,8); Result:=n+ext; end; Destructor TLFDCreator.Destroy; var i:integer; le:TLFDEntry; begin if pes<>nil then begin cf.Fseek(0); le.name:='resource'; le.tag:='RMAP'; le.size:=pes.count*sizeof(TLFDEntry); cf.FWrite(le,sizeof(le)); for i:=0 to pes.count-1 do begin cf.FWrite(TLFDEntry(pes[i]^),sizeof(TLFDEntry)); Dispose(pes[i]); end; pes.Free; end; Inherited Destroy; end; Function TLFDCreator.ValidateExt(e:string):String; begin Result:=UpperCase(e); if (result='') or (result='.') then Result:='.DATA' else if result='.TXT' then result:='.TEXT' else if result='.DLT' then result:='.DELT' else if result='.ANM' then result:='.ANIM' else if result='.FON' then result:='.FONT' else if result='.PLT' then result:='.PLTT' else if result='.GMD' then result:='.GMID' else if result='.VOC' then result:='.VOIC' else if result='.FLM' then result:='.FILM' else if length(result)<5 then while length(result)<5 do result:=result+'X'; end; end.
UNIT UEarthquake; INTERFACE USES UDate; {* make functions and procedures from UDate available in this scope *} {* exposed functions and procedures *} {* Inserts new earthquake to earthquakes list sorted by date (DESC) * * @param latitude REAL Latitude value of geopoint * @param longitude REAL Longitude value of geopoint * @param strength REAL Strength value of earthquake (richter magnitude scale) * @param city STRING City near geopoint of earthquake * @param date Date Date when earthquake occured. *} PROCEDURE AddEarthquake(latitude, longitude, strength: REAL; city: STRING; date: Date); {* Returns total number of earthquakes in list * * @return INTEGER Number of earthquakes *} FUNCTION TotalNumberOfEarthquakes: INTEGER; {* Returns Number of earthquakes between two given dates * * @paramIn fromDate Date (inclusive) date beginning of timespan * @paramIn toDate Date (inclusive) date ending of timespan * @return INTEGER Number of earthquakes found *} FUNCTION NumberOfEarthquakesInTimespan(fromDate, toDate: Date): INTEGER; {* Gets the data of earthquake with biggest strength in given region * * @paramIn latitudeIn1 REAL Latitude value of first geopoint * @paramIn longitudeIn1 REAL Longitude value of first geopoint * @paramIn latitudeIn2 REAL Latitude value of second geopoint * @paramIn longitudeIn2 REAL Longitude value of second geopoint * @paramOut latitudeOut REAL Latitude value of found earthquake * @paramOut longitudeOut REAL Longitude value of found earthquake * @paramOut strength REAL Strength value of found earthquake * @paramOut city STRING City of found earthquake * @paramOut day INTEGER day of found earthquake (part of date) * @paramOut month INTEGER month of found earthquake (part of date) * @paramOut year INTEGER year of found earthquake (part of date ) *} PROCEDURE GetStrongestEarthquakeInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2: REAL; VAR latitudeOut, longitudeOut, strength: REAL; VAR city: STRING; VAR day, month, year: INTEGER); {* Gets average earthquake strength in region * * @paramIn latitudeIn1 REAL Latitude value of first geopoint * @paramIn longitudeIn1 REAL Longitude value of first geopoint * @paramIn latitudeIn2 REAL Latitude value of second geopoint * @paramIn longitudeIn2 REAL Longitude value of second geopoint * @return REAL Average Strength value *} FUNCTION AverageEarthquakeStrengthInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2: REAL): REAL; {* Displays earthquakes list of entries close to city * * @paramIn city STRING City value to be searched for in earthquakes *} PROCEDURE PrintEarthquakesCloseToCity(city: STRING); {* Displays earthquakes list of entries with strength bigger or equal to strength * * @paramIn strength REAL Strength value to be searched for in earthquakes *} PROCEDURE PrintStrongCityEarthquakes(strength: REAL); {* Disposes the city list and all it's earthquakes and re-initializes the list anchor *} PROCEDURE Reset; {* Deletes earthquake list entries that occured before the given date and returns the number of deleted elements * * @paramIn beforeDate Date (inclusive) date which is after the dates * of entries that should be deleted. * @paramOut deletedElementCount INTEGER Number of elements that were deleted *} PROCEDURE DeleteAllEarthquakesBeforeDate(beforeDate: Date; VAR deletedElementCount: INTEGER); {* Deletes earthquake list entries that match the given city and returns the number of deleted elements * * @paramIn city STRING City value of entries that should be deleted * @paramOut deletedElementCount INTEGER Number of elements that were deleted *} PROCEDURE DeleteAllEarthquakesCloseToCity(city: STRING; VAR deletedElementCount: INTEGER); {* Displays all earthquake list entries grouped by their cities *} PROCEDURE PrintEarthquakesGroupedByCity; IMPLEMENTATION TYPE Earthquake = ^EarthquakeRec; {* Earthquake pointer *} EarthquakeRec = RECORD city: STRING; strength, latitude, longitude: REAL; date: Date; next: Earthquake; END; EarthquakeList = Earthquake; City = ^CityRec; {* City pointer *} CityRec = RECORD name: STRING; prev, next: City; earthquakes: EarthquakeList; {* Earthquake pointer *} END; CityList = City; VAR list: CityList; {* global list of city entries *} {* Initialize city list *} PROCEDURE InitCityList; VAR cityEntry: City; BEGIN {* create anchor element *} New(cityEntry); cityEntry^.next := cityEntry; cityEntry^.prev := cityEntry; list := cityEntry; END; {* returns the pointer of the searched city entry or the anchor if the searched entry can't be found *} FUNCTION GetCityPtrOrAnchor(name: STRING): City; VAR temp: City; BEGIN temp := list^.next; WHILE (temp <> list) AND (temp^.name <> name) DO temp := temp^.next; GetCityPtrOrAnchor := temp; END; PROCEDURE AddEarthquakeToList(earthquakeEntry: Earthquake; cityEntry: City); VAR found: BOOLEAN; temp, previousTemp: Earthquake; BEGIN found := false; temp := cityEntry^.earthquakes; previousTemp := temp; {* check of first list element, needs special handling since list pointer must be re-set => special case! *} IF LiesBefore(temp^.date, earthquakeEntry^.date) THEN BEGIN earthquakeEntry^.next := temp; cityEntry^.earthquakes := earthquakeEntry; END ELSE BEGIN WHILE (temp <> NIL) and (not found) DO BEGIN IF LiesBefore(temp^.date, earthquakeEntry^.date) THEN BEGIN earthquakeEntry^.next := temp; previousTemp^.next := earthquakeEntry; found := true; {* leave loop when the new entry's perfect position was found *} END ELSE BEGIN previousTemp := temp; temp := temp^.next; END; END; {* No perfect position was found so just append the entry to list *} IF not found THEN previousTemp^.next := earthquakeEntry; END; END; PROCEDURE AddEarthquake(latitude, longitude, strength: REAL; city: STRING; date: Date); VAR earthquakeEntry, temp, previousTemp: Earthquake; cityEntry: City; BEGIN {* fill earthquakeEntry properties with parameter values *} New(earthquakeEntry); earthquakeEntry^.date := date; earthquakeEntry^.latitude := latitude; earthquakeEntry^.longitude := longitude; earthquakeEntry^.strength := strength; earthquakeEntry^.city := city; earthquakeEntry^.next := NIL; cityEntry := GetCityPtrOrAnchor(city); IF cityEntry <> list THEN BEGIN {* add earthquake to city list *} AddEarthquakeToList(earthquakeEntry, cityEntry); END ELSE BEGIN {* create new city entry with the earthquake *} New(cityEntry); cityEntry^.name := city; cityEntry^.earthquakes := earthquakeEntry; cityEntry^.next := list; cityEntry^.prev := list^.prev; list^.prev^.next := cityEntry; list^.prev := cityEntry; END; END; PROCEDURE DisplayList(eqList: Earthquake); VAR temp: Earthquake; BEGIN temp := eqList; WHILE temp <> NIL DO BEGIN WriteLn(); Write('DATE: '); DisplayDate(temp^.date); WriteLn(); WriteLn('STRENGTH: ', temp^.strength); WriteLn('LATITUDE: ', temp^.latitude); WriteLn('LONGITUDE: ', temp^.longitude); WriteLn('CITY: ', temp^.city); WriteLn(); temp := temp^.next; END; END; FUNCTION TotalNumberOfEarthquakes: INTEGER; VAR tempEarthquake: Earthquake; tempCity: City; count: INTEGER; BEGIN tempCity := list^.next; count := 0; {* iterate over list and the earthquake lists of the city entries*} WHILE tempCity <> list DO BEGIN tempEarthquake := tempCity^.earthquakes; WHILE tempEarthquake <> NIL DO BEGIN Inc(count); {* increase count for every earthquake entry *} tempEarthquake := tempEarthquake^.next; END; tempCity := tempCity^.next; END; TotalNumberOfEarthquakes := count; END; FUNCTION NumberOfEarthquakesInTimespan(fromDate, toDate: Date): INTEGER; VAR count: INTEGER; tempDate: Date; tempEarthquake: Earthquake; tempCity: City; BEGIN {* Swap dates if toDate is earlier than fromDate *} IF not LiesBefore(fromDate, toDate) THEN {* exposed by UDate *} BEGIN tempDate := toDate; toDate := fromDate; fromDate := tempDate; END; count := 0; tempCity := list^.next; {* start iterating over all earthquakes in list *} WHILE tempCity <> list DO BEGIN tempEarthquake := tempCity^.earthquakes; WHILE tempEarthquake <> NIL DO BEGIN IF LiesBefore(fromDate, tempEarthquake^.date) and LiesBefore(tempEarthquake^.date, toDate) THEN BEGIN Inc(count); END; tempEarthquake := tempEarthquake^.next; {* go to next earthquake pointer *} END; tempCity := tempCity^.next; END; NumberOfEarthquakesInTimespan := count END; {* Swaps two REAL values and returns them *} PROCEDURE SwapValues(VAR val1, val2: REAL); VAR temp: REAL; BEGIN temp := val1; val1 := val2; val2 := temp; END; {* returns true if geopoint (checkLatitude and checkLongitude) is in region *} FUNCTION GeopointInRegion(latitude1, longitude1, latitude2, longitude2, checkLatitude, checkLongitude: REAL): BOOLEAN; BEGIN GeopointInRegion := false; IF latitude1 > latitude2 THEN BEGIN {* swap geopoints so check conditions will work *} SwapValues(latitude1, latitude2); SwapValues(longitude1, longitude2); END; {* check if given geopoint is in region. * The region can be seen as a rectangle in a coordinate system *} IF (checkLatitude >= latitude1) and (checkLatitude <= latitude2) THEN IF (checkLongitude >= longitude1) and (checkLongitude <= longitude2) THEN GeopointInRegion := true; END; PROCEDURE GetStrongestEarthquakeInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2: REAL; VAR latitudeOut, longitudeOut, strength: REAL; VAR city: STRING; VAR day, month, year: INTEGER); VAR tempEarthquake, strongestEarthquake: Earthquake; tempCity: City; BEGIN New(strongestEarthquake); {* dynamically allocate memory for strongestEarthquake *} strongestEarthquake^.strength := 0; {* initial value for the searched strength *} tempCity := list^.next; WHILE tempCity <> list DO BEGIN tempEarthquake := tempCity^.earthquakes; WHILE tempEarthquake <> NIL DO BEGIN IF GeopointInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2, tempEarthquake^.latitude, tempEarthquake^.longitude) THEN BEGIN {* earthquake is in the region, so compare it's strength to previosly found *} IF strongestEarthquake^.strength < tempEarthquake^.strength THEN strongestEarthquake^ := tempEarthquake^; END; tempEarthquake := tempEarthquake^.next; END; tempCity := tempCity^.next; END; {* Convert the found earthquake entry to primitive datatypes to return them *} latitudeOut := strongestEarthquake^.latitude; longitudeOut := strongestEarthquake^.longitude; strength := strongestEarthquake^.strength; city := strongestEarthquake^.city; day := strongestEarthquake^.date.day; month := strongestEarthquake^.date.month; year := strongestEarthquake^.date.year; {* dispose strongestEarthquake since it's not used anymore *} Dispose(strongestEarthquake); END; FUNCTION AverageEarthquakeStrengthInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2: REAL): REAL; VAR sum: REAL; count: INTEGER; tempEarthquake: Earthquake; tempCity: City; BEGIN sum := 0; count := 0; tempCity := list^.next; {* iterate all city entries *} WHILE tempCity <> list DO BEGIN tempEarthquake := tempCity^.earthquakes; {* iterate all earthquake entries of tempCity *} WHILE tempEarthquake <> NIL DO BEGIN IF GeopointInRegion(latitudeIn1, longitudeIn1, latitudeIn2, longitudeIn2, tempEarthquake^.latitude, tempEarthquake^.longitude) THEN BEGIN {* earthquake is in region, so add it's strength to sum * and increase the counter. *} sum := sum + tempEarthquake^.strength; Inc(count); END; tempEarthquake := tempEarthquake^.next; END; tempCity := tempCity^.next; END; IF count > 0 THEN AverageEarthquakeStrengthInRegion := sum / count ELSE AverageEarthquakeStrengthInRegion := 0; {* return 0 in case no earthquakes were found in region *} END; PROCEDURE DisplayEarthquake(earthquake: Earthquake); BEGIN WriteLn(); Write('DATE: '); DisplayDate(earthquake^.date); WriteLn(); WriteLn('STRENGTH: ', earthquake^.strength); WriteLn('LATITUDE: ', earthquake^.latitude); WriteLn('LONGITUDE: ', earthquake^.longitude); WriteLn('CITY: ', earthquake^.city); WriteLn(); END; PROCEDURE PrintEarthquakesCloseToCity(city: STRING); VAR tempEarthquake: Earthquake; tempCity: City; BEGIN WriteLn('-----------------------------------------------------'); WriteLn(); WriteLn('Earthquakes close to ' , city); WriteLn(); {* get the city with the name from the parameter *} tempCity := GetCityPtrOrAnchor(city); IF tempCity <> list THEN BEGIN tempEarthquake := tempCity^.earthquakes; {* print all earthquakes of tempCity *} WHILE tempEarthquake <> NIL DO BEGIN DisplayEarthquake(tempEarthquake); tempEarthquake := tempEarthquake^.next; END; END ELSE WriteLn('No entries found..'); WriteLn(); WriteLn('-----------------------------------------------------'); END; PROCEDURE PrintStrongCityEarthquakes(strength: REAL); VAR tempEarthquake: Earthquake; tempCity: City; BEGIN WriteLn('-----------------------------------------------------'); WriteLn(); WriteLn('Earthquakes with strength >= ' , strength); WriteLn(); {* copy list to tempEarthquake, so the list pointer won't be moved away from the first element *} tempCity := list^.next; WHILE tempCity <> list DO BEGIN tempEarthquake := tempCity^.earthquakes; WHILE tempEarthquake <> NIL DO BEGIN IF tempEarthquake^.strength >= strength THEN BEGIN {* print earthquake entry *} Write('Date: '); DisplayDate(tempEarthquake^.date); WriteLn(' | CITY: ', tempEarthquake^.city); END; tempEarthquake := tempEarthquake^.next; END; tempCity := tempCity^.next; END; WriteLn(); WriteLn('-----------------------------------------------------'); END; PROCEDURE DeleteAllEarthquakesBeforeDate(beforeDate: Date; VAR deletedElementCount: INTEGER); VAR tempCity: City; tempEarthquake, previousTemp: Earthquake; BEGIN tempCity := list^.next; deletedElementCount := 0; WHILE tempCity <> list DO BEGIN tempEarthquake := tempCity^.earthquakes; {* represents a "old" or previous copy of temp *} previousTemp := tempEarthquake; WHILE tempEarthquake <> NIL DO BEGIN {* check if temp is still beginning of list (= first element of list) => special case! *} IF LiesBefore(tempEarthquake^.date, beforeDate) and (tempEarthquake = tempCity^.earthquakes) THEN BEGIN {* Dispose tempEarthquake and make the second element the new first element of the list *} tempCity^.earthquakes := tempEarthquake^.next; Dispose(tempEarthquake); tempEarthquake := tempCity^.earthquakes; Inc(deletedElementCount); END ELSE BEGIN IF LiesBefore(tempEarthquake^.date, beforeDate) THEN BEGIN Inc(deletedElementCount); IF tempEarthquake^.next <> NIL THEN BEGIN {* Dispose tempEarthquake and replace it's position in the list with tempEarthquake^.next *} {* wire tempEarthquake's left neighbor to it's right neighbor *} previousTemp^.next := tempEarthquake^.next; Dispose(tempEarthquake); tempEarthquake := previousTemp; END ELSE BEGIN {* tempEarthquake has no next element so just dispose it *} {* also remove it's connection to the list *} previousTemp^.next := NIL; Dispose(tempEarthquake); END; END; previousTemp := tempEarthquake; {* keep reference of tempEarthquake in previosTemp *} tempEarthquake := tempEarthquake^.next; {* go to next element in list *} END; END; tempCity := tempCity^.next; END; END; PROCEDURE DeleteAllEarthquakesCloseToCity(city: STRING; VAR deletedElementCount: INTEGER); VAR tempEarthquake, previousTemp: Earthquake; tempCity, nextCity, prevCity: City; BEGIN deletedElementCount := 0; tempCity := GetCityPtrOrAnchor(city); IF tempCity <> list THEN BEGIN {* delete City with all earthquakes *} WHILE tempCity^.earthquakes <> NIL DO BEGIN tempEarthquake := tempCity^.earthquakes^.next; Dispose(tempCity^.earthquakes); tempCity^.earthquakes := tempEarthquake; Inc(deletedElementCount); END; nextCity := tempCity^.next; prevCity := tempCity^.prev; prevCity^.next := nextCity; nextCity^.prev := prevCity; Dispose(tempCity); END; END; PROCEDURE PrintEarthquakesGroupedByCity; VAR tempCity: City; BEGIN {* Check if list is empty *} IF list^.next <> list THEN BEGIN tempCity := list^.next; {* iterate all list entries and print it's earthquakes *} WriteLn; WriteLn('----------------------------------'); WHILE tempCity <> list DO BEGIN WriteLn; WriteLn('-- ', tempCity^.name, ' --'); IF tempCity^.earthquakes = NIL THEN WriteLn('No entries found..') ELSE DisplayList(tempCity^.earthquakes); tempCity := tempCity^.next; END; END ELSE WriteLn('No entries found..'); WriteLn('----------------------------------'); WriteLn; END; PROCEDURE Reset; VAR tempCity, nextCity: City; tempEarthquake: Earthquake; BEGIN tempCity := list^.next; WHILE tempCity <> list DO BEGIN WHILE tempCity^.earthquakes <> NIL DO BEGIN {* Dispose all pointers to earthquake entries *} tempEarthquake := tempCity^.earthquakes^.next; Dispose(tempCity^.earthquakes); tempCity^.earthquakes := tempEarthquake; END; {* Dispose all pointers to city entries *} nextCity := tempCity^.next; Dispose(tempCity); tempCity := nextCity; END; Dispose(list); {* Dispose anchor *} InitCityList; {* Re-initialize list anchor for upcoming operations *} END; BEGIN {* Init on first run of Unit *} InitCityList; END.
{================================================================================ Copyright (C) 1997-2002 Mills Enterprise Unit : rmClock Purpose : Visual UI eye-candy type component. Date : 11-21-2002 Author : Ryan J. Mills Version : 1.92 ================================================================================} unit rmClock; interface {$I CompilerDefines.INC} {$ifdef D6_or_higher} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, math, rmlibrary, types; {$else} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, math, rmlibrary; {$endif} type TClockBorder = (cbNone, cbSingle, cbRaised, cbLowered); TrmCustomClock = class(TGraphicControl) private { Private declarations } fBorder : TClockBorder; fFaceColor: TColor; fTime: TTime; fFaceDiameter : integer; fHandColor: TColor; procedure SetBorder(Value : TClockBorder); procedure SetFaceColor(const Value: TColor); procedure SetTime(const Value: TTime); procedure SetFaceSize(const Value: integer); procedure SetHandColor(const Value: TColor); procedure wmEraseBkgnd(var MSG : TMessage); message wm_EraseBkgnd; protected { Protected declarations } procedure paint; override; procedure GetBorderColors(var TopColor, BottomColor:TColor); property Border : TClockBorder read fborder write SetBorder default cbsingle; property FaceColor : TColor read fFaceColor write SetFaceColor default clSilver; property FaceSize : integer read fFaceDiameter write SetFaceSize default 100; property HandsColor : TColor read fHandColor write SetHandColor default clNavy; property Time : TTime read fTime write SetTime; public { Public declarations } constructor Create(AOwner:TComponent); override; published { Published declarations } end; TrmClock = class(TrmCustomClock) published property Border; property FaceColor; property FaceSize; property Time; end; implementation { TrmCustomClock } constructor TrmCustomClock.Create(AOwner:TComponent); begin inherited create(AOwner); ControlStyle := ControlStyle + [csopaque]; width := 100; height := 100; fborder := cbSingle; fFaceColor := clSilver; fFaceDiameter := 100; fHandColor := clNavy; fTime := now; end; procedure TrmCustomClock.paint; var bmp : TBitMap; topColor, bottomcolor : TColor; angle : double; h, m, s, ms : word; wLineSize : extended; loop : integer; CurPt : TPoint; TmpRect : TRect; begin bmp := tbitmap.create; bmp.width := width; bmp.height := height; bmp.canvas.brush.color := clBtnFace; bmp.canvas.fillrect(rect(0,0,width-1,height-1)); DecodeTime(fTime, h, m, s, ms); GetBorderColors(TopColor,BottomColor); with bmp.canvas do begin Brush.Color := fFaceColor; pen.color := fFaceColor; Ellipse(0, 0, fFaceDiameter-1, fFaceDiameter - 1); loop := 0; brush.color := clWindowFrame; while loop < 60 do begin Angle := (2 * Pi * loop / 60); CurPt := Point( trunc( ((fFaceDiameter DIV 2)-((fFaceDiameter div 2) div 10)) * sin( Angle)) + (fFacediameter div 2), trunc( -((fFaceDiameter DIV 2)-((fFaceDiameter div 2) div 10)) * cos( Angle)) + (fFacediameter div 2)); TmpRect := Rect( CurPt.X-1, CurPt.Y-1, CurPt.X+1, CurPt.Y+1); framerect(tmprect); inc(loop, 5); end; //Minute hand Pen.Width := 3; Pen.Color := fHandColor; Angle := (2 * Pi * m / 60); MoveTo( (fFaceDiameter div 2), (fFaceDiameter div 2)); wLineSize := 0.90 * (fFaceDiameter div 2); LineTo( trunc( wLineSize * sin( Angle)) + (fFaceDiameter div 2), trunc( -wLineSize * cos( Angle)) + (fFaceDiameter div 2)); //Hour hand Angle := (H MOD 12) * 2 * Pi / 12 + Angle / 12; MoveTo( (fFaceDiameter div 2), (fFaceDiameter div 2)); wLineSize := 0.65 * (fFaceDiameter div 2); LineTo( trunc( wLineSize * sin( Angle)) + (fFaceDiameter div 2), trunc( -wLineSize * cos( Angle)) + (fFaceDiameter div 2)); if border <> cbNone then begin Pen.Width := 1; Pen.Color := TopColor; Arc (0, 0, fFaceDiameter-1, fFaceDiameter-1, // ellipse fFaceDiameter-1, 0, // start 0, fFaceDiameter-1); // end Pen.Color := BottomColor; Arc (0, 0, fFaceDiameter-1, fFaceDiameter-1, // ellipse 0, fFaceDiameter-1, // start fFaceDiameter, 0); // end end; end; bitblt(canvas.handle,0,0,width-1,height-1,bmp.canvas.handle,0,0,srccopy); bmp.free; end; procedure TrmCustomClock.GetBorderColors(var TopColor, BottomColor:TColor); begin case border of cbSingle:begin topColor := clWindowFrame; bottomcolor := topcolor; end; cbRaised:begin topcolor := clbtnhighlight; bottomcolor := clbtnshadow; end; cbLowered:begin topcolor := clbtnshadow; bottomcolor := clbtnhighlight; end; else begin topcolor := clbtnface; bottomcolor := topcolor; end; end; end; procedure TrmCustomClock.SetBorder(Value : TClockBorder); begin if fborder <> value then begin fborder := value; invalidate; end; end; procedure TrmCustomClock.SetFaceColor(Const Value : TColor); begin if fFaceColor <> value then begin fFaceColor := Value; invalidate; end; end; procedure TrmCustomClock.SetTime(const Value: TTime); begin if ftime <> value then begin fTime := Value; Invalidate; end; end; procedure TrmCustomClock.SetFaceSize(const Value: integer); begin if facesize <> value then begin fFaceDiameter := Value; invalidate; end; end; procedure TrmCustomClock.SetHandColor(const Value: TColor); begin if fHandColor <> Value then begin fHandColor := Value; invalidate; end; end; procedure TrmCustomClock.wmEraseBkgnd(var MSG: TMessage); begin msg.Result := 1; end; end.
unit uTDeleteDownload; interface uses Windows, shellapi, shlobj, forms, sysUtils, Messages, Dialogs, Classes, uFrmNewLoader; type TFiles = record ZipFile : String; Description : String; end; type TDeleteDownload = class(TThread) private { Private declarations } aFile : array[0..10] of TFiles; Counted : integer; MyDescription : String; procedure UpdateMainThread; procedure Deletefile(_from: String); public procedure SetCount; procedure SetDeleteFiles(sFile, sDescription : String); function DeleteFiles:Boolean; protected procedure Execute; override; end; implementation { Important: Methods and properties of objects in VCL can only be used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure TDeleteDownload.UpdateCaption; begin Form1.Caption := 'Updated in a thread'; end; } { TDeleteDownload } procedure TDeleteDownload.Deletefile(_from: String); var f: TSHFileOPStruct; f_from, f_to: array[0..255] of char; k:integer; begin for k:=0 to 255 do begin f_from[k]:=#0; f_to[k]:=#0; end; F.Wnd := application.handle; F.wFunc := FO_DELETE; strpcopy(f_from,_from); F.pFrom := f_from; F.pTo := f_from; F.fFlags := FOF_NOCONFIRMATION; if ShFileOperation(F) <> 0 then ShowMessage('Error deleting file '+MyDescription+'.'); end; procedure TDeleteDownload.SetCount; begin Counted := 0; end; procedure TDeleteDownload.SetDeleteFiles(sFile, sDescription : String); begin aFile[Counted].ZipFile := sFile; aFile[Counted].Description := sDescription; inc(Counted); end; function TDeleteDownload.DeleteFiles:Boolean; var i : integer; begin { Place thread code here } try for i:=0 to Counted-1 do begin MyDescription := aFile[i].Description; Synchronize(UpdateMainThread); Deletefile(aFile[i].ZipFile); end; Result := true; except Result := false; end; end; procedure TDeleteDownload.UpdateMainThread; begin with FrmNewLoader do UpdateDeleteInfo(MyDescription); end; procedure TDeleteDownload.Execute; begin { Place thread code here } end; end.
unit PmAppPacket; //链路用户数据层包装 //为了避免歧义,应该每次都仅仅包含一个数据标识 //注意!!!!: 假设哪些afn需要消息认证是明确的 interface uses SysUtils, Classes, StrUtils, PmHelper, PmPacket; type TPmAppAFN = (afnQuerenOrFouren=0,afnFuwei=1,afnLianluJiance=2, afnZhongjiMingling=3,afnShezhiCanshu=4,afnKongzhiMingling=5, afnRenzheng=6,afnChaxunCanshu=$0A, afnYileishuju=$0C,afnErleiShuju=$0D,afnSanleiShuju=$0E, afnWenjianChuanshu=$0F,afnShujuZhuanfa=$10); TPmAppSeq = class private FValue: Byte; procedure SetValue(const Value: Byte); function GetJieshuZheng: Boolean; function GetKaishizheng: Boolean; function GetSeq: Byte; function GetShijianYouxiao: Boolean; function GetXuyaoQueren: Boolean; procedure SetJieshuZheng(const Value: Boolean); procedure SetKaishizheng(const Value: Boolean); procedure SetSeq(const Value: Byte); procedure SetShijianYouxiao(const Value: Boolean); procedure SetXuyaoQueren(const Value: Boolean); public property Value: Byte read FValue write SetValue; property ShijianYouxiao: Boolean read GetShijianYouxiao write SetShijianYouxiao; property IsKaishizheng: Boolean read GetKaishizheng write SetKaishizheng; property IsJieshuZheng: Boolean read GetJieshuZheng write SetJieshuZheng; property XuyaoQueren: Boolean read GetXuyaoQueren write SetXuyaoQueren; property Seq: Byte read GetSeq write SetSeq; function CStr: AnsiString; end; //DA由信息元组别(DA2)(1-255)和组内编码(DA1)(8位)表示1-8个信息元, //DA1是以位为编码的,DA2以值编码的 //最多表示8个信息元 //特别的:DA2=DA1=0 时表示p0 TPmAppDA = class private FDA2: Byte; FDA1: Byte; function GetValue: AnsiString; procedure SetValue(const Value: AnsiString); function GetIsP0: Boolean; public property Value: AnsiString read GetValue write SetValue; function GetPsList: TList; property IsP0: Boolean read GetIsP0; procedure SetP0; procedure AddPx(const Px: Word); end; //DT:信息类 //信息类和信息元的编码方法类似,区别在于DA2从1开始编码,DT1从0开始编码 TPmAppDT = class private FDT1: Byte; FDT2: Byte; function GetValue: AnsiString; procedure SetValue(const Value: AnsiString); public property Value: AnsiString read GetValue write SetValue; function GetFsList: TList; procedure AddFx(const Fx: Word); end; //TPmAppPW类用于封装认证码算法,因为目前算法未知,所以需要在未来扩展 TPmAppPW = class private FValue: AnsiString; procedure SetValue(const Value: AnsiString); function GetValue: AnsiString; public property Value: AnsiString read GetValue write SetValue; end; TPmAppEC = class private FEC1: Byte; FEC2: Byte; procedure SetZhongyanShijianJishuqi(const Value: Byte); procedure SetYibanShijianJishuqi(const Value: Byte); function GetValue: AnsiString; procedure SetValue(const Value: AnsiString); public property ZhongyanShijianJishuqi: Byte read FEC1 write SetZhongyanShijianJishuqi; property YibanShijianJishuqi: Byte read FEC2 write SetYibanShijianJishuqi; property Value: AnsiString read GetValue write SetValue; function CStr: AnsiString; end; //时间标签 TPmAppTp = class private FPFC: Byte; FFasongShibiao: TPmData16; FYunxuShiyian: Byte; procedure SetQidongzhengxuhaoJishuqi(const Value: Byte); procedure SetYunxuShiyian(const Value: Byte); function GetValue: AnsiString; procedure SetValue(const Value: AnsiString); public procedure AfterConstruction; override; destructor Destroy; override; property QidongzhengxuhaoJishuqi: Byte read FPFC write SetQidongzhengxuhaoJishuqi; property FasongShibiao: TPmData16 read FFasongShibiao; property YunxuShiyian: Byte read FYunxuShiyian write SetYunxuShiyian; property Value: AnsiString read GetValue write SetValue; function CStr: AnsiString; end; TPmAppDataUnit = class private FValue: AnsiString; function GetAsValue: AnsiString; procedure SetAsValue(const Value: AnsiString); public property Value: AnsiString read GetAsValue write SetAsValue; class function MakeDADT(Pn,Fn: Word): AnsiString; end; TPmAppPacket = class private FLinkLayerPacket: TPmLinkLayerPacket; FData: AnsiString; FSeq: TPmAppSeq; FAFN: Byte; FEC: TPmAppEC; FPW: TPmAppPW; FTp: TPmAppTp; procedure SetAFN(const Value: Byte); function GetAddress: TPmAddress; function GetControlcode: TPmControlCode; function GetAsBinStr: AnsiString; procedure SetAsBinStr(const Value: AnsiString); function HavePW(const afn: Byte): boolean; procedure SetData(const Value: AnsiString); function AFNName(afn: Byte): AnsiString; protected procedure FillLinklayerData; //应用层需要将appdata部分填到data中 procedure ParseLinklayerData(const Data: AnsiString); //应用层将data解析到自己的域里 public procedure AfterConstruction; override; destructor Destroy; override; property AFN: Byte read FAFN write SetAFN; property SEQ: TPmAppSeq read FSeq; property EC: TPmAppEC read FEC; property PW: TPmAppPW read FPW; property Tp: TPmAppTp read FTp; property Data: AnsiString read FData write SetData; class function GetAppPacket(var DataStr: AnsiString): TPmAppPacket; property ControlCode: TPmControlCode read GetControlcode; //链路控制字 property Address: TPmAddress read GetAddress; //链路地址域 property AsBinStr: AnsiString read GetAsBinStr write SetAsBinStr; function CStr: AnsiString; end; InvalidDataUnitIDException = class (Exception) end; InvalidAppPackDataLengthException = class(Exception) end; TRecvPmAppPacketEvent = procedure (Sender: TObject; const pack: TPmAppPacket; hasHouxuzhen: Boolean) of Object; implementation uses uBCDHelper; { TPmAppSeq } function TPmAppSeq.CStr: AnsiString; function BooleanToStr(b: Boolean): AnsiString; begin if b then Result := '1' else Result := '0'; end; begin Result := 'TpV='+BooleanToStr(ShijianYouxiao)+ '; FIR='+BooleanToStr(IsKaishizheng)+ '; FIN='+BooleanToStr(IsJieshuzheng)+ '; CON='+BooleanToStr(XuyaoQueren)+ '; Seq='+IntToStr(seq); end; function TPmAppSeq.GetJieshuZheng: Boolean; begin Result := (Fvalue and $20)=$20; end; function TPmAppSeq.GetKaishizheng: Boolean; begin Result := (FValue and $40)=$40; end; function TPmAppSeq.GetSeq: Byte; begin Result := FValue and $0F; end; function TPmAppSeq.GetShijianYouxiao: Boolean; begin Result := (FValue and $80)=$80; end; function TPmAppSeq.GetXuyaoQueren: Boolean; begin Result := (FValue and $10)=$10; end; procedure TPmAppSeq.SetJieshuZheng(const Value: Boolean); begin if Value then FValue := FValue or $20 else FValue := FValue and $DF; end; procedure TPmAppSeq.SetKaishizheng(const Value: Boolean); begin if Value then FValue := FValue or $40 else FValue := FValue and $BF; end; procedure TPmAppSeq.SetSeq(const Value: Byte); begin FValue := (FValue and $F0)+(Value and $0F); end; procedure TPmAppSeq.SetShijianYouxiao(const Value: Boolean); begin if Value then FValue := FValue or $80 else FValue := FValue and $7F; end; procedure TPmAppSeq.SetValue(const Value: Byte); begin FValue := Value; end; procedure TPmAppSeq.SetXuyaoQueren(const Value: Boolean); begin if Value then FValue := FValue or $10 else FValue := FValue and $EF; end; { TPmAppDA } function TPmAppDA.GetIsP0: Boolean; begin Result := (FDA1=0) and (FDA2=0); end; function TPmAppDA.GetValue: AnsiString; begin Result := Chr(FDA1)+Chr(FDA2); end; function TPmAppDA.GetPsList: TList; var lst: TList; i: Byte; b: Byte; begin lst := TList.Create; for i := 0 to 7 do begin b := 1 shl i; if ((FDA1 and b)=b) then lst.Add(Pointer((FDA2-1)*8+i+1)); end; if lst.Count=0 then lst.Add(Pointer(0)); Result := lst; end; procedure TPmAppDA.SetP0; begin FDA1 := 0; FDA2 := 0; end; procedure TPmAppDA.SetValue(const Value: AnsiString); begin if Length(Value)=2 then begin FDA1 := Ord(Value[1]); FDA2 := Ord(Value[2]); end else raise Exception.Create('信息点标识符必须是2字节'); end; procedure TPmAppDA.AddPx(const Px: Word); var da1,da2: Byte; begin if Px=0 then self.SetP0 else begin da1 := 1 shl ((Px-1) mod 8); da2 := ((Px-1) div 8)+1; if FDA2=0 then FDA2 := da2; if FDA2=da2 then FDA1 := FDA1 or da1; end; end; { TPmAppDT } procedure TPmAppDT.AddFx(const Fx: Word); var dt1,dt2: Byte; begin dt1 := 1 shl ((Fx-1) mod 8); dt2 := (Fx-1) div 8; if FDT1=0 then //FDT1只有初始时是0,只要增加过Fx,就变成非0 FDT2 := dt2; if FDT2=dt2 then FDT1 := FDT1 or dt1; end; function TPmAppDT.GetFsList: TList; var lst: TList; i: Byte; d1: Byte; begin lst := TList.Create; for i := 0 to 7 do begin d1 := 1 shl i; if ((FDT1 and d1)=d1) then lst.Add(Pointer(FDT2*8+i+1)); end; Result := lst; end; function TPmAppDT.GetValue: AnsiString; begin Result := Chr(FDT1)+Chr(FDT2); end; procedure TPmAppDT.SetValue(const Value: AnsiString); begin if Length(Value)=2 then begin FDT1 := Ord(Value[1]); FDT2 := Ord(Value[2]); end else raise Exception.Create('信息类标识符必须是2字节'); end; { TPmAppPW } function TPmAppPW.GetValue: AnsiString; begin if Length(FValue)>16 then Result := Copy(FValue,1,16) else if Length(FValue)=16 then Result := FValue else Result := FValue+DupeString(#0,16-Length(FValue)); Result := #1#2#3#4#5#6#7#8#9#0#$A#$B#$C#$D#$E#$F; end; procedure TPmAppPW.SetValue(const Value: AnsiString); begin FValue := Value; end; { TPmAppEC } function TPmAppEC.CStr: AnsiString; begin Result := '重要事件计数器='+IntToStr(ZhongyanShijianJishuqi)+ '; 一般事件计数器='+IntToStr(YibanShijianJishuqi); end; function TPmAppEC.GetValue: AnsiString; begin Result := Chr(FEC1)+Chr(FEC2); end; procedure TPmAppEC.SetValue(const Value: AnsiString); begin if Length(Value)=2 then begin FEC1 := Ord(Value[1]); FEC2 := Ord(Value[2]); end else raise Exception.Create('事件计数器必须为2字节'); end; procedure TPmAppEC.SetYibanShijianJishuqi(const Value: Byte); begin FEC2 := Value; end; procedure TPmAppEC.SetZhongyanShijianJishuqi(const Value: Byte); begin FEC1 := Value; end; { TPmAppTp } procedure TPmAppTp.AfterConstruction; begin inherited; FFasongShibiao := TPmData16.Create; end; function TPmAppTp.CStr: AnsiString; begin Result := '启动帧帧序号计数器='+IntToStr(self.FPFC)+ '; 启动帧发送时标='+self.FFasongShibiao.CStr+ '; 允许发送传输延时时间='+IntToStr(self.YunxuShiyian); end; destructor TPmAppTp.Destroy; begin FFasongShibiao.Free; inherited; end; function TPmAppTp.GetValue: AnsiString; begin Result := chr(FPFC)+FFasongShibiao.Value+chr(FYunxuShiyian); end; procedure TPmAppTp.SetQidongzhengxuhaoJishuqi(const Value: Byte); begin FPFC := Value; end; procedure TPmAppTp.SetValue(const Value: AnsiString); begin if length(Value)=6 then begin FPFC := Ord(Value[1]); FFasongShibiao.Value := Copy(Value,2,4); FYunxuShiyian := Ord(Value[6]); end else raise Exception.Create('Tp标签的长度必须是6字节'); end; procedure TPmAppTp.SetYunxuShiyian(const Value: Byte); begin FYunxuShiyian := Value; end; { TPmAppPacket } procedure TPmAppPacket.AfterConstruction; begin inherited; FSeq := TPmAppSeq.Create; FEC := TPmAppEC.Create; FPW := TPmAppPW.Create; FTp := TPmAppTp.Create; FLinkLayerPacket := TPmLinkLayerPacket.Create; end; destructor TPmAppPacket.Destroy; begin FSeq.Free; FEC.Free; FPW.Free; FTp.Free; FLinkLayerPacket.Free; inherited; end; class function TPmAppPacket.GetAppPacket( var DataStr: AnsiString): TPmAppPacket; var pack: TPmLinkLayerPacket; begin pack := TPmLinkLayerPacket.GetPacket(DataStr); if pack<>nil then begin Result := TPmAppPacket.Create; Result.FLinkLayerPacket.Free; Result.FLinkLayerPacket := pack; Result.ParseLinklayerData(pack.Data); end else Result := nil; end; procedure TPmAppPacket.SetAFN(const Value: Byte); begin FAFN := Value; end; function TPmAppPacket.GetAddress: TPmAddress; begin Result := FLinkLayerPacket.Address; end; function TPmAppPacket.GetControlcode: TPmControlCode; begin Result := FLinkLayerPacket.ControlCode; end; function TPmAppPacket.GetAsBinStr: AnsiString; begin FillLinklayerData; Result := FLinkLayerPacket.AsBinStr; end; procedure TPmAppPacket.SetAsBinStr(const Value: AnsiString); begin FLinkLayerPacket.AsBinStr := Value; ParseLinklayerData(self.FLinkLayerPacket.Data); end; procedure TPmAppPacket.FillLinklayerData; var temp: AnsiString; begin SEQ.XuyaoQueren := ((self.AFN=$1) or (self.afn=$4) or (self.afn=$5) or (self.AFN=$10)); temp := Chr(FAFN)+Chr(FSeq.Value); temp := temp+self.FData; if self.ControlCode.IsShangxingzhen then begin if self.ControlCode.IsShangxingYaoqiufangwen then temp := temp+FEC.Value; end else begin if HavePW(FAFN) then temp := temp+FPW.Value; end; if FSeq.ShijianYouxiao then temp := temp+FTP.Value; self.FLinkLayerPacket.Data := temp; end; procedure TPmAppPacket.ParseLinklayerData(const Data: AnsiString); var p,q: integer; len: integer; begin len := Length(Data); p := 1; if p>len then raise InvalidAppPackDataLengthException.Create('长度异常'); AFN := Ord(Data[p]); p := p+1; if p>len then raise InvalidAppPackDataLengthException.Create('长度异常'); SEQ.Value := Ord(Data[p]); p := p+1; q := Length(Data); if Seq.ShijianYouxiao then begin q := q-5; if p>q then raise InvalidAppPackDataLengthException.Create('长度异常'); self.FTp.Value := Copy(Data,q,6); q := q-1; end; if self.ControlCode.IsShangxingzhen then begin if ControlCode.XiaxingZhenjishuYouxiao then begin q := q-1; if p>q then raise InvalidAppPackDataLengthException.Create('长度异常'); FEC.Value := Copy(Data,q,2); q := q-1; end; end else begin if HavePW(FAFN) then begin q := q-15; if p>q then raise InvalidAppPackDataLengthException.Create('长度异常'); FPW.Value := Copy(Data,q,16); q := q-1; end; end; FData := Copy(Data,p,q-p+1); end; function TPmAppPacket.HavePW(const afn: Byte): boolean; begin case afn of 1,4,5,6,$0F,$10: Result := true; else Result := false; end; end; procedure TPmAppPacket.SetData(const Value: AnsiString); begin FData := Value; end; function TPmAppPacket.CStr: AnsiString; var Temp: AnsiString; begin Temp := ''; Temp := Temp+'控制域: '+self.ControlCode.CStr+#$0D#$0A; Temp := Temp+'地址域: '+self.Address.CStr+#$0D#$0A; Temp := Temp+'AFN='+format('%2.2x',[self.AFN])+' -'+AFNName(self.AFN)+#$0D#$0A; Temp := Temp+'帧序列域: '+self.SEQ.CStr+#$0D#$0A; Temp := Temp+'数据域:'+#$0D#$0A; Temp := Temp+TBcdHelper.BinStr2CStr(self.Data)+#$0D#$0A; Temp := Temp+'附加信息域:'+#$0D#$0A; if self.ControlCode.IsShangxingzhen then begin if self.ControlCode.IsShangxingYaoqiufangwen then temp := temp+'事件计数器: '+FEC.CStr+#$0D#$0A; end else begin if HavePW(FAFN) then temp := temp+'消息认证码字段: '+TBcdHelper.BinStr2CStr(FPW.Value,'')+#$0D#$0A; end; if FSeq.ShijianYouxiao then temp := temp+'时间标签: '+TBcdHelper.BinStr2CStr(FTP.Value,'')+'-'+FTP.CStr; Result := Temp+#$0D#$0A; end; function TPmAppPacket.AFNName(afn: Byte): AnsiString; begin case afn of $0: Result := '确认/否认'; $1: Result := '复位'; $2: Result := '链路接口检测'; $3: Result := '中继站命令'; $4: Result := '设置参数'; $5: Result := '控制命令'; $6: Result := '身份认证及密钥协商'; $7: Result := '备用'; $8: Result := '请求被级联终端主动上送'; $9: Result := '请求终端配置'; $A: Result := '查询参数'; $B: Result := '请求任务数据'; $C: Result := '请求一类数据(实时数据)'; $D: Result := '请求二类数据(历史数据)'; $E: Result := '请求三类数据(事件数据)'; $F: Result := '文件传输'; $10: Result := '数据转发'; else Result := '备用'; end; end; { TPmAppDataUnit } function TPmAppDataUnit.GetAsValue: AnsiString; begin Result := FValue; end; class function TPmAppDataUnit.MakeDADT(Pn, Fn: Word): AnsiString; var da: TPmAppDA; dt: TPmAppDT; begin da := TPmAppDA.Create; dt := TPmAppDT.Create; da.AddPx(Pn); dt.AddFx(Fn); Result := da.Value+dt.Value; da.Free; dt.Free; end; procedure TPmAppDataUnit.SetAsValue(const Value: AnsiString); begin FValue := Value; end; end.
unit TaskNodeInfo; interface Uses Classes,ComCtrls, CurrUnit , SysUtils; /////////////////////////////////////////////// // 用户信息 Useinfo //---------------------------- // [角色(工号)] // 姓名 = (姓名) // 部门 = (部门) // 职称 = (职称) // 密码 = (密码) //加密 // 权限 = (权限) type TUserInfo = ^TOperator; TOperator = record JobID:String; Name:String; Department:String; Title :String; Password:String; Permission:String; end; type TPartInfo = class(TPersistent) private FTitle: String; FDescribe: String; FUserList: TList; function GetUserInfo(index: Integer): TUserInfo; procedure SetUserInfo(index: Integer; const Value: TUserInfo); function GetUserCount: Integer; public constructor Create; destructor Destroy; override; Property Title:String Read FTitle Write FTitle; Property Describe:String Read FDescribe Write FDescribe; Procedure AssignUser(AListItems:TListItems); Procedure AssignUsersTo(AListItems:TListItems); Procedure DeleteUser(Index:Integer); overload; Procedure DeleteUser(AListItem:TListItem); overload; Procedure DeleteUser(AUserInfo:TUserInfo); overload; Procedure AddUser(AListItem:TListItem); property UserItems[index:Integer]:TUserInfo read GetUserInfo write SetUserInfo; Property UserCount:Integer read GetUserCount; procedure Assign(Source: TPersistent); Override; end; ////////////////////////////////////////////////////////////////// // [(任务名称)] // 考核时间 = (考核时间) // 任务主题 = (任务主题) // 工作角色 = (工作角色名称) // 位图信息 = (left,top,width,height) //用","分割 // 子任务(流水号) = (子任务名称) // ... TTaskNodeInfo = class(TPersistent) private FSetDate: Integer; FTitle: String; FChildTask: TList; FDescribe: String; FPartInfo: TPartInfo; procedure SetPartInfo(const Value: TPartInfo); function GetChildTask(Index: Integer): TStrings; procedure SetChildTask(Index: Integer; const Value: TStrings); procedure SetTitle(const Value: String); public constructor Create; destructor Destroy; override; Property Title:String read FTitle write SetTitle; Property SetDate:Integer read FSetDate write FSetDate; Property Describe:String Read FDescribe Write FDescribe; Property Part:TPartInfo Read FPartInfo Write SetPartInfo; Procedure AddChildTask(AChildTask:TStrings); Procedure DeleteChildTask(AChildTask:TStrings); Property ChildTaskItem[Index:Integer]:TStrings Read GetChildTask Write SetChildTask; Procedure Assign(Source: TPersistent); override; Function ChildTaskCount:Integer; end; Function UserInfoToListItem(AStrings:TUserInfo;AListItem:TListItem):Boolean; Function ListItemToUserInfo(AListItem:TListItem;AUserInfo:TUserInfo):Boolean; implementation Function UserInfoToListItem(AStrings:TUserInfo;AListItem:TListItem):Boolean; Begin try AListItem.Caption := AStrings.Name; AListItem.SubItems.Clear; AListItem.SubItems.Add(AStrings.JobID); AListItem.SubItems.Add(AStrings.Department); AListItem.SubItems.Add(AStrings.Title); AListItem.SubItems.Add(AStrings.Permission); AListItem.SubItems.Add(AStrings.Password); Result := True; except Result := False; end; end; Function ListItemToUserInfo(AListItem:TListItem;AUserInfo:TUserInfo):Boolean; Begin try AUserInfo.Name := Trim(AListItem.Caption); AUserInfo.JobID := Trim(AListItem.SubItems.Strings[0]); AUserInfo.Department := Trim(AListItem.SubItems.Strings[1]); AUserInfo.Title := Trim(AListItem.SubItems.Strings[2]); AUserInfo.Permission := Trim(AListItem.SubItems.Strings[3]); AUserInfo.Password := Trim(AListItem.SubItems.Strings[4]); Result := True; except Result := False; end; end; { TTaskNodeInfo } procedure TTaskNodeInfo.AddChildTask(AChildTask: TStrings); Var CTask:TStrings; begin CTask := TStringList.Create; try CTask.Assign(AChildTask); FChildTask.Add(CTask); except CTask.Free; end; end; procedure TTaskNodeInfo.Assign(Source: TPersistent); Var I:Integer; CTask:TStrings; ATaskNode:TTaskNodeInfo; begin //inherited Assign(Source); //if Not (Source is TTaskNodeInfo) then Exit; ATaskNode := TTaskNodeInfo(Source); SetDate := ATaskNode.SetDate; Title := ATaskNode.Title; Describe := ATaskNode.Describe; Part.Assign(ATaskNode.Part); for I := 1 to ATaskNode.ChildTaskCount -1 do begin CTask := TStringList.Create; try CTask.Assign(ATaskNode.ChildTaskItem[I]); AddChildTask(CTask); Except CTask.Free; end; end; end; function TTaskNodeInfo.ChildTaskCount: Integer; begin Result := FChildTask.Count; end; constructor TTaskNodeInfo.Create; begin inherited Create; FSetDate := 0; FTitle := ''; FPartInfo := TPartInfo.Create; FChildTask := TList.Create; end; procedure TTaskNodeInfo.DeleteChildTask(AChildTask: TStrings); Var Index:Integer; begin Index := FChildTask.IndexOf(AChildTask); if Index <> -1 then Begin FChildTask.Delete(Index); FChildTask.Pack; end; end; destructor TTaskNodeInfo.Destroy; begin FChildTask.Free; FPartInfo.Free; inherited Destroy; end; function TTaskNodeInfo.GetChildTask(Index: Integer): TStrings; begin Result := FChildTask.Items[Index]; end; procedure TTaskNodeInfo.SetChildTask(Index: Integer; const Value: TStrings); begin FChildTask.Items[Index] := Value; end; procedure TTaskNodeInfo.SetPartInfo(const Value: TPartInfo); begin FPartInfo.Assign(Value); end; procedure TTaskNodeInfo.SetTitle(const Value: String); begin FTitle := Value; end; { TPartInfo } procedure TPartInfo.AddUser(AListItem: TListItem); Var Employ:TUserInfo; begin New(Employ); try ListItemToUserInfo(AListItem,Employ); FUserList.Add(Employ); finally Dispose(Employ); end; end; procedure TPartInfo.Assign(Source: TPersistent); Var I:Integer; PartInfo:TPartInfo; Employ:TUserInfo; begin //inherited assign(Source); PartInfo := TPartInfo(Source); FTitle := PartInfo.Title; Describe:= PartInfo.Describe; FUserList.Clear; FUserList.Pack; for I := 0 to PartInfo.UserCount -1 do begin New(Employ); try Employ.JobID := PartInfo.UserItems[I].JobID; Employ.Name := PartInfo.UserItems[I].Name; Employ.Department := PartInfo.UserItems[I].Department; Employ.Title := PartInfo.UserItems[I].Title; Employ.Password := PartInfo.UserItems[I].Password; Employ.Permission := PartInfo.UserItems[I].Permission; FUserList.Add(Employ); except Dispose(Employ); end; end; end; procedure TPartInfo.AssignUser(AListItems: TListItems); Var I:Integer; begin FUserList.Clear; for I := 0 to AListItems.Count -1 do AddUser(AListItems.Item[I]); end; procedure TPartInfo.AssignUsersTo(AListItems: TListItems); Var I:Integer; Employ:TListItem; begin AListItems.Clear; for I := 0 to self.UserCount -1 do begin Employ := AListItems.Add; UserInfoToListItem(UserItems[I],Employ); end; end; constructor TPartInfo.Create; begin FUserList := TList.Create; end; procedure TPartInfo.DeleteUser(Index: Integer); begin if Index<>-1 then begin FUserList.Delete(Index); FUserList.Pack; end; end; procedure TPartInfo.DeleteUser(AListItem: TListItem); Var AUserInfo:TUserInfo; I:integer; begin New(AUserInfo); try I:=FUserList.IndexOf(AUserInfo); if I<>-1 then begin FUserList.Delete(I); FUserList.Pack; end; finally Dispose(AUserInfo); end; end; procedure TPartInfo.DeleteUser(AUserInfo: TUserInfo); Var I:Integer; begin I:=FUserList.IndexOf(AUserInfo); if I<>-1 then begin FUserList.Delete(I); FUserList.Pack; end; end; destructor TPartInfo.Destroy; begin FUserList.Free; inherited Destroy; end; function TPartInfo.GetUserCount: Integer; begin Result := FUserList.Count; end; function TPartInfo.GetUserInfo(index: Integer): TUserInfo; begin Result:= FUserList[Index]; end; procedure TPartInfo.SetUserInfo(index: Integer; const Value: TUserInfo); begin FUserList[Index] := Value; end; end.
unit uDlgFind_OKOF; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, uDlgFind, Menus, cxLookAndFeelPainters, cxGraphics, StdCtrls, cxRadioGroup, cxCheckBox, cxGroupBox, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxMRUEdit, cxButtons, ExtCtrls, cxDBTL; type TdlgFind_OKOF = class(TdlgFind) procedure btnFindNextClick(Sender: TObject); private FTree: TcxDBTreeList; { Private declarations } protected procedure SetDialogCaption; override; public property Tree: TcxDBTreeList read FTree write FTree; end; var dlgFind_OKOF: TdlgFind_OKOF; implementation {$R *.dfm} procedure TdlgFind_OKOF.btnFindNextClick(Sender: TObject); begin { Tree.OptionsBehavior.IncSearchItem:=Tree.FocusedColumn; Tree.SearchingText:=edtText.Text; repeat if not Tree.FindNext(rbFindDown.Checked) then begin Tree.CancelSearching; Break; end; until Tree.FocusedNode.Texts[Tree.FocusedColumn.ItemIndex] = edtText.Text;} try Tree.DataController.Search.SearchFromBegin:=false; Tree.DataController.Search.SearchWholeCell:=cbWholeCell.Checked; Tree.DataController.Search.SearchCaseSensitive:=cbCaseSensitive.Checked; Tree.SearchingText:=edtText.Text; // Tree.Controller.IncSearchingText:=edtText.Text; // Tree.DataController.Search.LocateNext(rbFindDown.Checked); finally Tree.DataController.Search.SearchFromBegin:=true; Tree.DataController.Search.SearchWholeCell:=false; Tree.DataController.Search.SearchCaseSensitive:=false; end; end; procedure TdlgFind_OKOF.SetDialogCaption; begin Caption:='Ïîèñê: ÎÊÎÔ'; end; end.
unit HelpUnit; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls; type { THelpForm } THelpForm = class(TForm) OkButton: TButton; HepMemo: TMemo; procedure FormCreate(Sender: TObject); procedure OkButtonClick(Sender: TObject); private { private declarations } public { public declarations } end; procedure langch(lang: String); resourcestring sHelpText = 'Этот каклькулятор имеет несколько режимов.' +#10+ 'Основные возможности:' +#10+ '- Поддержка ввода с клавиатуры (Esc, Пробел и тд)' +#10+#10+ '- Горячие клавиши' +#10+ 'Горячие клавиши:' +#10+ 'CTRL+C: копирование результата' +#10+ 'CTRL+V: вставка числа (текущее будет удалено)' +#10+ 'r: 1/x' +#10+ 'F9: +/-'; var HelpForm: THelpForm; implementation {$R *.lfm} { THelpForm } procedure THelpForm.OkButtonClick(Sender: TObject); begin HelpForm.Close; end; procedure THelpForm.FormCreate(Sender: TObject); begin HepMemo.Text:= sHelpText; end; procedure langch(lang: String); begin if lang='ru' then HelpForm.HepMemo.Text:= 'Этот каклькулятор имеет несколько режимов.' +#10+ 'Основные возможности:' +#10+ '- Поддержка ввода с клавиатуры (Esc, Пробел и тд)' +#10+#10+ '- Горячие клавиши' +#10+ 'Горячие клавиши:' +#10+ 'CTRL+C: копирование результата' +#10+ 'CTRL+V: вставка числа (текущее будет удалено)' +#10+ 'r: 1/x' +#10+ 'F9: +/-' else HelpForm.HepMemo.Text:= 'This calculator has only Simple mode.'+#10+'Main features:'+#10+'-keyboard input (with Esc, Backspace, etc.);'+#10+'-shortcuts and hotkeys;'+#10+#10+'Shortcuts and hotkeys:'+#10+'-Ctrl+C: copy the number;'+#10+'-Crtl+V: paste the number (the existing number is deleted);'+#10+'-r: 1/x;'+#10+'-F9: +/-.'; end; end.
//--------------------------------------------------------------------------- // This software is Copyright (c) 2011 Embarcadero Technologies, Inc. // You may only use this software if you are an authorized licensee // of Delphi, C++Builder or RAD Studio (Embarcadero Products). // This software is considered a Redistributable as defined under // the software license agreement that comes with the Embarcadero Products // and is subject to that software license agreement. //--------------------------------------------------------------------------- unit BindListVCLFormUnit1; interface // Example demonstrating TBindList components. // Double click BindCompList1 to view TBindList components, then // double a TBindList component to view and edit expressions. // AutoFill property causes lists to populate when app is loaded. // The BindCompVCLEditors unit must be used by this project in order to // register listbox and listview editors. uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Rtti, Vcl.ExtCtrls, Vcl.DBCtrls, Data.Bind.Components, Data.Bind.DBScope, Vcl.StdCtrls, Vcl.AppEvnts, Vcl.Mask, Data.DB, System.Generics.Collections, Vcl.DBCGrids, Vcl.ComCtrls, Data.Bind.EngExt, Vcl.Bind.DBEngExt, Vcl.Bind.Editors, System.Bindings.Outputs; type TForm1 = class(TForm) BindScopeDB1: TBindScopeDB; BindCompList1: TBindingsList; ListBoxCategories: TListBox; ButtonFillList: TButton; ButtonClearList: TButton; ListView1: TListView; ButtonClearListView: TButton; ButtonFillListView: TButton; BindListView: TBindList; ButtonFillListViewColumns: TButton; BindListViewColumns: TBindList; BindListBox: TBindList; procedure ButtonFillListClick(Sender: TObject); procedure ButtonClearListClick(Sender: TObject); procedure ButtonFillListViewClick(Sender: TObject); procedure ButtonClearListViewClick(Sender: TObject); procedure ButtonFillListViewColumnsClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation uses ClientDataSetModuleUnit1; {$R *.dfm} procedure TForm1.ButtonClearListClick(Sender: TObject); begin BindListBox.ClearList; end; procedure TForm1.ButtonClearListViewClick(Sender: TObject); begin BindListView.ClearList; end; procedure TForm1.ButtonFillListClick(Sender: TObject); begin BindListBox.FillList; end; procedure TForm1.ButtonFillListViewClick(Sender: TObject); begin BindListView.FillList; end; procedure TForm1.ButtonFillListViewColumnsClick(Sender: TObject); begin BindListViewColumns.FillList; end; end.
unit RemindersDlg; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Htmlview, StdCtrls, ExtCtrls, Db, DBISAMTb; type TRemindersDialog = class(TForm) Panel1: TPanel; DontRemindChkBox: TCheckBox; CloseButton: TButton; HtmlViewer: THTMLViewer; tblReminders: TDBISAMTable; procedure HtmlViewerHotSpotClick(Sender: TObject; const SRC: String; var Handled: Boolean); private { Private declarations } public end; var RemindersDialog: TRemindersDialog; procedure CheckForReminders(const RunCount : Integer; const ARemindersPath : String); implementation {$R *.DFM} uses StStrS, Main; procedure CheckForReminders(const RunCount : Integer; const ARemindersPath : String); var FirstShowCount, LastShowCount, RecurShowCount : Integer; Show : Boolean; Reminder : String; begin with RemindersDialog.tblReminders do begin try DatabaseName := ARemindersPath; TableName := 'Reminders'; Open; except exit; end; while not EOF do begin if (FieldValues['LastShownCount'] > RunCount) then begin Edit; FieldValues['LastShownCount'] := 0; Post; end; FirstShowCount := FieldValues['FirstShowCount']; RecurShowCount := FieldValues['RecurShowCount']; LastShowCount := FieldValues['LastShownCount']; if (LastShowCount > 0) then Show := (RunCount - LastShowCount > RecurShowCount) else Show := (RunCount >= FirstShowCount); if Show and FieldValues['Show'] then begin Reminder := FieldValues['Reminder']; RemindersDialog.HtmlViewer.LoadFromBuffer(PChar(Reminder), Length(Reminder)); RemindersDialog.DontRemindChkBox.Checked := not FieldValues['Show']; RemindersDialog.DontRemindChkBox.Enabled := FieldValues['AllowHide']; RemindersDialog.ShowModal; Edit; if RunCount = FirstShowCount then FieldValues['FirstShownOn'] := Date; FieldValues['LastShownOn'] := Date; FieldValues['LastShownCount'] := RunCount; FieldValues['Show'] := not RemindersDialog.DontRemindChkBox.Checked; Post; end; Next; end; end; end; procedure TRemindersDialog.HtmlViewerHotSpotClick(Sender: TObject; const SRC: String; var Handled: Boolean); begin MainForm.SetAddress(SRC); ModalResult := mrOk; end; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [SINDICATO] The MIT License Copyright: Copyright (C) 2014 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 *******************************************************************************} unit SindicatoVO; {$mode objfpc}{$H+} interface uses VO, Classes, SysUtils, FGL; type TSindicatoVO = class(TVO) private FID: Integer; FNOME: String; FCODIGO_BANCO: Integer; FCODIGO_AGENCIA: Integer; FCONTA_BANCO: String; FCODIGO_CEDENTE: String; FLOGRADOURO: String; FNUMERO: String; FBAIRRO: String; FMUNICIPIO_IBGE: Integer; FUF: String; FFONE1: String; FFONE2: String; FEMAIL: String; FTIPO_SINDICATO: String; FDATA_BASE: TDateTime; FPISO_SALARIAL: Extended; FCNPJ: String; FCLASSIFICACAO_CONTABIL_CONTA: String; published property Id: Integer read FID write FID; property Nome: String read FNOME write FNOME; property CodigoBanco: Integer read FCODIGO_BANCO write FCODIGO_BANCO; property CodigoAgencia: Integer read FCODIGO_AGENCIA write FCODIGO_AGENCIA; property ContaBanco: String read FCONTA_BANCO write FCONTA_BANCO; property CodigoCedente: String read FCODIGO_CEDENTE write FCODIGO_CEDENTE; property Logradouro: String read FLOGRADOURO write FLOGRADOURO; property Numero: String read FNUMERO write FNUMERO; property Bairro: String read FBAIRRO write FBAIRRO; property MunicipioIbge: Integer read FMUNICIPIO_IBGE write FMUNICIPIO_IBGE; property Uf: String read FUF write FUF; property Fone1: String read FFONE1 write FFONE1; property Fone2: String read FFONE2 write FFONE2; property Email: String read FEMAIL write FEMAIL; property TipoSindicato: String read FTIPO_SINDICATO write FTIPO_SINDICATO; property DataBase: TDateTime read FDATA_BASE write FDATA_BASE; property PisoSalarial: Extended read FPISO_SALARIAL write FPISO_SALARIAL; property Cnpj: String read FCNPJ write FCNPJ; property ClassificacaoContabilConta: String read FCLASSIFICACAO_CONTABIL_CONTA write FCLASSIFICACAO_CONTABIL_CONTA; end; TListaSindicatoVO = specialize TFPGObjectList<TSindicatoVO>; implementation initialization Classes.RegisterClass(TSindicatoVO); finalization Classes.UnRegisterClass(TSindicatoVO); end.
namespace Extension_Methods; interface uses System.Runtime.CompilerServices, System.Collections.Generic, System.Text; type ConsoleApp = class public class method Main; end; //Old Extension Methods Syntax //Interface Extension //Now each object of class derived from IEnumerable will have an Implode method regardless of it's elements type type [Extension] EnumerableExtender = public static class private public [Extension] class method Implode<T>(parts : IEnumerable<T>; glue : String) : String; end; //New Extension Methods Syntax //Defining an extension method is done by defining the method outside of any class and prefixing it with extension //Extension of class Integer: extension method Integer.IterateTo(endWith : Int32; interval: Int32; action: Action<Int32> ); implementation class method ConsoleApp.Main; begin //sequence implemets IEnumerable var numbers : sequence of Int32 := [1, 2, 3, 4, 5]; Console.WriteLine("Integer sequence:"); Console.WriteLine(numbers.Implode(', ')); Console.WriteLine(); //Queue implemets IEnumerable var dates : Queue<DateTime> := new Queue<DateTime>; dates.Enqueue(DateTime.Now.Date.AddDays(-1)); dates.Enqueue(DateTime.Now.Date); dates.Enqueue(DateTime.Now.Date.AddDays(1)); Console.WriteLine("DateTime queue:"); Console.WriteLine(dates.Implode(', then ')); Console.WriteLine(); var two: Int32 :=2; //Iterate from 2 to 10 with interval 1 two.IterateTo(10, 1, i -> Console.WriteLine(i)); Console.WriteLine(); var negativeTen: Int32 := -10; //Iterate from -10 to -30 with interval 5 negativeTen.IterateTo(-30, 5, c -> Console.Write(c+" ")); Console.ReadLine(); end; class method EnumerableExtender.Implode<T>(parts: IEnumerable<T>; glue: String): String; begin var sb := new StringBuilder; for p in parts do begin sb.Append(p); sb.Append(glue); end; sb.Remove(sb.Length-glue.Length, glue.Length); result := sb.ToString; end; extension method Integer.IterateTo(endWith, interval: Int32; action: Action<Int32>); begin var prefix : Int32; var modify : Func<Int32, Int32> := x -> x + interval; if (endWith < self) then prefix := -1 else prefix := 1; var i : Int32 := prefix * self; while i <= prefix * endWith do begin action(prefix * i); i := modify(i); end; end; end.
unit htColumns; interface uses Windows, SysUtils, Types, Classes, Controls, Graphics, htInterfaces, htMarkup; type ThtCustomColumns = class(TCustomControl, IhtGenerator) protected procedure AlignControls(AControl: TControl; var Rect: TRect); override; procedure Paint; override; public constructor Create(inOwner: TComponent); override; procedure Generate(inMarkup: ThtMarkup); end; // ThtColumns = class(ThtCustomColumns) published property Align; // property AutoSize default true; // property BorderColor; // property Borders; // property ContentColor; // property LeftPosition; // property Margins; // property OnGetContent; // property Padding; // property Position; // property TopPosition; property Visible; end; implementation uses LrControlIterator, LrVclUtils; { ThtCustomColumns } constructor ThtCustomColumns.Create(inOwner: TComponent); begin inherited; ControlStyle := ControlStyle + [ csAcceptsControls ]; end; procedure ThtCustomColumns.Paint; begin inherited; with Canvas do begin SetBkColor(Handle, ColorToRgb(Brush.Color)); //SetBkMode(Handle, TRANSPARENT); Brush.Style := bsVertical; Brush.Color := ColorToRgb(clSilver); Pen.Style := psClear; Rectangle(ClientRect); Brush.Style := bsSolid; Pen.Style := psSolid; //SetBkMode(Handle, OPAQUE); end; end; procedure ThtCustomColumns.AlignControls(AControl: TControl; var Rect: TRect); var i: Integer; begin for i := 0 to Pred(ControlCount) do Controls[i].Align := alLeft; inherited; end; procedure ThtCustomColumns.Generate(inMarkup: ThtMarkup); var g: IhtGenerator; w: string; begin // inMarkup.Add(Format( // '<table cellpadding="0" cellspacing="0" border="1" style="height:%dpx; table-layout: fixed;">', // [ Height ]) // ); inMarkup.Styles.Add(Format( '#%s_table { height:%dpx; width:100%%; table-layout: fixed; }', [ Name, Height ]) ); inMarkup.Add(Format( '<table id="%s_table" cellpadding="0" cellspacing="0" border="1">', [ Name ]) ); inMarkup.Add('<tr>'); with TLrSortedCtrlIterator.Create(Self, alLeft) do try while Next do begin if (Index = 2) then w := '' else w := Format('width="%dpx"', [ Ctrl.Width ]); // if (LrIsAs(Ctrl, IhtGenerator, g)) then begin inMarkup.Add(Format('<td %s>', [ w ])); // ' <td valign="top"%s>', [ w ])); g.Generate(inMarkup) end else begin inMarkup.Add(Format('<td %s>', [ w ])); // ' <td valign="top"%s>', [ w ])); // ' <td align="middle" valign="center" width="%dpx">', [ Ctrl.Width ])); inMarkup.Add(Ctrl.Name); end; // inMarkup.Add('</td>'); end; finally Free; end; inMarkup.Add('</tr>'); inMarkup.Add('</table>'); end; end.
////////////////////////////////////////////////////////////////////////// // This file is a part of NotLimited.Framework.Wpf NuGet package. // You are strongly discouraged from fiddling with it. // If you do, all hell will break loose and living will envy the dead. ////////////////////////////////////////////////////////////////////////// using System; using System.Windows; using System.Windows.Media.Animation; namespace NotLimited.Framework.Wpf.Animations { public class AnimationItem { private readonly Storyboard _storyboard; internal AnimationItem(Storyboard storyboard) { _storyboard = storyboard; _storyboard.Completed += OnStoryboardComplete; } public Action BeginAction { get; set; } public Action EndAction { get; set; } public DependencyObject Control { get; set; } public PropertyPath PropertyPath { get; set; } public void Start() { if (BeginAction != null) BeginAction(); _storyboard.Begin(); } public void Stop() { _storyboard.Stop(); OnStoryboardComplete(null, EventArgs.Empty); } private void OnStoryboardComplete(object sender, EventArgs e) { //var value = Storyboard.Children[0].EvaluateProperty<object>(new PropertyPath("To")); //Control.SetProperty(PropertyPath, value); //Storyboard.Remove(); _storyboard.Completed -= OnStoryboardComplete; if (EndAction != null) EndAction(); } } }
unit BasicDataTypes; interface uses Graphics, BasicMathsTypes; type PIntegerItem = ^TIntegerItem; TIntegerItem = record Value : integer; Next : PIntegerItem; end; T3DIntGrid = array of array of array of integer; P3DIntGrid = ^T3DIntGrid; T3DSingleGrid = array of array of array of single; P3DSingleGrid = ^T3DSingleGrid; T4DIntGrid = array of array of array of array of integer; P4DIntGrid = ^T4DIntGrid; PByte = ^Byte; PInteger = ^Integer; AInt32 = array of integer; AUInt32 = array of longword; AString = array of string; PAUint32 = ^AUInt32; ABool = array of boolean; AByte = array of byte; AFloat = array of single; TByteMap = array of array of byte; T2DBooleanMap = array of array of Boolean; TInt32Map = array of AInt32; TAByteMap = array of TByteMap; TABitmap = array of TBitmap; APointer = array of Pointer; TDistanceUnit = record x, y, z, Distance : single; end; TBinaryMap = array of array of array of single; //byte; T3DBooleanMap = array of array of array of boolean; TDistanceArray = array of array of array of TDistanceUnit; //single; T2DFrameBuffer = array of array of TVector4f; TWeightBuffer = array of array of real; TSeedTreeItem = record Left, Right: integer; end; TSeedTree = array of TSeedTreeItem; TPixelRGBAByteData = record r,g,b,a: byte; end; TPixelRGBByteData = record r,g,b: byte; end; TPixelRGBLongData = record r,g,b: longword; end; TPixelRGBIntData = record r,g,b: integer; end; TPixelRGBALongData = record r,g,b,a: longword; end; TPixelRGBAIntData = record r,g,b,a: integer; end; implementation end.
unit fos_sparelistgen; { (§LIC) (c) Autor,Copyright Dipl.Ing.- Helmut Hartl, Dipl.Ing.- Franz Schober, Dipl.Ing.- Christian Koch FirmOS Business Solutions GmbH www.openfirmos.org New Style BSD Licence (OSI) Copyright (c) 2001-2013, FirmOS Business Solutions GmbH 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 the <FirmOS Business Solutions GmbH> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (§LIC_END) } {$mode objfpc}{$H+} {$modeswitch nestedprocvars} interface uses sysutils; type { OFOS_SpareList } generic OFOS_SpareList<_TType> = object private type _PTType = ^_TType; TGFOS_SpareListType = array of _TType; TGFOS_ElemProcHalt = procedure (var x:_TType;const idx:NativeInt ; var halt_flag:boolean) is nested; { complexer cases } TGFOS_ElemProc = procedure (var x:_TType) is nested; { simple short form } TGFOS_ExtCompareElemProc = function (const x1,x2 : _PTType ; const extension_pointer : Pointer) : boolean; TGFOS_ExtCompareNullElemProc = function (const x1:_PTType) : boolean; private FArray : TGFOS_SpareListType; FCnt : NativeInt; FCurrSpares : NativeInt; FReservSpares : NativeInt; FExtensionPtr : Pointer; FNullElement : _TType; FCompareFunc : TGFOS_ExtCompareElemProc; FNullCompare : TGFOS_ExtCompareNullElemProc; function MyNullCompare (const x1:_PTType) : boolean; function MyExtCompare (const x1,x2 : _PTType) : boolean; procedure ERR_IndexOutOfBounds (const idx,lo,hi:NativeInt); public function Reserve : NativeInt; procedure InitSparseList (const NullElement:_TType ; const NullCompare : TGFOS_ExtCompareNullElemProc ; const Compare : TGFOS_ExtCompareElemProc ; const numberofemptyslots:NativeUint=25 ; const ExtensionPointer : Pointer=nil); procedure InitSparseListPtrCmp (const numberofemptyslots:NativeUint=25;const ExtensionPointer : Pointer=nil); function Add (const elem: _TType):NativeInt; // new result = insert index or -1 on exists function Exists (const elem: _TType):NativeInt; function Delete (const elem: _TType):Boolean; function GetElement (idx : NativeInt): _TType; procedure SetElement (idx : NativeInt; AValue: _TType); function Count : NativeInt; procedure ForAll (const elem_func : TGFOS_ElemProc); function ForAllBreak (const elem_func : TGFOS_ElemProcHalt):Boolean; function ForAllBreak2 (const elem_func : TGFOS_ElemProcHalt ; var halt : boolean):boolean; procedure ClearIndex (const idx : NativeInt); function GetLastNotNull (var elem : _TType):NativeInt; function GetFirstNotNull (var elem : _TType):NativeInt; property Element [idx : NativeInt]:_TType read GetElement write SetElement; default; procedure _DummyForceFPC_Recompile ; virtual ; abstract; end; implementation { OFOS_SpareList } function OFOS_SpareList.MyNullCompare(const x1: _PTType): boolean; begin if FNullCompare=nil then begin result := CompareMem(x1,@FNullElement,sizeof(_TType)); end else begin result := FNullCompare(x1); end; end; function OFOS_SpareList.MyExtCompare(const x1, x2: _PTType): boolean; begin if FCompareFunc=nil then result := CompareMem(x1,x2,sizeof(_TType)) else result := FCompareFunc(x1,x2,FExtensionPtr); end; procedure OFOS_SpareList.ERR_IndexOutOfBounds(const idx, lo, hi: NativeInt); begin raise Exception.create('index out of bounds');//'SPARELIST - INDEX OUT OF BOUNDS ix='+inttostr(idx)+', but should be between '+inttostr(lo)+' ... '+inttostr(hi)); end; function OFOS_SpareList.Reserve: NativeInt; var diff : NativeInt; begin result := high(FArray)+1; diff := FReservSpares-FCurrSpares; assert(diff>0); SetLength(FArray,Length(FArray)+diff); end; procedure OFOS_SpareList.InitSparseList(const NullElement: _TType; const NullCompare: TGFOS_ExtCompareNullElemProc; const Compare: TGFOS_ExtCompareElemProc; const numberofemptyslots: NativeUint; const ExtensionPointer: Pointer); var i : NAtiveInt; begin FCnt := 0; SetLength (FArray,numberofemptyslots); FCurrSpares := numberofemptyslots; FReservSpares := numberofemptyslots; FNullElement := NullElement; FNullCompare := NullCompare; FCompareFunc := Compare; for i := 0 to High(FArray) do FArray[i] := NullElement; FExtensionPtr := ExtensionPointer; end; procedure OFOS_SpareList.InitSparseListPtrCmp(const numberofemptyslots: NativeUint; const ExtensionPointer: Pointer); var nullelem : _TType; begin FillByte(nullelem,sizeof(FNullElement),0); InitSparseList(nullelem,nil,nil); FExtensionPtr := ExtensionPointer; end; function OFOS_SpareList.Add(const elem: _TType): NativeInt; var firstspare : NativeInt; i : NAtiveInt; begin if Exists(elem)<>-1 then exit(-1); firstspare:=-1; for i:=0 to high(FArray) do if MyNullCompare(@FArray[i]) then begin firstspare := i; break; end; if firstspare>=0 then begin FArray[firstspare] := elem; end else begin firstspare := Reserve; FArray[firstspare] := elem; end; result := firstspare; dec(FCurrSpares); inc(FCnt); end; function OFOS_SpareList.Exists(const elem: _TType): NativeInt; var i : NativeInt; isnull : boolean; cmpcnt : NativeInt; begin result := -1; cmpcnt := 0; if FCnt = 0 then exit(-1); for i:=0 to high(FArray) do if (not MyNullCompare(@FArray[i])) then begin if MyExtCompare(@FArray[i],@elem) then exit(i); inc(cmpcnt); if cmpcnt=FCnt then exit(-1); end; exit(-1); end; function OFOS_SpareList.Delete(const elem: _TType): Boolean; var idx : NativeInt; begin idx := Exists(elem); if idx<0 then exit(false); FArray[idx] := FNullElement; inc(FCurrSpares); dec(FCnt); result := true; end; function OFOS_SpareList.GetElement(idx: NativeInt): _TType; begin result := FArray[idx]; end; procedure OFOS_SpareList.SetElement(idx: NativeInt; AValue: _TType); begin if MyNullCompare(@FArray[idx]) then begin FArray[idx] := AValue; // Add dec(FCurrSpares); inc(FCnt); end else begin FArray[idx] := AValue; // Overwrite end end; function OFOS_SpareList.Count: NativeInt; begin result := FCnt; end; procedure OFOS_SpareList.ForAll(const elem_func: TGFOS_ElemProc); var i : NativeInt; cnt, maxarr : NativeInt; begin cnt := FCnt; maxarr := Length(FArray); i := 0; while (i < maxarr) and (cnt>0) do begin if not MyNullCompare(@FArray[i]) then begin elem_func(FArray[i]); dec(cnt); { decrement saved max item cnt for every non null element} end; inc(i); end; end; function OFOS_SpareList.ForAllBreak(const elem_func: TGFOS_ElemProcHalt): Boolean; var haltf : boolean; begin haltf := false; result := ForAllBreak2(elem_func,haltf); end; function OFOS_SpareList.ForAllBreak2(const elem_func: TGFOS_ElemProcHalt; var halt: boolean): boolean; var cnt,savecnt, maxarr,i : NativeInt; begin result := true; cnt := 0; maxarr := Length(FArray); i := 0; savecnt := FCnt; { a clearindex (which is allowed) would modify the count -> save it for local usage } while (i < maxarr) and (savecnt>0) do begin if not MyNullCompare(@FArray[i]) then begin elem_func(FArray[i],i,halt); inc(cnt); if cnt=savecnt then { search the whole array, but break if we have reached the element count, there cant be further non null elements} exit(halt); if halt then exit(true); end; inc(i); end; exit(false); end; procedure OFOS_SpareList.ClearIndex(const idx: NativeInt); begin if (idx>=0) and (idx<=high(FArray)) then begin FArray[idx] := FNullElement; Dec(FCnt); Inc(FCurrSpares); end else ERR_IndexOutOfBounds(idx,0,high(FArray)); end; function OFOS_SpareList.GetLastNotNull(var elem: _TType): NativeInt; var i : NativeInt; isnull : boolean; begin result := -1; elem := FNullElement; if FCnt = 0 then exit(-1); for i:= high(FArray) downto 0 do if (not MyNullCompare(@FArray[i])) then begin elem := FArray[i]; exit(i); end; exit(-1); end; function OFOS_SpareList.GetFirstNotNull(var elem: _TType): NativeInt; var i : NativeInt; isnull : boolean; begin result := -1; elem := FNullElement; if FCnt = 0 then exit(-1); for i:= 0 to high(FArray) do if (not MyNullCompare(@FArray[i])) then begin elem := FArray[i]; exit(i); end; exit(-1); end; end.
unit SearchFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, RzButton, ExtCtrls, ComCtrls, StdCtrls, Mask, RzEdit, RzLabel; type TfrmSearch = class(TForm) blAllContainer: TBevel; btnClose: TRzBitBtn; btnOK: TRzBitBtn; Listview: TListView; edSearchText: TRzEdit; RzLabel1: TRzLabel; procedure btnCloseClick(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure edSearchTextKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ListviewKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private FIsOK: boolean; FCustomerID: string; procedure SetIsOK(const Value: boolean); procedure SetCustomerID(const Value: string); { Private declarations } public { Public declarations } property IsOK : boolean read FIsOK write SetIsOK; property CustomerID : string read FCustomerID write SetCustomerID; end; var frmSearch: TfrmSearch; implementation {$R *.dfm} procedure TfrmSearch.btnCloseClick(Sender: TObject); begin FIsOK := false; Close; end; procedure TfrmSearch.btnOKClick(Sender: TObject); begin FIsOK := true; FCustomerID :='C121100001'; Close; end; procedure TfrmSearch.FormShow(Sender: TObject); begin FIsOK :=false; edSearchText.SetFocus; edSearchText.SelectAll; end; procedure TfrmSearch.SetIsOK(const Value: boolean); begin FIsOK := Value; end; procedure TfrmSearch.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key=VK_ESCAPE then btnCloseClick(nil); if Key=VK_F11 then btnOKClick(nil); end; procedure TfrmSearch.edSearchTextKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if key=vk_down then Listview.SetFocus; end; procedure TfrmSearch.ListviewKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key=vk_up then if Listview.Selected.Index=0 then begin edSearchText.SetFocus; edSearchText.SelectAll; end; if Key=VK_RETURN then btnOKClick(sender); end; procedure TfrmSearch.SetCustomerID(const Value: string); begin FCustomerID := Value; end; end.
{******************************************************************************* 作者: 289525016@163.com 2017-3-30 描述: 自助办卡窗口--葛洲坝钟祥水泥有限公司 *******************************************************************************} unit uZXNewCard; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxLabel, Menus, StdCtrls, cxButtons, cxGroupBox, cxRadioGroup, cxTextEdit, cxCheckBox, ExtCtrls, dxLayoutcxEditAdapters, dxLayoutControl, cxDropDownEdit, cxMaskEdit, cxButtonEdit, USysConst, cxListBox, ComCtrls,Uszttce_api,Contnrs; type TfFormNewCard = class(TForm) editWebOrderNo: TcxTextEdit; labelIdCard: TcxLabel; btnQuery: TcxButton; PanelTop: TPanel; PanelBody: TPanel; dxLayout1: TdxLayoutControl; BtnOK: TButton; BtnExit: TButton; EditValue: TcxTextEdit; EditCard: TcxTextEdit; EditID: TcxTextEdit; EditCus: TcxTextEdit; EditCName: TcxTextEdit; EditStock: TcxTextEdit; EditSName: TcxTextEdit; EditMax: TcxTextEdit; EditTruck: TcxButtonEdit; EditType: TcxComboBox; PrintFH: TcxCheckBox; EditFQ: TcxButtonEdit; EditGroup: TcxComboBox; dxLayoutGroup1: TdxLayoutGroup; dxGroup1: TdxLayoutGroup; dxGroupLayout1Group2: TdxLayoutGroup; dxLayout1Item5: TdxLayoutItem; dxLayout1Item9: TdxLayoutItem; dxlytmLayout1Item3: TdxLayoutItem; dxlytmLayout1Item4: TdxLayoutItem; dxGroup2: TdxLayoutGroup; dxlytmLayout1Item9: TdxLayoutItem; dxlytmLayout1Item10: TdxLayoutItem; dxGroupLayout1Group5: TdxLayoutGroup; dxLayout1Group4: TdxLayoutGroup; dxlytmLayout1Item13: TdxLayoutItem; dxLayout1Item12: TdxLayoutItem; dxLayout1Group3: TdxLayoutGroup; dxLayout1Item11: TdxLayoutItem; dxlytmLayout1Item11: TdxLayoutItem; dxGroupLayout1Group6: TdxLayoutGroup; dxlytmLayout1Item12: TdxLayoutItem; dxLayout1Item8: TdxLayoutItem; dxLayoutGroup3: TdxLayoutGroup; dxLayout1Item7: TdxLayoutItem; dxLayoutItem1: TdxLayoutItem; dxLayout1Item2: TdxLayoutItem; dxLayout1Group1: TdxLayoutGroup; pnlMiddle: TPanel; cxLabel1: TcxLabel; lvOrders: TListView; Label1: TLabel; btnClear: TcxButton; TimerAutoClose: TTimer; EditHd: TcxTextEdit; dxLayout1Item1: TdxLayoutItem; EditHdValue: TcxTextEdit; dxLayout1Item3: TdxLayoutItem; dxLayout1Group5: TdxLayoutGroup; procedure BtnExitClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure TimerAutoCloseTimer(Sender: TObject); procedure btnQueryClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure BtnOKClick(Sender: TObject); procedure lvOrdersClick(Sender: TObject); procedure editWebOrderNoKeyPress(Sender: TObject; var Key: Char); procedure btnClearClick(Sender: TObject); private { Private declarations } FSzttceApi:TSzttceApi; //发卡机驱动 FAutoClose:Integer; //窗口自动关闭倒计时(分钟) FWebOrderIndex:Integer; //商城订单索引 FWebOrderItems:array of stMallOrderItem; //商城订单数组 FCardData,FHdCardData:TStrings; //云天系统返回的大票号信息 FHdJiaoYan:Boolean;//袋装拼单校验结果 Fbegin:TDateTime; FLastClick: Int64; procedure InitListView; procedure SetControlsReadOnly; function DownloadOrder(const nCard:string):Boolean; procedure Writelog(nMsg:string); procedure AddListViewItem(var nWebOrderItem:stMallOrderItem); procedure LoadSingleOrder; function IsRepeatCard(const nWebOrderItem:string):Boolean; function CheckYunTianOrderInfo(const nOrderId:string;var nWebOrderItem:stMallOrderItem):Boolean; function CheckYunTianOrderHdInfo(const nHdOrderId:string; var nWebOrderItem:stMallOrderItem):Boolean; function do_YT_GetBatchCode(const nWebOrderItem:stMallOrderItem):Boolean; function VerifyCtrl(Sender: TObject; var nHint: string): Boolean; function SaveBillProxy:Boolean; function SaveWebOrderMatch(const nBillID,nWebOrderID:string):Boolean; public { Public declarations } procedure SetControlsClear; property SzttceApi:TSzttceApi read FSzttceApi write FSzttceApi; end; var fFormNewCard: TfFormNewCard; implementation uses ULibFun,UBusinessPacker,USysLoger,UBusinessConst,UFormMain,USysBusiness,USysDB, UAdjustForm,UFormBase,UDataReport,UDataModule,NativeXml,UMgrK720Reader,UFormWait, DateUtils; {$R *.dfm} { TfFormNewCard } procedure TfFormNewCard.SetControlsClear; var i:Integer; nComp:TComponent; begin editWebOrderNo.Clear; for i := 0 to dxLayout1.ComponentCount-1 do begin nComp := dxLayout1.Components[i]; if nComp is TcxTextEdit then begin TcxTextEdit(nComp).Clear; end; end; end; procedure TfFormNewCard.BtnExitClick(Sender: TObject); begin Close; end; procedure TfFormNewCard.FormClose(Sender: TObject; var Action: TCloseAction); begin FCardData.Free; FHdCardData.Free; Action:= caFree; fFormNewCard := nil; end; procedure TfFormNewCard.FormShow(Sender: TObject); begin SetControlsReadOnly; dxLayout1Item5.Visible := False; dxLayout1Item9.Visible := False; dxlytmLayout1Item13.Visible := False; dxLayout1Item12.Visible := False; EditTruck.Properties.Buttons[0].Visible := False; ActiveControl := editWebOrderNo; btnOK.Enabled := False; FAutoClose := gSysParam.FAutoClose_Mintue; TimerAutoClose.Interval := 60*1000; TimerAutoClose.Enabled := True; EditFQ.Properties.Buttons[0].Visible := False; end; procedure TfFormNewCard.SetControlsReadOnly; var i:Integer; nComp:TComponent; begin for i := 0 to dxLayout1.ComponentCount-1 do begin nComp := dxLayout1.Components[i]; if nComp is TcxTextEdit then begin TcxTextEdit(nComp).Properties.ReadOnly := True; end; end; EditFQ.Properties.ReadOnly := True; end; procedure TfFormNewCard.TimerAutoCloseTimer(Sender: TObject); begin if FAutoClose=0 then begin TimerAutoClose.Enabled := False; Close; end; Dec(FAutoClose); end; procedure TfFormNewCard.btnQueryClick(Sender: TObject); var nCardNo,nStr:string; begin FAutoClose := gSysParam.FAutoClose_Mintue; btnQuery.Enabled := False; try nCardNo := Trim(editWebOrderNo.Text); if nCardNo='' then begin nStr := '请先输入或扫描订单号'; ShowMsg(nStr,sHint); Writelog(nStr); Exit; end; lvOrders.Items.Clear; if not DownloadOrder(nCardNo) then Exit; btnOK.Enabled := True; finally btnQuery.Enabled := True; end; end; function TfFormNewCard.DownloadOrder(const nCard: string): Boolean; var nXmlStr,nData:string; nListA,nListB:TStringList; i:Integer; nWebOrderCount:Integer; begin Result := False; FWebOrderIndex := 0; nXmlStr := '<?xml version="1.0" encoding="UTF-8"?>' +'<DATA>' +'<head>' +'<Factory>%s</Factory>' +' <NO>%s</NO>' +' <status>-1</status>' //-1 开卡 0 开卡成功 +'</head>' +'</DATA>'; nXmlStr := Format(nXmlStr,[gSysParam.FFactory,nCard]); nXmlStr := PackerEncodeStr(nXmlStr); FBegin := Now; nData := get_shoporderbyno(nXmlStr); if nData='' then begin ShowMsg('未查询到网上商城订单详细信息,请检查订单号是否正确',sHint); Writelog('未查询到网上商城订单详细信息,请检查订单号是否正确'); Exit; end; Writelog('TfFormNewCard.DownloadOrder(nCard='''+nCard+''') 查询商城订单-耗时:'+InttoStr(MilliSecondsBetween(Now, FBegin))+'ms'); //解析网城订单信息 nData := PackerDecodeStr(nData); Writelog('get_shoporderbyno res:'+nData); nListA := TStringList.Create; nListB := TStringList.Create; try nListA.Text := nData; for i := nListA.Count-1 downto 0 do begin if Trim(nListA.Strings[i])='' then begin nListA.Delete(i); end; end; nWebOrderCount := nListA.Count; SetLength(FWebOrderItems,nWebOrderCount); for i := 0 to nWebOrderCount-1 do begin nListB.CommaText := nListA.Strings[i]; FWebOrderItems[i].FOrder_id := nListB.Values['order_id']; FWebOrderItems[i].FOrdernumber := nListB.Values['ordernumber']; FWebOrderItems[i].FGoodsID := nListB.Values['goodsID']; FWebOrderItems[i].FGoodstype := nListB.Values['goodstype']; FWebOrderItems[i].FGoodsname := nListB.Values['goodsname']; FWebOrderItems[i].FData := nListB.Values['data']; FWebOrderItems[i].Ftracknumber := nListB.Values['tracknumber']; FWebOrderItems[i].FYunTianOrderId := nListB.Values['fac_order_no']; FWebOrderItems[i].FHd_Order_no := nListB.Values['hd_fac_order_no']; FWebOrderItems[i].Fspare := nListB.Values['spare']; AddListViewItem(FWebOrderItems[i]); end; finally nListB.Free; nListA.Free; end; LoadSingleOrder; end; procedure TfFormNewCard.Writelog(nMsg: string); var nStr:string; begin nStr := 'weborder[%s]clientid[%s]clientname[%s]sotckno[%s]stockname[%s]'; nStr := Format(nStr,[editWebOrderNo.Text,EditCus.Text,EditCName.Text,EditStock.Text,EditSName.Text]); gSysLoger.AddLog(nStr+nMsg); end; procedure TfFormNewCard.AddListViewItem( var nWebOrderItem: stMallOrderItem); var nListItem:TListItem; begin nListItem := lvOrders.Items.Add; nlistitem.Caption := nWebOrderItem.FOrdernumber; nlistitem.SubItems.Add(nWebOrderItem.FGoodsID); nlistitem.SubItems.Add(nWebOrderItem.FGoodsname); nlistitem.SubItems.Add(nWebOrderItem.Ftracknumber); nlistitem.SubItems.Add(nWebOrderItem.FData); end; procedure TfFormNewCard.InitListView; var col:TListColumn; begin lvOrders.ViewStyle := vsReport; col := lvOrders.Columns.Add; col.Caption := '网上订单编号'; col.Width := 300; col := lvOrders.Columns.Add; col.Caption := '水泥型号'; col.Width := 200; col := lvOrders.Columns.Add; col.Caption := '水泥名称'; col.Width := 200; col := lvOrders.Columns.Add; col.Caption := '提货车辆'; col.Width := 200; col := lvOrders.Columns.Add; col.Caption := '办理吨数'; col.Width := 150; end; procedure TfFormNewCard.FormCreate(Sender: TObject); begin editWebOrderNo.Properties.MaxLength := gSysParam.FWebOrderLength; FCardData := TStringList.Create; FHdCardData := TStringList.Create; if not Assigned(FDR) then begin FDR := TFDR.Create(Application); end; InitListView; gSysParam.FUserID := 'AICM'; end; procedure TfFormNewCard.LoadSingleOrder; var nOrderItem:stMallOrderItem; nRepeat:Boolean; nWebOrderID:string; nMsg:string; begin FHdJiaoYan := False; nOrderItem := FWebOrderItems[FWebOrderIndex]; nWebOrderID := nOrderItem.FOrdernumber; FBegin := Now; nRepeat := IsRepeatCard(nWebOrderID); if nRepeat then begin nMsg := '此订单已成功办卡,请勿重复操作'; ShowMsg(nMsg,sHint); Writelog(nMsg); Exit; end; writelog('TfFormNewCard.LoadSingleOrder 检查商城订单是否重复使用-耗时:'+InttoStr(MilliSecondsBetween(Now, FBegin))+'ms'); //订单有效性校验 FBegin := Now; if not CheckYunTianOrderInfo(nOrderItem.FYunTianOrderId, nOrderItem) then begin BtnOK.Enabled := False; Exit; end; if (nOrderItem.FHd_Order_No <> '-1') and (Pos('袋',nOrderItem.FGoodsname) > 0) then begin if CheckYunTianOrderHdInfo(nOrderItem.FHd_Order_No, nOrderItem) then FHdJiaoYan := True; end; writelog('TfFormNewCard.LoadSingleOrder 订单有效性校验-耗时:'+InttoStr(MilliSecondsBetween(Now, FBegin))+'ms'); //填充界面信息 //基本信息 EditID.Text := FCardData.Values['XCB_ID']; EditCard.Text := FCardData.Values['XCB_CardId']; EditCus.Text := FCardData.Values['XCB_Client']; EditCName.Text := FCardData.Values['XCB_ClientName']; //提单信息 EditType.ItemIndex := 0; EditStock.Text := FCardData.Values['XCB_Cement']; EditSName.Text := FCardData.Values['XCB_CementName']; EditMax.Text := FCardData.Values['XCB_RemainNum']; EditValue.Text := nOrderItem.FData; EditTruck.Text := nOrderItem.Ftracknumber; EditHd.Text := nOrderItem.FHd_Order_No; EditHdValue.Text:= nOrderItem.Fspare; if gSysParam.FShuLiaoNeedBatchCode then begin FBegin := Now; if not do_YT_GetBatchCode(nOrderItem) then begin nMsg := '获取出厂编号失败。'; ShowMsg(nMsg,sHint); Writelog(nMsg); BtnOK.Enabled := False; Exit; end; writelog('TfFormNewCard.LoadSingleOrder 获取出厂编号-耗时:'+InttoStr(MilliSecondsBetween(Now, FBegin))+'ms'); EditFQ.Text := FCardData.Values['XCB_CementCode']; end; BtnOK.Enabled := not nRepeat; end; function TfFormNewCard.IsRepeatCard(const nWebOrderItem: string): Boolean; var nStr:string; begin Result := False; nStr := 'select * from %s where WOM_WebOrderID=''%s'' and WOM_deleted=''%s'''; nStr := Format(nStr,[sTable_WebOrderMatch,nWebOrderItem,sFlag_No]); with fdm.QueryTemp(nStr) do begin if RecordCount>0 then begin Result := True; end; end; end; function TfFormNewCard.CheckYunTianOrderInfo(const nOrderId: string; var nWebOrderItem: stMallOrderItem): Boolean; var nCardDataStr: string; nIn: TWorkerBusinessCommand; nOut: TWorkerBusinessCommand; nYuntianOrderItem:stMallOrderItem; nMsg:string; nOrderNumberWeb,nOrderNumberYT:Double; begin Result := False; FCardData.Clear; nCardDataStr := nOrderId; if not (YT_ReadCardInfo(nCardDataStr) and YT_VerifyCardInfo(nCardDataStr)) then begin ShowMsg(nCardDataStr,sHint); Writelog(nCardDataStr); Exit; end; FCardData.Text := PackerDecodeStr(nCardDataStr); nYuntianOrderItem.FGoodsID := FCardData.Values['XCB_Cement']; nYuntianOrderItem.FGoodsname := FCardData.Values['XCB_CementName']; nYuntianOrderItem.FOrdernumber := FCardData.Values['XCB_RemainNum']; nYuntianOrderItem.FCusID := FCardData.Values['XCB_Client']; nYuntianOrderItem.FCusName := FCardData.Values['XCB_ClientName']; if nWebOrderItem.FGoodsID<>nYuntianOrderItem.FGoodsID then begin nMsg := '商城订单中产品型号[%s]有误。'; nMsg := Format(nMsg,[nWebOrderItem.FGoodsID]); ShowMsg(nMsg,sError); Writelog(nMsg); Exit; end; if nWebOrderItem.FGoodsname<>nYuntianOrderItem.FGoodsname then begin nMsg := '商城订单中产品名称[%s]有误。'; nMsg := Format(nMsg,[nWebOrderItem.FGoodsname]); ShowMsg(nMsg,sError); Writelog(nMsg); Exit; end; nOrderNumberWeb := StrToFloatDef(nWebOrderItem.FData,0); nOrderNumberYT := StrToFloatDef(nYuntianOrderItem.FOrdernumber,0); if (nOrderNumberWeb<=0.00001) or (nOrderNumberYT<=0.00001) then begin nMsg := '订单中提货数量格式有误。'; ShowMsg(nMsg,sError); Writelog(nMsg); Exit; end; if nOrderNumberWeb-nOrderNumberYT>0.00001 then begin nMsg := '商城订单中提货数量有误,最多可提货数量为[%f]。'; nMsg := Format(nMsg,[nOrderNumberYT]); ShowMsg(nMsg,sError); Writelog(nMsg); Exit; end; Result := True; end; function TfFormNewCard.CheckYunTianOrderHdInfo(const nHdOrderId:string; var nWebOrderItem:stMallOrderItem):Boolean; var nCardDataStr: string; nIn: TWorkerBusinessCommand; nOut: TWorkerBusinessCommand; nYuntianOrderItem:stMallOrderItem; nMsg:string; nOrderNumberWeb,nOrderNumberYT:Double; begin Result := False; FHdCardData.Clear; nCardDataStr := nHdOrderId; if not (YT_ReadCardInfo(nCardDataStr) and YT_VerifyCardInfo(nCardDataStr)) then begin ShowMsg(nCardDataStr,sHint); Writelog(nCardDataStr); Exit; end; FHdCardData.Text := PackerDecodeStr(nCardDataStr); with nYuntianOrderItem, FHdCardData do begin FGoodsID := Values['XCB_Cement']; FGoodsname := Values['XCB_CementName']; FOrdernumber := Values['XCB_RemainNum']; FCusID := Values['XCB_Client']; FCusName := Values['XCB_ClientName']; end; if nWebOrderItem.FGoodsID<>nYuntianOrderItem.FGoodsID then begin nMsg := '商城订单中拼单产品型号[%s]有误。'; nMsg := Format(nMsg,[nWebOrderItem.FGoodsID]); ShowMsg(nMsg,sError); Writelog(nMsg); Exit; end; if nWebOrderItem.FGoodsname<>nYuntianOrderItem.FGoodsname then begin nMsg := '商城订单中拼单产品名称[%s]有误。'; nMsg := Format(nMsg,[nWebOrderItem.FGoodsname]); ShowMsg(nMsg,sError); Writelog(nMsg); Exit; end; nOrderNumberWeb := StrToFloatDef(nWebOrderItem.Fspare,0); nOrderNumberYT := StrToFloatDef(nYuntianOrderItem.FOrdernumber,0); if (nOrderNumberWeb<=0.00001) or (nOrderNumberYT<=0.00001) then begin nMsg := '订单中拼单提货数量格式有误。'; ShowMsg(nMsg,sError); Writelog(nMsg); Exit; end; if nOrderNumberWeb-nOrderNumberYT>0.00001 then begin nMsg := '商城订单中拼单提货数量有误,最多可提货数量为[%f]。'; nMsg := Format(nMsg,[nOrderNumberYT]); ShowMsg(nMsg,sError); Writelog(nMsg); Exit; end; Result := True; end; function TfFormNewCard.do_YT_GetBatchCode( const nWebOrderItem: stMallOrderItem): Boolean; var nInList,nOutList:TStrings; nData:string; nIdx:Integer; nCementRecords:TStrings; nCementRecordItem:TStrings; nCementValue,nOrderValue:Double; begin Result := False; nOrderValue := StrToFloat(nWebOrderItem.FData); nInList := TStringList.Create; nOutList := TStringList.Create; nCementRecords := TStringList.Create; nCementRecordItem := TStringList.Create; try nInList.Values['XCB_Cement'] := nWebOrderItem.FGoodsID; nInList.Values['Value'] := nWebOrderItem.FData; nOutList.Text := YT_GetBatchCode(nInList); if (nOutList.Values['XCB_CementCode']='') or (nOutList.Values['XCB_CementCodeID']='') then Exit; FCardData.Values['XCB_CementCode'] := nOutList.Values['XCB_CementCode']; FCardData.Values['XCB_CementCodeID'] := nOutList.Values['XCB_CementCodeID']; nCementRecords.Text := PackerDecodeStr(nOutList.Values['XCB_CementRecords']); for nIdx := 0 to nCementRecords.Count - 1 do begin nCementRecordItem.Text := PackerDecodeStr(nCementRecords[nIdx]); nCementValue := StrToFloatDef(nCementRecordItem.Values['XCB_CementValue'],0); if nCementValue-nOrderValue>0.00001 then begin FCardData.Values['XCB_CementCode'] := nCementRecordItem.Values['XCB_CementCode']; FCardData.Values['XCB_CementCodeID'] := nCementRecordItem.Values['XCB_CementCodeID']; Break; end; end; Result := True; finally nCementRecordItem.Free; nCementRecords.Free; nOutList.Free; nInList.Free; end; end; function TfFormNewCard.VerifyCtrl(Sender: TObject; var nHint: string): Boolean; var nVal: Double; begin Result := True; if Sender = EditTruck then begin Result := Length(EditTruck.Text) > 2; if not Result then begin nHint := '车牌号长度应大于2位'; Writelog(nHint); Exit; end; Result := TruckmultipleCard(EditTruck.Text,nHint); if not Result then begin Writelog(nHint); Exit; end; end; if Sender = EditValue then begin Result := IsNumber(EditValue.Text, True) and (StrToFloat(EditValue.Text)>0); if not Result then begin nHint := '请填写有效的办理量'; Writelog(nHint); Exit; end; nVal := StrToFloat(EditValue.Text); Result := FloatRelation(nVal, StrToFloat(EditMax.Text),rtLE); if not Result then begin nHint := '已超出可提货量'; Writelog(nHint); end; end; end; procedure TfFormNewCard.BtnOKClick(Sender: TObject); begin BtnOK.Enabled := False; try if not SaveBillProxy then Exit; Close; finally BtnOK.Enabled := True; end; end; function TfFormNewCard.SaveBillProxy: Boolean; var nHint:string; nList,nTmp,nStocks: TStrings; nPrint,nInFact:Boolean; nBillData:string; nBillID,nHdBillID :string; nWebOrderID:string; nNewCardNo:string; nidx:Integer; i,j:Integer; nRet: Boolean; begin Result := False; nWebOrderID := editWebOrderNo.Text; //校验提货单信息 if EditID.Text='' then begin ShowMsg('未查询网上订单',sHint); Writelog('未查询网上订单'); Exit; end; if not VerifyCtrl(EditTruck,nHint) then begin ShowMsg(nHint,sHint); Writelog(nHint); Exit; end; if not VerifyCtrl(EditValue,nHint) then begin ShowMsg(nHint,sHint); Writelog(nHint); Exit; end; if gSysParam.FShuLiaoNeedBatchCode then begin if EditFQ.Text='' then begin ShowMsg('出厂编号无效',sHint); Writelog('出厂编号无效'); Exit; end; end; if gSysParam.FCanCreateCard then begin nNewCardNo := ''; Fbegin := Now; //连续三次读卡均失败,则回收卡片,重新发卡 for i := 0 to 3 do begin for nIdx:=0 to 3 do begin if gMgrK720Reader.ReadCard(nNewCardNo) then Break; //连续三次读卡,成功则退出。 end; if nNewCardNo<>'' then Break; gMgrK720Reader.RecycleCard; end; if nNewCardNo = '' then begin ShowDlg('卡箱异常,请查看是否有卡.', sWarn, Self.Handle); Exit; end; Writelog('ReadCard: ' + nNewCardNo); nNewCardNo := gMgrK720Reader.ParseCardNO(nNewCardNo); WriteLog('ParseCardNO: ' + nNewCardNo); if nNewCardNo = '' then begin ShowDlg('卡号异常,解析失败.', sWarn, Self.Handle); Exit; end; //解析卡片 writelog('TfFormNewCard.SaveBillProxy 发卡机读卡-耗时:'+InttoStr(MilliSecondsBetween(Now, FBegin))+'ms'); end; //验证是否已经保存提货单 nRet := IFSaveBill(nWebOrderID, nBillID); //保存提货单 if not nRet then begin nStocks := TStringList.Create; nList := TStringList.Create; nTmp := TStringList.Create; try LoadSysDictItem(sFlag_PrintBill, nStocks); nTmp.Values['Type'] := FCardData.Values['XCB_CementType']; nTmp.Values['StockNO'] := FCardData.Values['XCB_Cement']; nTmp.Values['StockName'] := FCardData.Values['XCB_CementName']; nTmp.Values['Price'] := '0.00'; nTmp.Values['Value'] := EditValue.Text; nList.Add(PackerEncodeStr(nTmp.Text)); nPrint := nStocks.IndexOf(FCardData.Values['XCB_Cement']) >= 0; with nList do begin Values['Bills'] := PackerEncodeStr(nList.Text); Values['ZhiKa'] := PackerEncodeStr(FCardData.Text); Values['Truck'] := EditTruck.Text; Values['Lading'] := sFlag_TiHuo; Values['LineGroup'] := GetCtrlData(EditGroup); Values['Memo'] := EmptyStr; Values['IsVIP'] := Copy(GetCtrlData(EditType),1,1); Values['Seal'] := FCardData.Values['XCB_CementCodeID']; Values['HYDan'] := EditFQ.Text; Values['WebOrderID'] := nWebOrderID; Values['HdOrderId'] := EditHd.Text; if PrintFH.Checked then Values['PrintFH'] := sFlag_Yes; end; nBillData := PackerEncodeStr(nList.Text); FBegin := Now; nBillID := SaveBill(nBillData); if nBillID = '' then Exit; writelog('TfFormNewCard.SaveBillProxy 生成提货单['+nBillID+']-耗时:'+InttoStr(MilliSecondsBetween(Now, FBegin))+'ms'); FBegin := Now; SaveWebOrderMatch(nBillID,nWebOrderID); writelog('TfFormNewCard.SaveBillProxy 保存商城订单号-耗时:'+InttoStr(MilliSecondsBetween(Now, FBegin))+'ms'); finally nStocks.Free; nList.Free; nTmp.Free; end; end; nRet := SaveBillCard(nBillID,nNewCardNo); ShowMsg('提货单保存成功', sHint); FBegin := Now; if nRet then begin nRet := False; for nIdx := 0 to 3 do begin nRet := gMgrK720Reader.SendReaderCmd('FC0'); if nRet then Break; end; //发卡 end; if nRet then begin nHint := '商城订单号['+editWebOrderNo.Text+']发卡成功,卡号['+nNewCardNo+'],请收好您的卡片'; WriteLog(nHint); ShowMsg(nHint,sWarn); end else begin gMgrK720Reader.RecycleCard; nHint := '商城订单号['+editWebOrderNo.Text+'],卡号['+nNewCardNo+']关联订单失败,请到开票窗口重新关联。'; WriteLog(nHint); ShowDlg(nHint,sHint,Self.Handle); Close; end; writelog('TfFormNewCard.SaveBillProxy 发卡机出卡并关联磁卡号-耗时:'+InttoStr(MilliSecondsBetween(Now, FBegin))+'ms'); if FHdJiaoYan then begin nStocks := TStringList.Create; nList := TStringList.Create; nTmp := TStringList.Create; try LoadSysDictItem(sFlag_PrintBill, nStocks); nTmp.Values['Type'] := FHdCardData.Values['XCB_CementType']; nTmp.Values['StockNO'] := FHdCardData.Values['XCB_Cement']; nTmp.Values['StockName'] := FHdCardData.Values['XCB_CementName']; nTmp.Values['Price'] := '0.00'; nTmp.Values['Value'] := EditHdValue.Text; nList.Add(PackerEncodeStr(nTmp.Text)); nPrint := nStocks.IndexOf(FHdCardData.Values['XCB_Cement']) >= 0; with nList do begin Values['Bills'] := PackerEncodeStr(nList.Text); Values['ZhiKa'] := PackerEncodeStr(FHdCardData.Text); Values['Truck'] := EditTruck.Text; Values['Lading'] := sFlag_TiHuo; Values['LineGroup'] := GetCtrlData(EditGroup); Values['Memo'] := EmptyStr; Values['IsVIP'] := Copy(GetCtrlData(EditType),1,1); Values['Seal'] := FHdCardData.Values['XCB_CementCodeID']; Values['HYDan'] := EditFQ.Text; Values['WebOrderID'] := nWebOrderID; if PrintFH.Checked then Values['PrintFH'] := sFlag_Yes; end; nBillData := PackerEncodeStr(nList.Text); FBegin := Now; nHdBillID := SaveBill(nBillData); if nHdBillID = '' then Exit; writelog('TfFormNewCard.SaveBillProxy 生成拼单提货单['+nHdBillID+']-耗时:'+InttoStr(MilliSecondsBetween(Now, FBegin))+'ms'); FBegin := Now; SaveWebOrderMatch(nHdBillID,nWebOrderID); writelog('TfFormNewCard.SaveBillProxy 保存商城订单号-耗时:'+InttoStr(MilliSecondsBetween(Now, FBegin))+'ms'); finally nStocks.Free; nList.Free; nTmp.Free; end; if SaveBillCard(nHdBillID,nNewCardNo) then begin ShowMsg('拼单提货单关联磁卡成功', sHint); Writelog('拼单提货单[' + nHdBillID +'关联磁卡号[' + nNewCardNo +']成功'); end else begin ShowMsg('拼单提货单关联磁卡失败', sHint); Writelog('拼单提货单[' + nHdBillID +'关联磁卡号[' + nNewCardNo +']失败'); end; end; if nPrint then PrintBillReport(nBillID, True); //print report if IFPrintFYD then PrintBillFYDReport(nBillID, True); if nRet then Close; end; function TfFormNewCard.SaveWebOrderMatch(const nBillID, nWebOrderID: string):Boolean; var nStr:string; begin Result := False; nStr := 'insert into %s(WOM_WebOrderID,WOM_LID) values(''%s'',''%s'')'; nStr := Format(nStr,[sTable_WebOrderMatch,nWebOrderID,nBillID]); fdm.ADOConn.BeginTrans; try fdm.ExecuteSQL(nStr); fdm.ADOConn.CommitTrans; Result := True; except fdm.ADOConn.RollbackTrans; end; end; procedure TfFormNewCard.lvOrdersClick(Sender: TObject); var nSelItem:TListItem; i:Integer; begin if (GetTickCount - FLastClick < 3 * 1000) then begin ShowMsg('请不要频繁点击!', sHint); Exit; end; nSelItem := lvorders.Selected; if Assigned(nSelItem) then begin for i := 0 to lvOrders.Items.Count-1 do begin if nSelItem = lvOrders.Items[i] then begin FWebOrderIndex := i; LoadSingleOrder; Break; end; end; end; FLastClick := GetTickCount; end; procedure TfFormNewCard.editWebOrderNoKeyPress(Sender: TObject; var Key: Char); begin FAutoClose := gSysParam.FAutoClose_Mintue; if Key=Char(vk_return) then begin key := #0; btnQuery.SetFocus; btnQuery.Click; end; end; procedure TfFormNewCard.btnClearClick(Sender: TObject); begin FAutoClose := gSysParam.FAutoClose_Mintue; editWebOrderNo.Clear; ActiveControl := editWebOrderNo; end; end.
unit fVolumeY; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.Math, Vcl.Clipbrd, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Menus, Vcl.StdCtrls, Vcl.Buttons, Vcl.ComCtrls, Vcl.ExtCtrls; type TVolumeYForm = class(TForm) Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label1: TLabel; Label2: TLabel; Label7: TLabel; Label8: TLabel; PositiveButton: TSpeedButton; NegativeButton: TSpeedButton; TotalVolumeLabel: TLabel; EditIntegMin: TEdit; EditIntegMax: TEdit; EditCount: TEdit; UpDown1: TUpDown; EditOpacity: TEdit; UpDown2: TUpDown; RecalcBtn: TBitBtn; CloseBtn: TBitBtn; KeepRangeCheckBox: TCheckBox; ColorDialog: TColorDialog; HideFunctionCheckBox: TCheckBox; PositivePanel: TPanel; NegativePanel: TPanel; SurfaceAreaLabel: TLabel; procedure FormShow(Sender: TObject); procedure FormActivate(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure FormDeactivate(Sender: TObject); procedure ParseKeyPress(Sender: TObject; var Key: Char); procedure IntKeyPress(Sender: TObject; var Key: Char); procedure EditIntegMinKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditIntegMaxKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditCountKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditOpacityKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure UpDown1Click(Sender: TObject; Button: TUDBtnType); procedure UpDown2Click(Sender: TObject; Button: TUDBtnType); procedure UpDown1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure PositiveButtonClick(Sender: TObject); procedure NegativeButtonClick(Sender: TObject); procedure RecalcBtnClick(Sender: TObject); procedure IntegLabelClick(Sender: TObject); procedure KeepRangeCheckBoxClick(Sender: TObject); procedure CloseBtnClick(Sender: TObject); procedure HideFunctionCheckBoxClick(Sender: TObject); private procedure UpdateRangeData; public procedure ShowData; end; var VolumeYForm: TVolumeYForm; //================================================================= implementation //================================================================= uses uParser, uGlobal, fFuncts, fMain; {$R *.dfm} procedure TVolumeYForm.FormShow(Sender: TObject); begin KeepRangeCheckBox.Checked := KeepRange; ShowData; end; procedure TVolumeYForm.HideFunctionCheckBoxClick(Sender: TObject); begin MainForm.GLViewer.Invalidate; end; procedure TVolumeYForm.FormActivate(Sender: TObject); begin EditIntegMin.SetFocus; EditIntegMin.SelText; end; procedure TVolumeYForm.FormKeyPress(Sender: TObject; var Key: Char); begin case Key of #13:begin RecalcBtnClick(Sender); Key := #0; end; #27:begin Key := #0; Close; end; end; end; procedure TVolumeYForm.FormDeactivate(Sender: TObject); begin if KeepRange then UpdateRangeData; end; procedure TVolumeYForm.ParseKeyPress(Sender: TObject; var Key: Char); begin with Sender as TEdit do begin if not CharInSet(UpCase(Key), [' ', '!', '(', ')', '*', '+', '-', '.', ',', '/', '0'..'9', 'A'..'C', 'E', 'G'..'I', 'L', 'N'..'T', 'X', '^', '`', #8]) then begin Key := #0; Exit; end; if Key = '`' then Key := '°'; end; end; procedure TVolumeYForm.RecalcBtnClick(Sender: TObject); begin MainForm.GLViewer.Invalidate; end; procedure TVolumeYForm.IntegLabelClick(Sender: TObject); begin Clipboard.Clear; with Sender as TLabel do Clipboard.AsText := Copy(Caption, pos('=', Caption)+2, Length(Caption)); end; procedure TVolumeYForm.IntKeyPress(Sender: TObject; var Key: Char); begin with Sender as TEdit do if not CharInSet(Key, ['0'..'9', #8]) then Key := #0 end; procedure TVolumeYForm.KeepRangeCheckBoxClick(Sender: TObject); begin KeepRange := KeepRangeCheckBox.Checked; end; procedure TVolumeYForm.NegativeButtonClick(Sender: TObject); begin ColorDialog.Color := GraphData.NegAreaColor; if ColorDialog.Execute then begin GraphData.NegAreaColor := ColorDialog.Color; NegativePanel.Color := GraphData.NegAreaColor; MainForm.GLViewer.Invalidate; Altered := TRUE end; end; procedure TVolumeYForm.PositiveButtonClick(Sender: TObject); begin ColorDialog.Color := GraphData.PosAreaColor; if ColorDialog.Execute then begin GraphData.PosAreaColor := ColorDialog.Color; PositivePanel.Color := GraphData.PosAreaColor; MainForm.GLViewer.Invalidate; Altered := TRUE end; end; procedure TVolumeYForm.UpDown1Click(Sender: TObject; Button: TUDBtnType); var k: word; begin k := 0; EditCountKeyUp(Sender, k, []); end; procedure TVolumeYForm.UpDown1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin RecalcBtnClick(Sender); end; procedure TVolumeYForm.UpDown2Click(Sender: TObject; Button: TUDBtnType); var k: word; begin k := 0; EditOpacityKeyUp(Sender, k, []); end; procedure TVolumeYForm.EditIntegMinKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var s: string; e: byte; begin s := ScanText(EditIntegMin.Text); IntegMin := ParseAndEvaluate(s, e); //if isNAN(IntegMin) then IntegMin := 0; //if e > 0 then IntegMin := 0; if isNAN(IntegMin) or isInfinite(IntegMin) or (e > 0) then IntegMin := 0; end; procedure TVolumeYForm.EditIntegMaxKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var s: string; e: byte; begin s := ScanText(EditIntegMax.Text); IntegMax := ParseAndEvaluate(s, e); //if isNAN(IntegMax) then IntegMax := 0; //if e > 0 then IntegMax := 0; if isNAN(IntegMax) or isInfinite(IntegMax) or (e > 0) then IntegMax := 0; end; procedure TVolumeYForm.CloseBtnClick(Sender: TObject); begin Close; end; procedure TVolumeYForm.EditCountKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin with GraphData do begin try IntegCount := StrToInt(EditCount.Text); if IntegCount = 0 then IntegCount := IntegCountPos; except IntegCount := IntegCountPos; end; if IntegCount > IntegCountMax then IntegCount := IntegCountMax; end; Altered := true; end; procedure TVolumeYForm.EditOpacityKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var n: integer; begin try n := StrToInt(EditOpacity.Text); except n := 1; end; GraphData.AreaAlpha := n/100; Altered := true; MainForm.GLViewer.Invalidate; end; procedure TVolumeYForm.UpdateRangeData; begin KeptMin := IntegMin; KeptMax := IntegMax; end; procedure TVolumeYForm.ShowData; begin with GraphData, PlotData do begin EditCount.Text := IntToStr(IntegCount); UpDown2.Position := round(AreaAlpha*100); if TextStr = '' then Caption := '' else Caption := 'y = '+TextStr; KeepRangeCheckBox.Checked := KeepRange; PositivePanel.Color := PosAreaColor; NegativePanel.Color := NegAreaColor; if IsSegment then begin if KeepRange then begin IntegMin := KeptMin; IntegMax := KeptMax; end else begin IntegMin := SegMin; IntegMax := SegMax; end; end else begin if KeepRange then begin IntegMin := KeptMin; IntegMax := KeptMax; end else begin IntegMin := xMin; IntegMax := xMax; end; end; end; EditIntegMin.Text := FloatToStrF(IntegMin, ffGeneral, 13, 4); EditIntegMax.Text := FloatToStrF(IntegMax, ffGeneral, 13, 4); end; end.
unit BalancedTree; { Taken from Nicklaus Wirth : Algorithmen und Datenstrukturen ( in Pascal ) Balanced Binary Trees p 250 ++ Fixed By Giacomo Policicchio pgiacomo@tiscalinet.it 19/05/2000 Modifications by Wakan project, http://code.google.com/p/wakan/ } interface uses Classes; type TBinTreeItem = class(TObject) private count:integer; left,right:TBinTreeItem; bal:-1..1; public constructor Create; // a < self :-1 a=self :0 a > self :+1 function CompareData(const a):Integer; virtual; abstract; function Compare(a:TBinTreeItem):Integer; virtual; abstract; procedure Copy(ToA:TBinTreeItem); virtual; abstract; // data end; TBinTreeEnumerator = record FStack: array of TBinTreeItem; FStackUsed: integer; FBOF: boolean; procedure ResetEmpty; overload; procedure Reset(const ARoot: TBinTreeItem); overload; procedure Push(const AItem: TBinTreeItem); function Pop: TBinTreeItem; function GetCurrent: TBinTreeItem; function MoveNext: boolean; property Current: TBinTreeItem read GetCurrent; end; TBinTree=class(TPersistent) private root:TBinTreeItem; procedure Delete(item:TBinTreeItem;var p:TBinTreeItem;var h:boolean;var ok:boolean); function SearchAndInsert(item:TBinTreeItem;var p:TBinTreeItem;var h:boolean): TBinTreeItem; procedure balanceLeft(var p:TBinTreeItem;var h:boolean;dl:boolean); procedure balanceRight(var p:TBinTreeItem;var h:boolean;dl:boolean); public constructor Create; destructor Destroy; override; procedure Clear; function Add(item:TBinTreeItem):boolean; function AddOrSearch(item:TBinTreeItem):TBinTreeItem; function Remove(item:TBinTreeItem):boolean; function Search(item:TBinTreeItem):boolean; function SearchItem(const item:TBinTreeItem):TBinTreeItem; function SearchData(const data):TBinTreeItem; function GetEnumerator: TBinTreeEnumerator; end; implementation constructor TBinTreeItem.Create; begin inherited create; count:=0; end; procedure TBinTreeEnumerator.ResetEmpty; begin FStackUsed := 0; FBOF := true; end; procedure TBinTreeEnumerator.Reset(const ARoot: TBinTreeItem); begin if ARoot=nil then begin ResetEmpty; exit; end; if Length(FStack)<1 then SetLength(FStack, 4); FStack[0] := ARoot; FStackUsed := 1; FBOF := true; end; procedure TBinTreeEnumerator.Push(const AItem: TBinTreeItem); begin if FStackUsed>=Length(FStack) then SetLength(FStack, Length(FStack)*2+1); FStack[FStackUsed] := AItem; Inc(FStackUsed); end; function TBinTreeEnumerator.Pop: TBinTreeItem; begin if FStackUsed<=0 then begin Result := nil; exit; end; Dec(FStackUsed); Result := FStack[FStackUsed]; end; function TBinTreeEnumerator.GetCurrent: TBinTreeItem; begin if FStackUsed<=0 then Result := nil else Result := FStack[FStackUsed-1]; end; function TBinTreeEnumerator.MoveNext: boolean; var item: TBinTreeItem; begin if FStackUsed=0 then //no entries left Result := false else if FBOF then begin //Move to the leftmost node or remain on this one while Current.left<>nil do Push(Current.left); FBOF := false; Result := true; end else if Current.right<>nil then begin Push(Current.right); while Current.left<>nil do Push(Current.left); Result := true; end else begin repeat item := Pop(); until (Current=nil) or (item=Current.left); //search for the first parent where we were on the left subtree if Current=nil then Result := false else Result := true; end; end; constructor TBinTree.Create; begin inherited create; root:=nil; end; destructor TBinTree.Destroy; begin Clear; inherited destroy; end; procedure TBinTree.Clear; begin //Pretty stupid for a Clear(), we can do better. while root <> nil do remove(root); end; //Tries to locate identical item in the tree, or inserts the given item. //Returns the item located or the item inserted => if (Result==item) then Added else Found. function TBinTree.SearchAndInsert(item:TBinTreeItem;var p:TBinTreeItem;var h:boolean): TBinTreeItem; var cmp: integer; begin if p=nil then begin // word not in tree, insert it p:=item; p.count:=1; p.left:=nil; p.right:=nil; p.bal:=0; if root=nil then root:=p; Result:=p; h:=true; exit; end; cmp := item.compare(p); if cmp > 0 then // new < current begin Result := searchAndInsert(item,p.left,h); if h and (Result=item) then BalanceLeft(p,h,false); end else if cmp < 0 then // new > current begin Result := searchAndInsert(item,p.right,h); if h and (Result=item) then balanceRight(p,h,false); end else begin p.count:=p.count+1; h:=false; Result:=p; end; end; //searchAndInsert // returns a pointer to the equal item if found, nil otherwise function TBinTree.SearchItem(const item:TBinTreeItem):TBinTreeItem; var i: integer; begin Result := root; while Result<>nil do begin i := Result.Compare(item); if i=0 then exit else if i>0 then //item > Result Result := Result.right else //item < Result Result := Result.left; end; end; //Same but by Data (your BinTreeItems must support CompareData) function TBinTree.SearchData(const data):TBinTreeItem; var i: integer; begin Result := root; while Result<>nil do begin i := Result.CompareData(data); if i=0 then exit else if i>0 then //item > Result Result := Result.right else //item < Result Result := Result.left; end; end; function TBinTree.GetEnumerator: TBinTreeEnumerator; begin Result.Reset(root); end; procedure TBinTree.balanceRight(var p:TBinTreeItem;var h:boolean;Dl:boolean); var p1,p2:TBinTreeItem; Begin case p.bal of -1:begin p.bal:=0; if not dl then h:=false; end; 0: begin p.bal:=+1; if dl then h:=false; end; +1:begin // new balancing p1:=p.right; if (p1.bal=+1) or ((p1.bal=0) and dl) then begin // single rr rotation p.right:=p1.left; p1.left:=p; if not dl then p.bal:=0 else begin if p1.bal=0 then begin p.bal:=+1; p1.bal:=-1; h:=false; end else begin p.bal:=0; p1.bal:=0; (* h:=false; *) end; end; p:=p1; end else begin // double rl rotation p2:=p1.left; p1.left:=p2.right; p2.right:=p1; p.right:=p2.left; p2.left:=p; if p2.bal=+1 then p.bal:=-1 else p.bal:=0; if p2.bal=-1 then p1.bal:=+1 else p1.bal:=0; p:=p2; if dl then p2.bal:=0; end; if not dl then begin p.bal:=0; h:=false; end; end; end; // case End; procedure TBinTree.balanceLeft(var p:TBinTreeItem;var h:boolean;dl:boolean); var p1,p2:TBinTreeItem; Begin case p.bal of 1:begin p.bal:=0; if not dl then h:=false; end; 0:begin p.bal:=-1; if dl then h:=false; end; -1:(* if (p.Left<>nil) or not dl then *) begin // new balancing p1:=p.left; if (p1.bal=-1) or ((p1.bal=0) and dl) then begin // single ll rotation p.left:=p1.right;p1.right:=p; if not dl then p.bal:=0 else begin if p1.bal=0 then begin p.bal:=-1; p1.bal:=+1; h:=false; end else begin p.bal:=0; p1.bal:=0; (* h:=false; *) end; end; p:=p1; end else begin //double lr rotation p2:=p1.right; P1.Right:=p2.left; p2.left:=p1; p.left:=p2.right; p2.right:=p; if p2.bal=-1 then p.bal:=+1 else p.bal:=0; if p2.bal=+1 then p1.bal:=-1 else p1.bal:=0; p:=p2;if dl then p2.bal:=0; end; if not dl then begin p.bal:=0; h:=false; end; end; { -1 } end; { case } End; procedure TBinTree.Delete(item:TBinTreeItem;var p:TBinTreeItem;var h:boolean;var ok:boolean); var q:TBinTreeItem; //h=false; procedure del(var r:TBinTreeItem;var h:boolean); begin //h=false if r.right <> nil then begin del(r.right,h); if h then balanceLeft(r,h,True); end else begin r.copy(q); { q.key:=r.key; } q.count:=r.count; q:=r; r:=r.left;h:=true; end; end; begin { main of delete } ok:=true; if (p=nil) then begin Ok:=false;h:=false; end else if (item.compare(p) > 0){(x < p^.key)} then begin delete(item,p.left,h,ok); if h then balanceRight(p,h,True); end else if (item.compare(p) < 0){(x > p^.key)}then begin delete(item,p.right,h,ok); if h then balanceLeft(p,h,True); end else begin // remove q q:=p; if q.right=nil then begin p:=q.left;h:=true; end else if (q.left=nil) then begin p:=q.right;h:=true; end else begin del(q.left,h); if h then balanceRight(p,h,True); end; q.free; {dispose(q)}; end; end; { delete } //Returns true if the item was added, false if an identical one existed. function TBinTree.Add(item:TBinTreeItem):boolean; var h:boolean; begin Result:=SearchAndInsert(item,root,h)=item; end; //Same, but returns the item found or added function TBinTree.AddOrSearch(item:TBinTreeItem):TBinTreeItem; var h:boolean; begin Result:=SearchAndInsert(item,root,h); end; function TBinTree.Remove(item:TBinTreeItem):Boolean; var h,ok:boolean; begin Delete(item,root,h,ok); Result:=ok; end; function TBinTree.Search(item:TBinTreeItem):Boolean; begin Result:=SearchItem(item)<>nil; end; end.
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Program: EMULVT.PAS Description: Delphi component which does Ansi terminal emulation Not every escape sequence is implemented, but a large subset. Author: Fran鏾is PIETTE Creation: May, 1996 Version: 2.17 EMail: http://www.overbyte.be francois.piette@overbyte.be http://www.rtfm.be/fpiette francois.piette@rtfm.be francois.piette@pophost.eunet.be Support: Use the mailing list twsocket@elists.org Follow "support" link at http://www.overbyte.be for subscription. Legal issues: Copyright (C) 1997-2001 by Fran鏾is PIETTE Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56 <francois.piette@overbyte.be><francois.piette@pophost.eunet.be> This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. 4. You must register this software by sending a picture postcard to the author. Use a nice stamp and mention your name, street address, EMail address and any comment you like to say. Updates: Jul 22, 1997 Some optimization Adapted to Delphi 3 Sep 05, 1997 Version 2.01 Dec 16, 1997 V2.02 Corrected a bug int the paint routine which caused GDI resource leak when color was used. Feb 24, 1998 V2.03 Added AddFKey function Jul 15, 1998 V2.04 Adapted to Delphi 4 (moved DoKeyBuffer to protected section) Dec 04, 1998 V2.05 Added 'single char paint' and 'char zoom' features. Dec 09, 1998 V2.10 Added graphic char drawing using graphic primitives Added (with permission) scroll back code developed by Steve Endicott <s_endicott@compuserve.com> Dec 21, 1998 V2.11 Corrected some screen update problems related to scrollback. Added fixes from Steve Endicott. Beautified code. Mar 14, 1999 V2.12 Added OnKeyDown event. Corrected a missing band at right of screen when painting. Aug 15, 1999 V2.13 Moved KeyPress procedure to public section for BCB4 compat. Aug 20, 1999 V2.14 Added compile time options. Revised for BCB4. Nov 12, 1999 V2.15 Corrected display attribute error in delete line. Checked for range in SetLines/GetLine Aug 09, 2000 V2.16 Wilfried Mestdagh" <wilfried_sonal@compuserve.com> and Steve Endicott <s_endicott@compuserve.com> corrected a bug related to scroll back buffer. See WM + SE 09/08/00 tags in code. Jul 28, 2001 V2.17 Made FCharPos and FLinePos member variables instead of global to avoid conflict when sevaral components are used simultaneously. Suggested by Jeroen Cranendonk <j.p.cranendonk@student.utwente.nl> Nov 2, 2001 Chinese Input Output support,PaintOneLine, SingleCharPaint VScrollBar divide out as a property InvertRect Selection, WMPaint Url Link Support, new X_UNDERLINE attr PixelToRow, PixelToCol bug fixed TLine.Att change from BYTE -> WORD Nov 9, 2001 NeedBlink function to reduce blink TSelectMode(smBlock, smLine) AppMessageHandler: F10 is a WM_SYSKEYDOWN X_CODEPAGE2 attr -> '#27(0' '#27(B' Graphic Char, Xlat restore support TScreen.ProcessESC_D support * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} unit emulvt; {$B-} { Enable partial boolean evaluation } {$T-} { Untyped pointers } {$X+} { Enable extended syntax } {$IFNDEF VER80} { Not for Delphi 1 } {$H+} { Use long strings } {$J+} { Allow typed constant to be modified } {$ENDIF} {$IFDEF VER110} { C++ Builder V3.0 } {$ObjExportAll On} {$ENDIF} {$IFDEF VER125} { C++ Builder V4.0 } {$ObjExportAll On} {$ENDIF} interface {-$DEFINE SINGLE_CHAR_PAINT} {$DEFINE CHAR_ZOOM} uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ClipBrd; const EmulVTVersion = 217; CopyRight: string = ' TEmulVT (c) 1996-2000 F. Piette V2.17 '; MAX_ROW = 50; MAX_COL = 132; MAX_BACKROW = 8142; RightMargin = 3; BottomMargin = 2; NumPaletteEntries = 16; type TBackColors = (vtsBlack, vtsRed, vtsGreen, vtsYellow, vtsBlue, vtsMagenta, vtsCyan, vtsWhite); TCaretType = (ctBLine, ctBlock, ctBeam); TSelectMode = (smBlock, smLine); TScreenOption = (vtoBackColor, vtoCopyBackOnClear); TScreenOptions = set of TScreenOption; TXlatTable = array [0..255] of char; PXlatTable = ^TXlatTable; TFuncKeyValue = string[30]; PFuncKeyValue = ^TFuncKeyValue; TFuncAction = (faSend, faMenu); TFuncKey = record ScanCode: char; Shift: TShiftState; Ext: boolean; Act: TFuncAction; Value: TFuncKeyValue; end; TFuncKeysTable = array [0..63] of TFuncKey; PFuncKeysTable = ^TFuncKeysTable; TKeyBufferEvent = procedure(Sender: TObject; Buffer: PChar; Len: integer) of object; TKeyDownEvent = procedure(Sender: TObject; var VirtKey: integer; var Shift: TShiftState; var ShiftLock: boolean; var ScanCode: char; var Ext: boolean) of object; TFuncActionEvent = procedure(Sender: TObject; AFuncKey: TFuncKey) of object; type { TLine is an object used to hold one line of text on screen } TLine = class(TObject) public Txt: array [0..MAX_COL] of char; Att: array [0..MAX_COL] of word; constructor Create; procedure Clear(Attr: word); end; TLineArray = array [0..8192] of TLine; PLineArray = ^TLineArray; { TScreen is an object to hold an entire screen of line and handle } { Ansi escape sequences to update this virtual screen } TScreen = class(TObject) public FLines: PLineArray; FRow: integer; FCol: integer; FRowSaved: integer; FColSaved: integer; FScrollRowTop: integer; FScrollRowBottom: integer; FAttribute: word; FForceHighBit: boolean; FReverseVideo: boolean; FUnderLine: boolean; FRowCount: integer; FColCount: integer; FBackRowCount: integer; FBackEndRow: integer; FBackColor: TColor; FOptions: TScreenOptions; FEscBuffer: string[80]; FEscFlag: boolean; Focused: boolean; FAutoLF: boolean; FAutoCR: boolean; FAutoWrap: boolean; FCursorOff: boolean; FCKeyMode: boolean; FNoXlat: boolean; FNoXlatInitial: boolean; FCntLiteral: integer; FCodePage: integer;{fuse +} FCarbonMode: boolean; FXlatInputTable: PXlatTable; FXlatOutputTable: PXlatTable; FCharSetG0: char; FCharSetG1: char; FCharSetG2: char; FCharSetG3: char; FAllInvalid: boolean; FInvRect: TRect; FXtermMouse: boolean; {fuse +} FDefaultHighlight: boolean; {fuse +} FOnCursorVisible: TNotifyEvent; FOnBeepChar: TNotifyEvent; constructor Create; destructor Destroy; override; procedure AdjustFLines(NewCount: integer); procedure CopyScreenToBack; procedure SetRowCount(NewCount: integer); procedure SetBackRowCount(NewCount: integer); procedure InvRect(nRow, nCol: integer); procedure InvClear; procedure SetLines(I: integer; Value: TLine); function GetLines(I: integer): TLine; procedure WriteChar(Ch: char); procedure WriteStr(Str: string); function ReadStr: string; procedure GotoXY(X, Y: integer); procedure WriteLiteralChar(Ch: char); procedure ProcessEscape(EscCmd: char); procedure SetAttr(Att: char); procedure CursorRight; procedure CursorLeft; procedure CursorDown; procedure CursorUp; procedure CarriageReturn; procedure ScrollUp; procedure ScrollDown; procedure ClearScreen; procedure BackSpace; procedure Eol; procedure Eop; procedure ProcessESC_D; { Index } procedure ProcessESC_M; { Reverse index } procedure ProcessESC_E; { Next line } procedure ProcessCSI_u; { Restore Cursor } procedure ProcessCSI_I; { Select IBM char set } procedure ProcessCSI_J; { Clear the screen } procedure ProcessCSI_K; { Erase to End of Line } procedure ProcessCSI_L; { Insert Line } procedure ProcessCSI_M; { Delete Line } procedure ProcessCSI_m_lc; { Select Attributes } procedure ProcessCSI_n_lc; { Cursor position report } procedure ProcessCSI_at; { Insert character } procedure ProcessCSI_r_lc; { Scrolling margins } procedure ProcessCSI_s_lc; { Save cursor location } procedure ProcessCSI_u_lc; { Restore cursor location } procedure ProcessCSI_7; { Save cursor location } procedure ProcessCSI_8; { Restore cursor location } procedure ProcessCSI_H; { Set Cursor Position } procedure ProcessCSI_h_lc; { Terminal mode set } procedure ProcessCSI_l_lc; { Terminal mode reset } procedure ProcessCSI_A; { Cursor Up } procedure ProcessCSI_B; { Cursor Down } procedure ProcessCSI_C; { Cursor Right } procedure ProcessCSI_D; { Cursor Left } procedure ProcessCSI_d_lc; { set vertical posn } procedure ProcessCSI_E; { move down N lines and CR } procedure ProcessCSI_F; { move up N lines and CR } procedure ProcessCSI_G; { set horizontal posn } procedure ProcessCSI_P; { Delete Character } procedure ProcessCSI_S; { Scroll up } procedure ProcessCSI_T; { Scroll down } procedure ProcessCSI_X; { write N spaces w/o moving cursor } procedure process_charset_G0(EscCmd: char);{ G0 character set } procedure process_charset_G1(EscCmd: char);{ G1 character set } procedure process_charset_G2(EscCmd: char);{ G2 character set } procedure process_charset_G3(EscCmd: char);{ G3 character set } procedure UnimplementedEscape(EscCmd: char); procedure InvalidEscape(EscCmd: char); function GetEscapeParam(From: integer; var Value: integer): integer; property OnCursorVisible: TNotifyEvent read FonCursorVisible write FOnCursorVisible; property Lines[I: integer]: TLine read GetLines write SetLines; property OnBeepChar: TNotifyEvent read FOnBeepChar write FOnBeepChar; end; { TCustomEmulVT is an visual component wich does the actual display } { of a TScreen object wich is the virtual screen } { No property is published. See TEmulVT class } TCustomEmulVT = class(TCustomControl) private FFileHandle: TextFile; FCursorVisible: boolean; FCaretShown: boolean; FCaretCreated: boolean; FLineHeight: integer; FLineZoom: single; FCharWidth: integer; FCharZoom: single; FGraphicDraw: boolean; FInternalLeading: integer; FBorderStyle: TBorderStyle; FBorderWidth: integer; FAutoRepaint: boolean; FFont: TFont; FVScrollBar: TScrollBar; FTopLine: integer; FLocalEcho: boolean; FOnKeyBuffer: TKeyBufferEvent; FOnKeyDown: TKeyDownEvent; FFKeys: integer; FMonoChrome: boolean; FLog: boolean; FAppOnMessage: TMessageEvent; FFlagCirconflexe: boolean; FFlagTrema: boolean; FSelectRect: TRect; {fuse + } FNoScrollBar: boolean; FParseURL: boolean; FCaretType: TCaretType; FSelectMode: TSelectMode; FLastKeyinTime: TDateTime; FFuncAction: TFuncActionEvent; FReverseFG, FReverseBG: TColor; FSavePenColor: TColor; FSaveBrushColor: TColor; FSINGLE_CHAR_PAINT: boolean; xTextTemp: integer; {fuse + end} FPal: HPalette; FPaletteEntries: array[0..NumPaletteEntries - 1] of TPaletteEntry; procedure WMPaint(var Message: TWMPaint); message WM_PAINT; procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND; procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS; procedure WMKillFocus(var Message: TWMKillFocus); message WM_KILLFOCUS; procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN; procedure WMPaletteChanged(var Message: TMessage); message WM_PALETTECHANGED; procedure VScrollBarScroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: integer); procedure SetCaret; procedure AdjustScrollBar; function ProcessFKeys(ScanCode: char; Shift: TShiftState; Ext: boolean): boolean; function FindFKeys(ScanCode: char; Shift: TShiftState; Ext: boolean): PFuncKeyValue; procedure CursorVisibleEvent(Sender: TObject); procedure SetFont(Value: TFont); procedure SetAutoLF(Value: boolean); procedure SetAutoCR(Value: boolean); procedure SetXlat(Value: boolean); procedure SetLog(Value: boolean); procedure SetRows(Value: integer); procedure SetCols(Value: integer); procedure SetBackRows(Value: integer); procedure SetTopLine(Value: integer); procedure SetBackColor(Value: TColor); procedure SetOptions(Value: TScreenOptions); procedure SetLineHeight(Value: integer); function GetAutoLF: boolean; function GetAutoCR: boolean; function GetXlat: boolean; function GetRows: integer; function GetCols: integer; function GetBackRows: integer; function GetBackColor: TColor; function GetOptions: TScreenOptions; {fuse +} function GetDefaultHighlight: boolean; procedure SetDefaultHighlight(Value: boolean); {fuse -} protected FCharPos: array [0..MAX_COL + 1] of integer; FLinePos: array [0..MAX_ROW + 1] of integer; FScreen: TScreen; urlrect: TRect; indicatorrect: TRect; TopMargin: integer; LeftMargin: integer; FuncKeys : TFuncKeysTable; procedure AppMessageHandler(var Msg: TMsg; var Handled: boolean); procedure DoKeyBuffer(Buffer: PChar; Len: integer); virtual; procedure PaintGraphicChar(DC: HDC; X, Y: integer; rc: PRect; ch: char); procedure DrawEmulVT(DC: HDC; rc: TRect); procedure InvalidateSelectRect(rect: TRect); public FMouseCaptured: boolean; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ShowCursor; procedure SetCursor(Row, Col: integer); procedure WriteChar(Ch: char); procedure WriteStr(Str: string); procedure WriteBuffer(Buffer: Pointer; Len: integer); function ReadStr: string; procedure CopyHostScreen; procedure Clear; procedure UpdateScreen; function SnapPixelToRow(Y: integer): integer; function SnapPixelToCol(X: integer): integer; function PixelToRow(Y: integer): integer; function PixelToCol(X: integer): integer; procedure MouseToCell(X, Y: integer; var ACol, ARow: longint); procedure SetLineZoom(newValue: single); procedure SetCharWidth(newValue: integer); procedure SetCharZoom(newValue: single); procedure KeyPress(var Key: char); override; {fuse +} procedure DrawSelectRect(DC: HDC; rect: TRect); procedure DrawIndicatorLine(DC: HDC; rect: TRect); procedure SetVScrollBar(AScrollBar: TScrollBar); procedure SetNoScrollBar(Value: boolean); procedure SetCaretType(ACaretType: TCaretType); procedure SetSelectMode(ASelectMode: TSelectMode); procedure BlinkStateSet(State: integer); procedure UpdateBlinkRegion; procedure SetupFont; procedure SetupCaret; function NeedBlink: boolean; function GetPalColor(nPal: integer): TColor; procedure SetPalColor(nPal: integer; aColor: TColor); procedure GetTextRect(var r: TRect); procedure CenterTextRect; function DrawLineHeight(nRow: integer): integer; function DrawCharWidth(nCol: integer): integer; procedure VScrollBy(dy: integer); procedure InitFuncKeyTable; procedure LoadFuncKey(filename : string); {fuse + end} property LineZoom: single read FLineZoom write SetLineZoom; property CharWidth: integer read FCharWidth write SetCharWidth; property CharZoom: single read FCharZoom write SetCharZoom; property GraphicDraw: boolean read FGraphicDraw write FGraphicDraw; property TopLine: integer read FTopLine write SetTopLine; property SelectRect: TRect read FSelectRect write FSelectRect; {fuse + } property VScrollBar: TScrollBar read FVScrollBar write SetVScrollBar; property NoScrollBar: boolean read FNoScrollBar write SetNoScrollBar; property CaretType: TCaretType read FCaretType write SetCaretType; property SelectMode: TSelectMode read FSelectMode write SetSelectMode; property ParseURL: boolean read FParseURL write FParseURL; property LastKeyinTime: TDateTime read FLastKeyinTime write FLastKeyinTime; property OnFuncAction: TFuncActionEvent read FFuncAction write FFuncAction; property SingleCharPaint: boolean read FSINGLE_CHAR_PAINT write FSINGLE_CHAR_PAINT; property DefaultHighlight: boolean read GetDefaultHighlight write SetDefaultHighlight; {fuse + end} private procedure PaintOneLine(DC: HDC; Y, Y1: integer; const Line: TLine; nColFrom: integer; nColTo: integer); property Text: string read ReadStr write WriteStr; property OnMouseMove; property OnMouseDown; property OnMouseUp; property OnClick; property OnKeyPress; property OnKeyBuffer: TKeyBufferEvent read FOnKeyBuffer write FOnKeyBuffer; property OnKeyDown: TKeyDownEvent read FOnKeyDown write FOnKeyDown; property Ctl3D; property Align; property TabStop; property TabOrder; property BorderStyle: TBorderStyle read FBorderStyle write FBorderStyle; property AutoRepaint: boolean read FAutoRepaint write FAutoRepaint; property Font: TFont read FFont write SetFont; property LocalEcho: boolean read FLocalEcho write FLocalEcho; property AutoLF: boolean read GetAutoLF write SetAutoLF; property AutoCR: boolean read GetAutoCR write SetAutoCR; property Xlat: boolean read GetXlat write SetXlat; property MonoChrome: boolean read FMonoChrome write FMonoChrome; property Log: boolean read FLog write SetLog; property Rows: integer read GetRows write SetRows; property Cols: integer read GetCols write SetCols; property LineHeight: integer read FLineHeight write SetLineHeight; property FKeys: integer read FFKeys write FFKeys; property BackRows: integer read GetBackRows write SetBackRows; property BackColor: TColor read GetBackColor write SetBackColor; property Options: TScreenOptions read GetOptions write SetOptions; end; { Same as TCustomEmulVT, but with published properties } TEmulVT = class(TCustomEmulVT) public property Screen: TScreen read FScreen; property SelectRect; property Text; published property OnMouseMove; property OnMouseDown; property OnMouseUp; property OnClick; property OnKeyPress; property OnKeyDown; property OnKeyBuffer; property Ctl3D; property Align; property BorderStyle; property AutoRepaint; property Font; property LocalEcho; property AutoLF; property AutoCR; property Xlat; property MonoChrome; property Log; property Rows; property Cols; property BackRows; property BackColor; property Options; property LineHeight; property CharWidth; property TabStop; property TabOrder; property FKeys; end; const F_BLACK = $00; F_BLUE = $01; F_GREEN = $02; F_CYAN = $03; F_RED = $04; F_MAGENTA = $05; F_BROWN = $06; F_WHITE = $07; B_BLACK = $00; B_BLUE = $01; B_GREEN = $02; B_CYAN = $03; B_RED = $04; B_MAGENTA = $05; B_BROWN = $06; B_WHITE = $07; F_INTENSE = $08; B_BLINK = $80; X_UNDERLINE = $8000; X_INVERSE = $1000; X_CODEPAGE1 = $0100; X_CODEPAGE2 = $0200; { Function keys (VT100 Console) } FKeys1: TFuncKeysTable = ((ScanCode: #$48; Shift: []; Ext: True; Act: faSend; Value: #$1B + 'OA'), { UP } (ScanCode: #$50; Shift: []; Ext: True;Act: faSend; Value: #$1B + 'OB'), { DOWN } (ScanCode: #$4D; Shift: []; Ext: True;Act: faSend; Value: #$1B + 'OC'), { RIGHT } (ScanCode: #$4B; Shift: []; Ext: True;Act: faSend; Value: #$1B + 'OD'), { LEFT } (ScanCode: #$49; Shift: []; Ext: True; Value: #$1B + '[5~'), { PREV } (ScanCode: #$51; Shift: []; Ext: True; Value: #$1B + '[6~'), { NEXT } // (ScanCode: #$49; Shift: []; Ext: True;Act: faSend; Value: #$1B + 'v'), // (ScanCode: #$51; Shift: []; Ext: True;Act: faSend; Value: #$16), (ScanCode: #$47; Shift: []; Ext: True;Act: faSend; Value: #$1B + '[1~'), { HOME } (ScanCode: #$4F; Shift: []; Ext: True;Act: faSend; Value: #$1B + '[4~'), { END } (ScanCode: #$52; Shift: []; Ext: True;Act: faSend; Value: #$1B + '@'), { INS } (ScanCode: #$0F; Shift: []; Ext: False;Act: faSend; Value: #$9), { RTAB } (ScanCode: #$53; Shift: []; Ext: True;Act: faSend; Value: #$7F), { DEL } (ScanCode: #$3B; Shift: []; Ext: False;Act: faSend; Value: #$1B + 'OP'), { F1 } (ScanCode: #$3C; Shift: []; Ext: False;Act: faSend; Value: #$1B + 'OQ'), { F2 } (ScanCode: #$3D; Shift: []; Ext: False;Act: faSend; Value: #$1B + 'OR'), { F3 } (ScanCode: #$3E; Shift: []; Ext: False;Act: faSend; Value: #$1B + 'OS'), { F4 } (ScanCode: #$3F; Shift: []; Ext: False;Act: faSend; Value: #$1B + 'Ot'), { F5 } (ScanCode: #$40; Shift: []; Ext: False;Act: faSend; Value: #$1B + 'Ou'), { F6 } (ScanCode: #$41; Shift: []; Ext: False;Act: faSend; Value: #$1B + 'Ov'), { F7 } (ScanCode: #$42; Shift: []; Ext: False;Act: faSend; Value: #$1B + 'Ol'), { F8 } (ScanCode: #$43; Shift: []; Ext: False;Act: faSend; Value: #$1B + 'Ow'), { F9 } (ScanCode: #$44; Shift: []; Ext: False;Act: faSend; Value: #$1B + 'Ox'), { F10 } (ScanCode: #$57; Shift: []; Ext: False;Act: faSend; Value: #$1B + 'Oy'), { F11 } (ScanCode: #$58; Shift: []; Ext: False;Act: faMenu; Value: '地址簿'), { F12 } (ScanCode: #$3B; Shift: [ssShift]; Ext: False; Act: faSend; Value: #$1B + '[V'),{ SF1 should be 'Y' } (ScanCode: #$3C; Shift: [ssShift]; Ext: False;Act: faSend; Value: #$1B + '[Z'), (ScanCode: #$3D; Shift: [ssShift]; Ext: False;Act: faSend; Value: #$1B + '[a'), (ScanCode: #$3E; Shift: [ssShift]; Ext: False;Act: faSend; Value: #$1B + '[b'), (ScanCode: #$3F; Shift: [ssShift]; Ext: False;Act: faSend; Value: #$1B + '[c'), (ScanCode: #$40; Shift: [ssShift]; Ext: False;Act: faSend; Value: #$1B + '[d'), (ScanCode: #$41; Shift: [ssShift]; Ext: False;Act: faSend; Value: #$1B + '[e'), (ScanCode: #$42; Shift: [ssShift]; Ext: False;Act: faSend; Value: #$1B + '[f'), (ScanCode: #$43; Shift: [ssShift]; Ext: False;Act: faSend; Value: #$1B + '[g'), (ScanCode: #$44; Shift: [ssShift]; Ext: False;Act: faSend; Value: #$1B + '[h'), (ScanCode: #$85; Shift: [ssShift]; Ext: False;Act: faSend; Value: #$1B + '[i'), (ScanCode: #$86; Shift: [ssShift]; Ext: False;Act: faSend; Value: #$1B + '[j'),{ SF10 } (ScanCode: #$3B; Shift: [ssCtrl]; Ext: False;Act: faSend; Value: #$1B + '[k'), { CF1 } (ScanCode: #$3C; Shift: [ssCtrl]; Ext: False;Act: faSend; Value: #$1B + '[l'), (ScanCode: #$3D; Shift: [ssCtrl]; Ext: False;Act: faSend; Value: #$1B + '[m'), (ScanCode: #$3E; Shift: [ssCtrl]; Ext: False;Act: faMenu; Value: '关闭当前页'), { Ctrl-F4 } (ScanCode: #$3F; Shift: [ssCtrl]; Ext: False;Act: faMenu; Value: '切换辅助输入窗'), { Ctrl-F5 } (ScanCode: #$40; Shift: [ssCtrl]; Ext: False;Act: faSend; Value: #$1B + '[p'), (ScanCode: #$41; Shift: [ssCtrl]; Ext: False;Act: faSend; Value: #$1B + '[q'), (ScanCode: #$42; Shift: [ssCtrl]; Ext: False;Act: faSend; Value: #$1B + '[r'), (ScanCode: #$43; Shift: [ssCtrl]; Ext: False;Act: faSend; Value: #$1B + '[s'), (ScanCode: #$44; Shift: [ssCtrl]; Ext: False;Act: faSend; Value: #$1B + '[t'), (ScanCode: #$85; Shift: [ssCtrl]; Ext: False;Act: faSend; Value: #$1B + '[u'), (ScanCode: #$86; Shift: [ssCtrl]; Ext: False;Act: faSend; Value: #$1B + '[v'), { CF12 } (ScanCode: #$52; Shift: [ssCtrl]; Ext: False; Act: faMenu; Value: '拷贝'), { Ctrl-Insert } (ScanCode: #$52; Shift: [ssShift]; Ext: True; Act: faMenu; Value: '粘贴'), { Shift-Insert } (ScanCode: #$53; Shift: [ssCtrl]; Ext: True; Act: faMenu; Value: '自动回行粘贴'), {Ctrl-Delete} (ScanCode: #$0F; Shift: [ssCtrl]; Ext: False; Act: faMenu; Value: '页面切换'), (ScanCode: #$1C; Shift: [ssCtrl]; Ext: False; Act: faSend; Value: #$0D#$0A), { Ctrl-Enter } (ScanCode: #$00; Shift: []; Ext: False; Value: ''), (ScanCode: #$00; Shift: []; Ext: False; Value: ''), (ScanCode: #$00; Shift: []; Ext: False; Value: ''), (ScanCode: #$00; Shift: []; Ext: False; Value: ''), (ScanCode: #$00; Shift: []; Ext: False; Value: ''), (ScanCode: #$00; Shift: []; Ext: False; Value: ''), (ScanCode: #$00; Shift: []; Ext: False; Value: ''), (ScanCode: #$00; Shift: []; Ext: False; Value: ''), (ScanCode: #$00; Shift: []; Ext: False; Value: ''), (ScanCode: #$00; Shift: []; Ext: False; Value: ''), (ScanCode: #$00; Shift: []; Ext: False; Value: ''), (ScanCode: #$00; Shift: []; Ext: False; Value: '') ); { Ethernet to screen } ibm_iso8859_1_G0: TXlatTable = (#$00, #$01, #$02, #$03, #$04, #$05, #$06, #$07, { 00 - 07 } #$08, #$09, #$0A, #$0B, #$0C, #$0D, #$0E, #$0F, { 08 - 0F } #$10, #$11, #$12, #$13, #$14, #$15, #$16, #$17, { 10 - 17 } #$18, #$19, #$1A, #$1B, #$1C, #$1D, #$1E, #$1F, { 18 - 1F } #$20, #$21, #$22, #$23, #$24, #$25, #$26, #$27, { 20 - 27 } #$28, #$29, #$2A, #$2B, #$2C, #$2D, #$2E, #$2F, { 28 - 2F } #$30, #$31, #$32, #$33, #$34, #$35, #$36, #$37, { 30 - 37 } #$38, #$39, #$3A, #$3B, #$3C, #$3D, #$3E, #$3F, { 38 - 3F } #$40, #$41, #$42, #$43, #$44, #$45, #$46, #$47, { 40 - 47 } #$48, #$49, #$4A, #$4B, #$4C, #$4D, #$4E, #$4F, { 48 - 4F } #$50, #$51, #$52, #$53, #$54, #$55, #$56, #$57, { 50 - 57 } #$58, #$59, #$5A, #$5B, #$5C, #$5D, #$5E, #$5F, { 58 - 5F } #$60, #$61, #$62, #$63, #$64, #$65, #$66, #$67, { 60 - 67 } #$68, #$69, #$6A, #$6B, #$6C, #$6D, #$6E, #$6F, { 68 - 6F } #$70, #$71, #$72, #$73, #$74, #$75, #$76, #$77, { 70 - 77 } #$78, #$79, #$7A, #$7B, #$7C, #$7D, #$7E, #$7F, { 78 - 7F } #$20, #$20, #$20, #$20, #$20, #$20, #$20, #$20, { 80 - 87 } #$20, #$20, #$20, #$20, #$20, #$20, #$20, #$20, { 88 - 8F } #$20, #$20, #$20, #$20, #$20, #$20, #$20, #$20, { 90 - 97 } #$20, #$20, #$20, #$20, #$20, #$20, #$20, #$20, { 98 - 9F } #$B1, #$AD, #$9B, #$9C, #$0F, #$9D, #$B3, #$15, { A0 - A7 } #$20, #$43, #$A6, #$AE, #$AA, #$C4, #$52, #$C4, { A8 - AF } #$F8, #$F1, #$FD, #$20, #$27, #$E6, #$14, #$FA, { B0 - B7 } #$2C, #$20, #$A7, #$AF, #$AC, #$AB, #$20, #$A8, { B8 - BF } #$41, #$41, #$41, #$41, #$8E, #$8F, #$92, #$80, { C0 - C7 } #$45, #$45, #$45, #$45, #$45, #$49, #$49, #$49, { C8 - CF } #$44, #$A5, #$4F, #$4F, #$4F, #$4F, #$4F, #$78, { D0 - D7 } #$ED, #$55, #$55, #$55, #$55, #$59, #$70, #$E1, { D8 - DF } #$85, #$A0, #$83, #$61, #$84, #$86, #$91, #$87, { E0 - E7 } #$8A, #$82, #$88, #$89, #$8D, #$A1, #$8C, #$49, { E8 - EF } #$64, #$A4, #$95, #$A2, #$93, #$6F, #$94, #$F6, { F0 - F7 } #$ED, #$97, #$A3, #$96, #$9A, #$79, #$70, #$98); { F8 - FF } { Ethernet to screen } ibm_iso8859_1_G1: TXlatTable = (#$00, #$01, #$02, #$03, #$04, #$05, #$06, #$07, { 00 - 07 } #$08, #$09, #$0A, #$0B, #$0C, #$0D, #$0E, #$0F, { 08 - 0F } #$10, #$11, #$12, #$13, #$14, #$15, #$16, #$17, { 10 - 17 } #$18, #$19, #$1A, #$1B, #$1C, #$1D, #$1E, #$1F, { 18 - 1F } #$20, #$21, #$22, #$23, #$24, #$25, #$26, #$27, { 20 - 27 } #$28, #$29, #$2A, #$2B, #$2C, #$2D, #$2E, #$2F, { 28 - 2F } #$30, #$31, #$32, #$33, #$34, #$35, #$36, #$37, { 30 - 37 } #$38, #$39, #$3A, #$3B, #$3C, #$3D, #$3E, #$3F, { 38 - 3F } #$40, #$41, #$42, #$43, #$44, #$45, #$46, #$47, { 40 - 47 } #$48, #$49, #$4A, #$4B, #$4C, #$4D, #$4E, #$4F, { 48 - 4F } #$50, #$51, #$52, #$53, #$54, #$55, #$56, #$57, { 50 - 57 } #$58, #$59, #$5A, #$5B, #$5C, #$5D, #$5E, #$5F, { 58 - 5F } #$60, #$61, #$62, #$63, #$64, #$65, #$66, #$67, { 60 - 67 } #$68, #$69, #$D9, #$BF, #$DA, #$C0, #$C5, #$6F, { 68 - 6F } #$70, #$C4, #$72, #$73, #$C3, #$B4, #$C1, #$C2, { 70 - 77 } #$B3, #$79, #$7A, #$7B, #$7C, #$7D, #$7E, #$7F, { 78 - 7F } #$20, #$20, #$20, #$20, #$20, #$20, #$20, #$20, { 80 - 87 } #$20, #$20, #$20, #$20, #$20, #$20, #$20, #$20, { 88 - 8F } #$20, #$20, #$20, #$20, #$20, #$20, #$20, #$20, { 90 - 97 } #$20, #$20, #$20, #$20, #$20, #$20, #$20, #$20, { 98 - 9F } #$B1, #$AD, #$9B, #$9C, #$0F, #$9D, #$B3, #$15, { A0 - A7 } #$20, #$43, #$A6, #$AE, #$AA, #$C4, #$52, #$C4, { A8 - AF } #$F8, #$F1, #$FD, #$20, #$27, #$E6, #$14, #$FA, { B0 - B7 } #$2C, #$20, #$A7, #$AF, #$AC, #$AB, #$20, #$A8, { B8 - BF } #$41, #$41, #$41, #$41, #$8E, #$8F, #$92, #$80, { C0 - C7 } #$45, #$45, #$45, #$45, #$45, #$49, #$49, #$49, { C8 - CF } #$44, #$A5, #$4F, #$4F, #$4F, #$4F, #$4F, #$78, { D0 - D7 } #$ED, #$55, #$55, #$55, #$55, #$59, #$70, #$E1, { D8 - DF } #$85, #$A0, #$83, #$61, #$84, #$86, #$91, #$87, { E0 - E7 } #$8A, #$82, #$88, #$89, #$8D, #$A1, #$8C, #$49, { E8 - EF } #$64, #$A4, #$95, #$A2, #$93, #$6F, #$94, #$F6, { F0 - F7 } #$ED, #$97, #$A3, #$96, #$9A, #$79, #$70, #$98); { F8 - FF } { Keyboard to Ethernet } Output: TXlatTable = (#$00, #$01, #$02, #$03, #$04, #$05, #$06, #$07, { 00 - 07 } #$08, #$09, #$0A, #$0B, #$0C, #$0D, #$0E, #$0F, { 08 - 0F } #$10, #$11, #$12, #$13, #$14, #$15, #$16, #$17, { 10 - 17 } #$18, #$19, #$1A, #$1B, #$1C, #$1D, #$1E, #$1F, { 18 - 1F } #$20, #$21, #$22, #$23, #$24, #$25, #$26, #$27, { 20 - 27 } #$28, #$29, #$2A, #$2B, #$2C, #$2D, #$2E, #$2F, { 28 - 2F } #$30, #$31, #$32, #$33, #$34, #$35, #$36, #$37, { 30 - 37 } #$38, #$39, #$3A, #$3B, #$3C, #$3D, #$3E, #$3F, { 38 - 3F } #$40, #$41, #$42, #$43, #$44, #$45, #$46, #$47, { 40 - 47 } #$48, #$49, #$4A, #$4B, #$4C, #$4D, #$4E, #$4F, { 48 - 4F } #$50, #$51, #$52, #$53, #$54, #$55, #$56, #$57, { 50 - 57 } #$58, #$59, #$5A, #$5B, #$5C, #$5D, #$5E, #$5F, { 58 - 5F } #$60, #$61, #$62, #$63, #$64, #$65, #$66, #$67, { 60 - 67 } #$68, #$69, #$6A, #$6B, #$6C, #$6D, #$6E, #$6F, { 68 - 6F } #$70, #$71, #$72, #$73, #$74, #$75, #$76, #$77, { 70 - 77 } #$78, #$79, #$7A, #$7B, #$7C, #$7D, #$7E, #$7F, { 78 - 7F } #$C7, #$FC, #$E9, #$E2, #$E4, #$E0, #$E5, #$E7, { 80 - 87 } #$EA, #$EB, #$E8, #$EF, #$EE, #$EC, #$C4, #$C5, { 88 - 8F } #$C9, #$E6, #$C6, #$F4, #$F6, #$F2, #$FB, #$F9, { 90 - 97 } #$FF, #$F6, #$FC, #$A2, #$A3, #$A5, #$DE, #$20, { 98 - 9F } #$E1, #$ED, #$F3, #$FA, #$F1, #$D1, #$AA, #$BA, { A0 - A7 } #$BF, #$20, #$AC, #$BD, #$BC, #$A1, #$AB, #$BB, { A8 - AF } #$A0, #$A0, #$A0, #$A6, #$A6, #$A6, #$A6, #$AD, { B0 - B7 } #$2B, #$A6, #$A6, #$2B, #$2B, #$2B, #$2B, #$2B, { B8 - BF } #$2B, #$AD, #$AD, #$AD, #$A6, #$AD, #$2B, #$A6, { C0 - C7 } #$2B, #$2B, #$AD, #$AD, #$A6, #$AD, #$2B, #$AD, { C8 - CF } #$AD, #$AD, #$AD, #$2B, #$2B, #$2B, #$2B, #$2B, { D0 - D7 } #$2B, #$2B, #$2B, #$A0, #$A0, #$A0, #$A0, #$A0, { D8 - DF } #$20, #$20, #$20, #$AD, #$20, #$20, #$B5, #$20, { E0 - E7 } #$20, #$20, #$20, #$20, #$20, #$F8, #$20, #$20, { E8 - EF } #$A0, #$B1, #$20, #$20, #$20, #$20, #$F7, #$20, { F0 - F7 } #$B0, #$B0, #$B0, #$20, #$20, #$B2, #$A0, #$20); { F8 - FF } procedure Register; function FuncKeyValueToString(var S: TFuncKeyValue): string; function StringToFuncKeyValue(var S: string): TFuncKeyValue; procedure FKeysToFile(var FKeys: TFuncKeysTable; FName: string); procedure FileToFKeys(var FKeys: TFuncKeysTable; FName: string); function FindFKeys(FKeys: TFuncKeysTable; ScanCode: char; Shift: TShiftState; Ext: boolean; var Act: TFuncAction): PFuncKeyValue; function AddFKey(var FKeys: TFuncKeysTable; ScanCode: char; Shift: TShiftState; Ext: boolean; Act: TFuncAction; Value: TFuncKeyValue): boolean; var FBlinkState: integer; {0 or 1 - decides bkgrnd-col set or not set} implementation {-$DEFINE Debug} { Add or remove minus sign before dollar sign to } { generate code for debug message output } {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure Register; begin RegisterComponents('FPiette', [TEmulVT]); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function ShiftStateToString(var State: TShiftState): string; begin Result := ''; if ssShift in State then Result := Result + 'ssShift '; if ssAlt in State then Result := Result + 'ssAlt '; if ssCtrl in State then Result := Result + 'ssCtrl '; if ssLeft in State then Result := Result + 'ssLeft '; if ssRight in State then Result := Result + 'ssRight '; if ssMiddle in State then Result := Result + 'ssMiddle '; if ssDouble in State then Result := Result + 'ssDouble '; if Result = '' then Result := 'ssNormal'; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function StringToShiftState(var S: string): TShiftState; begin Result := []; if Pos('ssShift', S) <> 0 then Result := Result + [ssShift]; if Pos('ssAlt', S) <> 0 then Result := Result + [ssAlt]; if Pos('ssCtrl', S) <> 0 then Result := Result + [ssCtrl]; if Pos('ssLeft', S) <> 0 then Result := Result + [ssLeft]; if Pos('ssRight', S) <> 0 then Result := Result + [ssRight]; if Pos('ssMiddle', S) <> 0 then Result := Result + [ssMiddle]; if Pos('ssDouble', S) <> 0 then Result := Result + [ssDouble]; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function xdigit(Ch: char): integer; begin if ch in ['0'..'9'] then Result := Ord(ch) - Ord('0') else if ch in ['A'..'Z'] then Result := Ord(ch) - Ord('A') + 10 else if ch in ['a'..'z'] then Result := Ord(ch) - Ord('a') + 10 else Result := 0; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function xdigit2(S: PChar): integer; begin Result := 16 * xdigit(S[0]) + xdigit(S[1]); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function FuncKeyValueToString(var S: TFuncKeyValue): string; var I: integer; begin Result := ''; for I := 1 to Length(S) do begin if (Ord(S[I]) < 32) or (Ord(S[I]) >= 127) or (S[I] = '''') or (S[I] = '\') then Result := Result + '\x' + IntToHex(Ord(S[I]), 2) else Result := Result + S[I]; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function StringToFuncKeyValue(var S: string): TFuncKeyValue; var I: integer; begin Result := ''; I := 1; while I <= Length(S) do begin if (S[I] = '\') and ((I + 3) <= Length(S)) and (S[I + 1] = 'x') then begin Result := Result + chr(xdigit2(@S[I + 2])); I := I + 3; end else Result := Result + S[I]; Inc(I); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function FindFKeys(FKeys: TFuncKeysTable; ScanCode: char; Shift: TShiftState; Ext: boolean; var Act: TFuncAction): PFuncKeyValue; var I: integer; pFKeys: PFuncKeysTable; begin Result := nil; pFKeys := @FKeys; for I := Low(pFKeys^) to High(pFKeys^) do begin if (pFKeys^[I].ScanCode <> #0) and (pFKeys^[I].ScanCode = ScanCode) and (pFKeys^[I].Shift = Shift) { and (pFKeys^[I].Ext = Ext) }then begin Act := pFKeys^[I].Act; Result := @pFKeys^[I].Value; Break; end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function AddFKey(var FKeys: TFuncKeysTable; ScanCode: char; Shift: TShiftState; Ext: boolean; Act: TFuncAction; Value: TFuncKeyValue): boolean; var I: integer; begin { Search for existing key definition to replace it } for I := Low(FKeys) to High(FKeys) do begin if (FKeys[I].ScanCode = ScanCode) and (FKeys[I].Shift = Shift) { and(FKeys[I].Ext = Ext) }then begin FKeys[I].Act := Act; FKeys[I].Value := Value; Result := True; { Success} Exit; end; end; { Key not existing, add in an empty space } for I := Low(FKeys) to High(FKeys) do begin if FKeys[I].ScanCode = #0 then begin FKeys[I].ScanCode := ScanCode; FKeys[I].Shift := Shift; FKeys[I].Ext := Ext; FKeys[I].Act := Act; FKeys[I].Value := Value; Result := True; { Success} Exit; end; end; { Failure, no more space available } Result := False; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure FKeysToFile(var FKeys: TFuncKeysTable; FName: string); var I: integer; F: TextFile; sAct: string; begin AssignFile(F, FName); Rewrite(F); for I := Low(FKeys) to High(FKeys) do begin with FKeys[I] do begin if Act = faSend then sAct := 'faSend' else sAct := 'faMenu'; if Act = faSend then begin if ScanCode <> chr(0) then WriteLn(F, IntToHex(Ord(ScanCode), 2), ', ', ShiftStateToString(Shift), ', ', Ext, ', ', sAct, ', ''', FuncKeyValueToString(Value), ''''); end else begin if ScanCode <> chr(0) then WriteLn(F, IntToHex(Ord(ScanCode), 2), ', ', ShiftStateToString(Shift), ', ', Ext, ', ', sAct, ', ''', Value, ''''); end; end; end; CloseFile(F); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function GetToken(var S: string; var I: integer; Delim: char): string; begin Result := ''; while (I <= Length(S)) and (S[I] = ' ') do Inc(I); while (I <= Length(S)) and (S[I] <> Delim) do begin Result := Result + S[I]; Inc(I); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure FileToFKeys(var FKeys: TFuncKeysTable; FName: string); var I, J: integer; F: TextFile; S, T: string; sc: integer; aScanCode : char; aShift : TShiftState; aExt : boolean; aAct : TFuncAction; aValue : TFuncKeyValue; begin AssignFile(F, FName); {$I-} Reset(F); if IOResult <> 0 then begin { File do not exist, create default one } //FKeysToFile(FKeys1, FName); Exit; end; for I := Low(FKeys) to High(FKeys) do begin // with FKeys[I] do // begin aScanCode := chr(0); aShift := []; aExt := False; aValue := ''; if not EOF(F) then begin { 71, ssNormal, TRUE, '\x1B[H' } ReadLn(F, S); J := 1; T := GetToken(S, J, ','); if (Length(T) > 0) and (T[1] <> ';') then begin sc := xdigit2(@T[1]); if sc <> 0 then begin aScanCode := chr(sc); Inc(J); T := GetToken(S, J, ','); aShift := StringToShiftState(T); Inc(J); T := GetToken(S, J, ','); aExt := UpperCase(T) = 'TRUE'; Inc(J); T := GetToken(S, J, ','); if UpperCase(T) = 'FASEND' then aAct := faSend else aAct := faMenu; Inc(J); T := GetToken(S, J, ''''); Inc(J); T := GetToken(S, J, ''''); aValue := StringToFuncKeyValue(T); AddFKey(FKeys, aScanCode, aShift, aExt, aAct, aValue); end; end; end; // end; end; CloseFile(F); {$I+} end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure DebugString(Msg: string); const Cnt: integer = 0; {$IFDEF Debug} var Buf: string[20]; {$ENDIF} begin {$IFDEF Debug} Cnt := Cnt + 1; Buf := IntToHex(Cnt, 4) + ' ' + #0; OutputDebugString(@Buf[1]); {$IFNDEF WIN32} if Length(Msg) < High(Msg) then Msg[Length(Msg) + 1] := #0; {$ENDIF} OutputDebugString(@Msg[1]); {$ENDIF} end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {$IFNDEF WIN32} procedure SetLength(var S: string; NewLength: integer); begin S[0] := chr(NewLength); end; {$ENDIF} {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TLine.Create; var i: integer; begin inherited Create; FillChar(Txt, SizeOf(Txt), ' '); for i := 0 to MAX_COL - 1 do Att[i] := F_WHITE; //FillChar(Att, SizeOf(Att), Chr(F_WHITE)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TLine.Clear(Attr: word); var i: integer; begin FillChar(Txt, SizeOF(Txt), ' '); for i := 0 to MAX_COL - 1 do Att[i] := F_WHITE; //FillChar(Att, SizeOf(Att), Attr); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TScreen.Create; begin inherited Create; FRowCount := 0; FBackRowCount := 0; FBackEndRow := 0; FBackColor := clBlack; FOptions := []; SetRowCount(25); FColCount := 80; FRowSaved := -1; FColSaved := -1; FScrollRowTop := 0; FScrollRowBottom := FRowCount - 1; {// WM + SE 09/08/00 } FAttribute := F_WHITE; FDefaultHighlight := False; if FDefaultHighlight then FAttribute := FAttribute or F_INTENSE; FCodePage := 0; FAutoWrap := True; {fuse +} FXtermMouse := False; InvClear; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} destructor TScreen.Destroy; var nRow: integer; begin for nRow := 0 to FRowCount + FBackRowCount - 1 do FLines^[nRow].Free; FreeMem(FLines, (FRowCount + FBackRowCount) * SizeOf(TObject)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.AdjustFLines(NewCount: integer); var NewLines: PLineArray; CurrCount: integer; nRow: integer; begin CurrCount := FRowCount + FBackRowCount; if (NewCount <> CurrCount) and (NewCount > 0) then begin GetMem(NewLines, NewCount * SizeOf(TObject)); if NewCount > CurrCount then begin if CurrCount <> 0 then Move(FLines^, NewLines^, CurrCount * SizeOf(TObject)); for nRow := CurrCount to NewCount - 1 do NewLines^[nRow] := TLine.Create; if CurrCount <> 0 then FreeMem(FLines, CurrCount * SizeOf(TObject)); end else begin Move(FLines^, NewLines^, NewCount * SizeOf(TObject)); for nRow := NewCount to CurrCount - 1 do FLines^[nRow].Free; FreeMem(FLines, CurrCount * SizeOf(TObject)); end; FLines := NewLines; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.SetRowCount(NewCount: integer); begin if NewCount <> FRowCount then begin AdjustFLines(NewCount + FBackRowCount); Inc(FRow, NewCount - FRowCount); //if (FRow < 0) then ClearScreen; FRowCount := NewCount; FScrollRowBottom := FRowCount - 1; { WM + SE 09/08/00 } end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.SetBackRowCount(NewCount: integer); begin if NewCount <> FBackRowCount then begin AdjustFLines(FRowCount + NewCount); FBackRowCount := NewCount; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.CopyScreenToBack; { Copies the current host screen into the scrollback buffer. } var Temp: TLine; Row: integer; Pass: integer; // nCol: integer; begin if FBackRowCount >= FRowCount then begin Dec(FBackEndRow, FRowCount); if (0 - FBackEndRow) >= FBackRowCount then FBackEndRow := 1 - FBackRowCount; { We have to make FRowCount lines available at the head of the scrollback buffer. These will come from the end of the scrollback buffer. We'll make FRowCount passes through the scrollback buffer moving the available lines up to the top and the existing lines down a page at a time. Net result is that we only move each line once. } for Pass := 0 to FRowCount - 1 do begin Row := FBackEndRow + Pass; Temp := Lines[Row]; Inc(Row, FRowCount); while Row < 0 do begin Lines[Row - FRowCount] := Lines[Row]; Inc(Row, FRowCount); end; Lines[Row - FRowCount] := Temp; end; { Now, copy the host screen lines to the ons we made available. } for Row := 0 to FRowCount - 1 do begin Move(Lines[Row].Txt, Lines[Row - FRowCount].Txt, FColCount); Move(Lines[Row].Att, Lines[Row - FRowCount].Att, FColCount); { if vtoBackColor in FOptions then begin with Lines[Row - FRowCount] do begin for nCol := 0 to FColCount - 1 do begin Att[nCol] := Att[nCol] And $8F Or (Ord (FBackColor) shl 4); end; end; end; } end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ScrollUp; var Temp: TLine; Row: integer; // nCol: integer; begin if FBackRowCount > 0 then begin if (0 - FBackEndRow) < (FBackRowCount - 1) then Dec(FBackEndRow); Temp := Lines[FBackEndRow]; for Row := FBackEndRow + 1 to -1 do begin Lines[Row - 1] := Lines[Row]; end; Lines[-1] := Lines[FScrollRowTop]; { if vtoBackColor in FOptions then begin with Lines[-1] do begin for nCol := 0 to FColCount - 1 do begin Att[nCol] := Att[nCol] And $8F Or (Ord (FBackColor) shl 4); end; end; end; } end else Temp := Lines[FScrollRowTop]; for Row := FScrollRowTop + 1 to FScrollRowBottom do Lines[Row - 1] := Lines[Row]; Lines[FScrollRowBottom] := Temp; Temp.Clear(F_WHITE {FAttribute}); // FCodePage := 0; // Temp.Clear(FAttribute); FAllInvalid := True; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ScrollDown; var Temp: TLine; Row: integer; begin Temp := Lines[FScrollRowBottom]; for Row := FScrollRowBottom downto FScrollRowTop + 1 do Lines[Row] := Lines[Row - 1]; Lines[FScrollRowTop] := Temp; Temp.Clear(F_WHITE {FAttribute}); // FCodePage := 0; // Temp.Clear(FAttribute); FAllInvalid := True; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.CursorDown; begin Inc(FRow); if FRow > FScrollRowBottom then begin FRow := FScrollRowBottom; ScrollUp; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.CursorUp; begin Dec(FRow); if FRow < 0 then begin Inc(FRow); ScrollDown; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.CursorRight; begin Inc(FCol); if FCol >= FColCount then begin FCol := 0; CursorDown; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.CursorLeft; begin Dec(FCol); if FCol < 0 then begin FCol := FColCount - 1; CursorUp; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.CarriageReturn; begin FCol := 0; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TScreen.GetEscapeParam(From: integer; var Value: integer): integer; begin while (From <= Length(FEscBuffer)) and (FEscBuffer[From] = ' ') do From := From + 1; Value := 0; while (From <= Length(FEscBuffer)) and (FEscBuffer[From] in ['0'..'9']) do begin Value := Value * 10 + Ord(FEscBuffer[From]) - Ord('0'); From := From + 1; end; Result := From; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.UnimplementedEscape(EscCmd: char); {var Buf : String;} begin DebugString('Unimplemented Escape Sequence: ' + FEscBuffer + EscCmd + #13 + #10); { Buf := FEscBuffer + EscCmd + #0; MessageBox(0, @Buf[1], 'Unimplemented Escape Sequence', MB_OK); } end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.InvalidEscape(EscCmd: char); {var Buf : String;} begin DebugString('Invalid Escape Sequence: ' + FEscBuffer + EscCmd + #13 + #10); { Buf := FEscBuffer + EscCmd + #0; MessageBox(0, @Buf[1], 'Invalid Escape Sequence', MB_OK); } end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ProcessESC_D; { Index } begin // UnimplementedEscape('D'); // FAllInvalid := TRUE; Inc(FRow); if FRow > FScrollRowBottom then begin FRow := FScrollRowBottom; ScrollUp; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Move cursor Up, scroll down if necessary } procedure TScreen.ProcessESC_M; { Reverse index } begin Dec(FRow); if FRow < FScrollRowTop then begin FRow := FScrollRowTop; ScrollDown; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ProcessESC_E; { Next line } begin UnimplementedEscape('E'); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ProcessCSI_u; { Restore Cursor } begin UnimplementedEscape('u'); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { IBM character set operation (not part of the ANSI standard) } { <ESC>[0I => Set IBM character set } { <ESC>[1;nnnI => Literal mode for nnn next characters } { <ESC>[2;onoffI => Switch carbon mode on (1) or off (0) } { <ESC>[3;ch;cl;sh;slI => Receive carbon mode keyboard code } { <ESC>[4I => Select ANSI character set } procedure TScreen.ProcessCSI_I; var From, mode, nnn: integer; ch, cl, sh, sl: integer; begin From := GetEscapeParam(2, Mode); case Mode of 0: begin { Select IBM character set } FNoXlat := True; end; 1: begin { Set literal mode for next N characters } if FEscBuffer[From] = ';' then GetEscapeParam(From + 1, FCntLiteral) else FCntLiteral := 1; end; 2: begin { Switch carbon mode on or off } if FEscBuffer[From] = ';' then GetEscapeParam(From + 1, nnn) else nnn := 0; FCarbonMode := (nnn <> 0); end; 3: begin { Receive carbon mode key code } ch := 0; cl := 0; sh := 0; sl := 0; if FEscBuffer[From] = ';' then begin From := GetEscapeParam(From + 1, cl); if FEscBuffer[From] = ';' then begin From := GetEscapeParam(From + 1, ch); if FEscBuffer[From] = ';' then begin From := GetEscapeParam(From + 1, sl); if FEscBuffer[From] = ';' then begin GetEscapeParam(From + 1, sh); end; end; end; end; DebugString('Special key ' + IntToHex(ch, 2) + IntToHex(cl, 2) + ' ' + IntToHex(sh, 2) + IntToHex(sl, 2)); end; 4: begin { Select ANSI character set } FNoXlat := False; end; else UnimplementedEscape('I'); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.BackSpace; begin if FCol > 0 then Dec(FCol); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ClearScreen; var Row: integer; begin for Row := 0 to FRowCount - 1 do Lines[Row].Clear(FAttribute); FRow := 0; FCol := 0; FAllInvalid := True; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.InvClear; begin with FInvRect do begin Top := 9999; Left := 9999; Right := -1; Bottom := -1; end; FAllInvalid := False; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.InvRect(nRow, nCol: integer); begin if not FAllInvalid then begin if FInvRect.Top > nRow then FInvRect.Top := nRow; if FInvRect.Bottom < nRow then FInvRect.Bottom := nRow; if FInvRect.Left > nCol then FInvRect.Left := nCol; if FInvRect.Right < nCol then FInvRect.Right := nCol; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { The FLines array is inverted with the last host line at position 0 and the first host line as position FRowCount - 1. } procedure Tscreen.SetLines(I: integer; Value: TLine); begin if I >= FRowCount then FLines^[0] := Value else FLines^[FRowCount - 1 - I] := Value; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TScreen.GetLines(I: integer): TLine; begin if I >= FRowCount then Result := FLines^[0] else Result := FLines^[FRowCount - 1 - I]; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.Eol; var i: integer; begin with Lines[FRow] do begin FillChar(Txt[FCol], FColCount - FCol, ' '); for i := FCol to FColCount do Att[i] := FAttribute; //FillChar(Att[FCol], (FColCount - FCol) * SizeOf(Att[FCol]), FAttribute); end; InvRect(Frow, FCol); InvRect(Frow, FColCount); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.Eop; var Row: integer; begin Eol; for Row := FRow + 1 to FRowCount - 1 do Lines[Row].Clear(FAttribute); if FRow = 0 then FAllInvalid := True else begin InvRect(FRow, 0); InvRect(FRowCount, FColCount); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ProcessCSI_J; { Clear the screen } var Mode: integer; Row: integer; begin GetEscapeParam(2, Mode); case Mode of 0: begin { Cursor to end of screen } FAttribute := F_WHITE; if FDefaultHighlight then FAttribute := FAttribute or F_INTENSE; FReverseVideo := False; FCodePage := 0; Eop; end; 1: begin { Start of screen to cursor } for Row := 0 to FRow do Lines[Row].Clear(FAttribute); InvRect(0, 0); InvRect(FRow, FColCount); end; 2: begin { Entire screen } if vtoCopyBackOnClear in FOptions then CopyScreenToBack; ClearScreen; end; else InvalidEscape('J'); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ProcessCSI_K; { Erase to End of Line } begin Eol; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ProcessCSI_L; { Insert Line } var nLine: integer; nRow: integer; Temp: TLine; begin FCol := 0; GetEscapeParam(2, nLine); if nLine = 0 then nLine := 1; if (FRow + nLine) > FScrollRowBottom then begin for nRow := FRow to FScrollRowBottom do Lines[nRow].Clear(FAttribute); Exit; end; for nRow := FScrollRowBottom downto FRow + nLine do begin Temp := Lines[nRow]; Lines[nRow] := Lines[nRow - nLine]; Lines[nRow - nLine] := Temp; end; for nRow := FRow to FRow + nLine - 1 do Lines[nRow].Clear(FAttribute); FAllInvalid := True; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ProcessCSI_M; { Delete Line } var nLine: integer; nRow: integer; Temp: TLine; begin FAllInvalid := True; FCol := 0; GetEscapeParam(2, nLine); if nLine = 0 then nLine := 1; if (FRow + nLine) > FScrollRowBottom then begin for nRow := FRow to FScrollRowBottom do Lines[nRow].Clear(FAttribute); Exit; end; for nRow := FRow to FRow + nLine - 1 do Lines[nRow].Clear(FAttribute); { 12/11/99 } for nRow := FRow to FScrollRowBottom - nLine do begin Temp := Lines[nRow]; Lines[nRow] := Lines[nRow + nLine]; Lines[nRow + nLine] := Temp; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ProcessCSI_m_lc; { Select Attributes } var From, n: integer; begin if FEscBuffer[1] <> '[' then Exit; if Length(FEscBuffer) < 2 then begin FAttribute := F_WHITE; if FDefaultHighlight then FAttribute := FAttribute or F_INTENSE; FReverseVideo := False; FUnderLine := False; //FCodePage := 0; //if FCodePage=1 then FAttribute := FAttribute or X_CODEPAGE2; Exit; end; From := 2; while From <= Length(FEscBuffer) do begin if FEscBuffer[From] in [' ', '[', ';'] then Inc(From) else begin From := GetEscapeParam(From, n); case n of 0: begin { All attributes off } FAttribute := F_WHITE; //if FCodePage=1 then FAttribute := FAttribute or X_CODEPAGE2; FReverseVideo := False; FUnderLine := False; FCodePage := 0; end; 1: begin { High intensity } FAttribute := FAttribute or F_INTENSE; end; 4: begin { Underline } FUnderLine := True; end; 5: begin { Blinking } FAttribute := FAttribute or B_BLINK; end; 7: begin { Reverse video } FReverseVideo := True; end; 8: begin { Secret } FAttribute := 0; //if FCodePage=1 then FAttribute := FAttribute or X_CODEPAGE2; end; 10: begin { Don't force high bit } FForceHighBit := False; end; 12: begin { Force high bit on } FForceHighBit := True; end; 22: begin { Normal intensity } FAttribute := FAttribute and (not F_INTENSE); end; 27: begin { Normal characters } FAttribute := F_WHITE; if FDefaultHighlight then FAttribute := FAttribute or F_INTENSE; //if FCodePage=1 then FAttribute := FAttribute or X_CODEPAGE2; //FCodePage := 0; FReverseVideo := False; end; 30, 31, 32, 33, 34, 35, 36, 37: begin { Foreground color } FAttribute := (n mod 10) or (FAttribute and $F8); end; 40, 41, 42, 43, 44, 45, 46, 47: begin { Background color } FAttribute := ((n mod 10) shl 4) or (FAttribute and $8F); end; else InvalidEscape('m'); end; end; end; { if FReverseVideo then begin FAttribute := ((FAttribute and 7) shl 4) or ((FAttribute shr 4) and 7) or (FAttribute and $88); end; } //if FCodePage = 1 then FAttribute := FAttribute or X_CODEPAGE2; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ProcessCSI_n_lc; { Cursor position report } begin UnimplementedEscape('n'); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ProcessCSI_at; { Insert character } var nChar: integer; nCnt: integer; nCol: integer; Line: TLine; begin GetEscapeParam(2, nChar); if nChar = 0 then nChar := 1; nCnt := FColCount - FCol - nChar; if nCnt <= 0 then begin Eol; Exit; end; Line := Lines[FRow]; for nCol := FColCount - 1 downto FCol + nChar do begin Line.Txt[nCol] := Line.Txt[nCol - nChar]; Line.Att[nCol] := Line.Att[nCol - nChar]; InvRect(Frow, nCol); end; for nCol := FCol to FCol + nChar - 1 do begin Line.Txt[nCol] := ' '; Line.Att[nCol] := FAttribute; InvRect(Frow, nCol); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ProcessCSI_r_lc; { Scrolling margins } var From, Top, Bottom: integer; begin From := GetEscapeParam(2, Top); if (Top = 0) then begin { Default = full screen } FScrollRowTop := 0; FScrollRowBottom := FRowCount - 1; end else begin while (From <= Length(FEscBuffer)) and (FEscBuffer[From] = ' ') do From := From + 1; if FEscBuffer[From] = ';' then GetEscapeParam(From + 1, Bottom) else Bottom := 1; FScrollRowTop := Top - 1; FScrollRowBottom := Bottom - 1; if (FScrollRowBottom <= FScrollRowTop) or (FScrollRowTop < 0) or (FScrollRowBottom >= FRowCount) then begin FScrollRowTop := 0; FScrollRowBottom := FRowCount - 1; end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ProcessCSI_s_lc; { Save cursor location } begin ProcessCSI_7; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ProcessCSI_u_lc; { Restore cursor location } begin ProcessCSI_8; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ProcessCSI_7; { Save cursor location } begin FRowSaved := FRow; FColSaved := FCol; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ProcessCSI_8; { Restore cursor location } begin if FRowSaved = -1 then GotoXY(0, 0) else GotoXY(FColSaved, FRowSaved); { FRowSaved := -1; FColSaved := -1; } end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ProcessCSI_H; { Set Cursor Position } var From, Row, Col: integer; begin From := GetEscapeParam(2, Row); while (From <= Length(FEscBuffer)) and (FEscBuffer[From] = ' ') do From := From + 1; if FEscBuffer[From] = ';' then GetEscapeParam(From + 1, Col) else Col := 1; GotoXY(Col - 1, Row - 1); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ProcessCSI_h_lc; { Terminal mode set } var Priv: boolean; Mode: integer; begin if FEscBuffer[1] <> '[' then begin UnimplementedEscape('h'); Exit; end; Priv := (FEscBuffer[2] = '?'); if not Priv then begin UnimplementedEscape('h'); Exit; end; GetEscapeParam(3, Mode); case Mode of 1: { ANSI cursor keys } FCKeyMode := True; 4: { Smooth scroll OFF } { Ignore }; 7: { Auto-wrap OFF } FAutoWrap := True; 25: { Cursor visible } begin FCursorOff := False; if Assigned(FOnCursorVisible) then FOnCursorVisible(Self); end; 1000: begin FXtermMouse := True; // not FXtermMouse; end else UnimplementedEscape('h'); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ProcessCSI_l_lc; { Terminal mode reset } var Priv: boolean; Mode: integer; begin if FEscBuffer[1] <> '[' then begin UnimplementedEscape('l'); Exit; end; Priv := (FEscBuffer[2] = '?'); if not Priv then begin UnimplementedEscape('l'); Exit; end; GetEscapeParam(3, Mode); case Mode of 1: { ANSI cursor keys } FCKeyMode := False; 4: { Smooth scroll OFF } { Ignore }; 7: { Auto-wrap OFF } FAutoWrap := False; 25: { Cursor invisible } begin FCursorOff := True; if Assigned(FOnCursorVisible) then FOnCursorVisible(Self); end; 1000: FXTermMouse := False; else UnimplementedEscape('l'); end; FCodePage := 0; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ProcessCSI_A; { Cursor Up } var Row: integer; begin GetEscapeParam(2, Row); if Row <= 0 then Row := 1; FRow := FRow - Row; if FRow < 0 then FRow := 0; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ProcessCSI_B; { Cursor Down } var Row: integer; begin GetEscapeParam(2, Row); if Row <= 0 then Row := 1; FRow := FRow + Row; if FRow >= FRowCount then FRow := FRowCount - 1; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ProcessCSI_C; { Cursor Right } var Col: integer; begin GetEscapeParam(2, Col); if Col <= 0 then Col := 1; FCol := FCol + Col; if FCol >= FColCount then begin if FAutoWrap then begin FCol := FCol - FColCount; Inc(FRow); if FRow >= FRowCount then FRow := FRowCount - 1; end else FCol := FColCount - 1; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ProcessCSI_D; { Cursor Left } var Col: integer; begin GetEscapeParam(2, Col); if Col <= 0 then Col := 1; FCol := FCol - Col; if FCol < 0 then FCol := 0; end; procedure TScreen.ProcessCSI_E; { move down N lines and CR } var Row: integer; begin GetEscapeParam(2, Row); if Row <= 0 then Row := 1; FRow := FRow + Row; if FRow >= FRowCount then FRow := FRowCount - 1; FCol := 0; end; procedure TScreen.ProcessCSI_F; { move up N lines and CR } var Row: integer; begin GetEscapeParam(2, Row); if Row <= 0 then Row := 1; FRow := FRow - Row; if FRow < 0 then FRow := 0; FCol := 0; end; procedure TScreen.ProcessCSI_G; { set horizontal posn } var Col: integer; begin GetEscapeParam(2, Col); if Col <= 0 then Col := 1; if Col > FColCount then Col := FColCount; FCol := Col; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ProcessCSI_d_lc; { set vertical posn } var Row: integer; begin GetEscapeParam(2, Row); if Row <= 0 then Row := 1; if Row >= FRowCount then Row := FRowCount - 1; FRow := Row; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ProcessCSI_P; { Delete Character } var Count: integer; nCol: integer; begin GetEscapeParam(2, Count); if Count <= 0 then Count := 1; with Lines[FRow] do begin for nCol := Fcol to FColCount - Count - 1 do begin Txt[nCol] := Txt[nCol + Count]; Att[nCol] := Att[nCol + Count]; end; for nCol := FcolCount - Count - 1 to FColCount - 1 do begin Txt[nCol] := ' '; Att[nCol] := F_WHITE; end; end; InvRect(Frow, FCol); InvRect(Frow, FColCount); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ProcessCSI_S; { Scroll up } begin ScrollUp; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ProcessCSI_T; { Scroll down } begin UnimplementedEscape('T'); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ProcessCSI_X; { write N spaces w/o moving cursor } var Count: integer; nCol: integer; begin GetEscapeParam(2, Count); if FCol + Count > FColCount then Count := FColCount - FCol; if Count < 0 then Exit; with Lines[FRow] do begin for nCol := Fcol to FCol + Count - 1 do begin Txt[nCol] := ' '; Att[nCol] := FAttribute; end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.process_charset_G0(EscCmd: char); { G0 character set } begin case EscCmd of '0': begin FCharSetG0 := EscCmd; FXlatInputTable := @ibm_iso8859_1_G1; FXlatOutputTable := @ibm_iso8859_1_G1; FNoXlat := FNoXlatInitial; FCodePage := 1; FAttribute := FAttribute or X_CODEPAGE2; { FNoXlat := FALSE;} end; 'B': begin FCharSetG0 := EscCmd; FXlatInputTable := @ibm_iso8859_1_G0; FXlatOutputTable := @ibm_iso8859_1_G0; FNoXlat := FNoXlatInitial; FCodePage := 0; FAttribute := FAttribute and (not X_CODEPAGE2); end; else InvalidEscape(EscCmd); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.process_charset_G1(EscCmd: char); { G1 character set } begin FCharSetG1 := EscCmd; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.process_charset_G2(EscCmd: char); { G2 character set } begin FCharSetG2 := EscCmd; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.process_charset_G3(EscCmd: char); { G2 character set } begin FCharSetG3 := EscCmd; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.ProcessEscape(EscCmd: char); begin if Length(FEscBuffer) = 0 then begin case EscCmd of 'D': ProcessESC_D; { Index } 'M': ProcessESC_M; { Reverse index } 'E': ProcessESC_E; { Next line } 'H':; { Tabulation set } '7': ProcessCSI_7; { Save cursor } '8': ProcessCSI_8; { Restore Cursor } '=':; { VT52 } { Enter Alternate keypad } '>':; { VT52 } { Exit Alternate keypad } '<':; { VT52 } { Enter ANSI mode } #7:; else InvalidEscape(EscCmd); WriteLiteralChar(EscCmd); end; Exit; end; case FEscBuffer[1] of ' ': begin case EscCmd of 'F':; else InvalidEscape(EscCmd); end; end; '[': begin case EscCmd of 'I': ProcessCSI_I; { Select IBM char set } { Extension F. Piette !! } 'J': ProcessCSI_J; { Clear the screen } 'K': ProcessCSI_K; { Erase to End of Line } 'L': ProcessCSI_L; { Insert Line } 'M': ProcessCSI_M; { Delete Line } 'm': ProcessCSI_m_lc; { Select Attributes } 'n': ProcessCSI_n_lc; { Cursor position report } '@': ProcessCSI_at; { Insert character } 'r': ProcessCSI_r_lc; { Set Top and Bottom marg } 's': ProcessCSI_s_lc; { Save cursor location } 'u': ProcessCSI_u_lc; { Restore cursor location } 'H': ProcessCSI_H; { Set Cursor Position } 'f': ProcessCSI_H; { Set Cursor Position } 'g':; { Tabulation Clear } 'h': ProcessCSI_h_lc; { Terminal mode set } 'l': ProcessCSI_l_lc; { Terminal mode reset } 'A': ProcessCSI_A; { Cursor Up } 'e', 'B': ProcessCSI_B; { Cursor Down } 'a', 'C': ProcessCSI_C; { Cursor Right } 'D': ProcessCSI_D; { Cursor Left } 'E': ProcessCSI_E; { move down N lines and CR } 'F': ProcessCSI_F; { move up N lines and CR } '`', 'G': ProcessCSI_G; { set horizontal posn } 'd': ProcessCSI_d; { set vertical posn } 'P': ProcessCSI_P; { Delete Character } 'S': ProcessCSI_S; { Scroll up } 'T': ProcessCSI_T; { Scroll down } 'X': ProcessCSI_X; { Scroll down } '>':; { } else InvalidEscape(EscCmd); end; end; '(': process_charset_G0(EscCmd); { G0 character set } ')': process_charset_G1(EscCmd); { G1 character set } '*': process_charset_G2(EscCmd); { G2 character set } '+': process_charset_G3(EscCmd); { G3 character set } ']': UnimplementedEscape(']'); else InvalidEscape(EscCmd); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.WriteLiteralChar(Ch: char); var Line: TLine; begin if FCol >= FColCount then begin if FAutoWrap then begin FCol := 0; Inc(FRow); if FRow >= FRowCount then begin Dec(FRow); ScrollUp; end; end; end; {if FForceHighBit then Ch := Chr(Ord(ch) or $80); } if FReverseVideo then FAttribute := FAttribute or X_INVERSE; if FCodePage = 1 then FAttribute := FAttribute or X_CODEPAGE2; if FUnderLine then FAttribute := FAttribute or X_UNDERLINE; Line := Lines[FRow]; Line.Txt[FCol] := Ch; Line.Att[FCol] := FAttribute; InvRect(Frow, FCol); if FCol < High(Line.Txt) then Inc(FCol); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.SetAttr(Att: char); begin { Not implemented } end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Write a single character at current cursor location. } { Update cursor position. } procedure TScreen.WriteChar(Ch: char); var bProcess: boolean; begin if FCntLiteral > 0 then begin if (FCntLiteral and 1) <> 0 then WriteLiteralChar(Ch) else SetAttr(Ch); Dec(FCntLiteral); Exit; end; //if ch <= #$A0 then begin if (not FEscFLag) and FNoXlat and (FXlatInputTable = @ibm_iso8859_1_G1) then begin Ch := FXlatInputTable^[Ord(Ch)]; FCodePage := 1; end else begin FCodePage := 0; end; { if ch = #$DA then begin WriteLiteralChar(Ch) end; } if FEscFLag then begin bProcess := False; if (Length(FEscBuffer) = 0) and (Ch in ['D', 'M', 'E', 'H', '7', '8', '=', '>', '<']) then bProcess := True else if (Length(FEscBuffer) = 1) and (FEscBuffer[1] in ['(', ')', '*', '+']) then bProcess := True else if (Length(FEscBuffer) = 0) and (Ch = ']') then begin FEscBuffer := FEscBuffer + Ch; end else if (FEscBuffer[1] = ']') then begin if (ch = #7) then bProcess := True else begin FEscBuffer := FEscBuffer + Ch; if Length(FEscBuffer) >= High(FEscBuffer) then begin MessageBeep(MB_ICONASTERISK); FEscBuffer := ''; FEscFlag := False; end; end; end else if (Ch in ['0'..'9', ';', '?', ' ']) or ((Length(FEscBuffer) = 0) and (ch in ['[', '(', ')', '*', '+'])) then begin FEscBuffer := FEscBuffer + Ch; if Length(FEscBuffer) >= High(FEscBuffer) then begin MessageBeep(MB_ICONASTERISK); FEscBuffer := ''; FEscFlag := False; end; end else bProcess := True; if bProcess then begin ProcessEscape(Ch); FEscBuffer := ''; FEscFlag := False; end; Exit; end; case Ch of #0:; #7: begin //MessageBeep(MB_ICONASTERISK); FAllInvalid := True; if Assigned(FOnBeepChar) then OnBeepChar(self); end; #8: BackSpace; #9: begin repeat Inc(FCol); until (FCol mod 8) = 0; end; #10: begin CursorDown; if FAutoCR then CarriageReturn; end; #13: begin CarriageReturn; if FAutoLF then CursorDown; end; #14: begin FXlatInputTable := @ibm_iso8859_1_G1; FXlatOutputTable := @ibm_iso8859_1_G1; end; #15: begin FXlatInputTable := @ibm_iso8859_1_G0; FXlatOutputTable := @ibm_iso8859_1_G0; end; #27: begin FEscBuffer := ''; FEscFlag := True; end; else WriteLiteralChar(Ch); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Write characters at current cursor location. Update cursor position. } procedure TScreen.WriteStr(Str: string); var I: integer; begin for I := 1 to Length(Str) do WriteChar(Str[I]); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Read characters from the cursor to end of line } function TScreen.ReadStr: string; var Line: TLine; Len: integer; begin Line := Lines[FRow]; Len := FColCount - FCol; if Len <= 0 then Result := '' else begin SetLength(Result, Len); Move(Line.Txt[FCol], Result[1], Len); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TScreen.GotoXY(X, Y: integer); begin if X < 0 then FCol := 0 else if X >= FColCount then FCol := FColCount - 1 else FCol := X; if Y < 0 then FRow := 0 else if Y >= FRowCount then FRow := FRowCount - 1 else FRow := Y; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.SetCaret; var c: integer; begin if (FScreen.FRow - FTopLine < 0) or (FScreen.FRow - FTopLine > FScreen.FRowCount) then begin SetCaretPos(-50, - 50); {SetCaretPos(FCharPos[FScreen.FCol] + LeftMargin, (FScreen.FRow -FTopLine) * FLineHeight + TopMargin); } Exit; end; if FCaretType = ctBLine then c := FLinePos[2] - FLinePos[1] - 2 else if Font.Size <= 7 then c := 0 else if Font.Size <= 9 then c := 1 else if Font.Size <= 12 then c := 2 else if Font.Size <= 16 then c := 3 else c := 4; {$IFDEF CHAR_ZOOM} SetCaretPos(FCharPos[FScreen.FCol] + LeftMargin, FLinePos[FScreen.FRow - FTopLine] + TopMargin + c); {$ELSE} SetCaretPos(FScreen.FCol * FCharWidth + LeftMargin, (FScreen.FRow - FTopLine) * FLineHeight + TopMargin); {$ENDIF} end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { Adjusts the scrollbar properties to match the number of host and scrollback lines that we can scroll through. } procedure TCustomEmulVT.AdjustScrollBar; var VisibleLines: integer; begin if FNoScrollBar or (not Assigned(VScrollBar)) then Exit; FVScrollBar.Min := FScreen.FBackEndRow; if LineHeight = 0 then LineHeight := 12; {$IFDEF CHAR_ZOOM} VisibleLines := Trunc((Height - TopMargin - BottomMargin) / (LineHeight * FLineZoom)); {$ELSE} VisibleLines := (Height - TopMargin - BottomMargin) div LineHeight; {$ENDIF} if VisibleLines > FScreen.FRowCount then VisibleLines := FScreen.FRowCount; FVScrollBar.Max := FScreen.FRowCount - VisibleLines; FVScrollBar.Position := FTopLine; FVScrollBar.SmallChange := 1; FVScrollBar.LargeChange := VisibleLines; FVScrollBar.Enabled := FVScrollBar.Max > FVScrollBar.Min; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.Clear; begin FScreen.ClearScreen; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.SetCursor(Row, Col: integer); begin FScreen.GotoXY(Col - 1, Row - 1); { SetCaret; } end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.WriteChar(Ch: char); begin if FCaretCreated and FCaretShown then begin HideCaret(Handle); FCaretShown := False; end; if FLog then Write(FFileHandle, Ch); FScreen.WriteChar(ch); if FAutoRepaint then UpdateScreen; { SetCaret; } end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.WriteStr(Str: string); var I: integer; begin if FCaretCreated and FCaretShown then begin HideCaret(Handle); FCaretShown := False; end; for I := 1 to Length(Str) do begin if FLog then Write(FFileHandle, Str[I]); FScreen.WriteChar(Str[I]); end; if FAutoRepaint then UpdateScreen; { SetCaret; } end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.WriteBuffer(Buffer: Pointer; Len: integer); var I: integer; begin if FCaretCreated and FCaretShown then begin HideCaret(Handle); FCaretShown := False; end; for I := 0 to Len - 1 do begin if FLog then Write(FFileHandle, PChar(Buffer)[I]); FScreen.WriteChar(PChar(Buffer)[I]); end; if FAutoRepaint then UpdateScreen; { SetCaret;} end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomEmulVT.ReadStr: string; begin Result := FScreen.ReadStr; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.CopyHostScreen; begin FScreen.CopyScreenToBack; AdjustScrollBar; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} constructor TCustomEmulVT.Create(AOwner: TComponent); type TMyLogPalette = record palVersion: word; palNumEntries: word; palPalEntry: array[0..NumPaletteEntries - 1] of TPaletteEntry; end; TPLogPalette = ^TLogPalette; var plgpl: ^TMyLogPalette; I: integer; begin inherited Create(AOwner); ControlStyle := ControlStyle + [csOpaque]; New(plgpl); plgpl^.palNumEntries := High(plgpl^.palPalEntry) + 1; plgpl^.palVersion := $300; FPaletteEntries[0].peRed := 0; { Black } FPaletteEntries[0].peGreen := 0; FPaletteEntries[0].peBlue := 0; FPaletteEntries[1].peRed := 128; { Red } FPaletteEntries[1].peGreen := 0; FPaletteEntries[1].peBlue := 0; FPaletteEntries[2].peRed := 0; { Green } FPaletteEntries[2].peGreen := 128; FPaletteEntries[2].peBlue := 0; FPaletteEntries[3].peRed := 128; { Yellow } FPaletteEntries[3].peGreen := 128; FPaletteEntries[3].peBlue := 0; FPaletteEntries[4].peRed := 0; { Dark Blue } FPaletteEntries[4].peGreen := 0; FPaletteEntries[4].peBlue := 128; FPaletteEntries[5].peRed := 128; { Magenta } FPaletteEntries[5].peGreen := 0; FPaletteEntries[5].peBlue := 128; FPaletteEntries[6].peRed := 0; { Cyan } FPaletteEntries[6].peGreen := 128; FPaletteEntries[6].peBlue := 128; FPaletteEntries[7].peRed := 200; { White } FPaletteEntries[7].peGreen := 200; FPaletteEntries[7].peBlue := 200; FPaletteEntries[8].peRed := 84; { Grey } FPaletteEntries[8].peGreen := 84; FPaletteEntries[8].peBlue := 84; FPaletteEntries[9].peRed := 255; { Red Highlight } FPaletteEntries[9].peGreen := 0; FPaletteEntries[9].peBlue := 0; FPaletteEntries[10].peRed := 0; { Green Highlight } FPaletteEntries[10].peGreen := 255; FPaletteEntries[10].peBlue := 0; FPaletteEntries[11].peRed := 255; { Yellow Highlight } FPaletteEntries[11].peGreen := 255; FPaletteEntries[11].peBlue := 0; FPaletteEntries[12].peRed := 0; { Blue Highlight } FPaletteEntries[12].peGreen := 0; FPaletteEntries[12].peBlue := 255; FPaletteEntries[13].peRed := 255; { Magenta Highlight } FPaletteEntries[13].peGreen := 20; FPaletteEntries[13].peBlue := 255; FPaletteEntries[14].peRed := 0; { Cyan highlight } FPaletteEntries[14].peGreen := 255; FPaletteEntries[14].peBlue := 255; FPaletteEntries[15].peRed := 255; { White Highlight } FPaletteEntries[15].peGreen := 255; FPaletteEntries[15].peBlue := 255; for I := 0 to High(plgpl^.palPalEntry) do begin plgpl^.PalPalEntry[I].peRed := FPaletteEntries[I].peRed; plgpl^.PalPalEntry[I].peGreen := FPaletteEntries[I].peGreen; plgpl^.PalPalEntry[I].peBlue := FPaletteEntries[I].peBlue; plgpl^.PalPalEntry[I].peFlags := PC_NOCOLLAPSE; end; FPal := CreatePalette(TPLogPalette(plgpl)^); Dispose(plgpl); FReverseFG := clBlack; FReverseBG := clSilver; urlrect.Top := -1; indicatorrect.Top := -1; FScreen := TScreen.Create; FFont := TFont.Create; FFont.Name := 'Fixedsys'; FFont.Size := 12; FFont.Style := []; FCharZoom := 1.0; FLineZoom := 1.36; SetupFont; FBlinkState := 0; FSINGLE_CHAR_PAINT := True; LeftMargin := 3; TopMargin := 2; FScreen.FXlatInputTable := @ibm_iso8859_1_G0; FScreen.FXlatOutputTable := @ibm_iso8859_1_G0; FScreen.FCodePage := 0; FScreen.OnCursorVisible := CursorVisibleEvent; FCursorVisible := True; FCaretType := ctBlock; Width := 250; Height := 100; FBorderStyle := bsSingle; FBorderWidth := 1; FAutoRepaint := False; InitFuncKeyTable; FFkeys := 1; FGraphicDraw := True; FNoScrollBar := True; { FVScrollBar := TScrollBar.Create(Self); with FVScrollBar do begin Parent := Self; Kind := sbVertical; Width := 16; Visible := TRUE; Align := alRight; OnScroll := VScrollBarScroll; end; } with FScreen do begin GotoXY(0, 0); WriteStr('EmulVT'); GotoXY(0, 1); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.SetRows(Value: integer); begin with FScreen do begin if FRowCount <> Value then begin SetRowCount(Value); AdjustScrollBar; //ClearScreen; UpdateScreen; Repaint; end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomEmulVT.GetRows: integer; begin Result := FScreen.FRowCount; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.SetCols(Value: integer); begin with FScreen do begin if FColCount <> Value then begin FColCount := Value; //ClearScreen; Repaint; end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomEmulVT.GetCols: integer; begin Result := FScreen.FColCount; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.CursorVisibleEvent(Sender: TObject); begin if FScreen.FCursorOff then begin if FCaretShown then begin HideCaret(Handle); FCaretShown := False; end; end else begin if FScreen.Focused and not FCaretShown then begin ShowCaret(Handle); FCaretShown := True; end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.SetAutoLF(Value: boolean); begin FScreen.FAutoLF := Value; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.SetAutoCR(Value: boolean); begin FScreen.FAutoCR := Value; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.SetLog(Value: boolean); begin if FLog = Value then Exit; FLog := Value; if FLog then begin {$I-} AssignFile(FFileHandle, 'EMULVT.LOG'); Append(FFileHandle); if IOResult <> 0 then Rewrite(FFileHandle); Write(FFileHandle, '<Open>'); {$I+} end else begin Write(FFileHandle, '<Close>'); CloseFile(FFileHandle); end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.SetXlat(Value: boolean); begin FScreen.FNoXlat := not Value; FScreen.FNoXlatInitial := not Value; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomEmulVT.GetXlat: boolean; begin Result := not FScreen.FNoXlatInitial; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomEmulVT.GetAutoLF: boolean; begin Result := FScreen.FAutoLF; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomEmulVT.GetAutoCR: boolean; begin Result := FScreen.FAutoCR; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} destructor TCustomEmulVT.Destroy; begin if FLog then Log := False; FFont.Free; //FVScrollBar.Free; FScreen.Free; DeleteObject(FPal); inherited Destroy; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.SetBackRows(Value: integer); begin with FScreen do begin if FBackRowCount <> Value then begin SetBackRowCount(Value); AdjustScrollBar; end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.SetTopLine(Value: integer); begin if not Assigned(VScrollBar) then Exit; if Value < FVScrollBar.Min then Value := FVScrollBar.Min; if Value > FVScrollBar.Max then Value := FVScrollBar.Max; FTopLine := Value; FVScrollBar.Position := FTopLine; Repaint; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomEmulVT.GetBackRows: integer; begin Result := FScreen.FBackRowCount; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.SetBackColor(Value: TColor); begin FScreen.FBackColor := Value; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomEmulVT.GetBackColor: TColor; begin Result := FScreen.FBackColor; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.SetOptions(Value: TScreenOptions); begin FScreen.FOptions := Value; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomEmulVT.GetOptions: TScreenOptions; begin Result := FScreen.FOptions; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.SetupFont; var DC: HDC; Metrics: TTextMetric; hObject: THandle; begin DC := GetDC(0); hObject := SelectObject(DC, FFont.Handle); GetTextMetrics(DC, Metrics); SelectObject(DC, hOBject); ReleaseDC(0, DC); //SetCharWidth(Metrics.tmMaxCharWidth); SetCharWidth(Metrics.tmAveCharWidth); SetLineHeight(Metrics.tmHeight); // FCharZoom := (Metrics.tmHeight / 2.0) / Metrics.tmAveCharWidth; FInternalLeading := Metrics.tmInternalLeading; // UpdateScreen; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.SetCharWidth(newValue: integer); var nCol: integer; begin FCharWidth := newValue; for nCol := Low(FCharPos) to High(FCharPos) do FCharPos[nCol] := Trunc(FCharWidth * nCol * FCharZoom); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.SetCharZoom(newValue: single); begin FCharZoom := newValue; SetCharWidth(FCharWidth); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.SetLineHeight(Value: integer); var nRow: integer; temp, t2: integer; begin FLineHeight := Value; temp := 0; t2 := Round(FLineHeight * FLineZoom); for nRow := 0 to MAX_ROW do begin FLinePos[nRow] := temp; //Trunc(FLineHeight * nRow * FLineZoom); temp := temp + t2; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.SetLineZoom(newValue: single); begin FLineZoom := newValue; SetLineHeight(FLineHeight); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.SetFont(Value: TFont); begin FFont.Assign(Value); {-$IFNDEF SINGLE_CHAR_PAINT} if not FSINGLE_CHAR_PAINT then FFont.Pitch := fpFixed; //fpDefault; {-$ENDIF} SetupFont; SetCaret; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.WMLButtonDown(var Message: TWMLButtonDown); begin inherited; SetFocus; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.VScrollBarScroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: integer); begin FTopLine := ScrollPos; Repaint; SetFocus; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.DoKeyBuffer(Buffer: PChar; Len: integer); var J: integer; ch: char; begin if Assigned(FOnKeyBuffer) then FOnKeyBuffer(Self, Buffer, Len) else begin for J := 0 to Len - 1 do begin ch := Buffer[J]; KeyPress(ch); end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomEmulVT.FindFKeys(ScanCode: char; Shift: TShiftState; Ext: boolean): PFuncKeyValue; var I: integer; pFKeys: PFuncKeysTable; begin Result := nil; pFKeys := @FuncKeys; { case FKeys of 0: pFKeys := @FKeys1; 1: pFKeys := @FKeys2; 2: pFKeys := @FKeys3; else pFKeys := @FKeys2; end; } for I := Low(pFKeys^) to High(pFKeys^) do begin if (pFKeys^[I].ScanCode <> #0) and (pFKeys^[I].ScanCode = ScanCode) and (pFKeys^[I].Shift = Shift) and (pFKeys^[I].Ext = Ext) then begin Result := @pFKeys^[I].Value; Break; end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomEmulVT.ProcessFKeys(ScanCode: char; Shift: TShiftState; Ext: boolean): boolean; var I: integer; pFKeys: PFuncKeysTable; begin FLastKeyinTime := Now; Result := False; pFKeys := @FuncKeys; { case FKeys of 0: pFKeys := @FKeys1; 1: pFKeys := @FKeys2; 2: pFKeys := @FKeys3; else pFKeys := @FKeys2; end; } for I := Low(pFKeys^) to High(pFKeys^) do begin if (pFKeys^[I].ScanCode <> #0) and (pFKeys^[I].ScanCode = ScanCode) and (pFKeys^[I].Shift = Shift) and (pFKeys^[I].Ext = Ext) then begin if pFKeys^[I].Act = faSend then begin Result := True; DoKeyBuffer(@pFKeys^[I].Value[1], Length(pFKeys^[I].Value)); end else begin if Assigned(FFuncAction) then FFuncAction(self, pFKeys^[I]); Result := True; end; Break; end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.AppMessageHandler(var Msg: TMsg; var Handled: boolean); const v1: string = 'aeiou'; v2: string = 'aeiou'; v3: string = 'aeiou'; SpyFlag: boolean = False; var Shift: TShiftState; ShiftLock: boolean; VirtKey: integer; Key: char; I: integer; ScanCode: char; Ext: boolean; SpyBuffer: string; FnBuffer: string; pFV: PFuncKeyValue; begin if (Msg.hWnd = Handle) and ((Msg.Message = WM_KEYDOWN) or (Msg.Message = WM_SYSKEYDOWN)) then begin if Msg.wParam = $E5 then begin Exit; end; VirtKey := Msg.wParam; Key := chr(Msg.wParam and $FF); { DebugString('AppMessageHandler KEYDOWN ' + IntToHex(Msg.wParam, 4) + #13 + #10); } Shift := KeyDataToShiftState(Msg.lParam); ShiftLock := ((GetKeyState(VK_CAPITAL) and 1) > 0); ScanCode := Chr(LOBYTE(HIWORD(Msg.lParam))); Ext := ((Msg.lParam and $1000000) <> 0); if ssAlt in Shift then begin Exit; end; if Assigned(FOnKeyDown) then begin FOnKeyDown(Self, VirtKey, Shift, ShiftLock, ScanCode, Ext); if VirtKey = 0 then begin Handled := True; Exit; end; end; if (Msg.wParam <> VK_SHIFT) and (Msg.wParam <> VK_CONTROL) and (Msg.wParam <> VK_MENU) then begin if (ScanCode = '7') and (Shift = [ssAlt, ssCtrl]) and (Ext = False) then begin { This is CTRL-ALT-* (on num pad) } SpyFlag := True; Handled := True; Exit; end; if SpyFlag then begin SpyFlag := False; pFV := FindFKeys(ScanCode, Shift, Ext); SpyBuffer := IntToHex(Ord(ScanCode), 2) + ', ' + ShiftStateToString(Shift) + ', '; if Ext then SpyBuffer := SpyBuffer + 'TRUE' else SpyBuffer := SpyBuffer + 'FALSE'; if pFV <> nil then SpyBuffer := SpyBuffer + ', ''' + FuncKeyValueToString(pFV^) + ''''; SpyBuffer := SpyBuffer + #0; ClipBoard.SetTextBuf(@SpyBuffer[1]); FnBuffer := 'Key definition from tnchrk' + IntToStr(FKeys) + '.cfg' + #0; Application.MessageBox(@SpyBuffer[1], @FnBuffer[1], MB_OK); Handled := True; Exit; end; if ProcessFKeys(ScanCode, Shift, Ext) then begin Handled := True; Exit; end; end; case Msg.wParam of VK_SHIFT, VK_CONTROL, VK_MENU:; VK_NEXT, VK_PRIOR, VK_UP, VK_DOWN, VK_LEFT, VK_RIGHT, VK_HOME, VK_END: begin if ProcessFKeys(ScanCode, Shift, True) then begin Handled := True; Exit; end; end; VK_TAB, VK_RETURN, VK_ESCAPE, VK_BACK: begin Handled := True; end; { $DD: begin if not (ssAlt in Shift) then begin Key := #0; Handled := TRUE; if (ssShift in Shift) then FFlagTrema := TRUE else FFlagCirconflexe := TRUE; end; end; } Ord('A')..Ord('Z'): begin if (ssCtrl in Shift) then Key := chr(word(Key) and $1F) else if not ShiftLock and not (ssShift in Shift) then Key := chr(word(Key) or $20); if (FFlagCirconflexe) then begin for I := Length(v1) downto 1 do begin if Key = v1[I] then begin Key := v2[I]; Break; end; end; FFlagCirconflexe := False; end; if (FFlagTrema) then begin for I := Length(v1) downto 1 do begin if Key = v1[I] then begin Key := v3[I]; Break; end; end; FFlagTrema := False; end; Handled := True; end; end; { DebugString('Char = ' + IntToHex(Integer(Key), 2) + #13 + #10); } if Handled and (Key <> #0) then KeyPress(Key); end; if not Handled and Assigned(FAppOnMessage) then FAppOnMessage(Msg, Handled); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.KeyPress(var Key: char); begin { if not FScreen.FNoXlat then Key := FScreen.FXlatOutputTable^[ord(Key)]; } inherited KeyPress(Key); if FLocalEcho then begin WriteChar(Key); if not FAutoRepaint then UpdateScreen; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.WMSetFocus(var Message: TWMSetFocus); begin { inherited; } FScreen.Focused := True; { SetupFont; } if not FCursorVisible then Exit; SetupCaret; { CreateCaret(Handle, 0, 2, FLineHeight); FCaretCreated := TRUE; SetCaret;} if not FScreen.FCursorOff then begin ShowCaret(Handle); FCaretShown := True; end; FAppOnMessage := Application.OnMessage; Application.OnMessage := AppMessageHandler; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.WMKillFocus(var Message: TWMKillFocus); begin { inherited; } FScreen.Focused := False; if not FCursorVisible then Exit; if FCaretShown then begin HideCaret(Handle); FCaretShown := False; end; if FCaretCreated then begin DestroyCaret; FCaretCreated := False; end; Application.OnMessage := FAppOnMessage; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.MouseToCell(X, Y: integer; var ACol, ARow: longint); begin {$IFDEF CHAR_ZOOM} aRow := FScreen.FRowCount - 1; while (Y - TopMargin) <= FLinePos[aRow] do Dec(aRow); {$ELSE} aRow := (Y - TopMargin) div FLineHeight; {$ENDIF} if aRow < 0 then aRow := 0 else if aRow >= FScreen.FRowCount then aRow := FScreen.FRowCount - 1; {$IFDEF CHAR_ZOOM} aCol := FScreen.FColCount - 1; while (X - LeftMargin) <= FCharPos[aCol] do Dec(aCol); {$ELSE} aCol := (X - LeftMargin) div FCharWidth; {$ENDIF} if aCol < 0 then aCol := 0 else if aCol >= FScreen.FColCount then aCol := FScreen.FColCount - 1; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.ShowCursor; begin SetCaret; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.WMPaletteChanged(var Message: TMessage); {var HandleDC : HDC;} begin { if Message.wParam <> Handle then begin HandleDC := GetDC(Handle); SelectPalette(HandleDC, FPal, FALSE); if RealizePalette(HandleDC) <> 0 then begin InvalidateRect(Handle, nil, TRUE); MessageBeep(0); end; ReleaseDC(Handle, HandleDC); end; } end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.UpdateScreen; var rc: TRect; // nRow: integer; begin if FScreen.FAllInvalid then begin FSelectRect.Top := -1; InvalidateRect(Handle, nil, False); end else begin {$Q-} with FScreen.FInvRect do begin {$IFDEF CHAR_ZOOM} if Left = 9999 then begin rc.Top := 0; rc.Bottom := 0; rc.Left := 0; rc.Right := 0; end else if (Top - FTopLine >= 0) and (Top - FTopLine <= MAX_ROW) then begin rc.Top := TopMargin + FLinePos[Top - FTopLine] + FInternalLeading; rc.Bottom := TopMargin + FLinePos[Bottom + 1 - FTopLine] + FInternalLeading; rc.Left := LeftMargin + FCharPos[Left]; rc.Right := LeftMargin + FCharPos[Right + 1]; end; {$ELSE} rc.Top := TopMargin + FLineHeight * (Top - FTopLine) + FInternalLeading; rc.Bottom := TopMargin + FLineHeight * (Bottom + 1 - FTopLine) + FInternalLeading; rc.Left := LeftMargin + FCharWidth * Left; rc.Right := LeftMargin + FCharWidth * (Right + 1); {$ENDIF} end; InvalidateRect(Handle, @rc, False); {$Q+} end; if (not FNOScrollBar) and FScreen.FAllInvalid and (FScreen.FRow - FTopLine < MAX_ROW) and (FScreen.FRow - FTopLine >= 0) then begin //fuse. 2001.1027 AdjustScrollBar; end; if FScreen.Focused then SetCaret; { Invalidate the region where the caret is. I should'nt do that, but } { if I do'nt, the caret remains where it is ! Bug ? } { $IFDEF CHAR_ZOOM rc.Top := FLinePos[FScreen.FRow - FTopLine] + TopMargin; rc.Bottom := FLinePos[FScreen.FRow - FTopLine + 1] + TopMargin; rc.Left := LeftMargin + FCharPos[FScreen.FCol]; rc.Right := LeftMargin + FCharPos[FScreen.FCol + 1]; $ELSE rc.Top := TopMargin + FLineHeight * (FScreen.FRow - FTopLine); rc.Bottom := rc.Top + FLineHeight; rc.Left := LeftMargin + FCharWidth * FScreen.FCol; rc.Right := rc.Left + FCharWidth; $ENDIF InvalidateRect(Handle, @rc, FALSE); } FScreen.InvClear; if (not FAutoRepaint) and FScreen.Focused and FCaretCreated then begin ShowCaret(Handle); FCaretShown := True; end; //SetCaret; end; function TCustomEmulVT.DrawLineHeight(nRow: integer): integer; begin if nRow = MAX_ROW then Result := FLinePos[nRow] - FLinePos[nRow - 1] else Result := FLinePos[nRow + 1] - FLinePos[nRow]; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomEmulVT.SnapPixelToRow(Y: integer): integer; var nRow: integer; begin nRow := PixelToRow(Y); {$IFDEF CHAR_ZOOM} Result := TopMargin + FLinePos[nRow]; {$ELSE} Result := TopMargin + nRow * FLineHeight; {$ENDIF} end; function TCustomEmulVT.DrawCharWidth(nCol: integer): integer; begin if nCol = MAX_COL then Result := FCharPos[nCol] - FCharPos[nCol - 1] else Result := FCharPos[nCol + 1] - FCharPos[nCol]; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomEmulVT.SnapPixelToCol(X: integer): integer; var nCol: integer; begin nCol := PixelToCol(X); {$IFDEF CHAR_ZOOM} Result := LeftMargin + FCharPos[nCol]; {$ELSE} Result := LeftMargin + nCol * FCharWidth; {$ENDIF} end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomEmulVT.PixelToRow(Y: integer): integer; var nRow: integer; begin if (Y >= FLinePos[MAX_ROW]) then begin Result := MAX_ROW; Exit; end; if (Y <= TopMargin) or (Y <= 0) then begin Result := 0; Exit; end; {$IFDEF CHAR_ZOOM} nRow := MAX_ROW;// FScreen.FRowCount - 1; while (nRow > 0) and ((Y - TopMargin) < FLinePos[nRow]) do Dec(nRow); {$ELSE} nRow := (Y - TopMargin) div FLineHeight; {$ENDIF} if nRow < 0 then nRow := 0; Result := nRow; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} function TCustomEmulVT.PixelToCol(X: integer): integer; var nCol: integer; begin if (X >= FCharPos[MAX_COL]) then begin Result := MAX_COL; Exit; end; if (X <= LeftMargin) or (X <= 0) then begin Result := 0; Exit; end; {$IFDEF CHAR_ZOOM} nCol := MAX_COL; //FScreen.FColCount; while (X - LeftMargin) < FCharPos[nCol] do Dec(nCol); {$ELSE} nCol := (X - LeftMargin) div FCharWidth; {$ENDIF} if nCol < 0 then nCol := 0; Result := nCol; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} { This procedure will paint graphic char from the OEM charset (lines, } { corners, T and other like) using GDI functions. This will result in } { autosized characters, necessary for example to draw a frame when zoom } { affect character and line spacing. } procedure TCustomEmulVT.PaintGraphicChar(DC: HDC; X, Y: integer; rc: PRect; ch: char); const OneSpace: char = ' '; var X1, X2, X3: integer; Y1, Y2, Y3: integer; Co: TColor; apen, savepen: THandle; abrush, savebrush: THandle; begin ExtTextOut(DC, X, Y, ETO_OPAQUE or ETO_CLIPPED, rc, @OneSpace, 1, nil); apen := CreatePen(PS_SOLID, 1, FSavePenColor); abrush := CreateSolidBrush(FSaveBrushColor); savepen := SelectObject(DC, apen); savebrush := SelectObject(DC, abrush); X1 := X; X3 := rc^.Right; X2 := (X1 + X3) div 2; Y1 := rc^.Top; Y3 := rc^.Bottom; Y2 := (Y1 + Y3) div 2; case Ch of #$C4: begin { Horizontal single line } MoveToEx(DC, X1, Y2, nil); LineTo(DC, X3, Y2); end; #$B3: begin { Vertical single line } MoveToEx(DC, X2, Y1, nil); LineTo(DC, X2, Y3); end; #$DA: begin { Upper Left Single Corner } MoveToEx(DC, X3, Y2, nil); LineTo(DC, X2, Y2); LineTo(DC, X2, Y3); end; #$C0: begin { Bottom Left Single Corner } MoveToEx(DC, X2, Y1, nil); LineTo(DC, X2, Y2); LineTo(DC, X3, Y2); end; #$C1: begin { Reverse T } MoveToEx(DC, X2, Y1, nil); LineTo(DC, X2, Y2); MoveToEx(DC, X1, Y2, nil); LineTo(DC, X3, Y2); end; #$C2: begin { T } MoveToEx(DC, X2, Y3, nil); LineTo(DC, X2, Y2); MoveToEx(DC, X1, Y2, nil); LineTo(DC, X3, Y2); end; #$C3: begin { Left T } MoveToEx(DC, X2, Y1, nil); LineTo(DC, X2, Y3); MoveToEx(DC, X2, Y2, nil); LineTo(DC, X3, Y2); end; #$B4: begin { Right T } MoveToEx(DC, X2, Y1, nil); LineTo(DC, X2, Y3); MoveToEx(DC, X2, Y2, nil); LineTo(DC, X1 - 1, Y2); end; #$BF: begin { Top Right Single Corner } MoveToEx(DC, X1, Y2, nil); LineTo(DC, X2, Y2); LineTo(DC, X2, Y3); end; #$D9: begin { Bottom Right Single Corner } MoveToEx(DC, X1, Y2, nil); LineTo(DC, X2, Y2); LineTo(DC, X2, Y1 - 1); end; #$D6: begin { Upper Left Single/Double Corner } MoveToEx(DC, X3, Y2, nil); LineTo(DC, X2 - 1, Y2); LineTo(DC, X2 - 1, Y3); MoveToEx(DC, X2 + 1, Y2, nil); LineTo(DC, X2 + 1, Y3); end; #$D3: begin { Bottom Left Single/Double Corner } MoveToEx(DC, X2 - 1, Y1, nil); LineTo(DC, X2 - 1, Y2); LineTo(DC, X3, Y2); MoveToEx(DC, X2 + 1, Y1, nil); LineTo(DC, X2 + 1, Y2); end; #$B7: begin { Top Right Single/Double Corner } MoveToEx(DC, X1, Y2, nil); LineTo(DC, X2 + 1, Y2); LineTo(DC, X2 + 1, Y3); MoveToEx(DC, X2 - 1, Y2, nil); LineTo(DC, X2 - 1, Y3); end; #$BD: begin { Bottom Right Single/Double Corner } MoveToEx(DC, X2 + 1, Y1, nil); LineTo(DC, X2 + 1, Y2); LineTo(DC, X1 - 1, Y2); MoveToEx(DC, X2 - 1, Y1, nil); LineTo(DC, X2 - 1, Y2); end; #$D5: begin { Upper Left Double/Single Corner } MoveToEx(DC, X3, Y2 - 1, nil); LineTo(DC, X2, Y2 - 1); LineTo(DC, X2, Y3); MoveToEx(DC, X3, Y2 + 1, nil); LineTo(DC, X2, Y2 + 1); end; #$D4: begin { Bottom Left Double/Single Corner } MoveToEx(DC, X2, Y1, nil); LineTo(DC, X2, Y2 + 1); LineTo(DC, X3, Y2 + 1); MoveToEx(DC, X2, Y2 - 1, nil); LineTo(DC, X3, Y2 - 1); end; #$B8: begin { Top Right Double/Single Corner } MoveToEx(DC, X1, Y2 - 1, nil); LineTo(DC, X2, Y2 - 1); LineTo(DC, X2, Y3); MoveToEx(DC, X1, Y2 + 1, nil); LineTo(DC, X2, Y2 + 1); end; #$BE: begin { Bottom Right Double/Single Corner } MoveToEx(DC, X2, Y1, nil); LineTo(DC, X2, Y2 + 1); LineTo(DC, X1 - 1, Y2 + 1); MoveToEx(DC, X1, Y2 - 1, nil); LineTo(DC, X2, Y2 - 1); end; #$CD: begin { Horizontal Double line } MoveToEx(DC, X1, Y2 + 1, nil); LineTo(DC, X3, Y2 + 1); MoveToEx(DC, X1, Y2 - 1, nil); LineTo(DC, X3, Y2 - 1); end; #$BA: begin { Vertical Double line } MoveToEx(DC, X2 + 1, Y1, nil); LineTo(DC, X2 + 1, Y3); MoveToEx(DC, X2 - 1, Y1, nil); LineTo(DC, X2 - 1, Y3); end; #$D1: begin { T Top Horizontal Double line } MoveToEx(DC, X1, Y2 + 1, nil); LineTo(DC, X3, Y2 + 1); MoveToEx(DC, X1, Y2 - 1, nil); LineTo(DC, X3, Y2 - 1); MoveToEx(DC, X2, Y2 + 1, nil); LineTo(DC, X2, Y3); end; #$CF: begin { T Bottom Horizontal Double line } MoveToEx(DC, X1, Y2 + 1, nil); LineTo(DC, X3, Y2 + 1); MoveToEx(DC, X1, Y2 - 1, nil); LineTo(DC, X3, Y2 - 1); MoveToEx(DC, X2, Y2 - 1, nil); LineTo(DC, X2, Y1); end; #$C6: begin { T Left Horizontal Double line } MoveToEx(DC, X2, Y2 + 1, nil); LineTo(DC, X3, Y2 + 1); MoveToEx(DC, X2, Y2 - 1, nil); LineTo(DC, X3, Y2 - 1); MoveToEx(DC, X2, Y1, nil); LineTo(DC, X2, Y3); end; #$B5: begin { T Right Horizontal Double line } MoveToEx(DC, X1, Y2 + 1, nil); LineTo(DC, X2, Y2 + 1); MoveToEx(DC, X1, Y2 - 1, nil); LineTo(DC, X2, Y2 - 1); MoveToEx(DC, X2, Y1, nil); LineTo(DC, X2, Y3); end; #$C9: begin { Upper Left Double Corner } MoveToEx(DC, X3, Y2 - 1, nil); LineTo(DC, X2 - 1, Y2 - 1); LineTo(DC, X2 - 1, Y3); MoveToEx(DC, X3, Y2 + 1, nil); LineTo(DC, X2 + 1, Y2 + 1); LineTo(DC, X2 + 1, Y3); end; #$C8: begin { Bottom Left Double Corner } MoveToEx(DC, X2 - 1, Y1, nil); LineTo(DC, X2 - 1, Y2 + 1); LineTo(DC, X3, Y2 + 1); MoveToEx(DC, X2 + 1, Y1, nil); LineTo(DC, X2 + 1, Y2 - 1); LineTo(DC, X3, Y2 - 1); end; #$BB: begin { Top Right Double Corner } MoveToEx(DC, X1, Y2 - 1, nil); LineTo(DC, X2 + 1, Y2 - 1); LineTo(DC, X2 + 1, Y3); MoveToEx(DC, X1, Y2 + 1, nil); LineTo(DC, X2 - 1, Y2 + 1); LineTo(DC, X2 - 1, Y3); end; #$BC: begin { Bottom Right Double Corner } MoveToEx(DC, X2 - 1, Y1, nil); LineTo(DC, X2 - 1, Y2 - 1); LineTo(DC, X1 - 1, Y2 - 1); MoveToEx(DC, X2 + 1, Y1, nil); LineTo(DC, X2 + 1, Y2 + 1); LineTo(DC, X1 - 1, Y2 + 1); end; #$CC: begin { Double left T } MoveToEx(DC, X2 - 1, Y1, nil); LineTo(DC, X2 - 1, Y3); MoveToEx(DC, X2 + 1, Y1, nil); LineTo(DC, X2 + 1, Y2 - 1); LineTo(DC, X3, Y2 - 1); MoveToEx(DC, X3, Y2 + 1, nil); LineTo(DC, X2 + 1, Y2 + 1); LineTo(DC, X2 + 1, Y3); end; #$B9: begin { Double Right T } MoveToEx(DC, X2 + 1, Y1, nil); LineTo(DC, X2 + 1, Y3); MoveToEx(DC, X2 - 1, Y1, nil); LineTo(DC, X2 - 1, Y2 - 1); LineTo(DC, X1 - 1, Y2 - 1); MoveToEx(DC, X1, Y2 + 1, nil); LineTo(DC, X2 - 1, Y2 + 1); LineTo(DC, X2 - 1, Y3); end; #$C7: begin { Double T Single Left } MoveToEx(DC, X2 + 1, Y1, nil); LineTo(DC, X2 + 1, Y3); MoveToEx(DC, X2 - 1, Y1, nil); LineTo(DC, X2 - 1, Y3); MoveToEx(DC, X2 + 1, Y2, nil); LineTo(DC, X3, Y2); end; #$B6: begin { Double T Single Right } MoveToEx(DC, X2 + 1, Y1, nil); LineTo(DC, X2 + 1, Y3); MoveToEx(DC, X2 - 1, Y1, nil); LineTo(DC, X2 - 1, Y3); MoveToEx(DC, X2 - 1, Y2, nil); LineTo(DC, X1 - 1, Y2); end; #$D2: begin { Single T Double Top } MoveToEx(DC, X1, Y2, nil); LineTo(DC, X3, Y2); MoveToEx(DC, X2 - 1, Y2, nil); LineTo(DC, X2 - 1, Y3); MoveToEx(DC, X2 + 1, Y2, nil); LineTo(DC, X2 + 1, Y3); end; #$D0: begin { Single T Double Bottom } MoveToEx(DC, X1, Y2, nil); LineTo(DC, X3, Y2); MoveToEx(DC, X2 - 1, Y2, nil); LineTo(DC, X2 - 1, Y1); MoveToEx(DC, X2 + 1, Y2, nil); LineTo(DC, X2 + 1, Y1); end; #$DB: begin { Full Block } Rectangle(DC, X1, Y1, X3, Y3); end; #$DC: begin { Half Bottom Block } Rectangle(DC, X1, Y2, X3, Y3); end; #$DD: begin { Half Left Block } Rectangle(DC, X1, Y1, X2, Y3); end; #$DE: begin { Half Right Block } Rectangle(DC, X2, Y1, X3, Y3); end; #$DF: begin { Half Top Block } Rectangle(DC, X1, Y1, X2, Y2); end; #$C5: begin { Single Cross } MoveToEx(DC, X1, Y2, nil); LineTo(DC, X3, Y2); MoveToEx(DC, X2, Y1, nil); LineTo(DC, X2, Y3); end; #$CE: begin { Double Cross } MoveToEx(DC, X1, Y2 - 1, nil); LineTo(DC, X2 - 1, Y2 - 1); LineTo(DC, X2 - 1, Y1); MoveToEx(DC, X1, Y2 + 1, nil); LineTo(DC, X2 - 1, Y2 + 1); LineTo(DC, X2 - 1, Y3); MoveToEx(DC, X2 + 1, Y1, nil); LineTo(DC, X2 + 1, Y2 - 1); LineTo(DC, X3, Y2 - 1); MoveToEx(DC, X2 + 1, Y3, nil); LineTo(DC, X2 + 1, Y2 + 1); LineTo(DC, X3, Y2 + 1); end; #$D8: begin { Cross Double Horizontal Single vertical } MoveToEx(DC, X1, Y2 + 1, nil); LineTo(DC, X3, Y2 + 1); MoveToEx(DC, X1, Y2 - 1, nil); LineTo(DC, X3, Y2 - 1); MoveToEx(DC, X2, Y1, nil); LineTo(DC, X2, Y3); end; #$D7: begin { Cross Single Horizontal Double Vertical } MoveToEx(DC, X2 + 1, Y1, nil); LineTo(DC, X2 + 1, Y3); MoveToEx(DC, X2 - 1, Y1, nil); LineTo(DC, X2 - 1, Y3); MoveToEx(DC, X1, Y2, nil); LineTo(DC, X3, Y2); end; #$CA: begin { Double T bottom } MoveToEx(DC, X1, Y2 - 1, nil); LineTo(DC, X2 - 1, Y2 - 1); LineTo(DC, X2 - 1, Y1); MoveToEx(DC, X2 + 1, Y1, nil); LineTo(DC, X2 + 1, Y2 - 1); LineTo(DC, X3, Y2 - 1); MoveToEx(DC, X1, Y2 + 1, nil); LineTo(DC, X3, Y2 + 1); end; #$CB: begin { Double T } MoveToEx(DC, X1, Y2 + 1, nil); LineTo(DC, X2 - 1, Y2 + 1); LineTo(DC, X2 - 1, Y3); MoveToEx(DC, X2 + 1, Y3, nil); LineTo(DC, X2 + 1, Y2 + 1); LineTo(DC, X3, Y2 + 1); MoveToEx(DC, X1, Y2 - 1, nil); LineTo(DC, X3, Y2 - 1); end; #$B0: begin Co := FSavePenColor; for Y := Y1 to Y3 do begin X := X1 + (Y mod 3); while X < X3 do begin //canvas.Pixels[X, Y] := Co; SetPixel(DC, X, Y, Co); X := X + 3; end; end; end; #$B1: begin Co := FSavePenColor; for Y := Y1 to Y3 do begin X := X1 + (Y and 1); while X < X3 do begin //canvas.Pixels[X, Y] := Co; SetPixel(DC, X, Y, Co); X := X + 2; end; end; end; #$B2: begin Co := FSavePenColor; for Y := Y1 to Y3 do begin X := X1 + (Y mod 3); while X < X3 do begin //canvas.Pixels[X, Y] := Co; SetPixel(DC, X, Y, Co); Inc(X); if X < X3 then SetPixel(DC, X, Y, Co); //canvas.Pixels[X, Y] := Co; Inc(X); Inc(X); end; end; end; end; SelectObject(DC, savePen); SelectObject(DC, saveBrush); DeleteObject(aPen); DeleteObject(aBrush); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.PaintOneLine(DC: HDC; Y, Y1: integer; const Line: TLine; nColFrom: integer; nColTo: integer); var rc: TRect; nCnt: integer; nAtt: word; X: integer; nChr: integer; Ch: array[0..3] of char; nCC: integer; // size1: TSize; //backrgb: longint; // chfrom, chto: integer; savepen, apen: THandle; // savecolor: COLORREF; b0: boolean; begin nAtt := Line.Att[nColFrom]; if not FMonoChrome then begin {blink works only in color-mode (standard) for omnisec} {if blink-attribute for text-run is set and blinkstate = 1 then another blink-background is chosen.} if (FblinkState = 0) or (natt and b_blink = 0) then begin if (natt and X_INVERSE) = X_INVERSE then begin SetTextColor(DC, FReverseFG); FSavePenColor := FReverseFG; FSaveBrushColor := FReverseBG; //apen := CreatePen(PS_SOLID, 1, FReverseFG); //abrush := CreateSolidBrush(FReverseBG); //SelectObject(DC, apen); //SelectObject(DC, abrush); end else begin with FPaletteEntries[nAtt and $0F] do begin SetTextColor(DC, PALETTERGB(peRed, peGreen, peBlue)); FSavePenColor := PALETTERGB(peRed, peGreen, peBlue); FSaveBrushColor := PALETTERGB(peRed, peGreen, peBlue); //apen := CreatePen(PS_SOLID, 1, PALETTERGB(peRed, peGreen, peBlue)); //abrush := CreateSolidBrush(PALETTERGB(peRed, peGreen, peBlue)); //SelectObject(DC, apen); //SelectObject(DC, abrush); //SetBkColor(DC, PALETTERGB(peRed, peGreen, peBlue)); end; end; end else begin if ((nAtt shr 4) and $7) = 0 then begin SetTextColor(DC, ($02000000 or BackColor)); end else with FPaletteEntries[(nAtt shr 4) and $07] do begin SetTextColor(DC, PALETTERGB(peRed, peGreen, peBlue)); FSavePenColor := PALETTERGB(peRed, peGreen, peBlue); FSaveBrushColor := PALETTERGB(peRed, peGreen, peBlue); //apen := CreatePen(PS_SOLID, 1, PALETTERGB(peRed, peGreen, peBlue)); //SelectObject(DC, apen); //abrush := CreateSolidBrush(PALETTERGB(peRed, peGreen, peBlue)); //SelectObject(DC, abrush); //acanvas.Brush.Color := PALETTERGB(peRed, peGreen, peBlue); end; end; {if} // with FPaletteEntries[(nAtt shr 4) and $0F] do begin if (natt and X_INVERSE) = X_INVERSE then begin SetBkColor(DC, FReverseBG); end else begin if (((nAtt shr 4) and $F) = $0) or ((nAtt shr 4) = $8) then begin SetBkColor(DC, BackColor); //($02000000 or BackColor)); end else begin //if (nAtt >= $80) then with FPaletteEntries[(nAtt shr 4) and $07] do begin SetBkColor(DC, PALETTERGB(peRed, peGreen, peBlue)); end; end; end; end else begin if (nAtt div $0F) <> 0 then SetBkColor(DC, RGB(127, 127, 127)) else SetBkColor(DC, RGB(255, 255, 255)); if (nAtt and $0F) <> 0 then SetTextColor(DC, RGB(0, 0, 0)) else SetTextColor(DC, RGB(255, 255, 255)); end; nCnt := nColTo - nColFrom; nChr := 0; //savecolor := GetTextColor(DC); if FSINGLE_CHAR_PAINT or (nAtt and X_CODEPAGE2 = X_CODEPAGE2) then begin while nChr < nCnt do begin {$IFDEF CHAR_ZOOM} X := LeftMargin + FCharPos[nColFrom + nChr]; rc.Top := Y + FInternalLeading; rc.Bottom := Y1 + FInternalLeading; rc.Left := X; rc.Right := LeftMargin + FCharPos[nColFrom + nChr + 1]; {$ELSE} X := LeftMargin + (nColFrom + nChr) * FCharWidth; rc.Top := Y + FInternalLeading; rc.Bottom := Y1 + FInternalLeading; rc.Left := X; rc.Right := rc.Left + FCharWidth; {$ENDIF} Ch[0] := Line.Txt[nColFrom + nChr]; Ch[1] := Line.Txt[nColFrom + nChr + 1]; Ch[2] := #$0; nCC := 0; if FGraphicDraw and ((Line.Att[nColFrom + nChr] and X_CODEPAGE2) = X_CODEPAGE2) then begin b0 := (Ch[0] in [#$B3, #$C4, #$DA, #$C0, #$C1, #$C2, #$C3, #$B4, #$BF, #$D9, #$DB, #$DC, #$DD, #$DE, #$DF, #$BA, #$CD, #$C9, #$C8, #$BB, #$BC, #$CC, #$B9, #$C7, #$B6, #$D2, #$D0, #$D5, #$D4, #$B8, #$BE, #$C6, #$D1, #$B5, #$CF, #$D6, #$B7, #$D3, #$BD, #$C5, #$CE, #$D8, #$D7, #$CA, #$CB, #$B0, #$B1, #$B2]); if b0 then begin PaintGraphicChar(DC, X, Y, @rc, Ch[0]); nCC := 1; end; end; if nCC = 0 then begin // fuse 2001.10.23 if (Ch[0] >= #$80) and (Ch[1] >= #$80) then begin rc.Right := LeftMargin + FCharPos[nColFrom + nChr + 2]; ExtTextOut(DC, X, Y, ETO_OPAQUE or ETO_CLIPPED, @rc, @Ch, 2, nil); //TextOut(DC, X, Y, @Ch, 2); nCC := 2; end else if (Ch[0] >= #$80) and (Ch[1] < #$80) then begin rc.Right := LeftMargin + FCharPos[nColFrom + nChr + 2]; ExtTextOut(DC, X, Y, ETO_OPAQUE or ETO_CLIPPED, @rc, @Ch, 2, nil); //TextOut(DC, X, Y, @Ch, 2); nCC := 2; end else begin ExtTextOut(DC, X, Y, ETO_OPAQUE or ETO_CLIPPED, @rc, @Ch, 1, nil); //TextOut(DC, X, Y, @Ch, 1); nCC := 1; end; end; Inc(nChr, nCC); end; if ((FblinkState = 0) or (natt and b_blink = 0)) and ((Line.Att[nColFrom] and X_UNDERLINE) = X_UNDERLINE) then begin apen := CreatePen(PS_SOLID, 1, FSavePenColor); savepen := SelectObject(DC, apen); //GetStockObject(WHITE_PEN)); MoveToEx(DC, LeftMargin + FCharPos[nColFrom], Y1 + FInternalLeading - 2, nil); LineTo(DC, LeftMargin + FCharPos[nColTo], Y1 + FInternalLeading - 2); SelectObject(DC, savepen); DeleteObject(apen); end; end else begin {$IFDEF CHAR_ZOOM} //X := xTextTemp; X := LeftMargin + FCharPos[nColFrom]; rc.Top := Y + FInternalLeading; rc.Bottom := Y1 + FInternalLeading; rc.Left := X; rc.Right := LeftMargin + FCharPos[nColFrom + nCnt]; {$ELSE} X := LeftMargin + nColFrom * FCharWidth; rc.Top := Y + FInternalLeading; rc.Bottom := Y1 + FInternalLeading; rc.Left := X; rc.Right := rc.Left + nCnt * FCharWidth; {$ENDIF} { if nColFrom = 0 then rc.Left := rc.Left - LeftMargin; if nColTo >= FScreen.FColCount then rc.Right := rc.Right + RightMargin; } ExtTextOut(DC, X, Y, ETO_OPAQUE or ETO_CLIPPED, @rc, @Line.Txt[nColFrom], nCnt, nil); // TextOut(DC, X, Y, @Line.Txt[nColFrom], nCnt); //GetTextExtentPoint32(DC, @Line.Txt[nColFrom], nCnt, size1); //xTextTemp := xTextTemp + size1.cx; if ((FblinkState = 0) or (natt and b_blink = 0)) and ((Line.Att[nColFrom] and X_UNDERLINE) = X_UNDERLINE) then begin apen := CreatePen(PS_SOLID, 1, FSavePenColor); savepen := SelectObject(DC, apen); //GetStockObject(WHITE_PEN)); MoveToEx(DC, rc.Left, rc.Bottom - 1, nil); LineTo(DC, rc.Right, rc.Bottom - 1); SelectObject(DC, savepen); DeleteObject(apen); end; end; end; procedure TCustomEmulVT.DrawIndicatorLine(DC: HDC; rect: TRect); var apen, savepen: THandle; begin apen := CreatePen(PS_SOLID, 1, clOlive); savepen := SelectObject(DC, apen); MoveToEx(DC, rect.Left, rect.Bottom, nil); LineTo(DC, rect.Right, rect.Bottom); SelectObject(DC, savepen); DeleteObject(aPen); end; procedure TCustomEmulVT.InvalidateSelectRect(rect: TRect); var x1, y1: integer; l1, l2, ln: integer; srect, r1: TRect; begin if FSelectMode = smBlock then begin InvalidateRect(Handle, @rect, False); end else begin srect := rect; if srect.Bottom < srect.Top then begin x1 := srect.Top; y1 := srect.Left; srect.Top := srect.Bottom; srect.Left := srect.Right; srect.Bottom := x1; srect.Right := y1; end; l1 := PixelToRow(srect.Top); l2 := PixelToRow(srect.Bottom - 2); ln := l2 - l1; x1 := LeftMargin + FCharPos[FScreen.FColCount]; r1 := srect; //if (l1<0) or (l2<1) then Exit; if ln >= 1 then begin r1.Bottom := FLinePos[l1 + 1] + TopMargin; r1.Right := x1; InvalidateRect(Handle, @r1, False); if (ln >= 2) then begin r1.Top := srect.Top + (FLinePos[l1 + 1] - FLinePos[l1]); r1.Left := FCharPos[0] + LeftMargin; r1.Right := x1; r1.Bottom := FLinePos[l2] + TopMargin; InvalidateRect(Handle, @r1, False); end; if l2 > 2 then r1.Top := FLinePos[l2] + TopMargin else r1.Top := srect.Bottom - (FLinePos[2] - FLinePos[1]); r1.Left := FCharPos[0] + LeftMargin; r1.Bottom := srect.Bottom; r1.Right := srect.Right; InvalidateRect(Handle, @r1, False); end else if ln = 0 then begin InvalidateRect(Handle, @srect, False); end; end; end; procedure TCustomEmulVT.DrawSelectRect(DC: HDC; rect: TRect); var x1, y1: integer; l1, l2, ln: integer; srect, r1: TRect; begin if FSelectMode = smBlock then begin srect := rect; if rect.Bottom < rect.Top then begin y1 := srect.Top; x1 := srect.Left; srect.Top := srect.Bottom; srect.Left := srect.Right; srect.Bottom := y1; srect.Right := x1; if srect.Top < TopMargin then begin srect.Top := TopMargin; end else begin l1 := PixelToRow(srect.Top); srect.Top := FLinePos[l1 + 1] + TopMargin; end; l1 := PixelToRow(srect.Bottom); srect.Bottom := FLinePos[l1 + 1] + TopMargin; { if rect.Bottom < TopMargin then begin rect.Bottom := TopMargin; end; else begin l1 := PixelToRow(rect.Top); rect.Top := FLinePos[l1+1]+TopMargin; l1 := PixelToRow(rect.Bottom); rect.Bottom := FLinePos[l1+1]+TopMargin; end; } end; WinProcs.InvertRect(DC, srect); end else begin srect := rect; if srect.Bottom <= srect.Top then begin y1 := srect.Top; x1 := srect.Left; //ln := Round(LineHeight*LineZoom); srect.Top := srect.Bottom; srect.Left := srect.Right; srect.Bottom := y1; srect.Right := x1; if srect.Top < TopMargin then begin srect.Top := TopMargin; end else begin l1 := PixelToRow(srect.Top); srect.Top := FLinePos[l1 + 1] + TopMargin; end; l1 := PixelToRow(srect.Bottom); srect.Bottom := FLinePos[l1 + 1] + TopMargin; end; l1 := PixelToRow(srect.Top); l2 := PixelToRow(srect.Bottom - 2); ln := l2 - l1; x1 := LeftMargin + FCharPos[FScreen.FColCount]; r1 := srect; //if (l1<0) or (l2<1) then Exit; if ln >= 1 then begin r1.Bottom := FLinePos[l1 + 1] + TopMargin; r1.Right := x1; WinProcs.InvertRect(DC, r1); if (ln >= 2) then begin r1.Top := srect.Top + (FLinePos[l1 + 1] - FLinePos[l1]); r1.Left := FCharPos[0] + LeftMargin; r1.Right := x1; r1.Bottom := FLinePos[l2] + TopMargin; WinProcs.InvertRect(DC, r1); end; if l2 > 2 then r1.Top := FLinePos[l2] + TopMargin else r1.Top := srect.Bottom - FLinePos[1]; r1.Left := FCharPos[0] + LeftMargin; r1.Bottom := srect.Bottom; r1.Right := srect.Right; WinProcs.InvertRect(DC, r1); end else if ln = 0 then begin WinProcs.InvertRect(DC, srect); end; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TCustomEmulVT.WMPaint(var Message: TWMPaint); var DC: HDC; rc: TRect; PS: TPaintStruct; OldPen: THandle; OldBrush: THandle; BackBrush: THandle; RealDC: HDC; BackBMP: HBITMAP; OldBackBMP: HBITMAP; begin if not GetUpdateRect(WindowHandle, rc, False) then Exit; BackBrush := 0; DC := Message.DC; if DC = 0 then DC := BeginPaint(WindowHandle, PS); try OldPen := SelectObject(DC, GetStockObject(NULL_PEN)); BackBrush := CreateSolidBrush(BackColor); OldBrush := SelectObject(DC, BackBrush); //if (FSelectRect.Top = -1) then begin if rc.Top <= TopMargin then begin WinProcs.Rectangle(DC, rc.Left, rc.Top, rc.Right, TopMargin); end; if (rc.Left <= LeftMargin) then begin WinProcs.Rectangle(DC, rc.left, rc.Top, LeftMargin + 1, rc.Bottom); end; if (rc.Bottom >= TopMargin + FLinePos[FScreen.FRowCount]) and (FScreen.FRowCount <= MAX_ROW) then WinProcs.Rectangle(DC, rc.Left, TopMargin + FLinePos[FScreen.FRowCount], rc.Right, rc.Bottom + 1); if (rc.Right >= LeftMargin + FCharPos[FScreen.FColCount]) and (FScreen.FColCount <= MAX_COL) then begin WinProcs.Rectangle(DC, LeftMargin + FCharPos[FScreen.FColCount], rc.Top, rc.Right + 1, rc.Bottom); end; //end; SelectObject(DC, OldPen); SelectObject(DC, OldBrush); if BackBrush <> 0 then DeleteObject(BackBrush); DrawEmulVT(DC, rc); //fuse 2001.10.26 if (FSelectRect.Top <> -1) then begin DrawSelectRect(DC, FSelectRect); end; //if FMouseCaptured then Exit; if urlrect.Top > 0 then begin DrawSelectRect(DC, urlrect); end; if indicatorrect.Top > 0 then begin DrawIndicatorLine(DC, indicatorrect); end; finally if Message.DC = 0 then EndPaint(WindowHandle, PS); end; end; procedure TCustomEmulVT.DrawEmulVT(DC: HDC; rc: TRect); var Y, Y1: integer; OldPen: THandle; OldBrush: THandle; OldFont: THandle; // DrawRct: TRect; nRow: integer; nCol: integer; nColFrom: integer; Line: TLine; BackBrush: HBrush; begin BackBrush := 0; OldBrush := 0; if not FMonoChrome then begin SelectPalette(DC, FPal, False); RealizePalette(DC); end; BackBrush := CreateSolidBrush(BackColor); OldBrush := SelectObject(DC, BackBrush); OldPen := SelectObject(DC, GetStockObject(NULL_PEN)); OldFont := SelectObject(DC, FFont.Handle); nRow := PixelToRow(rc.top); nRow := nRow - 1; if nRow < 0 then nRow := 0; {$IFDEF CHAR_ZOOM} Y := TopMargin + FLinePos[nRow]; Y1 := TopMargin + FLinePos[nRow + 1]; {$ELSE} Y := TopMargin + nRow * FLineHeight; Y1 := Y + FLineHeight; {$ENDIF} { if rc.Top <= TopMargin then begin WinProcs.Rectangle(DC, rc.Left, rc.Top, rc.Right + 1, TopMargin + 1); end; if (rc.Left <= LeftMargin) then begin WinProcs.Rectangle(DC, rc.left, rc.Top, LeftMargin + 1, rc.Bottom + 1); end; } nRow := nRow + FTopLine; while nRow < FScreen.FRowCount do begin Line := FScreen.Lines[nRow]; nCol := 0; nColFrom := 0; xTextTemp := LeftMargin; while nCol < FScreen.FColCount do begin while (nCol < FScreen.FColCount) and (Line.Att[nCol] = Line.Att[nColFrom]) do Inc(nCol); PaintOneLine(DC, Y, Y1, Line, nColFrom, nCol); nColFrom := nCol; end; nRow := nRow + 1; {$IFDEF CHAR_ZOOM} Y := TopMargin + FLinePos[nRow - FTopLine]; Y1 := TopMargin + FLinePos[nRow + 1 - FTopLine]; {$ELSE} Y := Y + FLineHeight; Y1 := Y + FLineHeight; {$ENDIF} if Y > rc.Bottom then Break; end; SelectObject(DC, OldFont); SelectObject(DC, OldPen); SelectObject(DC, OldBrush); if BackBrush <> 0 then DeleteObject(BackBrush); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} {fuse +} procedure TCustomEmulVT.WMEraseBkgnd(var Message: TWMEraseBkgnd); var DC: HDC; rc: TRect; PS: TPaintStruct; OldPen: THandle; OldBrush: THandle; BackBrush: THandle; // DrawRct: TRect; begin //inherited; //Exit; if (csDesigning in ComponentState) then begin inherited; Exit; end; // if not GetUpdateRect(WindowHandle, rc, False) then // Exit; rc := GetClientRect; BackBrush := 0; DC := Message.DC; if DC = 0 then DC := BeginPaint(WindowHandle, PS); try OldPen := SelectObject(DC, GetStockObject(NULL_PEN)); BackBrush := CreateSolidBrush(BackColor); OldBrush := SelectObject(DC, BackBrush); //WinProcs.Rectangle(DC, rc.Left, rc.Top, rc.Right, rc.Bottom); if rc.Top <= TopMargin then begin WinProcs.Rectangle(DC, rc.Left, rc.Top, rc.Right, TopMargin + 1); end; if (rc.Left <= LeftMargin) then begin WinProcs.Rectangle(DC, rc.left, rc.Top, LeftMargin + 1, rc.Bottom); end; if (rc.Bottom >= TopMargin + FLinePos[FScreen.FRowCount]) and (FScreen.FRowCount <= MAX_ROW) then WinProcs.Rectangle(DC, rc.Left, TopMargin + FLinePos[FScreen.FRowCount], rc.Right, rc.Bottom + 1); if (rc.Right >= LeftMargin + FCharPos[FScreen.FColCount]) and (FScreen.FColCount <= MAX_COL) then begin WinProcs.Rectangle(DC, LeftMargin + FCharPos[FScreen.FColCount], rc.Top, rc.Right + 1, rc.Bottom); end; SelectObject(DC, OldPen); SelectObject(DC, OldBrush); if BackBrush <> 0 then DeleteObject(BackBrush); // DrawEmulVT(DC, rc); finally if Message.DC = 0 then EndPaint(WindowHandle, PS); end; end; procedure TCustomEmulVT.SetNoScrollBar(Value: boolean); begin if Value = True then begin if Assigned(FVScrollBar) then FVScrollBar.Visible := False; end else begin if Assigned(FVScrollBar) then FVScrollBar.Visible := True; end; FNoScrollBar := Value; end; procedure TCustomEmulVT.SetCaretType(ACaretType: TCaretType); begin FCaretType := ACaretType; SetupCaret; end; procedure TCustomEmulVT.SetVScrollBar(AScrollBar: TScrollBar); begin if AScrollBar = nil then begin FNoScrollBar := True; SetBackRows(0); end else begin FNoScrollBar := False; FVScrollBar := AScrollBar; with FVScrollBar do begin OnScroll := VScrollBarScroll; end; FNoScrollBar := False; //BackRows := FRowCount; end; end; procedure TCustomEmulVT.SetupCaret; begin if not FCursorVisible then Exit; { fuse FCharWidth div 2 replace 6 } if FCaretCreated then begin DestroyCaret; FCaretCreated := False; end; if FCaretShown then begin HideCaret(Handle); FCaretShown := False; end; if FCaretType = ctBlock then CreateCaret(Handle, 0, FCharWidth, FLineHeight) else if FCaretType = ctBLine then CreateCaret(Handle, 0, FCharWidth, 2) else if FCaretType = ctBeam then CreateCaret(Handle, 0, 2, FLineHeight); FCaretCreated := True; SetCaret; if FScreen.Focused and (not FScreen.FCursorOff) then begin ShowCaret(Handle); FCaretShown := True; end; end; procedure TCustomEmulVT.SetSelectMode(ASelectMode: TSelectMode); begin FSelectMode := ASelectMode; Repaint; end; procedure TCustomEmulVT.BlinkStateSet(State: integer); begin if (State = 0) then FBlinkState := 0 else if (State = 1) then FBlinkState := 1 else if (State = 2) then begin {switch automatically} if (FBlinkState = 0) then FBlinkState := 1 else if (FBlinkState = 1) then FBlinkState := 0; UpdateBlinkRegion; end; end; function TCustomEmulVT.NeedBlink: boolean; var i, j: integer; ALine: TLine; bHasBlink: boolean; begin bHasBlink := False; for i := 0 to FScreen.FRowCount - 1 do begin ALine := FScreen.Lines[i]; for j := 0 to FScreen.FColCount - 1 do begin if (ALine.Att[j] and B_BLINK) = B_BLINK then begin bHasBlink := True; Result := bHasBlink; Exit; end; end; end; Result := bHasBlink; end; procedure TCustomEmulVT.UpdateBlinkRegion; var i, j: integer; ALine: TLine; rc: TRect; begin if FMouseCaptured then Exit; for i := 0 to FScreen.FRowCount - 1 do begin ALine := FScreen.Lines[i]; for j := 0 to FScreen.FColCount - 1 do begin if (ALine.Att[j] and B_BLINK) = B_BLINK then begin rc.Left := LeftMargin + FCharPos[j]; rc.Right := LeftMargin + FCharPos[j + 1]; rc.Top := TopMargin + FLinePos[i]; rc.Bottom := TopMargin + FLinePos[i + 1]; InvalidateRect(Handle, @rc, False); end; end; end; end; function TCustomEmulVT.GetPalColor(nPal: integer): TColor; begin with FPaletteEntries[nPal] do begin Result := TColor(RGB(peRed, peGreen, peBlue)); end; end; procedure TCustomEmulVT.SetPalColor(nPal: integer; aColor: TColor); begin with FPaletteEntries[nPal] do begin peRed := GetRValue(aColor); peGreen := GetGValue(aColor); peBlue := GetBValue(aColor); end; end; procedure TCustomEmulVT.GetTextRect(var r: TRect); begin r.Left := LeftMargin; r.Top := TopMargin; r.Right := LeftMargin + FCharPos[FScreen.FColCount]; r.Bottom := TopMargin + FLinePos[FScreen.FRowCount]; end; procedure TCustomEmulVT.CenterTextRect; begin LeftMargin := (Width - FCharPos[FScreen.FColCount]) div 2; if LeftMargin < 1 then LeftMargin := 1; TopMargin := (Height - FLinePos[FScreen.FRowCount]) div 2; if TopMargin < 1 then TopMargin := 1; SetupCaret; end; {fuse +} function TCustomEmulVT.GetDefaultHighlight: boolean; begin Result := FScreen.FDefaultHighlight; end; procedure TCustomEmulVT.SetDefaultHighlight(Value: boolean); begin FScreen.FDefaultHighlight := Value; end; procedure TCustomEmulVT.VScrollBy(dy: integer); begin VScrollBarScroll(self, scLineDown, dy); end; procedure TCustomEmulVT.InitFuncKeyTable; begin Move(FKeys1, FuncKeys, SizeOf(TFuncKeysTable)); end; procedure TCustomEmulVT.LoadFuncKey(filename : string); begin FileToFKeys(FuncKeys, filename); end; {fuse -} end.
// // Generated by JavaToPas v1.5 20180804 - 083221 //////////////////////////////////////////////////////////////////////////////// unit android.telephony.mbms.StreamingService; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, android.net.Uri, android.telephony.mbms.StreamingServiceInfo; type JStreamingService = interface; JStreamingServiceClass = interface(JObjectClass) ['{96221F8D-2962-4DD0-916A-EB33CDD6303F}'] function _GetBROADCAST_METHOD : Integer; cdecl; // A: $19 function _GetREASON_BY_USER_REQUEST : Integer; cdecl; // A: $19 function _GetREASON_END_OF_SESSION : Integer; cdecl; // A: $19 function _GetREASON_FREQUENCY_CONFLICT : Integer; cdecl; // A: $19 function _GetREASON_LEFT_MBMS_BROADCAST_AREA : Integer; cdecl; // A: $19 function _GetREASON_NONE : Integer; cdecl; // A: $19 function _GetREASON_NOT_CONNECTED_TO_HOMECARRIER_LTE : Integer; cdecl; // A: $19 function _GetREASON_OUT_OF_MEMORY : Integer; cdecl; // A: $19 function _GetSTATE_STALLED : Integer; cdecl; // A: $19 function _GetSTATE_STARTED : Integer; cdecl; // A: $19 function _GetSTATE_STOPPED : Integer; cdecl; // A: $19 function _GetUNICAST_METHOD : Integer; cdecl; // A: $19 function getInfo : JStreamingServiceInfo; cdecl; // ()Landroid/telephony/mbms/StreamingServiceInfo; A: $1 function getPlaybackUri : JUri; cdecl; // ()Landroid/net/Uri; A: $1 procedure close ; cdecl; // ()V A: $1 property BROADCAST_METHOD : Integer read _GetBROADCAST_METHOD; // I A: $19 property REASON_BY_USER_REQUEST : Integer read _GetREASON_BY_USER_REQUEST; // I A: $19 property REASON_END_OF_SESSION : Integer read _GetREASON_END_OF_SESSION; // I A: $19 property REASON_FREQUENCY_CONFLICT : Integer read _GetREASON_FREQUENCY_CONFLICT;// I A: $19 property REASON_LEFT_MBMS_BROADCAST_AREA : Integer read _GetREASON_LEFT_MBMS_BROADCAST_AREA;// I A: $19 property REASON_NONE : Integer read _GetREASON_NONE; // I A: $19 property REASON_NOT_CONNECTED_TO_HOMECARRIER_LTE : Integer read _GetREASON_NOT_CONNECTED_TO_HOMECARRIER_LTE;// I A: $19 property REASON_OUT_OF_MEMORY : Integer read _GetREASON_OUT_OF_MEMORY; // I A: $19 property STATE_STALLED : Integer read _GetSTATE_STALLED; // I A: $19 property STATE_STARTED : Integer read _GetSTATE_STARTED; // I A: $19 property STATE_STOPPED : Integer read _GetSTATE_STOPPED; // I A: $19 property UNICAST_METHOD : Integer read _GetUNICAST_METHOD; // I A: $19 end; [JavaSignature('android/telephony/mbms/StreamingService')] JStreamingService = interface(JObject) ['{EB6BABC7-292B-49A1-8436-C9975C070D98}'] function getInfo : JStreamingServiceInfo; cdecl; // ()Landroid/telephony/mbms/StreamingServiceInfo; A: $1 function getPlaybackUri : JUri; cdecl; // ()Landroid/net/Uri; A: $1 procedure close ; cdecl; // ()V A: $1 end; TJStreamingService = class(TJavaGenericImport<JStreamingServiceClass, JStreamingService>) end; const TJStreamingServiceBROADCAST_METHOD = 1; TJStreamingServiceREASON_BY_USER_REQUEST = 1; TJStreamingServiceREASON_END_OF_SESSION = 2; TJStreamingServiceREASON_FREQUENCY_CONFLICT = 3; TJStreamingServiceREASON_LEFT_MBMS_BROADCAST_AREA = 6; TJStreamingServiceREASON_NONE = 0; TJStreamingServiceREASON_NOT_CONNECTED_TO_HOMECARRIER_LTE = 5; TJStreamingServiceREASON_OUT_OF_MEMORY = 4; TJStreamingServiceSTATE_STALLED = 3; TJStreamingServiceSTATE_STARTED = 2; TJStreamingServiceSTATE_STOPPED = 1; TJStreamingServiceUNICAST_METHOD = 2; implementation end.
unit EditSupplierFrm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, DB, DBClient, StdCtrls, DBCtrls, Mask, RzEdit, RzDBEdit, RzButton, RzLabel, ExtCtrls, RzPanel,CommonLIB; type TfrmEditSupplier = class(TForm) RzPanel1: TRzPanel; RzLabel1: TRzLabel; RzLabel3: TRzLabel; RzLabel2: TRzLabel; btnSave: TRzBitBtn; btnCancel: TRzBitBtn; RzDBEdit17: TRzDBEdit; RzDBEdit1: TRzDBEdit; DBCheckBox1: TDBCheckBox; RzDBEdit2: TRzDBEdit; cdsSupplier: TClientDataSet; dsSupplier: TDataSource; RzLabel4: TRzLabel; RzDBEdit3: TRzDBEdit; RzLabel5: TRzLabel; RzDBEdit4: TRzDBEdit; RzLabel6: TRzLabel; RzDBEdit5: TRzDBEdit; RzLabel7: TRzLabel; RzDBEdit6: TRzDBEdit; procedure btnSaveClick(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btnCancelClick(Sender: TObject); private FSupplierCode: integer; FAppParameter: TDLLParameter; procedure SetAppParameter(const Value: TDLLParameter); procedure SetSupplierCode(const Value: integer); { Private declarations } public { Public declarations } property SupplierCode : integer read FSupplierCode write SetSupplierCode; property AppParameter : TDLLParameter read FAppParameter write SetAppParameter; end; var frmEditSupplier: TfrmEditSupplier; implementation {$R *.dfm} uses CdeLIB, STDLIB; { TfrmEditSupplier } procedure TfrmEditSupplier.SetAppParameter(const Value: TDLLParameter); begin FAppParameter := Value; end; procedure TfrmEditSupplier.SetSupplierCode(const Value: integer); begin FSupplierCode := Value; cdsSupplier.Data :=GetDataSet('select * from ICMTTSUP where SUPCOD='+IntToStr(FSupplierCode)); end; procedure TfrmEditSupplier.btnSaveClick(Sender: TObject); var IsNew : boolean; begin IsNew := false; if cdsSupplier.State in [dsinsert] then begin IsNew := true; cdsSupplier.FieldByName('SUPCOD').AsInteger :=getCdeRun('SETTING','RUNNING','SUPCOD','CDENM1'); if cdsSupplier.FieldByName('SUPACT').IsNull then cdsSupplier.FieldByName('SUPACT').AsString:='A'; setEntryUSRDT(cdsSupplier,FAppParameter.UserID); setSystemCMP(cdsSupplier,FAppParameter.Company,FAppParameter.Branch,FAppParameter.Department,FAppParameter.Section); end; if cdsSupplier.State in [dsinsert,dsedit] then setModifyUSRDT(cdsSupplier,FAppParameter.UserID); if cdsSupplier.State in [dsedit,dsinsert] then cdsSupplier.Post; if cdsSupplier.ChangeCount>0 then begin UpdateDataset(cdsSupplier,'select * from ICMTTSUP where SUPCOD='+IntToStr(FSupplierCode)) ; if IsNew then setCdeRun('SETTING','RUNNING','SUPCOD','CDENM1'); end; FSupplierCode:= cdsSupplier.FieldByName('SUPCOD').AsInteger; Close; end; procedure TfrmEditSupplier.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key=VK_ESCAPE then btnCancelClick(nil); if Key=VK_F11 then btnSaveClick(nil); end; procedure TfrmEditSupplier.btnCancelClick(Sender: TObject); begin Close; end; end.
unit Unit_Simul; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, Vcl.StdCtrls, Vcl.Samples.Spin, Vcl.ExtCtrls, Vcl.Buttons, VrControls, VrBlinkLed; type TForm_Simul = class(TForm) SG_Fit_Table: TStringGrid; Label1: TLabel; SpinEdit1: TSpinEdit; Panel1: TPanel; Label2: TLabel; SpeedButton1: TSpeedButton; SpeedButton2: TSpeedButton; CheckBox1: TCheckBox; CB_Fix_Width: TCheckBox; CB_Fix_Pos: TCheckBox; StringGrid1: TStringGrid; SpeedButton3: TSpeedButton; Button1: TButton; LabeledEdit19: TLabeledEdit; LabeledEdit18: TLabeledEdit; Blink: TVrBlinkLed; procedure SG_Fit_TableMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure SG_Fit_TableMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure FormCreate(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); procedure SpinEdit1Change(Sender: TObject); procedure SpeedButton2Click(Sender: TObject); procedure SpeedButton3Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure SG_Fit_TableDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); private { Private declarations } public { Public declarations } end; var Form_Simul: TForm_Simul; implementation uses mainUnit; {$R *.dfm} procedure TForm_Simul.Button1Click(Sender: TObject); vaR fnE, fnG,fld,fmeth: String; fl: TextFIle; od, ka,i: Integer; xf, yf, lin: String; BEGIN fmeth := '_ExpGauss\'; fld := ExtractFilepath(Files[0]) + fmeth; if DirectoryExists(fld) = false then if not CreateDir(fld) then raise Exception.Create('Error creating folders: ' + fld); fnE := ChangeFileExt(ExtractFIleName(Files[FOrm1.CheckListBOx1.ItemIndex]), '.exg'); fnE := fld + '_ExpG_E_'+fnE; AssignFile(fl, fnE); od:=StrToInt(Form1.Edit3.text); ka:= StrToInt(Form1.Edit4.text); Rewrite(fl); for i := od to ka do begin yf :=StringGrid1.Cells[1,i]; Xf := StringGrid1.Cells[0,i]; lin := Xf + #9 + yf; WriteLn(fl, lin); end; CloseFile(fl); fnE := ChangeFileExt(ExtractFIleName(Files[FOrm1.CheckListBOx1.ItemIndex]), '.exg'); fnE := fld + '_ExpG_G_'+fnE; AssignFile(fl, fnE); od:=StrToInt(Form1.Edit3.text); ka:= StrToInt(Form1.Edit4.text); Rewrite(fl); for i := od to ka do begin yf :=StringGrid1.Cells[8,i]; Xf := StringGrid1.Cells[0,i]; lin := Xf + #9 + yf; WriteLn(fl, lin); end; CloseFile(fl); end; procedure TForm_Simul.FormCreate(Sender: TObject); begin Form1.OpenIniFIle; SG_Fit_TAble.ColWidths[0]:=75; SG_Fit_TAble.Cells[0,1]:='a0 or G-Height'; SG_Fit_TAble.Cells[0,2]:='S or G-Width'; SG_Fit_TAble.Cells[0,3]:='K or G-Pos'; SG_Fit_TAble.Cells[1,0]:='Exp'; //SG_Fit_TAble.Cells[2,0]:='Gauss 1'; //SG_Fit_TAble.Cells[3,0]:='Gauss 2'; //SG_Fit_TAble.Cells[4,0]:='Gauss 3'; end; procedure TForm_Simul.SG_Fit_TableDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); begin Rect.Right:=Rect.Right-2; if (acol>0) and (SG_Fit_Table.Cells[acol, 2]<>'') and (arow=2)then if StrTofloat(SG_Fit_Table.Cells[acol, 2])>=StrToFloat(form_Simul.LabeledEdit19.Text) then SG_Fit_Table.Canvas.Font.Color:=clRed else SG_Fit_Table.Canvas.Font.Color := clblack;; SG_Fit_Table.Canvas.TextOut(Rect.Left+2 , Rect.Top+2, SG_Fit_Table.Cells[ACol, ARow]); end; procedure TForm_Simul.SG_Fit_TableMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); var row,col,f,i: Integer; pomak: Double; begin Handled := true; row:=SG_Fit_Table.Row; Col:=SG_Fit_Table.Col; if row=3 then pomak:=0.995 else pomak:=0.98; SG_Fit_TAble.Cells[col,row]:=FormatFloat('0.0000',StrToFloat(SG_Fit_TAble.Cells[col,row])*pomak); form1.SpeedButton3Click(self); f:=Form1.Checklistbox1.ItemIndex; Form1.StringGrid1.Cells[2, f + 1] := FormatFloat('0.00000', vg[1]); Form1.StringGrid1.Cells[3, f + 1] := FormatFloat('0.00000', sg[1]); Form1.StringGrid1.Cells[6, f + 1] := FormatFloat('0.0000', vg[0]); Form1.StringGrid1.Cells[16, f + 1] := FormatFloat('0.0000', vg[2]); // Edit2.Text; for i := 0 to NoGauss - 1 do begin Form1.StringGrid1.Cells[6 * 3 + i * 3, f + 1] := FormatFloat('0.0000', vg[3 + 3 * i]); // Edit2.Text; Form1.StringGrid1.Cells[6 * 3 + i * 3 + 1, f + 1] := FormatFloat('0.00', vg[4 + 3 * i]); // Edit2.Text; Form1.StringGrid1.Cells[6 * 3 + i * 3 + 2, f + 1] := FormatFloat('0.0', vg[5 + 3 * i]); // Edit2.Text; end; Form1.StringGrid1.Refresh; ParManChanged:=true; end; procedure TForm_Simul.SG_Fit_TableMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); var row,col, f,i: Integer; pomak: Double; begin Handled := true; row:=SG_Fit_Table.Row; Col:=SG_Fit_Table.Col; if row=3 then pomak:=1.005 else pomak:=1.02; SG_Fit_TAble.Cells[col,row]:=FormatFloat('0.0000',StrToFloat(SG_Fit_TAble.Cells[col,row])*pomak); form1.SpeedButton3Click(self); f:=Form1.Checklistbox1.ItemIndex; Form1.StringGrid1.Cells[2, f + 1] := FormatFloat('0.00000', vg[1]); Form1.StringGrid1.Cells[3, f + 1] := FormatFloat('0.00000', sg[1]); Form1.StringGrid1.Cells[6, f + 1] := FormatFloat('0.0000', vg[0]); Form1.StringGrid1.Cells[16, f + 1] := FormatFloat('0.0000', vg[2]); // Edit2.Text; for i := 0 to NoGauss - 1 do begin Form1.StringGrid1.Cells[6 * 3 + i * 3, f + 1] := FormatFloat('0.0000', vg[3 + 3 * i]); // Edit2.Text; Form1.StringGrid1.Cells[6 * 3 + i * 3 + 1, f + 1] := FormatFloat('0.00', vg[4 + 3 * i]); // Edit2.Text; Form1.StringGrid1.Cells[6 * 3 + i * 3 + 2, f + 1] := FormatFloat('0.0', vg[5 + 3 * i]); // Edit2.Text; end; //form1.SpeedButton3C Form1.StringGrid1.Refresh; ParManChanged:=true; end; procedure TForm_Simul.SpeedButton1Click(Sender: TObject); var i: Integer; begin NoPointsA[0]:=540; for I := 1 to NoPointsA[0] do begin x[0,i]:=209+i; end; form1.Edit3.Text:='1'; form1.Edit4.Text:='350'; Form1.Simulate(1, NoPointsA[0], CheckBox1.Checked); Form1.SpeedButton3Click(self); end; procedure TForm_Simul.SpeedButton2Click(Sender: TObject); VAR f: TextFile; Fname: String; i: Integer; bl:Boolean; begin fname:=ExtractFilePath(ParamStr(0))+'TempFile.txt'; AssignFIle(f, fname); rewrite(f); for i := NoPointsA[0] downto 1 do Writeln(f,FormatFloat('000',x[0,i])+#9+FormatFloat('0.000000000',y[0,i])); closefile(f); files.Clear; FIles.Add(fname); FOrm1.StringGrid1.RowCount:=2; FOrm1.StringGrid1.Rows[1].Clear; Form1.Caption:='ASFit - '+ExtractFilePath(files[0]); resetSP:=True; FOrm1.CheckListBox1.Clear; if (FileExists(FOrm1.FileNameEdit1.FileName)=False) and FOrm1.RB3.Checked then bl:=False else bl:=True; if resetSP then begin FOrm1.OpenFile(x[0],y[0], PathL[0],NoPointsA[0],FIles[0]); if FOrm1.CheckBox8.Checked then FOrm1.Reconstructspectra(x[0],y[0],NoPointsA[0]); if FOrm1.CB_Smooth.Checked then FOrm1.SGSmutiranje(y[0], 1, NoPointsA[0], FOrm1.SpinEdit1.Value); if bl then FOrm1.SubtractBaseline(x[0],y[0],YBln[0],NoPointsA[0]); if FOrm1.CB_Derivative.Checked then FOrm1.DeriveSG(y[0],1,NoPointsA[0]); end; FOrm1.CheckListBox1.Items.Add(ExtractFIleName(files[0])); FOrm1.CheckListBox1.State[FOrm1.CheckListBox1.items.Count-1]:=cbChecked; BOja[0]:=clBlack; FOrm1.CheckListBox1.ItemIndex:=0; FOrm1.Label5.Caption:='Number of files: '+IntToStr(1); FOrm1.RChart1.Caption:=FOrm1.CheckListBox1.items[0]; FOrm1.Plotallspectra1Click(Self); end; procedure TForm_Simul.SpeedButton3Click(Sender: TObject); begin Form1.CopyTable(StringGrid1); end; procedure TForm_Simul.SpinEdit1Change(Sender: TObject); var I,stWL, pomak, st, sel,f : Integer; stWL2:Double; begin //if sender=Form1.Button6 then SHowMessage('Button6') else ShowMessage(Sender.UnitName); //SpinEdit1.Text:=Form1.SpinEdit2.Text; Form1.SpinEdit4.Value:=SpinEdit1.Value; sel:=Form1.CheckListBox1.itemindex; //Form1.SpinEdit2.Value:=SpinEdit1.Value; Nogauss:=SpinEdit1.value; stWL2:=StrToFloat(Form1.LabeledEdit6.text); st:=0; for I := 1 to NoPointsA[sel]-1 do if abs(x[sel,i]-stWL2)<2 then begin st:=i; break; end; if st=0 then st:=20; for I := 1 to 6 do if i>Nogauss then begin SG_Fit_TAble.cols[i+1].Clear; end; for I := 1 to Nogauss do Form_Simul.SG_Fit_Table.Cells[i+1, 0] := 'Gauss '+IntToStr(i);; if sender=SpinEdit1 then exit; if Form1.CB_slope.Checked then begin SG_Fit_Table.Cells[1, 1] := '0'; SG_Fit_Table.Cells[1, 2] := '0'; SG_Fit_Table.Cells[1, 3] := '0'; stWL:=270; end else begin SG_Fit_Table.Cells[1, 1] := formatFloat('0.000',Y[sel, st]); SG_Fit_Table.Cells[1, 2] := '0.020'; SG_Fit_Table.Cells[1, 3] := '0'; stWL:=270; end; //form1.Button6Click(Self); case Nogauss of 2: pomak:=80; 3: pomak:=60; 4: pomak:=40; 5: pomak:=30; 6: pomak:=30; end; if Form1.CB_slope.Checked then pomak:=50; SG_Fit_Table.Cells[1, 0] := 'Exp 1'; //ShowMessage(IntToStr(Nogauss)); for I := 1 to Nogauss do begin // if Form1.CB_slope.Checked then pomak:=pomak+0; SG_Fit_Table.Cells[i+1, 0] := 'Gauss '+IntToStr(i);; if Form1.CB_slope.Checked then SG_Fit_Table.Cells[i+1, 1] := formatFloat('0.000',0.06*Y[sel, st]*(36/i/i)) else SG_Fit_Table.Cells[i+1, 1] := formatFloat('0.000',0.003*Y[sel, st]*(36/i/i)); SG_Fit_Table.Cells[i+1, 2] := formatFloat('0.0',15*(1+0.18*i)); if (Form1.CheckBox13.Checked=false) or (sender=Form1.SpinEdit2) then begin SG_Fit_Table.Cells[i+1, 3]:=IntToStr(stWL+(i-1)*pomak); // if I=1 then SG_Fit_Table.Cells[i+1, 3] := '270'; //if I=2 then SG_Fit_Table.Cells[i+1, 3] := '300'; //if I=3 then SG_Fit_Table.Cells[i+1, 3] := '330'; //if I=4 then SG_Fit_Table.Cells[i+1, 3] := '360'; //if I=5 then SG_Fit_Table.Cells[i+1, 3] := '390'; //if I=6 then SG_Fit_Table.Cells[i+1, 3] := '420';; end; end; SG_Fit_Table.Refresh; // if (sender=Form1.SpinEdit2) or (sender=Form1.button6) then form1.SpeedButton3Click(self); exit; f:=Form1.Checklistbox1.ItemIndex; Form1.StringGrid1.Rows[f+1].Clear; Form1.StringGrid1.Cells[2, f + 1] := FormatFloat('0.00000', vg[1]); Form1.StringGrid1.Cells[3, f + 1] := FormatFloat('0.00000', sg[1]); Form1.StringGrid1.Cells[6, f + 1] := FormatFloat('0.0000', vg[0]); Form1.StringGrid1.Cells[16, f + 1] := FormatFloat('0.0000', vg[2]); // Edit2.Text; for i := 0 to NoGauss - 1 do begin Form1.StringGrid1.Cells[6 * 3 + i * 3, f + 1] := FormatFloat('0.0000', vg[3 + 3 * i]); // Edit2.Text; Form1.StringGrid1.Cells[6 * 3 + i * 3 + 1, f + 1] := FormatFloat('0.00', vg[4 + 3 * i]); // Edit2.Text; Form1.StringGrid1.Cells[6 * 3 + i * 3 + 2, f + 1] := FormatFloat('0.0', vg[5 + 3 * i]); // Edit2.Text; end; end; end.
program GameMain; uses SwinGame, sgMaps; procedure Main(); begin OpenAudio(); OpenGraphicsWindow('Hello World', 800, 600); LoadDefaultColors(); ShowSwinGameSplashScreen(); WriteLn('Testing LoadBitmap'); LoadBitmapNamed('testing','testing.bmp'); WriteLn('Testing LoadSoundEffect'); LoadSoundEffectNamed('testing2','testing.wav'); WriteLn('Testing LoadMusic'); LoadMusicNamed('testing3','testing.wav'); WriteLn('Testing LoadFont'); LoadFontNamed('testingfont', 'testing.ttf',12); WriteLn('Testing LoadPanel'); LoadPanelNamed('testing panel', 'testing panel'); try WriteLn('Testing LoadMap'); LoadMapNamed('testing map', 'testmap'); except end; try WriteLn('Testing LoadBundle'); LoadResourceBundleNamed('bundle testing','bundlefile', true); except end; try WriteLn('Testing LoadCharacter'); LoadCharacterNamed('testing character' , 'testing.character'); except end; repeat // The game loop... ProcessEvents(); ClearScreen(ColorWhite); DrawFramerate(0,0); RefreshScreen(); until WindowCloseRequested(); CloseAudio(); ReleaseAllResources(); end; begin Main(); end.
unit MVCBr.NavigateModel; interface uses System.Classes, System.SysUtils, MVCBr.Interf, MVCBr.Model, MVCBr.Controller; Type TNavigateModelFactory = class(TModelFactory, INavigateModel) protected FController:IController; public function Controller(const AController: IController): INavigateModel;reintroduce;virtual; end; implementation { TPersistentModelFactory } function TNavigateModelFactory.Controller(const AController: IController) : INavigateModel; begin FController := AController; end; end.
unit CSV.Interfaces; interface uses System.Classes, Spring, MVVM.Interfaces, MVVM.Interfaces.Architectural, MVVM.Bindings; type TProgresoProcesamiento = procedure(const AData: Integer) of Object; ICSVFile_Model = Interface(IModel) ['{8B9E3855-735B-4641-AA49-8C20E5F6759A}'] function GetFileName: String; procedure SetFileName(const AFileName: String); function GetIsPathOK: Boolean; function GetProgresoProcesamiento: Integer; function GetOnProgresoProcesamiento: IEvent<TProgresoProcesamiento>; function GetOnPropertyChanged: IEvent<TNotifySomethingChangedEvent>; function LoadFile: TStrings; function ProcesarFicheroCSV: Boolean; function ProcesarFicheroCSV_Parallel: Boolean; property IsPathOk: Boolean read GetIsPathOK; property FileName: String read GetFileName write SetFileName; property ProgresoProcesamiento: Integer read GetProgresoProcesamiento; property OnPropertyChanged: IEvent<TNotifySomethingChangedEvent> read GetOnPropertyChanged; property OnProgresoProcesamiento: IEvent<TProgresoProcesamiento> read GetOnProgresoProcesamiento; end; TFinProcesamiento = procedure(const AData: String) of Object; ICSVFile_ViewModel = Interface(IViewModel) ['{A3EA9B78-2144-4AE3-98CE-6EF522DCDBF7}'] function GetFileName: String; procedure SetFileName(const AFileName: String); function GetProgresoProcesamiento: Integer; function GetOnProcesamientoFinalizado: IEvent<TFinProcesamiento>; function GetOnProgresoProcesamiento: IEvent<TProgresoProcesamiento>; function GetIsValidFile: Boolean; procedure SetModel(AModel: ICSVFile_Model); procedure ProcesarFicheroCSV; procedure ProcesarFicheroCSV_Parallel; procedure CreateNewView; property IsValidFile: Boolean read GetIsValidFile; property FileName: String read GetFileName write SetFileName; property ProgresoProcesamiento: Integer read GetProgresoProcesamiento; property OnProcesamientoFinalizado: IEvent<TFinProcesamiento> read GetOnProcesamientoFinalizado; property OnProgresoProcesamiento: IEvent<TProgresoProcesamiento> read GetOnProgresoProcesamiento; end; const ICSVFile_View_NAME = 'ICSVFile_View'; implementation end.
namespace RemObjects.Elements.EUnit; interface type Assert = public partial static class {$IF NOUGAT}mapped to Object{$ENDIF} public method AreEqual<T>(Actual, Expected : sequence of T; IgnoreOrder: Boolean := false; Message: String := nil); {$IF NOUGAT}where T is class;{$ENDIF} method AreNotEqual<T>(Actual, Expected: sequence of T; IgnoreOrder: Boolean := false; Message: String := nil); {$IF NOUGAT}where T is class;{$ENDIF} method Contains<T>(Item: T; InSequence: sequence of T; Message: String := nil); {$IF NOUGAT}where T is class;{$ENDIF} method DoesNotContains<T>(Item: T; InSequence: sequence of T; Message: String := nil); {$IF NOUGAT}where T is class;{$ENDIF} method IsEmpty<T>(Actual: sequence of T; Message: String := nil); {$IF NOUGAT}where T is class;{$ENDIF} method IsNotEmpty<T>(Actual: sequence of T; Message: String := nil); {$IF NOUGAT}where T is class;{$ENDIF} end; implementation class method Assert.AreEqual<T>(Actual: sequence of T; Expected: sequence of T; IgnoreOrder: Boolean; Message: String := nil); begin var Error := if IgnoreOrder then SequenceHelper.Same(Actual, Expected) else SequenceHelper.Equals(Actual, Expected); FailIfNot(Error = nil, coalesce(Message, Error)); end; class method Assert.AreNotEqual<T>(Actual: sequence of T; Expected: sequence of T; IgnoreOrder: Boolean; Message: String := nil); begin var Error := if IgnoreOrder then SequenceHelper.Same(Actual, Expected) else SequenceHelper.Equals(Actual, Expected); FailIf(Error = nil, coalesce(Message, AssertMessages.SequenceEquals)); end; class method Assert.Contains<T>(Item: T; InSequence: sequence of T; Message: String := nil); begin ArgumentNilException.RaiseIfNil(InSequence, "InSequence"); var Error := SequenceHelper.Contains(Item, InSequence); FailIfNot(Error = nil, Item, "Sequence", coalesce(Message, AssertMessages.DoesNotContains)); end; class method Assert.DoesNotContains<T>(Item: T; InSequence: sequence of T; Message: String := nil); begin ArgumentNilException.RaiseIfNil(InSequence, "InSequence"); var Error := SequenceHelper.Contains(Item, InSequence); FailIf(Error = nil, Item, "Sequence", coalesce(Message, AssertMessages.UnexpectedContains)); end; class method Assert.IsEmpty<T>(Actual: sequence of T; Message: String := nil); begin ArgumentNilException.RaiseIfNil(Actual, "Actual"); var Count := SequenceHelper.Count(Actual); FailIfNot(Count = 0, Count, "Sequence", coalesce(Message, AssertMessages.IsNotEmpty)); end; class method Assert.IsNotEmpty<T>(Actual: sequence of T; Message: String := nil); begin ArgumentNilException.RaiseIfNil(Actual, "Actual"); var Count := SequenceHelper.Count(Actual); FailIf(Count = 0, Count, "Sequence", coalesce(Message, AssertMessages.IsEmpty)); end; end.
{******************************************************************************* * uFloatControl * * * * Библиотека компонентов для работы с формой редактирования (qFControls) * * Работа с вводом дробных чисел (TqFFloatControl) * * Copyright © 2005, Олег Г. Волков, Донецкий Национальный Университет * *******************************************************************************} unit uFloatControl; interface uses SysUtils, Classes, Controls, uFControl, StdCtrls, Graphics, uLabeledFControl, uCharControl, Registry; type TqFFloatControl = class(TqFCharControl) private FNegativeAllowed: Boolean; FPrecision: Integer; FFormat: String; protected procedure SetValue(Val: Variant); override; function GetValue: Variant; override; procedure BlockKeys(Sender: TObject; var Key: Char); procedure SetPrecision(Prec: Integer); public constructor Create(AOwner: TComponent); override; function Check: String; override; function ToString: String; override; procedure LoadFromRegistry(reg: TRegistry); override; // vallkor procedure SaveIntoRegistry(reg: TRegistry); override; // vallkor published property NegativeAllowed: Boolean read FNegativeAllowed write FNegativeAllowed; property Precision: Integer read FPrecision write SetPrecision; property Format: String read FFormat write FFormat; end; procedure Register; {$R *.res} implementation uses qFStrings, Variants; procedure TqFFloatControl.SetPrecision(Prec: Integer); var i: Integer; begin FPrecision := Prec; FFormat := '#########0'; if Prec > 0 then begin FFormat := FFormat + '.'; for i:=1 to Prec do FFormat := FFormat + '0'; end; end; constructor TqFFloatControl.Create(AOwner: TComponent); begin inherited Create(AOwner); FEdit.OnKeyPress := BlockKeys; Precision := 2; end; procedure TqFFloatControl.BlockKeys(Sender: TObject; var Key: Char); var p: Integer; begin if not ( Key in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', #8, '.', ','] ) then Key := #0; p := Pos('.', FEdit.Text); if p = 0 then p := Pos(',', FEdit.Text); if ( p <> 0 ) and ( Key in ['.', ','] ) then Key := #0; { if ( p <> 0 ) and ( Key <> #8 ) and ( FEdit.SelStart >= p ) and ( Length(FEdit.Text) - p >= FPrecision ) then Key := #0;} if ( p = 0 ) and ( Key in ['.', ','] ) and ( Length(FEdit.Text) - FEdit.SelStart > FPrecision ) then Key := #0; end; function TqFFloatControl.ToString: String; var ds: Char; begin if Trim(FEdit.Text) = '' then if Required then Result := '0' else Result := 'Null' else begin ds := DecimalSeparator; DecimalSeparator := '.'; Result := FloatToStr(Value); DecimalSeparator := ds; end; end; function TqFFloatControl.Check: String; var val: Variant; begin val := Value; Check := ''; if ( Trim(FEdit.Text) = '' ) and Required then Check := qFFieldIsEmpty + '"' + DisplayName + '"!' else if VarIsNull(val) and ( Trim(FEdit.Text) <> '' ) then Check := DisplayName + qFNotFloat else if Required then if ( not NegativeAllowed ) and ( val < 0 ) then Check := DisplayName + qFNegative; end; procedure TqFFloatControl.SetValue(Val: Variant); begin if VarIsNull(Val) or VarIsEmpty(Val) then FEdit.Text := '' else begin FEdit.Text := FormatFloat(FFormat, Val); if Asterisk then Asterisk := False; end; end; function TqFFloatControl.GetValue: Variant; var str: String; f: Extended; begin str := FEdit.Text; str := StringReplace(str, '.', DecimalSeparator, []); str := StringReplace(str, ',', DecimalSeparator, []); if TryStrToFloat(str, f) then Result := f else Result := Null; end; procedure Register; begin RegisterComponents('qFControls', [TqFFloatControl]); end; procedure TqFFloatControl.LoadFromRegistry(reg: TRegistry); // vallkor begin inherited LoadFromRegistry(reg); Value := Reg.ReadFloat('Value'); end; procedure TqFFloatControl.SaveIntoRegistry(reg: TRegistry); // vallkor begin inherited SaveIntoRegistry(reg); Reg.WriteFloat('Value', Value); end; end.
unit XLS_RC4; interface uses Classes, SysUtils; type TRC4Key = record State: array[0..255] of byte; x,y: byte; end; procedure RC4PrepareKey(KeyData: PByteArray; DataLen: integer; var Key: TRC4Key); procedure RC4(Buffer: PByteArray; BuffLen: integer; var Key: TRC4Key); implementation procedure SwapByte(var A,B: byte); var T: byte; begin T := A; A := B; B := T; end; procedure RC4PrepareKey(KeyData: PByteArray; DataLen: integer; var Key: TRC4Key); var Index1: byte; Index2: byte; State: PByteArray; Counter: longword; begin State := @Key.state; for Counter := 0 to 255 do State[Counter] := Counter; Key.X := 0; Key.Y := 0; Index1 := 0; Index2 := 0; for Counter := 0 to 255 do begin Index2 := (KeyData[Index1] + State[counter] + Index2) mod 256; SwapByte(State[Counter],State[Index2]); Index1 := (Index1 + 1) mod DataLen; end; end; procedure RC4(Buffer: PByteArray; BuffLen: integer; var Key: TRC4Key); var X: byte; Y: byte; State: PByteArray; XorIndex: byte; Counter: longword; begin if BuffLen <= 0 then Exit; X := Key.X; Y := Key.Y; State := @Key.state; for Counter := 0 to BuffLen - 1 do begin X := (X + 1) mod 256; Y := (State[X] + Y) mod 256; SwapByte(State[X],State[Y]); XorIndex := (State[X] + State[Y]) mod 256; Buffer[Counter] := Buffer[Counter] xor State[XorIndex]; end; Key.X := X; Key.Y := Y; end; end.
unit OTFECrossCrypt_PasswordEntry; // Description: // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, OTFECrossCrypt_DriverAPI; type TOTFECrossCrypt_PasswordEntry_F = class(TForm) Label1: TLabel; Label2: TLabel; pbOK: TButton; pbCancel: TButton; cbDrive: TComboBox; Label3: TLabel; ckReadonly: TCheckBox; ckMountAsCD: TCheckBox; cbCipher: TComboBox; ckMultipleKey: TCheckBox; rePasswords: TRichEdit; lblPasswordCount: TLabel; pbLoadFromFile: TButton; OpenKeyfileDlg: TOpenDialog; procedure FormShow(Sender: TObject); procedure pbOKClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormCreate(Sender: TObject); procedure ckMultipleKeyClick(Sender: TObject); procedure cbCipherChange(Sender: TObject); procedure ckMountAsCDClick(Sender: TObject); procedure rePasswordsChange(Sender: TObject); procedure pbCancelClick(Sender: TObject); procedure pbLoadFromFileClick(Sender: TObject); private FConfirm: boolean; FMinPasswordLength: integer; FCipher: TCROSSCRYPT_CIPHER_TYPE; FDriveLetter: Ansichar; FMountReadOnly: boolean; FMountAsCD: boolean; FMultipleKey: boolean; FPasswords: TStringList; FOnlyReadWrite: boolean; function GetUnusedDriveLetters(): string; procedure ClearPasswords(); function DetermineSelectedCipher(): TCROSSCRYPT_CIPHER_TYPE; procedure UpdatePasswordCount(); procedure WipeGUI(); procedure WipeInternal(); procedure EnableDisable(); procedure UserPasswordMask(mask: boolean); public // Confirm - if set, the user will be asked to confirm their passwords, or // that they wish to proceed if the cipher they choose is // "cphrNone" property Confirm: boolean read FConfirm write FConfirm; // MinPasswordLength - if set, the user will additionally be prompted to // confirm the passwords are correct, if their password // is shorter than this number of chars. // Set to 0 to disable this confirmation property MinPasswordLength: integer read FMinPasswordLength write FMinPasswordLength; property Cipher: TCROSSCRYPT_CIPHER_TYPE read FCipher write FCipher; property DriveLetter: Ansichar read FDriveLetter write FDriveLetter; property MountReadOnly: boolean read FMountReadOnly write FMountReadOnly; property MountAsCD: boolean read FMountAsCD write FMountAsCD; property MultipleKey: boolean read FMultipleKey write FMultipleKey; // If this is set, the user will not be able to specify "readonly" or "CD" property OnlyReadWrite: boolean read FOnlyReadWrite write FOnlyReadWrite; procedure GetSinglePassword(var password: Ansistring); procedure GetMultiplePasswords(passwords: TStringList); procedure AddPassword(password: string); // Clear down the dialog's internals... procedure Wipe(); end; implementation {$R *.DFM} uses SDUGeneral, OTFECrossCrypt_PasswordConfirm; const CRLF = #13+#10; procedure TOTFECrossCrypt_PasswordEntry_F.FormShow(Sender: TObject); var ct: TCROSSCRYPT_CIPHER_TYPE; i: integer; drvs: string; driveLetterColon: string; driveIdx: integer; begin rePasswords.PlainText := TRUE; rePasswords.Lines.Clear(); UserPasswordMask(TRUE); rePasswords.Lines.AddStrings(FPasswords); for ct:=low(CROSSCRYPT_CIPHER_NAMES) to high(CROSSCRYPT_CIPHER_NAMES) do begin if (ct<>cphrUnknown) then begin cbCipher.items.add(CROSSCRYPT_CIPHER_NAMES[ct]); end; end; if (Cipher = cphrUnknown) then begin Cipher := cphrNone; end; cbCipher.ItemIndex := ord(Cipher); // Setup the drives the user is allowed to select drvs := GetUnusedDriveLetters(); for i:=1 to length(drvs) do begin if ( (drvs[i] <> 'A') and (drvs[i] <> 'B') ) then begin cbDrive.items.Add(drvs[i]+':'); end; end; cbDrive.sorted := TRUE; // Select the appropriate drive letter... driveLetterColon := DriveLetter+':'; driveIdx := cbDrive.Items.IndexOf(driveLetterColon); if (driveIdx < 0) then begin driveIdx := 0; end; cbDrive.ItemIndex := driveIdx; ckReadonly.checked := MountReadOnly; ckMountAsCD.checked := MountAsCD; ckMultipleKey.checked := MultipleKey; EnableDisable(); end; procedure TOTFECrossCrypt_PasswordEntry_F.pbOKClick(Sender: TObject); var tmpDriveStr: Ansistring; allOK: boolean; confirmDlg: TOTFECrossCrypt_PasswordConfirm_F; confirmMultiplePw: TStringList; confirmSinglePw: Ansistring; i: integer; origSinglePw: Ansistring; msgDlgReply: word; askUser: boolean; begin allOK := TRUE; // Ensure that in multikey mode, we have MULTIKEY_PASSWORD_REQUIREMENT passwords if ckMultipleKey.checked and (Cipher<>cphrNone)then begin if (rePasswords.Lines.count<MULTIKEY_PASSWORD_REQUIREMENT) then begin MessageDlg('You must enter a total of '+inttostr(MULTIKEY_PASSWORD_REQUIREMENT)+' passwords, one per line.'+CRLF+ CRLF+ 'You have entered '+inttostr(rePasswords.Lines.count)+' passwords.'+CRLF+ CRLF+ 'Please correct, and try again.', mtError, [mbOK], 0); allOK := FALSE; end; end; // Transfer the data stored in the GUI into the internal store if allOK then begin FPasswords.Clear(); FPasswords.AddStrings(rePasswords.Lines); Cipher := DetermineSelectedCipher(); tmpDriveStr := cbDrive.items[cbDrive.ItemIndex]; DriveLetter := tmpDriveStr[1]; MountReadOnly := ckReadonly.checked; MountAsCD := ckMountAsCD.checked; MultipleKey := ckMultipleKey.checked; end; // If we are to confirm the user's passwords, we confirm if the user selected // "none" as the encryption algorithm if allOK then begin if Confirm and (Cipher=cphrNone) then begin msgDlgReply := MessageDlg( 'You have selected "'+cbCipher.Items[cbCipher.ItemIndex]+'" as the encryption algorithm.'+CRLF+ CRLF+ 'This means that although CrossCrypt will operate as normal,'+CRLF+ 'no actual encryption of your data will take place.'+CRLF+ CRLF+ 'Do you wish to continue?', mtConfirmation, [mbYes, mbNo], 0 ); allOK := (msgDlgReply = mrYes); end; end; // If we're supposed to get the user to confirm short password(s)... if (allOK) then begin if (MinPasswordLength>0) then begin msgDlgReply := mrYes; if (MultipleKey) then begin confirmMultiplePw := TStringList.Create(); try GetMultiplePasswords(confirmMultiplePw); askUser:= FALSE; for i:=0 to (confirmMultiplePw.count-1) do begin if (length(confirmMultiplePw[i]) < MinPasswordLength) then begin askUser:= TRUE; break; end; end; finally confirmMultiplePw.Text := StringOfChar('X', length(confirmMultiplePw.text)); confirmMultiplePw.Free(); end; // No point in warning the user if there's no encryption! if askUser and (Cipher<>cphrNone) then begin msgDlgReply := MessageDlg('One or more of the keyphrases you entered is less than '+inttostr(MinPasswordLength)+' characters long.'+CRLF+ CRLF+ 'In order to be able to use this box with Linux, all of'+CRLF+ 'your keyphrases must be longer than '+inttostr(MinPasswordLength)+' characters long.'+CRLF+ CRLF+ 'Do you wish to proceed?', mtWarning, [mbYes, mbNo], 0 ); end; end else begin GetSinglePassword(origSinglePw); // No point in warning the user if there's no encryption! if (Length(origSinglePw) < MinPasswordLength) and (Cipher<>cphrNone) then begin msgDlgReply := MessageDlg('The keyphrase you entered is less than '+inttostr(MinPasswordLength)+' characters long.'+CRLF+ CRLF+ 'In order to be able to use this box with Linux,'+CRLF+ 'your keyphrase must be longer than '+inttostr(MinPasswordLength)+' characters long.'+CRLF+ CRLF+ 'Do you wish to proceed?', mtWarning, [mbYes, mbNo], 0 ); end; origSinglePw := StringOfChar('X', length(origSinglePw)); end; allOK := (msgDlgReply = mrYes); end; end; // If we are to confirm the user's passwords, do that now... if allOK then begin // Note: We don't confirm if there's no encryption! if Confirm and (Cipher<>cphrNone) then begin // Switch to assuming password mismatch allOK := FALSE; confirmDlg := TOTFECrossCrypt_PasswordConfirm_F.Create(nil); try confirmDlg.MultipleKey := MultipleKey; if (confirmDlg.ShowModal = mrOK) then begin if (MultipleKey) then begin confirmMultiplePw := TStringList.Create(); try confirmDlg.GetMultiplePasswords(confirmMultiplePw); if (confirmMultiplePw.count = rePasswords.lines.count) then begin // Back to assuming allOK = TRUE; allOK := TRUE; for i:=0 to (confirmMultiplePw.count-1) do begin if (confirmMultiplePw[i] <> rePasswords.lines[i]) then begin allOK := FALSE; break; end; end; end; finally confirmMultiplePw.Text := StringOfChar('X', length(confirmMultiplePw.text)); confirmMultiplePw.Free(); end; end else begin confirmDlg.GetSinglePassword(confirmSinglePw); GetSinglePassword(origSinglePw); if (origSinglePw = confirmSinglePw) then begin allOK := TRUE; end; origSinglePw := StringOfChar('X', length(origSinglePw)); confirmSinglePw := StringOfChar('X', length(confirmSinglePw)); end; if (not(allOK)) then begin MessageDlg('The passwords you entered do not match.'+#13+#10+''+#13+#10+'Please try again.', mtError, [mbOK], 0); end; end; // if (confirmDlg.ShowModal = mrOK) then finally confirmDlg.Wipe(); confirmDlg.Free(); end; end; // if Confirm then end; // if allOK then if allOK then begin // All OK, exit... ModalResult := mrOK; end; end; // Returns a string containing the drive letters of "unallocated" drives function TOTFECrossCrypt_PasswordEntry_F.GetUnusedDriveLetters(): string; var driveLetters: string; DriveNum: Integer; DriveBits: set of 0..25; begin driveLetters := ''; Integer(DriveBits) := GetLogicalDrives(); for DriveNum := 0 to 25 do begin if not(DriveNum in DriveBits) then begin driveLetters := driveLetters + Char(DriveNum + Ord('A')); end; end; Result := driveLetters; end; function TOTFECrossCrypt_PasswordEntry_F.DetermineSelectedCipher(): TCROSSCRYPT_CIPHER_TYPE; begin Result := TCROSSCRYPT_CIPHER_TYPE(cbCipher.ItemIndex); end; procedure TOTFECrossCrypt_PasswordEntry_F.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin WipeGUI(); end; procedure TOTFECrossCrypt_PasswordEntry_F.Wipe(); begin WipeInternal(); end; procedure TOTFECrossCrypt_PasswordEntry_F.WipeGUI(); begin // Cleardown the GUI components... rePasswords.Text := StringOfChar('X', length(rePasswords.text)); cbCipher.ItemIndex := 0; cbDrive.ItemIndex := 0; ckReadonly.checked := FALSE; ckMountAsCD.checked := FALSE; end; procedure TOTFECrossCrypt_PasswordEntry_F.WipeInternal(); begin // Cleardown the internal store... ClearPasswords(); FCipher := low(TCROSSCRYPT_CIPHER_TYPE); FDriveLetter := #0; FMountReadonly := FALSE; FMountAsCD := FALSE; FMultipleKey := FALSE; end; procedure TOTFECrossCrypt_PasswordEntry_F.ClearPasswords(); var i: integer; begin for i:=0 to (FPasswords.count-1) do begin FPasswords[i] := StringOfChar('X', length(FPasswords[i])); end; FPasswords.Clear(); end; // Get the single password procedure TOTFECrossCrypt_PasswordEntry_F.GetSinglePassword(var password: Ansistring); begin password := FPasswords.Text; { TODO 1 -otdk -cbug : alert user if use unicode } // Trim off the CRLF Delete(password, (Length(password)-1), 2); end; // Returns '' on failure procedure TOTFECrossCrypt_PasswordEntry_F.GetMultiplePasswords(passwords: TStringList); begin passwords.Text := StringOfChar('X', length(passwords.text)); passwords.Clear(); passwords.AddStrings(FPasswords); end; procedure TOTFECrossCrypt_PasswordEntry_F.AddPassword(password: string); begin FPasswords.Add(password); end; procedure TOTFECrossCrypt_PasswordEntry_F.FormCreate(Sender: TObject); begin FPasswords:= TStringList.Create(); // Initialize... Confirm := FALSE; MinPasswordLength := 0; Cipher := cphrAES256; DriveLetter:= #0; MountReadOnly:= FALSE; MountAsCD:= FALSE; MultipleKey:= FALSE; end; procedure TOTFECrossCrypt_PasswordEntry_F.ckMultipleKeyClick(Sender: TObject); begin // If we're only accepting a single password, wordwrap; if multiple // passwords, then they need to be entered one per line. rePasswords.WordWrap := not(ckMultipleKey.checked); UpdatePasswordCount(); if ckMultipleKey.checked then begin MessageDlg( 'Please enter your '+inttostr(MULTIKEY_PASSWORD_REQUIREMENT)+' passwords, one password per line', mtInformation, [mbOK], 0 ); end; UserPasswordMask(TRUE); end; procedure TOTFECrossCrypt_PasswordEntry_F.cbCipherChange(Sender: TObject); begin // Enable, disable controls as appropriate... EnableDisable(); end; procedure TOTFECrossCrypt_PasswordEntry_F.ckMountAsCDClick(Sender: TObject); begin // Enable, disable controls as appropriate... EnableDisable(); end; procedure TOTFECrossCrypt_PasswordEntry_F.EnableDisable(); begin // Enable, disable controls as appropriate... if (DetermineSelectedCipher() = cphrUnknown) OR (DetermineSelectedCipher() = cphrNone) then begin ckMultipleKey.checked := FALSE; SDUEnableControl(rePasswords, FALSE); SDUEnableControl(ckMultipleKey, FALSE); end else begin SDUEnableControl(rePasswords, TRUE); SDUEnableControl(ckMultipleKey, TRUE); end; if OnlyReadWrite then begin ckMountAsCD.checked := FALSE; ckReadonly.checked := FALSE; SDUEnableControl(ckMountAsCD, FALSE); SDUEnableControl(ckReadonly, FALSE); end else begin SDUEnableControl(ckMountAsCD, TRUE); if ckMountAsCD.checked then begin ckReadonly.checked := TRUE; SDUEnableControl(ckReadonly, FALSE); end else begin ckReadonly.checked := FALSE; SDUEnableControl(ckReadonly, TRUE); end; end; UserPasswordMask(TRUE); end; procedure TOTFECrossCrypt_PasswordEntry_F.rePasswordsChange(Sender: TObject); begin UpdatePasswordCount(); end; procedure TOTFECrossCrypt_PasswordEntry_F.UpdatePasswordCount(); begin if (ckMultipleKey.checked) then begin lblPasswordCount.caption := 'Passwords entered: '+inttostr(rePasswords.lines.count)+'/'+inttostr(MULTIKEY_PASSWORD_REQUIREMENT); end else begin lblPasswordCount.caption := ''; end; end; procedure TOTFECrossCrypt_PasswordEntry_F.pbCancelClick(Sender: TObject); begin // Cleardown... Wipe(); ModalResult := mrCancel; end; procedure TOTFECrossCrypt_PasswordEntry_F.pbLoadFromFileClick( Sender: TObject); begin if OpenKeyfileDlg.Execute() then begin rePasswords.Lines.LoadFromFile(OpenKeyfileDlg.Filename); end; end; procedure TOTFECrossCrypt_PasswordEntry_F.UserPasswordMask(mask: boolean); var maskChar: char; begin // Mask the user's password... maskChar := #0; if mask then begin maskChar := '*'; end; SendMessage(rePasswords.Handle, EM_SETPASSWORDCHAR, Ord(maskChar), 0); end; END.
//--------------------------------------------------------------------------- // This software is Copyright (c) 2015 Embarcadero Technologies, Inc. // You may only use this software if you are an authorized licensee // of an Embarcadero developer tools product. // This software is considered a Redistributable as defined under // the software license agreement that comes with the Embarcadero Products // and is subject to that software license agreement. //--------------------------------------------------------------------------- unit TabbedMap; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Maps, FMX.TabControl, FMX.Controls.Presentation, FMX.StdCtrls; type TForm2 = class(TForm) TabControl1: TTabControl; TabItem1: TTabItem; TabItem2: TTabItem; MapPiter: TMapView; MapFrisco: TMapView; CameraInfo: TLabel; ZoomOut: TButton; ZoomIn: TButton; procedure FormShow(Sender: TObject); procedure CameraChanged(Sender: TObject); procedure ZoomOutClick(Sender: TObject); procedure ZoomInClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form2: TForm2; implementation {$R *.fmx} procedure TForm2.ZoomOutClick(Sender: TObject); begin MapPiter.Zoom := MapPiter.Zoom - 1; MapFrisco.Zoom := MapFrisco.Zoom - 1; end; procedure TForm2.ZoomInClick(Sender: TObject); begin MapPiter.Zoom := MapPiter.Zoom + 1; MapFrisco.Zoom := MapFrisco.Zoom + 1; end; procedure TForm2.FormShow(Sender: TObject); begin MapPiter.Location := TMapCoordinate.Create(59.965, 30.35); MapPiter.Zoom := 10; MapFrisco.Location := TMapCoordinate.Create(37.82, -122.5); MapFrisco.Zoom := 10; end; procedure TForm2.CameraChanged(Sender: TObject); begin CameraInfo.Text := Format('Camera at %3.3f, %3.3f Zoom=%2f', [TMapView(Sender).Location.Latitude, TMapView(Sender).Location.Longitude, TMapView(Sender).Zoom]); end; end.
unit UnTar; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, DsgnIntf, tarfile; CONST BUFSIZE = 512 * 128; // 512 = SECSIZE in unit tarfile type TZeroHundred = 0..100; TOverwriteMode = ( omSkip, omRename, omReplace ); TNextFile = record name : string; size : longint; timestamp : TDateTime end; TAboutProperty = class(TPropertyEditor) public procedure Edit; override; function GetAttributes: TPropertyAttributes; override; function GetValue: string; override; end; TUnTar = class(TComponent) private { Private declarations } FAbout : TAboutProperty; FOnNextFile : TNotifyEvent; FNextFile : TNextFile; FCreateEmptyDir: boolean; FOnExtractOverwrite : TNotifyEvent; FOnProgress : TNotifyEvent; FProgress : integer; FProgressStep : TZeroHundred; FOverwriteMode : TOverwriteMode; FOverwriteThisTime : TOverwriteMode; FOverwriteFilename : String; FFileSource : string; FUnpackPath : string; FNewFileName : string; procedure DoProgress( tarfile : TTarFile); procedure CreateNextFile( tarfile: TTarfile); function TranslateDate( dt : TDateTime): longint; protected { Protected declarations } procedure DoOnNextFile; virtual; procedure DoOnExtractOverwrite; virtual; procedure DoOnProgress; virtual; public { Public declarations } constructor Create( AOwner: TComponent); override; // destructor Free; procedure UnTar; procedure UnTarSelected( list: TStringList); procedure GetInfo; property Progress : integer read FProgress; property NextFile : TNextfile read FNextFile; property OverwriteThisTime : TOverwriteMode read FOverwriteThisTime write FOverwriteThisTime; property OverwriteFilename : String read FOverwriteFilename write FOverwriteFilename; published { Published declarations } property About: TAboutProperty read FAbout write FAbout; property FileSource : String read FFileSource write FFileSource; property UnpackPath : String read FUnpackPath write FUnpackPath; property ProgressStep : TZeroHundred read FProgressStep write FProgressStep; property OnProgress : TNotifyEvent read FOnProgress write FOnProgress; Property OverwriteMode : TOverwriteMode read FOverwriteMode write FOverwriteMode; Property CreateEmptyDir: boolean read FCreateEmptyDir write FCreateEmptyDir; Property OnExtractOverwrite : TNotifyEvent read FOnExtractOverwrite write FOnExtractOverwrite; Property OnNextFile : TNotifyEvent read FOnNextFile write FOnNextFile; end; procedure Register; implementation uses utils, filectrl; procedure TAboutProperty.Edit; var utils : TUtils; begin ShowMessage(utils.CreateAboutMsg('DelphiUnTar')) end; function TAboutProperty.GetAttributes: TPropertyAttributes; begin Result := [paMultiSelect, paDialog, paReadOnly]; end; function TAboutProperty.GetValue: string; begin Result := 'DelphiUnTar'; end; constructor TUnTar.Create( AOwner: TComponent); begin inherited Create( AOwner); FFileSource := ''; FUnpackPath := ''; FProgressStep := 0; FCreateEmptyDir := false; FOverwriteMode := omRename end; procedure TUnTar.DoOnNextFile; begin if Assigned (FOnNextFile) then FOnNextFile (self) end; procedure TUnTar.DoOnExtractOverwrite; begin if Assigned (FOnExtractOverwrite) then FOnExtractOverwrite (self) end; procedure TUnTar.DoOnProgress; begin if Assigned (FOnProgress) then FOnProgress (self) end; procedure TUnTar.DoProgress( tarfile : TTarFile); var dummy : integer; begin if FProgressStep > 0 then begin dummy := tarfile.Progress; if (dummy >= FProgress + FProgressStep) or (dummy = 100) then begin FProgress := dummy - (dummy mod FProgressStep); if dummy = 100 then FProgress := dummy; DoOnProgress end end end; function TUnTar.TranslateDate( dt : TDateTime) : longint; begin Result := DateTimeToFileDate( EncodeDate( dt.year, dt.month, dt.day) + EncodeTime( dt.hour, dt.min, dt.sec, 0)) end; procedure TUnTar.CreateNextFile( tarfile: TTarfile); type TBuffer = Array [0..Pred(BUFSIZE)] Of byte; var outfiledir: string; outf: TFileStream; iread: longint; buffer: TBuffer; begin outfileDir := ExtractFileDir(FNextFile.name); // Check if sub-dir exists, if not create if not(DirectoryExists(outfileDir)) and (outfileDir<>'') then begin outfileDir := ExpandFileName(outfileDir); ForceDirectories(outfileDir); end; if outfileDir <> '' then outfileDir := outfileDir + '\'; FNewFilename := outfileDir+ExtractFileName(FNextFile.name); FOverwriteThisTime := omRename; while (FileExists( FNewFilename)) and (FOverwriteMode = omRename)and (FOverwriteThisTime = omRename) do begin FOverwriteFilename := ''; // Raise event to ask what should be done DoOnExtractOverwrite; if (FOverwriteThisTime = omRename) and (FOverwriteFilename <> '') then FNewFilename := FOverwriteFilename end; if (not FileExists( FNewFilename)) or (FOverwriteMode = omReplace) or (FOverwriteThisTime = omReplace) then begin outf := TFileStream.Create(FNewFilename, fmCreate or fmShareDenyWrite); while FNextFile.size > 0 do begin iread := tarfile.ReadFile( buffer, BUFSIZE); outf.Write( buffer, iread); FNextFile.size := FNextFile.size - iread; DoProgress(tarfile) end; FileSetDate(outf.Handle, translateDate(FNextFile.timestamp)); outf.Free end else begin tarfile.SkipFile; // We do not need the file DoProgress(tarfile) end end; procedure TUnTar.UnTar; var oldDir, outfileDir : string; tarfile : TTarFile; begin FProgress := 0; oldDir := getCurrentDir; // check if destination-path exists if FUnpackPath <> '' then begin if not(DirectoryExists(FUnpackPath)) then ForceDirectories(FUnpackPath); setCurrentDir(FUnpackPath); end; tarfile := TTarFile.Create( FFileSource); DoProgress(tarfile); while not( tarfile.EOF) do begin FNextFile.name := tarfile.GetNextFilename; DoProgress( tarfile); outfileDir := ExtractFileDir(FNextFile.name); if FCreateEmptyDir then // Check if sub-dir exists, if not create if not(DirectoryExists(outfileDir)) and (outfileDir<>'') then begin outfileDir := ExpandFileName(outfileDir); ForceDirectories(outfileDir); end; FNextFile.size := tarfile.GetNextSize; if FNextFile.size > 0 then begin FNextFile.timestamp := tarfile.GetNextDate; DoOnNextFile; // raise event that we start with new file // Info is now read and in FNextFile // Create the file CreateNextFile(tarfile) end end; DoProgress( tarfile); tarfile.Free; setCurrentDir(oldDir) end; procedure TUnTar.UnTarSelected( list: TStringList); var oldDir, outfileDir : string; tarfile : TTarFile; begin FProgress := 0; oldDir := getCurrentDir; // check if destination-path exists if FUnpackPath <> '' then begin if not(DirectoryExists(FUnpackPath)) then ForceDirectories(FUnpackPath); setCurrentDir(FUnpackPath); end; tarfile := TTarFile.Create( FFileSource); DoProgress(tarfile); while not( tarfile.EOF) do begin FNextFile.name := tarfile.GetNextFilename; DoProgress( tarfile); outfileDir := ExtractFileDir(FNextFile.name); FNextFile.size := tarfile.GetNextSize; if FNextFile.size > 0 then begin FNextFile.timestamp := tarfile.GetNextDate; if list.IndexOf(FNextFile.Name) > -1 then begin DoOnNextFile; // raise event that we start with new file // Info is now read and in FNextFile // Create the file CreateNextFile(tarfile) end else tarFile.SkipFile end end; DoProgress( tarfile); tarfile.Free; setCurrentDir(oldDir) end; procedure TUnTar.GetInfo; var tarfile : TTarFile; begin FProgress := 0; tarfile := TTarFile.Create( FFileSource); DoProgress( tarfile); while not( tarfile.EOF) do begin FNextFile.name := tarfile.GetNextFilename; FNextFile.size := tarfile.GetNextSize; DoProgress( tarfile); if FNextFile.size > 0 then begin FNextFile.timestamp := tarfile.GetNextDate; tarfile.SkipFile; DoOnNextFile; DoProgress( tarfile) end end; DoProgress( tarfile); tarfile.Free; end; procedure Register; begin RegisterComponents('Samples', [TUnTar]); RegisterPropertyEditor(TypeInfo(TAboutProperty), TUnTar, 'ABOUT', TAboutProperty); end; end.
PROGRAM patternMatching; VAR comps : LONGINT; FUNCTION EQ(c1,c2 : CHAR) : BOOLEAN; BEGIN comps := comps + 1; EQ := c1 = c2; END; (* BruteForce Left To Right Two Loops *) Procedure BruteForceLR2L(s,p : STRING; Var pos : INTEGER); VAR sLen, pLen, i, j : INTEGER; BEGIN sLen := Length(s); pLen := Length(p); pos := 0; i := 1; WHILE (pos = 0) AND (i + pLen - 1 <= sLen) DO BEGIN j := 1; WHILE (j <= pLen) AND EQ(p[j] , s[i + j - 1]) DO BEGIN j := j+1; END; IF j > pLen THEN pos := i; i := i+1; END; END; (* BruteForce Left To Right One Loops *) Procedure BruteForceLR1L(s,p : STRING; Var pos : INTEGER); VAR sLen, pLen, i, j : INTEGER; BEGIN sLen := Length(s); pLen := Length(p); i := 1; j := 1; REPEAT IF EQ(s[i], p[j]) THEN BEGIN i := i+1; j := j+1; END ELSE BEGIN i := i -j +1+1; j := 1; END; UNTIl (i > sLen) OR (j > pLen); IF j > pLen THEN pos := i - pLen ELSE pos := 0; END; (* KnuthMorrisPratt1 *) Procedure KnuthMorrisPratt1(s,p : STRING; Var pos : INTEGER); VAR sLen, pLen, i, j : INTEGER; next : ARRAY[1..255] OF INTEGER; PROCEDURE InitNext; VAR i,j :INTEGER; BEGIN i := 1; j := 0; next[i] := 0; WHILE i < pLen DO BEGIN IF (j = 0) OR (EQ(p[i],p[j])) THEN BEGIN i := i+1; j := j+1; next[i] := j; END ELSE BEGIN j := next[j]; END; END; END; BEGIN sLen := Length(s); pLen := Length(p); InitNext; i := 1; j := 1; REPEAT IF (j = 0) OR (EQ(s[i], p[j])) THEN BEGIN i := i+1; j := j+1; END ELSE BEGIN i := i -j +1+1; j := 1; END; UNTIl (i > sLen) OR (j > pLen); IF j > pLen THEN pos := i - pLen ELSE pos := 0; END; (* KnuthMorrisPratt2 *) Procedure KnuthMorrisPratt2(s,p : STRING; Var pos : INTEGER); VAR sLen, pLen, i, j : INTEGER; next : ARRAY[1..255] OF INTEGER; PROCEDURE InitNextImproved; VAR i,j :INTEGER; BEGIN i := 1; j := 0; next[i] := 0; WHILE i < pLen DO BEGIN IF (j = 0) OR (EQ(p[i],p[j])) THEN BEGIN i := i+1; j := j+1; IF NOT EQ(p[i],p[j]) THEN next[i] := j ELSE next[i] := next[j]; END ELSE BEGIN j := next[j]; END; END; END; BEGIN sLen := Length(s); pLen := Length(p); InitNextImproved; i := 1; j := 1; REPEAT IF (j = 0) OR (EQ(s[i], p[j])) THEN BEGIN i := i+1; j := j+1; END ELSE BEGIN i := i -j +1+1; j := 1; END; UNTIl (i > sLen) OR (j > pLen); IF j > pLen THEN pos := i - pLen ELSE pos := 0; END; (* BruteForce Right To Left One Loops *) Procedure BruteForceRL1L(s,p : STRING; Var pos : INTEGER); VAR sLen, pLen, i, j : INTEGER; BEGIN sLen := Length(s); pLen := Length(p); i := pLen; j := pLen; REPEAT IF EQ(s[i], p[j]) THEN BEGIN i := i-1; j := j-1; END ELSE BEGIN i := i + pLen - j + 1; j := pLen; END; UNTIl (i > sLen) OR (j < 1); IF j < 1 THEN pos := i + 1 ELSE pos := 0; END; (* BoyerMoore *) Procedure BoyerMoore(s,p : STRING; Var pos : INTEGER); VAR sLen, pLen, i, j : INTEGER; skip : ARRAY[CHAR] OF INTEGER; PROCEDURE InitSkip; Var ch : CHAR; j : INTEGER; BEGIN for ch := Chr(0) to Chr(255) DO BEGIN skip[ch] := pLen; END; FOR j := 1 TO pLen DO BEGIN skip[p[j]] := pLen - j; END; END; BEGIN sLen := Length(s); pLen := Length(p); i := pLen; j := pLen; InitSkip; REPEAT IF EQ(s[i], p[j]) THEN BEGIN i := i-1; j := j-1; END ELSE BEGIN IF pLen - j + 1 > skip[s[i]] THEN i := i + pLen - j + 1 ELSE i := i + skip[s[i]]; j := pLen; END; UNTIl (i > sLen) OR (j < 1); IF j < 1 THEN pos := i + 1 ELSE pos := 0; END; VAR s,p : String; pos : INTEGER; BEGIN s := 'aadfacdafkjlccdcdxaabcdcdaadfacdafkjlccdcdxaabcdcdaadfacdafkjlccdcdxaabcdcdaadfacdafkjlccdcdxaabcdcd'; p := 'aabcdcd'; comps := 0; BruteForceLR2L(s,p,pos); writeln('BruteForceLR2L pos: ',pos , ' comps: ', comps); comps := 0; BruteForceLR1L(s,p,pos); writeln('BruteForceLR1L pos: ',pos , ' comps: ', comps); comps := 0; KnuthMorrisPratt1(s,p,pos); writeln('KnuthMorrisPratt1 pos: ',pos , ' comps: ', comps); comps := 0; KnuthMorrisPratt2(s,p,pos); writeln('KnuthMorrisPratt2 pos: ',pos , ' comps: ', comps); comps := 0; BruteForceRL1L(s,p,pos); writeln('BruteForceRL1L pos: ',pos , ' comps: ', comps); comps := 0; BoyerMoore(s,p,pos); writeln('BoyerMoore pos: ',pos , ' comps: ', comps); END.
{ ****************************************************** EMI Background Viewer Copyright (c) 2004 - 2010 Bgbennyboy Http://quick.mixnmojo.com ****************************************************** } unit frmMain; interface uses Windows, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, pngimage, ComCtrls, JvBaseDlg, JvBrowseFolder, Menus, ImgList, jclfileutils, jclsysinfo, uEMIUtils, uLABManager, uMemReader; type TformMain = class(TForm) OpenDialog1: TOpenDialog; SaveDialog1: TSaveDialog; PopupMenu1: TPopupMenu; menuSave: TMenuItem; menuDebug: TMenuItem; dlgBrowseFolder: TJvBrowseForFolderDialog; panelSide: TPanel; panelButtons: TPanel; ProgressBar1: TProgressBar; panelImage: TPanel; Image1: TImage; listBoxImages: TListBox; ImageList1: TImageList; btnOpen: TButton; btnDebug: TButton; btnSave: TButton; btnSaveAll: TButton; btnAbout: TButton; btnCancel: TButton; procedure btnOpenClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure SaveDialog1TypeChange(Sender: TObject); procedure btnSaveAllClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure menuSaveClick(Sender: TObject); procedure menuDebugClick(Sender: TObject); procedure btnAboutClick(Sender: TObject); procedure listBoxImagesClick(Sender: TObject); procedure listBoxImagesDblClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnDebugClick(Sender: TObject); procedure FormDestroy(Sender: TObject); private procedure DoButtons(Value: boolean); procedure ViewTile(Width: integer; Height: Integer); procedure DecodeTile(OutBmp: Tbitmap; Width: integer; Height: integer; ShowProgress: boolean; Source: TExplorerMemoryStream); function GetImageWidth: integer; function GetImageHeight: integer; { Private declarations } public { Public declarations } end; var formMain: TformMain; CancelSaveAll: boolean; ShowDebug: boolean; fLabReader: TLABManager; type EInvalidTilImage = class(exception); implementation uses About; {$R *.dfm} //{$R Extra.RES} function RGBToColor(R, G, B : byte): TColor; inline; begin Result := ((R and $FF) shl 16) + ((G and $FF) shl 8) + (B and $FF); end; function MyMessageDialog(const Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons; Captions: array of string): Integer; var aMsgDlg: TForm; i: Integer; dlgButton: TButton; CaptionIndex: Integer; begin { Create the Dialog } aMsgDlg := CreateMessageDialog(Msg, DlgType, Buttons); captionIndex := 0; { Loop through Objects in Dialog } for i := 0 to aMsgDlg.ComponentCount - 1 do begin { If the object is of type TButton, then } if (aMsgDlg.Components[i] is TButton) then begin dlgButton := TButton(aMsgDlg.Components[i]); if CaptionIndex > High(Captions) then Break; { Give a new caption from our Captions array} dlgButton.Caption := Captions[CaptionIndex]; Inc(CaptionIndex); end; end; Result := aMsgDlg.ShowModal; aMsgDlg.Free;// free the dialog end; procedure TformMain.DoButtons(Value: boolean); begin btnOpen.Enabled:=value; btnSave.Enabled:=value; btnSaveAll.Enabled:=value; btnAbout.enabled:=value; btnDebug.enabled := value; listBoxImages.Enabled:=value; menuSave.Enabled:=value; menuDebug.Enabled:=value; PopupMenu1.AutoPopup := value; end; procedure TformMain.FormCreate(Sender: TObject); begin OpenDialog1.InitialDir := GetEMIPath; SaveDialog1.InitialDir := GetDesktopDirectoryFolder; dlgBrowseFolder.RootDirectory:=fdDesktopDirectory; dlgBrowseFolder.RootDirectoryPath:=GetDesktopDirectoryFolder; ShowDebug := false; end; procedure TformMain.FormDestroy(Sender: TObject); begin if fLabReader <> nil then fLabReader.Free; end; function TformMain.GetImageHeight: integer; begin if ShowDebug = true then result := 512 else result := 480; end; function TformMain.GetImageWidth: integer; begin if ShowDebug = true then result := 766 else result := 640; end; procedure TformMain.listBoxImagesClick(Sender: TObject); begin if listBoxImages.Count = 0 then exit; Viewtile(GetImageWidth, GetImageHeight); end; procedure TformMain.listBoxImagesDblClick(Sender: TObject); begin if listBoxImages.Count = 0 then exit; Viewtile(GetImageWidth, GetImageHeight); end; procedure TformMain.btnOpenClick(Sender: TObject); var I: Integer; begin if OpenDialog1.Execute = false then exit; if fLabReader <> nil then begin fLabReader.Free; listBoxImages.Clear; Image1.Picture := nil; DoButtons(false); btnOpen.Enabled := true; btnAbout.Enabled := true; end; fLabReader := TLABManager.Create(OpenDialog1.FileName); fLabReader.ParseFiles; for I := 0 to fLabReader.Count - 1 do begin if ExtractFileExt( fLabReader.FileName[i] ) = '.til' then listBoxImages.Items.AddObject( ExtractFileName( fLabReader.FileName[i] ), TObject(i) ); end; if listBoxImages.Count > 0 then begin listBoxImages.Selected[0] := true; listBoxImages.OnClick(formMain); DoButtons( True ); end; end; procedure TformMain.ViewTile(Width: integer; Height: Integer); var tempbmp: tbitmap; TempStream: TExplorerMemoryStream; begin if listBoxImages.ItemIndex=-1 then exit; tempbmp:=tbitmap.Create; try TempStream := TExplorerMemoryStream.Create; try fLabReader.SaveFileToStream( integer( listBoxImages.Items.Objects[listBoxImages.ItemIndex] ), TempStream, true); DecodeTile(tempbmp, width, height, true, TempStream); image1.Picture.Assign(tempbmp); finally TempStream.Free; end; finally tempbmp.Free; end; if listBoxImages.Enabled then listBoxImages.SetFocus; //Set the focus back to the listbox so the arrow keys work again end; procedure TformMain.btnSaveClick(Sender: TObject); var TempPng: TPngImage; begin if listBoxImages.ItemIndex = -1 then Exit; SaveDialog1.FileName:=PathExtractFileNameNoExt( listBoxImages.Items.Strings[listBoxImages.itemindex] ); if SaveDialog1.Execute = false then Exit; if SaveDialog1.FilterIndex = 1 then begin TempPng := TPngImage.Create; try TempPng.Assign( Image1.Picture.Graphic ); TempPng.SaveToFile(SaveDialog1.FileName); finally TempPng.Free; end; end else image1.Picture.SaveToFile(savedialog1.FileName); end; procedure TformMain.SaveDialog1TypeChange(Sender: TObject); begin if savedialog1.filterindex=1 then savedialog1.defaultext:='.jpg' else if savedialog1.filterindex=2 then savedialog1.defaultext:='.bmp'; end; procedure TformMain.btnSaveAllClick(Sender: TObject); var I: Integer; MyDialog: tmodalresult; TempBmp: TBitmap; TempPng: TPngImage; TempStream :TExplorerMemoryStream; begin if listBoxImages.Count < 1 then exit; if dlgbrowsefolder.Execute = false then exit; MyDialog := MyMessageDialog( 'Select the format to save as', mtConfirmation, mbYesNoCancel,['Png', 'Bitmap'] ); if MyDialog = mrCancel then exit; TempBmp := TBitmap.Create; try TempBmp.FreeImage; DoButtons(false); BtnCancel.Visible:=true; ProgressBar1.Max := listBoxImages.Count; ProgressBar1.Min:=0; CancelSaveAll:=false; for I := 0 to listBoxImages.Count - 1 do begin if CancelSaveAll then Exit; ProgressBar1.StepIt; Application.ProcessMessages; TempStream := TExplorerMemoryStream.Create; try fLabReader.SaveFileToStream( integer( listBoxImages.Items.Objects[i] ), TempStream, true); DecodeTile(TempBmp, GetImageWidth, GetImageHeight, true, TempStream); finally TempStream.Free; end; case MyDialog of mrYes: //png begin TempPng := TPngImage.Create; try TempPng.Assign( TempBmp ); TempPng.SaveToFile( dlgbrowsefolder.Directory + '\' + pathextractfilenamenoext(listBoxImages.Items.Strings[i]) + '.png' ); finally TempPng.Free; end; end; mrNo: begin TempBmp.SaveToFile(dlgbrowsefolder.Directory + '\' + pathextractfilenamenoext(listBoxImages.Items.Strings[i]) + '.bmp'); end; end; end; finally TempBmp.Free; btnCancel.Visible:=false; DoButtons(true); ProgressBar1.Position:=0; end; end; procedure TformMain.btnCancelClick(Sender: TObject); begin CancelSaveAll:=true; end; procedure TformMain.btnDebugClick(Sender: TObject); begin ShowDebug := not ShowDebug; menudebug.Checked := ShowDebug; Viewtile(GetImageWidth, GetImageHeight); if ShowDebug then btnDebug.Caption := 'Debug On' else btnDebug.Caption := 'Debug'; end; procedure TformMain.menuSaveClick(Sender: TObject); begin btnSave.Click; end; procedure TformMain.menuDebugClick(Sender: TObject); begin btnDebug.Click; end; procedure TformMain.btnAboutClick(Sender: TObject); begin frmAbout.showmodal; end; procedure TformMain.DecodeTile(OutBmp: Tbitmap; Width: integer; Height: integer; ShowProgress: boolean; Source: TExplorerMemoryStream); var BMoffset, NoTiles, i, i2, tilesize: integer; xpos, ypos, globalxpos, globalypos: integer; ID: string; totalcolour: tcolor; sourcerect, destrect: trect; IsPS2: boolean; red, green, blue: integer; begin IsPS2 := False; Outbmp.Width := Width + 128; //strip of extra tile Outbmp.Height := Height; //Header ID := Source.ReadBlockName; if ID = 'TIL0' then else begin //Outbmp.LoadFromResourceName(0, 'ErrorMessage'); raise EInvalidTilImage.Create('Invalid .til image!'); end; //Bitmap Header BMOffset := Source.ReadDWord; Source.Seek( bmoffset + 16, sofrombeginning ); NoTiles := Source.ReadDWord; Source.Seek( 16, sofromcurrent ); //seek 16 then check if = 16 or 32 if Source.ReadDWord =16 then IsPS2 := true; Source.Seek (88, sofromcurrent ); globalxpos:=0; globalypos:=0; {if ShowProgress=true then Progressbar1.Max:=NoTiles;} for i:=1 to NoTiles do begin {if ShowProgress =true then ProgressBar1.Position :=i; } TileSize := Source.ReadDWord * Source.ReadDWord; //Width * Height xpos:=0; ypos:=0; if IsPS2=true then for i2:=1 to tilesize do begin TotalColour:= Source.ReadDWord; red:=(((TotalColour shr 10) and 31) * 255) div 31; Green := (((TotalColour shr 5) and 31) * 255) div 31; Blue := ((TotalColour and 31) * 255) div 31; Outbmp.Canvas.Pixels[xpos + globalxpos, ypos + globalypos]:=rgbtocolor(red, green, blue); inc(xpos); if xpos=256 then //a line of a tile is fully drawn begin xpos:=0; inc(ypos); //go to next line end end else for i2:=1 to tilesize do begin Source.Read(totalcolour,3); Outbmp.Canvas.Pixels[xpos + globalxpos, ypos + globalypos]:=TotalColour; Source.Seek(1, sofromcurrent); inc(xpos); if xpos=256 then //a line of a tile is fully drawn begin xpos:=0; inc(ypos); //go to next line end; end; if globalxpos=512 then //we've drawn 3 tiles begin globalxpos:=0; inc(globalypos, 256); //go to next tile line down end else inc(globalxpos, 256); //tile is 256 wide, so inc it every time a tile is drawn end; //copy third tile to where it should be sourcerect:=Rect(640, 0, 768, 256); destrect:=Rect(512, 256, 640, 512); Outbmp.Canvas.CopyRect(destrect, Outbmp.Canvas, sourcerect); Outbmp.Width:=width; {if ShowProgress=true then ProgressBar1.Position:=0;} end; end.