text
stringlengths
14
6.51M
unit BVE.SVGPrintPreviewFormVCL; // ------------------------------------------------------------------------------ // // SVG Control Package 2.0 // Copyright (c) 2015 Bruno Verhue // // ------------------------------------------------------------------------------ // The SVG Editor need at least version v2.40 update 9 of the SVG library // See here a discussion on multipage in SVG: // https://wiki.inkscape.org/wiki/index.php/Multipage {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses {$IFnDEF FPC} Winapi.Windows, Winapi.Messages, Winapi.ShellApi, System.SysUtils, System.Variants, System.Types, System.Classes, System.Generics.Collections, System.Actions, System.Math, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ToolWin, Vcl.ActnMan, Vcl.ActnCtrls, Vcl.ActnList, Vcl.ExtCtrls, Vcl.PlatformDefaultStyleActnCtrls, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.ActnMenus, Vcl.Grids, Vcl.ValEdit, Vcl.ImgList, Vcl.Printers, {$ELSE} {$IFDEF MSWINDOWS} Windows, {$ENDIF} Types, Classes, SysUtils, Math, Forms, Controls, StdCtrls, Graphics, Clipbrd, Generics.Collections, ExtCtrls, ComCtrls, ActnList, Dialogs, ExtDlgs, LclType, Printers, {$ENDIF} BVE.SVG2Intf, BVE.SVG2Types, BVE.SVGPrintPreviewVCL; type TSVGPrintPreviewForm = class(TForm) private FActionOrientationLandscape: TAction; FActionCancel: TAction; FActionPrint: TAction; FActionPrinterSelect: TAction; FActionOrientationPortait: TAction; FActionIdenticalMargins: TAction; FEditOutputDevice: TEdit; FEditPagesHorizontal: TEdit; FEditPagesVertical: TEdit; FEditMarginLeft: TEdit; FEditMarginTop: TEdit; FEditMarginRight: TEdit; FEditMarginBottom: TEdit; FEditGlueEdge: TEdit; FComboBoxUnits: TComboBox; FComboboxAlign: TComboBox; FComboboxMeetOrSlice: TComboBox; FCheckBoxAutoViewbox: TCheckBox; FPrintDialog: TPrintDialog; FPrintPreview: TSVGPrintPreview; FTimerUpdate: TTimer; FRecursion: Integer; protected function GetRoot: ISVGRoot; procedure SetRoot(const Value: ISVGRoot); procedure SetActionCancel(const Value: TAction); procedure SetActionIdenticalMargins(const Value: TAction); procedure SetActionOrientationLandscape(const Value: TAction); procedure SetActionOrientationPortait(const Value: TAction); procedure SetActionPrint(const Value: TAction); procedure SetActionPrinterSelect(const Value: TAction); procedure SetCheckBoxAutoViewbox(const Value: TCheckBox); procedure SetComboBoxUnits(const Value: TComboBox); procedure SetComboboxAlign(const Value: TComboBox); procedure SetComboboxMeetOrSlice(const Value: TComboBox); procedure SetEditOutputDevice(const Value: TEdit); procedure SetEditPagesHorizontal(const Value: TEdit); procedure SetEditPagesVertical(const Value: TEdit); procedure SetEditGlueEdge(const Value: TEdit); procedure SetEditMarginBottom(const Value: TEdit); procedure SetEditMarginLeft(const Value: TEdit); procedure SetEditMarginRight(const Value: TEdit); procedure SetEditMarginTop(const Value: TEdit); procedure EditNumberKeyPress(Sender: TObject; var Key: Char); procedure EditNumberKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditIntegerKeyPress(Sender: TObject; var Key: Char); procedure EditIntegerKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ActionIdenticalMarginsExecute(Sender: TObject); procedure ActionOrientationLandscapeExecute(Sender: TObject); procedure ActionOrientationPortaitExecute(Sender: TObject); procedure ActionPrintExecute(Sender: TObject); procedure ActionCancelExecute(Sender: TObject); procedure ActionPrinterSelectExecute(Sender: TObject); procedure MarginChange(Sender: TObject); procedure PageSettingsChange(Sender: TObject); procedure TimerUpdateTimer(Sender: TObject); procedure DoShow; override; procedure PreviewSetProperties; procedure UpdatePreview(const aImmediately: Boolean = False); procedure EnableActions; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property ActionOrientationLandscape: TAction read FActionOrientationLandscape write SetActionOrientationLandscape; property ActionOrientationPortait: TAction read FActionOrientationPortait write SetActionOrientationPortait; property ActionPrint: TAction read FActionPrint write SetActionPrint; property ActionCancel: TAction read FActionCancel write SetActionCancel; property ActionPrinterSelect: TAction read FActionPrinterSelect write SetActionPrinterSelect; property ActionIdenticalMargins: TAction read FActionIdenticalMargins write SetActionIdenticalMargins; property ComboBoxUnits: TComboBox read FComboBoxUnits write SetComboBoxUnits; property ComboboxAlign: TComboBox read FComboboxAlign write SetComboboxAlign; property ComboboxMeetOrSlice: TComboBox read FComboboxMeetOrSlice write SetComboboxMeetOrSlice; property CheckBoxAutoViewbox: TCheckBox read FCheckBoxAutoViewbox write SetCheckBoxAutoViewbox; property EditOutputDevice: TEdit read FEditOutputDevice write SetEditOutputDevice; property EditPagesHorizontal: TEdit read FEditPagesHorizontal write SetEditPagesHorizontal; property EditPagesVertical: TEdit read FEditPagesVertical write SetEditPagesVertical; property EditMarginLeft: TEdit read FEditMarginLeft write SetEditMarginLeft; property EditMarginTop: TEdit read FEditMarginTop write SetEditMarginTop; property EditMarginRight: TEdit read FEditMarginRight write SetEditMarginRight; property EditMarginBottom: TEdit read FEditMarginBottom write SetEditMarginBottom; property EditGlueEdge: TEdit read FEditGlueEdge write SetEditGlueEdge; property Root: ISVGRoot read GetRoot write SetRoot; end; implementation { TSVGPrintPreviewForm } procedure TSVGPrintPreviewForm.ActionCancelExecute(Sender: TObject); begin ModalResult := mrOk; Close; end; procedure TSVGPrintPreviewForm.ActionIdenticalMarginsExecute(Sender: TObject); begin // end; procedure TSVGPrintPreviewForm.ActionOrientationLandscapeExecute( Sender: TObject); begin if FRecursion > 0 then Exit; Printer.Orientation := TPrinterOrientation.poLandscape; FPrintPreview.Repaint end; procedure TSVGPrintPreviewForm.ActionOrientationPortaitExecute(Sender: TObject); begin if FRecursion > 0 then Exit; Printer.Orientation := TPrinterOrientation.poPortrait; FPrintPreview.Repaint; end; procedure TSVGPrintPreviewForm.ActionPrinterSelectExecute(Sender: TObject); begin if FPrintDialog.Execute then begin EnableActions; end; end; procedure TSVGPrintPreviewForm.ActionPrintExecute(Sender: TObject); begin FPrintPreview.Print('SVG Editor'); end; constructor TSVGPrintPreviewForm.Create(AOwner: TComponent); begin inherited; FRecursion := 0; FPrintDialog := TPrintDialog.Create(Self); FPrintPreview := TSVGPrintPreview.Create(Self); FPrintPreview.Parent := Self; FPrintPreview.Align := alClient; FTimerUpdate := TTimer.Create(Self); FTimerUpdate.Enabled := False; FTimerUpdate.Interval := 300; FTimerUpdate.OnTimer := TimerUpdateTimer; end; destructor TSVGPrintPreviewForm.Destroy; begin inherited; end; procedure TSVGPrintPreviewForm.DoShow; begin inherited; EnableActions; end; procedure TSVGPrintPreviewForm.EditIntegerKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var ValueInt: Integer; begin if not(Sender is TEdit) then Exit; if not TryStrToInt((Sender as TEdit).Text, ValueInt) then Exit; case Key of VK_UP: Inc(ValueInt); VK_DOWN: if ValueInt > 0 then Dec(ValueInt); else Exit; end; (Sender as TEdit).Text := IntToStr(ValueInt); end; procedure TSVGPrintPreviewForm.EditIntegerKeyPress(Sender: TObject; var Key: Char); begin case Key of '0'..'9':; #8, #9:; else Key := #0; end; end; procedure TSVGPrintPreviewForm.EditNumberKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var ValueFloat: TSVGFloat; begin if not(Sender is TEdit) then Exit; if not TryStrToFloat((Sender as TEdit).Text, ValueFloat, USFormatSettings) then Exit; case Key of VK_UP: ValueFloat := ValueFloat + 1; VK_DOWN: if ValueFloat > 0 then ValueFloat := ValueFloat - 1; else Exit; end; (Sender as TEdit).Text := FloatToStr(ValueFloat, USFormatSettings); end; procedure TSVGPrintPreviewForm.EditNumberKeyPress(Sender: TObject; var Key: Char); begin case Key of '0'..'9':; #8, #9:; '.': begin if Pos('.', TEdit(Sender).Text) > 0 then Key := #0; end else Key := #0; end; end; procedure TSVGPrintPreviewForm.EnableActions; begin Inc(FRecursion); try FEditOutputDevice.Text := Printer.Printers[Printer.PrinterIndex]; if Printer.Orientation = TPrinterOrientation.poPortrait then ActionOrientationPortait.Checked := True else ActionOrientationLandscape.Checked := True; finally Dec(FRecursion); end; end; function TSVGPrintPreviewForm.GetRoot: ISVGRoot; begin Result := FPrintPreview.Root; end; procedure TSVGPrintPreviewForm.MarginChange(Sender: TObject); var Edit: TEdit; begin if FRecursion > 0 then Exit; if ActionIdenticalMargins.Checked and (Sender is TEdit) then begin Edit := Sender as TEdit; Inc(FRecursion); try if EditMarginLeft <> Edit then EditMarginLeft.Text := Edit.Text; if EditMarginTop <> Edit then EditMarginTop.Text := Edit.Text; if EditMarginRight <> Edit then EditMarginRight.Text := Edit.Text; if EditMarginBottom <> Edit then EditMarginBottom.Text := Edit.Text; finally Dec(FRecursion); end; end; UpdatePreview; end; procedure TSVGPrintPreviewForm.PageSettingsChange(Sender: TObject); begin UpdatePreview; end; procedure TSVGPrintPreviewForm.PreviewSetProperties; var ValueInt: Integer; ValueFloat: TSVGFloat; begin if not TryStrToInt(EditPagesHorizontal.Text, ValueInt) then ValueInt := 1; FPrintPreview.PagesHorizontal := ValueInt;; if not TryStrToInt(EditPagesVertical.Text, ValueInt) then ValueInt := 1; FPrintPreview.PagesVertical := ValueInt; if not TryStrToFloat(EditMarginLeft.Text, ValueFloat, USFormatSettings) then ValueFloat := 0; FPrintPreview.MarginLeft := ValueFloat; if not TryStrToFloat(EditMarginRight.Text, ValueFloat, USFormatSettings) then ValueFloat := 0; FPrintPreview.MarginRight := ValueFloat; if not TryStrToFloat(EditMarginTop.Text, ValueFloat, USFormatSettings) then ValueFloat := 0; FPrintPreview.MarginTop := ValueFloat; if not TryStrToFloat(EditMarginBottom.Text, ValueFloat, USFormatSettings) then ValueFloat := 0; FPrintPreview.MarginBottom := ValueFloat; if not TryStrToFloat(EditGlueEdge.Text, ValueFloat, USFormatSettings) then ValueFloat := 0; FPrintPreview.GlueEdge := ValueFloat; FPrintPreview.Units := TSVGPrintUnits(ComboboxUnits.ItemIndex); FPrintPreview.AutoViewbox := CheckboxAutoViewbox.Checked; FPrintPreview.AspectRatioAlign := TSVGAspectRatioAlign(ComboBoxAlign.ItemIndex); FPrintPreview.AspectRatioMeetOrSlice := TSVGAspectRatioMeetOrSlice(ComboBoxMeetOrSlice.ItemIndex); end; procedure TSVGPrintPreviewForm.SetActionCancel(const Value: TAction); begin FActionCancel := Value; if assigned(FActionCancel) then FActionCancel.OnExecute := ActionCancelExecute; end; procedure TSVGPrintPreviewForm.SetActionIdenticalMargins(const Value: TAction); begin FActionIdenticalMargins := Value; if assigned(FActionIdenticalMargins) then begin FActionIdenticalMargins.OnExecute := ActionIdenticalMarginsExecute; FActionIdenticalMargins.AutoCheck := True; end; end; procedure TSVGPrintPreviewForm.SetActionOrientationLandscape( const Value: TAction); begin FActionOrientationLandscape := Value; if assigned(FActionOrientationLandscape) then FActionOrientationLandscape.OnExecute := ActionOrientationLandscapeExecute; end; procedure TSVGPrintPreviewForm.SetActionOrientationPortait( const Value: TAction); begin FActionOrientationPortait := Value; if assigned(FActionOrientationPortait) then FActionOrientationPortait.OnExecute := ActionOrientationPortaitExecute; end; procedure TSVGPrintPreviewForm.SetActionPrint(const Value: TAction); begin FActionPrint := Value; if assigned(FActionPrint) then FActionPrint.OnExecute := ActionPrintExecute; end; procedure TSVGPrintPreviewForm.SetActionPrinterSelect(const Value: TAction); begin FActionPrinterSelect := Value; if assigned(FActionPrinterSelect) then FActionPrinterSelect.OnExecute := ActionPrinterSelectExecute; end; procedure TSVGPrintPreviewForm.SetCheckBoxAutoViewbox(const Value: TCheckBox); begin FCheckBoxAutoViewbox := Value; if assigned(FCheckboxAutoViewBox) then FCheckboxAutoViewbox.OnClick := PageSettingsChange; end; procedure TSVGPrintPreviewForm.SetComboboxAlign(const Value: TComboBox); begin FComboboxAlign := Value; if assigned(FComboboxAlign) then begin FComboBoxAlign.Items.Clear; FComboBoxAlign.Items.Add('None'); FComboBoxAlign.Items.Add('X-Min Y-Min'); FComboBoxAlign.Items.Add('X-Mid Y-Min'); FComboBoxAlign.Items.Add('X-Max Y-Min'); FComboBoxAlign.Items.Add('X-Min Y-Mid'); FComboBoxAlign.Items.Add('X-Mid Y-Mid'); FComboBoxAlign.Items.Add('X-Max Y-Mid'); FComboBoxAlign.Items.Add('X-Min Y-Max'); FComboBoxAlign.Items.Add('X-Mid Y-Max'); FComboBoxAlign.Items.Add('X-Max Y-Max'); FComboBoxAlign.ItemIndex := Ord(TSVGAspectRatioAlign.arXMidYMid); FComboBoxAlign.OnChange := PageSettingsChange; end; end; procedure TSVGPrintPreviewForm.SetComboboxMeetOrSlice(const Value: TComboBox); begin FComboboxMeetOrSlice := Value; if assigned(FComboboxMeetOrSlice) then begin FComboboxMeetOrSlice.Items.Clear; FComboboxMeetOrSlice.Items.Add('Meet'); FComboboxMeetOrSlice.Items.Add('Slice'); FComboboxMeetOrSlice.ItemIndex := Ord(TSVGAspectRatioMeetOrSlice.arMeet); FComboboxMeetOrSlice.OnChange := PageSettingsChange; end; end; procedure TSVGPrintPreviewForm.SetComboBoxUnits(const Value: TComboBox); begin FComboBoxUnits := Value; if assigned(FComboBoxUnits) then begin FComboBoxUnits.Items.Clear; FComboBoxUnits.Items.Add('mm'); FComboBoxUnits.Items.Add('cm'); FComboBoxUnits.Items.Add('inch'); FComboBoxUnits.Items.Add('px'); FComboBoxUnits.ItemIndex := Ord(TSVGPrintUnits.puMm); FComboBoxUnits.OnChange := PageSettingsChange; end; end; procedure TSVGPrintPreviewForm.SetEditGlueEdge(const Value: TEdit); begin FEditGlueEdge := Value; if assigned(FEditGlueEdge) then begin FEditGlueEdge.OnKeyPress := EditNumberKeyPress; FEditGlueEdge.OnKeyDown := EditNumberKeyDown; FEditGlueEdge.OnChange := PageSettingsChange; end; end; procedure TSVGPrintPreviewForm.SetEditMarginBottom(const Value: TEdit); begin FEditMarginBottom := Value; if assigned(FEditMarginBottom) then begin FEditMarginBottom.OnKeyPress := EditNumberKeyPress; FEditMarginBottom.OnKeyDown := EditNumberKeyDown; FEditMarginBottom.OnChange := MarginChange; end; end; procedure TSVGPrintPreviewForm.SetEditMarginLeft(const Value: TEdit); begin FEditMarginLeft := Value; if assigned(FEditMarginLeft) then begin FEditMarginLeft.OnKeyPress := EditNumberKeyPress; FEditMarginLeft.OnKeyDown := EditNumberKeyDown; FEditMarginLeft.OnChange := MarginChange; end; end; procedure TSVGPrintPreviewForm.SetEditMarginRight(const Value: TEdit); begin FEditMarginRight := Value; if assigned(FEditMarginRight) then begin FEditMarginRight.OnKeyPress := EditNumberKeyPress; FEditMarginRight.OnKeyDown := EditNumberKeyDown; FEditMarginRight.OnChange := MarginChange; end; end; procedure TSVGPrintPreviewForm.SetEditMarginTop(const Value: TEdit); begin FEditMarginTop := Value; if assigned(FEditMarginTop) then begin FEditMarginTop.OnKeyPress := EditNumberKeyPress; FEditMarginTop.OnKeyDown := EditNumberKeyDown; FEditMarginTop.OnChange := MarginChange; end; end; procedure TSVGPrintPreviewForm.SetEditOutputDevice(const Value: TEdit); begin FEditOutputDevice := Value; if assigned(FEditOutputDevice) then begin FEditOutputDevice.ReadOnly := True; end; end; procedure TSVGPrintPreviewForm.SetEditPagesHorizontal(const Value: TEdit); begin FEditPagesHorizontal := Value; if assigned(FEditPagesHorizontal) then begin FEditPagesHorizontal.OnKeyPress := EditIntegerKeyPress; FEditPagesHorizontal.OnKeyDown := EditIntegerKeyDown; FEditPagesHorizontal.OnChange := PageSettingsChange; end; end; procedure TSVGPrintPreviewForm.SetEditPagesVertical(const Value: TEdit); begin FEditPagesVertical := Value; if assigned(FEditPagesVertical) then begin FEditPagesVertical.OnKeyPress := EditIntegerKeyPress; FEditPagesVertical.OnKeyDown := EditIntegerKeyDown; FEditPagesVertical.OnChange := PageSettingsChange; end; end; procedure TSVGPrintPreviewForm.SetRoot(const Value: ISVGRoot); begin FPrintPreview.Root := Value; end; procedure TSVGPrintPreviewForm.TimerUpdateTimer(Sender: TObject); begin FTimerUpdate.Enabled := False; PreviewSetProperties; end; procedure TSVGPrintPreviewForm.UpdatePreview(const aImmediately: Boolean); begin if aImmediately then begin PreviewSetProperties; end else begin FTimerUpdate.Enabled := False; FTimerUpdate.Enabled := True; end; end; end.
unit UnitActionsForm; interface uses System.SysUtils, System.Classes, Winapi.Windows, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ImgList, Dmitry.Utils.Files, Dmitry.Controls.Base, Dmitry.Controls.WebLink, ImageHistoryUnit, UnitDBFileDialogs, uDBIcons, uDBForm, uMemory, uDBFileTypes, uThemesUtils, uConstants; type TActionObject = class(TObject) public Action: string; ImageIndex: Integer; constructor Create(AAction : string; AImageIndex : Integer); end; TActionsForm = class(TDBForm) ActionList: TListBox; TopPanel: TPanel; SaveToFileLink: TWebLink; LoadFromFileLink: TWebLink; CloseLink: TWebLink; ActionsImageList: TImageList; procedure FormCreate(Sender: TObject); procedure CloseLinkClick(Sender: TObject); procedure ActionListDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure SaveToFileLinkClick(Sender: TObject); procedure LoadFromFileLinkClick(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } FParent: TDBForm; Actions: TList; Cursor: Integer; protected { Protected declarations } function GetFormID: string; override; procedure CustomFormAfterDisplay; override; public { Public declarations } procedure LoadLanguage; procedure AddAction(Action: string; Atype: THistoryAction); procedure SetParentForm(Parent: TDBForm); procedure LoadIcons; procedure Reset; end; var ActionsForm: TActionsForm; implementation uses ImEditor, EffectsToolUnit; {$R *.dfm} procedure TActionsForm.FormCreate(Sender: TObject); begin LoadLanguage; SaveToFileLink.LoadFromHIcon(Icons[DB_IC_SAVETOFILE]); LoadFromFileLink.LoadFromHIcon(Icons[DB_IC_LOADFROMFILE]); CloseLink.LoadFromHIcon(Icons[DB_IC_EXIT]); Cursor := 0; Actions := TList.Create; end; procedure TActionsForm.FormDestroy(Sender: TObject); begin FreeList(Actions); end; procedure TActionsForm.CloseLinkClick(Sender: TObject); begin Close; end; procedure TActionsForm.CustomFormAfterDisplay; begin inherited; if ActionList <> nil then ActionList.Refresh; end; procedure TActionsForm.LoadLanguage; begin BeginTranslate; try Caption := L('Actions'); SaveToFileLink.Text := L('Save to file'); LoadFromFileLink.Text := L('Load from file'); CloseLink.Text := L('Close'); finally EndTranslate; end; end; procedure TActionsForm.AddAction(Action: string; Atype: THistoryAction); var ID, Filter_ID, Filter_Name, StrAction: string; Ico, I: Integer; EM: TEffectsManager; ActionObject : TActionObject; begin if (Atype = [THA_Undo]) then Dec(Cursor); if (Atype = [THA_Redo]) then Inc(Cursor); if (Atype = [THA_Add]) then begin if Cursor <> Actions.Count then begin for I := 1 to Actions.Count - Cursor do begin ActionList.Items.Delete(Cursor); TObject(Actions[Cursor]).Free; Actions.Delete(Cursor); end; end; Inc(Cursor); ID := Copy(Action, 2, 38); Filter_ID := Copy(Action, 42, 38); Ico := 0; if ID = '{59168903-29EE-48D0-9E2E-7F34C913B94A}' then begin Ico := 0; StrAction := L('Open', 'Editor'); end; if ID = '{5AA5CA33-220E-4D1D-82C2-9195CE6DF8E4}' then begin Ico := 1; StrAction := L('Crop', 'Editor'); end; if ID = '{747B3EAF-6219-4A96-B974-ABEB1405914B}' then begin Ico := 2; StrAction := L('Rotate', 'Editor'); end; if ID = '{29C59707-04DA-4194-9B53-6E39185CC71E}' then begin Ico := 3; StrAction := L('Resize', 'Editor'); end; if ID = '{2AA20ABA-9205-4655-9BCE-DF3534C4DD79}' then begin EM := TEffectsManager.Create; try EM.InitializeBaseEffects; Filter_Name := EM.GetEffectNameByID(Filter_ID); finally F(EM); end; Ico := 4; StrAction := L('Effects', 'Editor') + ' [' + Filter_Name + ']'; end; if ID = '{E20DDD6C-0E5F-4A69-A689-978763DE8A0A}' then begin Ico := 5; StrAction := L('Colors', 'Editor'); end; // red if ID = '{3D2B384F-F4EB-457C-A11C-BDCE1C20FFFF}' then begin Ico := 6; StrAction := L('Red eye', 'Editor'); end; // text if ID = '{E52516CC-8235-4A1D-A135-6D84A2E298E9}' then begin Ico := 7; StrAction := L('Text', 'Editor'); end; // brush if ID = '{542FC0AD-A013-4973-90D4-E6D6E9F65D2C}' then begin Ico := 8; StrAction := L('Brush', 'Editor'); end; // insert if ID = '{CA9E5AFD-E92D-4105-8F7B-978A6EBA9D74}' then begin Ico := 9; StrAction := L('Insert image', 'Editor'); end; ActionObject := TActionObject.Create(Action, Ico); Actions.Add(ActionObject); ActionList.Items.Add(StrAction); end; ActionList.Refresh; end; procedure TActionsForm.SetParentForm(Parent: TDBForm); begin FParent := Parent; end; procedure TActionsForm.LoadIcons; procedure AAddIcon(Icon: TIcon); begin ActionsImageList.AddIcon(Icon); end; begin AAddIcon(TImageEditor(FParent).OpenFileLink.Icon); AAddIcon(TImageEditor(FParent).CropLink.Icon); AAddIcon(TImageEditor(FParent).RotateLink.Icon); AAddIcon(TImageEditor(FParent).ResizeLink.Icon); AAddIcon(TImageEditor(FParent).EffectsLink.Icon); AAddIcon(TImageEditor(FParent).ColorsLink.Icon); AAddIcon(TImageEditor(FParent).RedEyeLink.Icon); AAddIcon(TImageEditor(FParent).TextLink.Icon); AAddIcon(TImageEditor(FParent).BrushLink.Icon); AAddIcon(TImageEditor(FParent).InsertImageLink.Icon); end; procedure TActionsForm.ActionListDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); begin if Cursor = Index + 1 then begin //current item ActionList.Canvas.Brush.Color := Theme.ListSelectedColor; ActionList.Canvas.Pen.Color := Theme.ListSelectedColor; end else begin ActionList.Canvas.Brush.Color := Theme.ListColor; ActionList.Canvas.Pen.Color := Theme.ListColor; end; ActionList.Canvas.Rectangle(Rect); ActionList.Canvas.Pen.Color := Theme.WindowColor; if Cursor = Index + 1 then ActionList.Canvas.Font.Color := Theme.ListFontSelectedColor else ActionList.Canvas.Font.Color := Theme.ListFontColor; ActionsImageList.Draw(ActionList.Canvas, Rect.Left + 2, Rect.Top + 2, TActionObject(Actions[index]).ImageIndex); ActionList.Canvas.TextOut(Rect.Left + 25, Rect.Top + 2, ActionList.Items[index]); end; procedure TActionsForm.SaveToFileLinkClick(Sender: TObject); var SaveDialog: DBSaveDialog; FileName: string; StringActions: TStrings; I: Integer; begin SaveDialog := DBSaveDialog.Create; try SaveDialog.Filter := L('PhotoDB actions file (*.dbact)|*.dbact'); SaveDialog.FilterIndex := 1; if SaveDialog.Execute then begin FileName := SaveDialog.FileName; if GetEXT(FileName) <> 'DBACT' then FileName := FileName + '.dbact'; StringActions := TStringList.Create; try for I := 0 to Actions.Count - 1 do StringActions.Add(TActionObject(Actions[I]).Action); SaveActionsTofile(FileName, StringActions); finally F(StringActions); end; end; finally F(SaveDialog); end; end; procedure TActionsForm.LoadFromFileLinkClick(Sender: TObject); var AActions: TStrings; OpenDialog: DBOpenDialog; begin OpenDialog := DBOpenDialog.Create; try OpenDialog.Filter := L('PhotoDB actions file (*.dbact)|*.dbact'); OpenDialog.FilterIndex := 1; if OpenDialog.Execute then begin AActions := TStringList.Create; try LoadActionsFromfileA(OpenDialog.FileName, AActions); TImageEditor(FParent).ReadActions(AActions); finally F(AActions); end; end; finally F(OpenDialog); end; end; procedure TActionsForm.Reset; var I: Integer; begin ActionList.Items.Clear; Cursor := 0; for I := 0 to Actions.Count - 1 do TObject(Actions[I]).Free; Actions.Clear; end; function TActionsForm.GetFormID: string; begin Result := 'ActionsList'; end; { TActionObject } constructor TActionObject.Create(AAction: string; AImageIndex: Integer); begin Action := AAction; ImageIndex := AImageIndex; end; end.
unit Base64; interface uses SysUtils, IdCoder, IdCoder3to4, IdCoderMIME; function Base64Decode(const Text : string; AEncoding:TEncoding = nil): string; function Base64Encode(const Text : string; AEncoding:TEncoding = nil): string; implementation function Base64Decode(const Text : string; AEncoding:TEncoding): string; var Decoder : TIdDecoderMime; begin Decoder := TIdDecoderMime.Create(nil); try Result := Decoder.DecodeString(Text, AEncoding); finally FreeAndNil(Decoder) end end; function Base64Encode(const Text : string; AEncoding:TEncoding): string; var Encoder : TIdEncoderMime; begin Encoder := TIdEncoderMime.Create(nil); try Result := Encoder.EncodeString(Text, AEncoding); finally FreeAndNil(Encoder); end end; end.
unit chelpers; interface Type size_t = SizeInt; float64 = extended; // fixes precision errors shown when using double pvoid = pointer; sigset_t = LongWord; function IIF(expression: boolean; TrueValue: LongWord; FalseValue: LongWord): LongWord; overload; inline; function IIF(expression: boolean; TrueValue: Byte; FalseValue: Byte): Byte; overload; inline; function memcpy(destination: pvoid; const source: pvoid; num: size_t): pvoid; inline; function memset(ptr: pvoid; value: byte; num: size_t): pvoid; inline; implementation (* Copy block of memory Copies the values of num bytes from the location pointed by source directly to the memory block pointed by destination. The underlying type of the objects pointed by both the source and destination pointers are irrelevant for this function; The result is a binary copy of the data. The function does not check for any terminating null character in source - it always copies exactly num bytes. To avoid overflows, the size of the arrays pointed by both the destination and source parameters, shall be at least num bytes, and should not overlap (for overlapping memory blocks, memmove is a safer approach). *) function memcpy(destination: pvoid; const source: pvoid; num: size_t): pvoid; inline; begin Move(Source^, Destination^, num); memcpy := destination; end; (* Fill block of memory Sets the first num bytes of the block of memory pointed by ptr to the specified value (interpreted as an unsigned char). *) function memset(ptr: pvoid; value: byte; num: size_t): pvoid; inline; begin FillChar(ptr^, num, value); memset := ptr; end; (* Immediate If 'simulation'. *) function IIF(expression: boolean; TrueValue: LongWord; FalseValue: LongWord): LongWord; overload; inline; begin if expression then IIF := truevalue else IIF := falsevalue; end; function IIF(expression: boolean; TrueValue: Byte; FalseValue: Byte): Byte; overload; inline; begin if expression then IIF := truevalue else IIF := falsevalue; end; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.IDE.Main; interface uses ToolsAPI, System.SysUtils, Vcl.Dialogs, DPM.IDE.Wizard; function InitWizard(const BorlandIDEServices : IBorlandIDEServices; RegisterProc : TWizardRegisterProc; var Terminate : TWizardTerminateProc) : Boolean; stdcall; exports InitWizard name ToolsAPI.WizardEntryPoint; implementation uses WinApi.ActiveX, Vcl.Graphics, DPM.IDE.Constants; var SplashImage : TBitmap; wizardIdx : integer = -1; function CreateWizard(const BorlandIDEServices : IBorlandIDEServices) : IOTAWizard; begin try result := TDPMWizard.Create; SplashImage := Vcl.Graphics.TBitmap.Create; SplashImage.LoadFromResourceName(HInstance, 'DPMIDELOGO'); SplashScreenServices.AddPluginBitmap(cWizardTitle, SplashImage.Handle); (BorlandIDEServices as IOTAAboutBoxServices).AddPluginInfo(cWizardTitle, cWizardDescription, SplashImage.Handle); except on E : Exception do begin MessageDlg('Failed to create Wizard instance ' + #13#10 + e.Message , mtError, [mbOK], 0); result := nil; end; end; end; // Remove the wizard when terminating. procedure TerminateWizard; var Services : IOTAWizardServices; begin Services := BorlandIDEServices as IOTAWizardServices; Services.RemoveWizard(wizardIdx); end; function InitWizard(const BorlandIDEServices : IBorlandIDEServices; RegisterProc : TWizardRegisterProc; var Terminate : TWizardTerminateProc) : Boolean; stdcall; //FI:O804 var wizard : IOTAWizard; begin CoInitializeEx(nil,COINIT_APARTMENTTHREADED); try wizard := CreateWizard(BorlandIDEServices); if wizard <> nil then begin RegisterProc(wizard); Result := True; Terminate := TerminateWizard; end else Result := False; except on E : Exception do begin MessageDlg('Failed to load wizard. internal failure:' + E.ClassName + ':' + E.Message, mtError, [mbOK], 0); Result := False; end; end; end; end.
unit SuppliersTable; {$mode objfpc}{$H+} //======================================================================================== // // Unit : SuppliersTable.pas // // Description : // // Called By : AppSettings : frmSettings.CreateUserDataDirectories // // Calls : HUValidations : VaildAddressCharacter // ValidAlphaCharacter // ValidNameCharacter // ValidCityCharacter // ValidPhoneCharacter // ValidPostalCodeCharacter // ValidProvStateCharacter // Main : TerminateApp // // Ver. : 1.0.0 // // Date : 21 Dec 2019 // //======================================================================================== interface uses Classes, FileUtil, SysUtils, sqlite3conn, sqldb, db, Forms, Controls, Graphics, Dialogs, Buttons, DBCtrls, DBGrids, StdCtrls, ComCtrls, ExtCtrls, Menus; // Application Units // HULib Units //HUValidations; //======================================================================================== // PUBLIC VARIABLES //======================================================================================== //======================================================================================== // PUBLIC CONSTANTS //======================================================================================== type { TfrmSuppliersTable } TfrmSuppliersTable = class(TForm) bbtOk: TBitBtn; bbtCancel: TBitBtn; dbeC1Name: TDBEdit; dbeC1Dept: TDBEdit; dbeC1Phone: TDBEdit; dbeC1Email: TDBEdit; dbeC3Dept: TDBEdit; dbeC3Email: TDBEdit; dbeC3Phone: TDBEdit; dbeSupplierName: TDBEdit; dbeGenDept: TDBEdit; dbeGenName: TDBEdit; dbeC2Name: TDBEdit; dbeC3Name: TDBEdit; dbeGenEmail: TDBEdit; dbeC2Dept: TDBEdit; dbeC2Phone: TDBEdit; dbeC2Email: TDBEdit; dbeGenPhone: TDBEdit; Label10: TLabel; Label11: TLabel; Label12: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; pnlContacts: TPanel; SupplierTableDataSource: TDataSource; dbeAddress1: TDBEdit; dbeAddress2: TDBEdit; dbeCity: TDBEdit; dbePostalCode: TDBEdit; dbeProvState: TDBEdit; dbeID: TDBEdit; dbgSuppliersTable: TDBGrid; DBNavigator1: TDBNavigator; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; StatusBar1: TStatusBar; SupplierDBConnection: TSQLite3Connection; SupplierTableQuery: TSQLQuery; SupplierTransaction: TSQLTransaction; procedure bbtOkClick(Sender: TObject); procedure bbtCancelClick(Sender: TObject); procedure dbeAddress1Change(Sender: TObject); procedure dbeAddress1KeyPress(Sender: TObject; var Key: char); procedure dbeAddress2Change(Sender: TObject); procedure dbeAddress2KeyPress(Sender: TObject; var Key: char); procedure dbeC1DeptChange(Sender: TObject); procedure dbeC1DeptKeyPress(Sender: TObject; var Key: char); procedure dbeC1EmailChange(Sender: TObject); procedure dbeC1EmailKeyPress(Sender: TObject; var Key: char); procedure dbeC1NameChange(Sender: TObject); procedure dbeC1NameKeyPress(Sender: TObject; var Key: char); procedure dbeC1PhoneChange(Sender: TObject); procedure dbeC1PhoneKeyPress(Sender: TObject; var Key: char); procedure dbeC2DeptChange(Sender: TObject); procedure dbeC2DeptKeyPress(Sender: TObject; var Key: char); procedure dbeC2EmailChange(Sender: TObject); procedure dbeC2EmailKeyPress(Sender: TObject; var Key: char); procedure dbeC2NameChange(Sender: TObject); procedure dbeC2NameKeyPress(Sender: TObject; var Key: char); procedure dbeC2PhoneChange(Sender: TObject); procedure dbeC2PhoneKeyPress(Sender: TObject; var Key: char); procedure dbeC3DeptChange(Sender: TObject); procedure dbeC3DeptKeyPress(Sender: TObject; var Key: char); procedure dbeC3EmailChange(Sender: TObject); procedure dbeC3EmailKeyPress(Sender: TObject; var Key: char); procedure dbeC3NameChange(Sender: TObject); procedure dbeC3PhoneChange(Sender: TObject); procedure dbeC3PhoneKeyPress(Sender: TObject; var Key: char); procedure dbeCityChange(Sender: TObject); procedure dbeCityKeyPress(Sender: TObject; var Key: char); procedure dbeGenDeptChange(Sender: TObject); procedure dbeGenDeptKeyPress(Sender: TObject; var Key: char); procedure dbeGenEmailChange(Sender: TObject); procedure dbeGenEmailKeyPress(Sender: TObject; var Key: char); procedure dbeGenNameChange(Sender: TObject); procedure dbeGenNameKeyPress(Sender: TObject; var Key: char); procedure dbeGenPhoneChange(Sender: TObject); procedure dbeGenPhoneKeyPress(Sender: TObject; var Key: char); procedure dbeIDChange(Sender: TObject); procedure dbePostalCodeChange(Sender: TObject); procedure dbePostalCodeKeyPress(Sender: TObject; var Key: char); procedure dbeProvStateChange(Sender: TObject); procedure dbeProvStateKeyPress(Sender: TObject; var Key: char); procedure dbeSupplierNameChange(Sender: TObject); procedure dbeSupplierNameKeyPress(Sender: TObject; var Key: char); procedure DBNavigator1BeforeAction(Sender: TObject; Button: TDBNavButtonType); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); private public end;// TfrmSuppliersTable var frmSuppliersTable: TfrmSuppliersTable; implementation {$R *.lfm} uses AppSettings, Main; //======================================================================================== // PRIVATE CONSTANTS //======================================================================================== const cstrSuppliersDatabaseName = 'SuppliersDB.sl3'; cstrSuppliersTableName = 'Suppliers.Tbl'; //======================================================================================== // PRIVATE VARIABLES //======================================================================================== //======================================================================================== // PRIVATE ROUTINES //======================================================================================== //================== // Field Validation //================== function ValidRecord : Boolean; begin Result := False; end;// function ValidRecord : Boolean; //======================================================================================== function ValidSupplierName : Boolean; begin Result := False; end;// function ValidSupplierName : Boolean; //======================================================================================== function ValidAddress1 : Boolean; begin Result := False; end;// function ValidAddress1 : Boolean; //======================================================================================== function ValidAddress2 : Boolean; begin Result := False; end;// function ValidAddress2 : Boolean; //======================================================================================== function ValidCity : Boolean; begin Result := False; end;// function ValidCity : Boolean; //======================================================================================== function ValidProvState : Boolean; begin Result := False; end;// function ValidProvState : Boolean; //======================================================================================== function ValidPostalCode : Boolean; begin Result := False; end;// function ValidPostalCode : Boolean; //======================================================================================== function ValidGenName : Boolean; begin Result := False; end;// function ValidGenName : Boolean; //======================================================================================== function ValidGenDept : Boolean; begin Result := False; end;// function ValidGenDept : Boolean; //======================================================================================== function ValidGenPhone : Boolean; begin Result := False; end;// function ValidGenPhone : Boolean; //======================================================================================== function ValidGenEmail : Boolean; begin Result := False; end;// function ValidGenEmail : Boolean; //======================================================================================== function ValidC1Name : Boolean; begin Result := False; end;// function ValidC1Name : Boolean; //======================================================================================== function ValidC1Dept : Boolean; begin Result := False; end;// function ValidC1Dept : Boolean; //======================================================================================== function ValidC1Phone : Boolean; begin Result := False; end;// function ValidC1Phone : Boolean; //======================================================================================== function ValidC1Email : Boolean; begin Result := False; end;// function ValidC1Email : Boolean; //======================================================================================== function ValidC2Name : Boolean; begin Result := False; end;// function ValidC2Name : Boolean; //======================================================================================== function ValidC2Dept : Boolean; begin Result := False; end;// function ValidC2Dept : Boolean; //======================================================================================== function ValidC2Phone : Boolean; begin Result := False; end;// function ValidC2Phone : Boolean; //======================================================================================== function ValidC2Email : Boolean; begin Result := False; end;// function ValidC2Email : Boolean; //======================================================================================== function ValidC3Name : Boolean; begin Result := False; end;// function ValidC3Name : Boolean; //======================================================================================== function ValidC3Dept : Boolean; begin Result := False; end;// function ValidC3Dept : Boolean; //======================================================================================== function ValidC3Phone : Boolean; begin Result := False; end;// function ValidC3Phone : Boolean; //======================================================================================== function ValidC3Email : Boolean; begin Result := False; end;// function ValidC3Email : Boolean; //======================================================================================== // PUBLIC ROUTINES //======================================================================================== //======================================================================================== // PROPERTY ROUTINES //======================================================================================== //======================================================================================== // MENU ROUTINES //======================================================================================== //======================================================================================== // COMMAND BUTTON ROUTINES //======================================================================================== procedure TfrmSuppliersTable.bbtCancelClick(Sender: TObject); begin end;// procedure TfrmSuppliersTable.BitBtn2Click //======================================================================================== procedure TfrmSuppliersTable.bbtOkClick(Sender: TObject); begin end;// procedure TfrmSuppliersTable.BitBtn1Click //======================================================================================== // CONTROL ROUTINES //======================================================================================== //========== // dbEdit Routines //========== //========== // On Change //========== procedure TfrmSuppliersTable.dbeAddress1Change(Sender: TObject); begin dbeAddress1.Hint := ' ' + dbeAddress1.Text + ' '; end;// procedure TfrmSuppliersTable.dbeAddress1Change //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeAddress2Change(Sender: TObject); begin dbeAddress2.Hint := ' ' + dbeAddress2.Text + ' '; end;// procedure TfrmSuppliersTable.dbeAddress2Change //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeC1DeptChange(Sender: TObject); begin dbeC1Dept.Hint := ' ' + dbeC1Dept.Text + ' '; end;// procedure TfrmSuppliersTable.dbeC1DeptChange //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeC1EmailChange(Sender: TObject); begin dbeC1Email.Hint := ' ' + dbeC1Email.Text + ' '; end;// procedure TfrmSuppliersTable.dbeC1EmailChange //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeC1NameChange(Sender: TObject); begin dbeC1Name.Hint := ' ' + dbeC1Name.Text + ' '; end;// procedure TfrmSuppliersTable.dbeC1NameChange //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeC1PhoneChange(Sender: TObject); begin dbeC1Phone.Hint := ' ' + dbeC1Phone.Text + ' '; end;// procedure TfrmSuppliersTable.dbeC1PhoneChange //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeC2DeptChange(Sender: TObject); begin dbeC2Dept.Hint := ' ' + dbeC2Dept.Text + ' '; end;// procedure TfrmSuppliersTable.dbeC2DeptChange //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeC2EmailChange(Sender: TObject); begin dbeC2Email.Hint := ' ' + dbeC2Email.Text + ' '; end;// procedure TfrmSuppliersTable.dbeC2EmailChange //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeC2NameChange(Sender: TObject); begin dbeC2Name.Hint := ' ' + dbeC2Name.Text + ' '; end;// procedure TfrmSuppliersTable.dbeC2NameChange //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeC2PhoneChange(Sender: TObject); begin dbeC2Phone.Hint := ' ' + dbeC2Phone.Text + ' '; end;// procedure TfrmSuppliersTable.dbeC2PhoneChange //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeC3DeptChange(Sender: TObject); begin dbeC3Dept.Hint := ' ' + dbeC3Dept.Text + ' '; end;// procedure TfrmSuppliersTable.dbeC3DeptChange //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeC3EmailChange(Sender: TObject); begin dbeC3Email.Hint := ' ' + dbeC3Email.Text + ' '; end;// procedure TfrmSuppliersTable.dbeC3EmailChange //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeC3NameChange(Sender: TObject); begin dbeC3Name.Hint := ' ' + dbeC3Name.Text + ' '; end;// procedure TfrmSuppliersTable.dbeC3NameChange //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeC3PhoneChange(Sender: TObject); begin dbeC3Phone.Hint := ' ' + dbeC3Phone.Text + ' '; end;// procedure TfrmSuppliersTable.dbeC3PhoneChange //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeCityChange(Sender: TObject); begin dbeCity.Hint := ' ' + dbeCity.Text + ' '; end; //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeGenDeptChange(Sender: TObject); begin dbeGenDept.Hint := ' ' + dbeGenDept.Text + ' '; end;// procedure TfrmSuppliersTable.dbeGenDeptChange //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeGenEmailChange(Sender: TObject); begin dbeGenEmail.Hint := ' ' + dbeGenEmail.Text + ' '; end;// procedure TfrmSuppliersTable.dbeGenEmailChange //=--------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeGenNameChange(Sender: TObject); begin dbeGenName.Hint := ' ' + dbeGenName.Text + ' '; end;// procedure TfrmSuppliersTable.dbeGenNameChange //=--------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeGenPhoneChange(Sender: TObject); begin dbeGenPhone.Hint := ' ' + dbeGenPhone.Text + ' '; end;// procedure TfrmSuppliersTable.dbeGenPhoneChange //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeIDChange(Sender: TObject); begin dbeID.Hint := ' ' + dbeID.Text + ' '; end;// procedure TfrmSuppliersTable.dbeIDChange //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeProvStateChange(Sender: TObject); begin dbeProvState.Hint := ' ' + dbeProvState.Text + ' '; end; //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbePostalCodeChange(Sender: TObject); begin dbePostalCode.Hint := ' ' + dbePostalCode.Text + ' '; end;// procedure TfrmSuppliersTable.dbePostalCodeChange //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeSupplierNameChange(Sender: TObject); begin dbeSupplierName.Hint := ' ' + dbeSupplierName.Text + ' '; end;// procedure TfrmSuppliersTable.dbeSupplierNameChange //======================================================================================== //========== // On Keypress //========== procedure TfrmSuppliersTable.dbeSupplierNameKeyPress(Sender: TObject; var Key: char); begin // Key := ValidNameCharacter(Key); end;// procedure TfrmSuppliersTable.dbeSupplierNameKeyPress //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeAddress1KeyPress(Sender: TObject; var Key: char); begin // Key := ValidAddressCharacter(Key); end;// procedure TfrmSuppliersTable.dbeAddress1KeyPress //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeAddress2KeyPress(Sender: TObject; var Key: char ); begin // Key := ValidAddressCharacter(Key); end;// procedure TfrmSuppliersTable.dbeAddress2KeyPress //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeCityKeyPress(Sender: TObject; var Key: char); begin // Key := ValidCityCharacter(Key); end; //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeGenDeptKeyPress(Sender: TObject; var Key: char); begin // Key := ValidAlphaCharacter(Key); end;// procedure TfrmSuppliersTable.dbeGenDeptKeyPress //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeGenEmailKeyPress(Sender: TObject; var Key: char ); begin // Key := ValidEmailCharacter(Key); end;// procedure TfrmSuppliersTable.dbeGenEmailKeyPress //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeGenNameKeyPress(Sender: TObject; var Key: char); begin // Key := ValidNameCharacter(Key); end;// procedure TfrmSuppliersTable.dbeGenNameKeyPress //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeGenPhoneKeyPress(Sender: TObject; var Key: char); begin // Key := ValidPhoneCharacter(Key); end;// procedure TfrmSuppliersTable.dbeGenPhoneKeyPress //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeC1DeptKeyPress(Sender: TObject; var Key: char); begin // Key := ValidAlphaCharacter(Key); end;// procedure TfrmSuppliersTable.dbeC1DeptKeyPress //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeC1EmailKeyPress(Sender: TObject; var Key: char); begin // Key := ValidEmailCharacter(Key); end;// procedure TfrmSuppliersTable.dbeC1EmailKeyPress //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeC1NameKeyPress(Sender: TObject; var Key: char); begin // Key := ValidNameCharacter(Key); end;// procedure TfrmSuppliersTable.dbeC1NameKeyPress //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeC1PhoneKeyPress(Sender: TObject; var Key: char); begin // Key := ValidPhoneCharacter(Key); end;// procedure TfrmSuppliersTable.dbeC1PhoneKeyPress //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeC2DeptKeyPress(Sender: TObject; var Key: char); begin // Key := ValidAlphaCharacter(Key); end;// procedure TfrmSuppliersTable.dbeC2DeptKeyPress //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeC2EmailKeyPress(Sender: TObject; var Key: char); begin // Key := ValidEmailCharacter(Key); end;// procedure TfrmSuppliersTable.dbeC2EmailKeyPress //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeC2NameKeyPress(Sender: TObject; var Key: char); begin // Key := ValidNameCharacter(Key); end;// procedure TfrmSuppliersTable.dbeC2NameKeyPress //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeC2PhoneKeyPress(Sender: TObject; var Key: char); begin // Key := ValidPhoneCharacter(Key); end;// procedure TfrmSuppliersTable.dbeC2PhoneKeyPress //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeC3DeptKeyPress(Sender: TObject; var Key: char); begin // Key := ValidAlphaCharacter(Key); end;// procedure TfrmSuppliersTable.dbeC3DeptKeyPress //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeC3EmailKeyPress(Sender: TObject; var Key: char); begin // Key := ValidEmailCharacter(Key); end;// procedure TfrmSuppliersTable.dbeC3DeptKeyPress //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeC3PhoneKeyPress(Sender: TObject; var Key: char); begin // Key := ValidPhoneCharacter(Key); end;// procedure TfrmSuppliersTable.dbeC3PhoneKeyPress //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbeProvStateKeyPress(Sender: TObject; var Key: char); begin // Key := ValidProvStateCharacter(Key); end;// procedure TfrmSuppliersTable.dbeProvStateKeyPress //---------------------------------------------------------------------------------------- procedure TfrmSuppliersTable.dbePostalCodeKeyPress(Sender: TObject; var Key: char); begin // Key := ValidPostalCodeCharacter(Key); end;// procedure TfrmSuppliersTable.dbePostalCodeKeyPress //======================================================================================== //========== // dbNavigator Routines //========== procedure TfrmSuppliersTable.DBNavigator1BeforeAction(Sender: TObject; Button: TDBNavButtonType); begin if Button = nbPost then begin showmessage('Post'); // Validate Name, Address1, City, Prov.State, Postal Code. // If any field is invalid we retun to edit or cancel if not ValidREcord then Abort; end;// if Button = nbPost if Button = nbCancel then begin showmessage('Cancel'); Abort; end;// if Button = nbCancel if Button = nbRefresh then begin showmessage('Cancel'); SupplierTableQuery.Close; SupplierTableQuery.Open; Abort; end;// if Button = nbRefresh end;// procedure TfrmSuppliersTable.DBNavigator1BeforeAction //======================================================================================== // FILE ROUTINES //======================================================================================== //======================================================================================== // FORM ROUTINES //======================================================================================== procedure TfrmSuppliersTable.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin SupplierTableQuery.Close; SupplierDBConnection.Close; end;// procedure TfrmSuppliersTable.FormClose //======================================================================================== procedure TfrmSuppliersTable.FormCreate(Sender: TObject); begin end;// procedure TfrmSuppliersTable.FormCreate //======================================================================================== procedure TfrmSuppliersTable.FormShow(Sender: TObject); begin SupplierDBConnection.DatabaseName := cstrSuppliersDatabaseName; SupplierDBConnection.Transaction := SupplierTransaction; SupplierDBConnection.Connected := False; SupplierTransaction.Active := False; // Supplier Table SupplierTableQuery.DataBase := SupplierDBConnection; SupplierTableQuery.Active := False; SupplierTableDataSource.DataSet := SupplierTableQuery; dbgSuppliersTable.DataSource := SupplierTableDataSource; SupplierTableQuery.SQL.Text := 'select * from SuppliersTable'; SupplierTableQuery.Transaction := SupplierTransaction; SupplierDBConnection.Open; SupplierTransaction.Active := True; SupplierTableQuery.Open; end;// procedure TfrmSuppliersTable.FormShow //======================================================================================== end. // unit SuppliersTable
unit notificationmanager; {$mode delphi} interface uses Classes, SysUtils, And_jni, And_jni_Bridge, AndroidWidget, Laz_And_Controls; type {Draft Component code by "Lazarus Android Module Wizard" [2/3/2015 17:14:54]} {https://github.com/jmpessoa/lazandroidmodulewizard} {jControl template} jNotificationManager = class(jControl) private FId: integer; FTitle: string; FSubject: string; FBody: string; FIConIdentifier: string; // ../res/drawable ex: 'ic_launcher' FLightsColor: TARGBColorBridge; protected public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Init(refApp: jApp); override; function jCreate(): jObject; procedure jFree(); procedure Notify(_id: integer; _title: string; _subject: string; _body: string; _iconIdentifier: string; _color: TARGBColorBridge); overload; procedure Notify(); overload; procedure Cancel(_id: integer); procedure CancelAll(); procedure SetLightsColorAndTimes(_color: TARGBColorBridge; _onMills: integer; _offMills: integer); //TFPColorBridgeArray procedure SetLightsColor(_lightsColor: TARGBColorBridge); procedure SetLightsEnable(_enable: boolean); published property Id: integer read FId write FId; property Title: string read FTitle write FTitle; property Subject: string read FSubject write FSubject; property Body: string read FBody write FBody; property IConIdentifier: string read FIConIdentifier write FIConIdentifier; property LightsColor: TARGBColorBridge read FLightsColor write SetLightsColor; end; function jNotificationManager_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject; procedure jNotificationManager_jFree(env: PJNIEnv; _jnotificationmanager: JObject); procedure jNotificationManager_Notify(env: PJNIEnv; _jnotificationmanager: JObject; _id: integer; _title: string; _subject: string; _body: string; _iconIdentifier: string; _color: DWord); procedure jNotificationManager_Cancel(env: PJNIEnv; _jnotificationmanager: JObject; _id: integer); procedure jNotificationManager_CancelAll(env: PJNIEnv; _jnotificationmanager: JObject); procedure jNotificationManager_SetLightsColorAndTime(env: PJNIEnv; _jnotificationmanager: JObject; _color: integer; _onMills: integer; _offMills: integer); procedure jNotificationManager_SetLightsEnable(env: PJNIEnv; _jnotificationmanager: JObject; _enable: boolean); implementation {--------- jNotificationManager --------------} constructor jNotificationManager.Create(AOwner: TComponent); begin inherited Create(AOwner); //your code here.... FId:= 1001; FTitle:= 'Lamw'; FSubject:='Hello'; FBody:= 'Lamw: Hello System Notification ...'; FIConIdentifier:= 'ic_launcher'; FLightsColor:= colbrDefault; end; destructor jNotificationManager.Destroy; begin if not (csDesigning in ComponentState) then begin if FjObject <> nil then begin jFree(); FjObject:= nil; end; end; //you others free code here...' inherited Destroy; end; procedure jNotificationManager.Init(refApp: jApp); begin if FInitialized then Exit; inherited Init(refApp); //set default ViewParent/FjPRLayout as jForm.View! //your code here: set/initialize create params.... FjObject:= jCreate(); //jSelf ! FInitialized:= True; end; function jNotificationManager.jCreate(): jObject; begin Result:= jNotificationManager_jCreate(FjEnv, int64(Self), FjThis); end; procedure jNotificationManager.jFree(); begin //in designing component state: set value here... if FInitialized then jNotificationManager_jFree(FjEnv, FjObject); end; procedure jNotificationManager.Notify(_id: integer; _title: string; _subject: string; _body: string; _iconIdentifier: string; _color: TARGBColorBridge); var tempColor: TARGBColorBridge; begin //in designing component state: set value here... if FInitialized then begin tempColor:= _color; if tempColor = colbrDefault then tempColor:= colbrBlue; jNotificationManager_Notify(FjEnv, FjObject, _id ,_title ,_subject ,_body ,_iconIdentifier, GetARGB(FCustomColor, tempColor) ) end; end; procedure jNotificationManager.Notify(); begin //in designing component state: set value here... if FInitialized then begin Notify(FId , FTitle, FSubject, FBody, FIconIdentifier, FLightsColor); end; end; procedure jNotificationManager.Cancel(_id: integer); begin //in designing component state: set value here... if FInitialized then jNotificationManager_Cancel(FjEnv, FjObject, _id); end; procedure jNotificationManager.CancelAll(); begin //in designing component state: set value here... if FInitialized then jNotificationManager_CancelAll(FjEnv, FjObject); end; procedure jNotificationManager.SetLightsColorAndTimes(_color: TARGBColorBridge; _onMills: integer; _offMills: integer); var tempColor: TARGBColorBridge; begin //in designing component state: set value here... FLightsColor:= _color; if FInitialized then begin tempColor:= _color; if tempColor = colbrDefault then tempColor:= colbrBlue; jNotificationManager_SetLightsColorAndTime(FjEnv, FjObject, GetARGB(FCustomColor, tempColor) ,_onMills ,_offMills); end; end; procedure jNotificationManager.SetLightsColor(_lightsColor: TARGBColorBridge); var tempColor: TARGBColorBridge; begin //in designing component state: set value here... FLightsColor:= _lightsColor; if FInitialized then begin tempColor:= _lightsColor; if tempColor = colbrDefault then tempColor:= colbrBlue; jNotificationManager_SetLightsColorAndTime(FjEnv, FjObject, GetARGB(FCustomColor, tempColor), -1 , -1); end; end; procedure jNotificationManager.SetLightsEnable(_enable: boolean); begin //in designing component state: set value here... if FInitialized then jNotificationManager_SetLightsEnable(FjEnv, FjObject, _enable); end; {-------- jNotificationManager_JNI_Bridge ----------} function jNotificationManager_jCreate(env: PJNIEnv;_Self: int64; this: jObject): jObject; var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].j:= _Self; jCls:= Get_gjClass(env); jMethod:= env^.GetMethodID(env, jCls, 'jNotificationManager_jCreate', '(J)Ljava/lang/Object;'); Result:= env^.CallObjectMethodA(env, this, jMethod, @jParams); Result:= env^.NewGlobalRef(env, Result); end; (* //Please, you need insert: public java.lang.Object jNotificationManager_jCreate(long _Self) { return (java.lang.Object)(new jNotificationManager(this,_Self)); } //to end of "public class Controls" in "Controls.java" *) procedure jNotificationManager_jFree(env: PJNIEnv; _jnotificationmanager: JObject); var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jnotificationmanager); jMethod:= env^.GetMethodID(env, jCls, 'jFree', '()V'); env^.CallVoidMethod(env, _jnotificationmanager, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jNotificationManager_Notify(env: PJNIEnv; _jnotificationmanager: JObject; _id: integer; _title: string; _subject: string; _body: string; _iconIdentifier: string; _color: DWord); var jParams: array[0..5] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _id; jParams[1].l:= env^.NewStringUTF(env, PChar(_title)); jParams[2].l:= env^.NewStringUTF(env, PChar(_subject)); jParams[3].l:= env^.NewStringUTF(env, PChar(_body)); jParams[4].l:= env^.NewStringUTF(env, PChar(_iconIdentifier)); jParams[5].i:= _color; jCls:= env^.GetObjectClass(env, _jnotificationmanager); jMethod:= env^.GetMethodID(env, jCls, 'Notify', '(ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V'); env^.CallVoidMethodA(env, _jnotificationmanager, jMethod, @jParams); env^.DeleteLocalRef(env,jParams[1].l); env^.DeleteLocalRef(env,jParams[2].l); env^.DeleteLocalRef(env,jParams[3].l); env^.DeleteLocalRef(env,jParams[4].l); env^.DeleteLocalRef(env, jCls); end; procedure jNotificationManager_Cancel(env: PJNIEnv; _jnotificationmanager: JObject; _id: integer); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _id; jCls:= env^.GetObjectClass(env, _jnotificationmanager); jMethod:= env^.GetMethodID(env, jCls, 'Cancel', '(I)V'); env^.CallVoidMethodA(env, _jnotificationmanager, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jNotificationManager_CancelAll(env: PJNIEnv; _jnotificationmanager: JObject); var jMethod: jMethodID=nil; jCls: jClass=nil; begin jCls:= env^.GetObjectClass(env, _jnotificationmanager); jMethod:= env^.GetMethodID(env, jCls, 'CancelAll', '()V'); env^.CallVoidMethod(env, _jnotificationmanager, jMethod); env^.DeleteLocalRef(env, jCls); end; procedure jNotificationManager_SetLightsEnable(env: PJNIEnv; _jnotificationmanager: JObject; _enable: boolean); var jParams: array[0..0] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].z:= JBool(_enable); jCls:= env^.GetObjectClass(env, _jnotificationmanager); jMethod:= env^.GetMethodID(env, jCls, 'SetLightsEnable', '(Z)V'); env^.CallVoidMethodA(env, _jnotificationmanager, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; procedure jNotificationManager_SetLightsColorAndTime(env: PJNIEnv; _jnotificationmanager: JObject; _color: integer; _onMills: integer; _offMills: integer); var jParams: array[0..2] of jValue; jMethod: jMethodID=nil; jCls: jClass=nil; begin jParams[0].i:= _color; jParams[1].i:= _onMills; jParams[2].i:= _offMills; jCls:= env^.GetObjectClass(env, _jnotificationmanager); jMethod:= env^.GetMethodID(env, jCls, 'SetLightsColorAndTime', '(III)V'); env^.CallVoidMethodA(env, _jnotificationmanager, jMethod, @jParams); env^.DeleteLocalRef(env, jCls); end; end.
unit Pospolite.View.Version; { +-------------------------+ | Package: Pospolite View | | Author: Matek0611 | | Email: matiowo@wp.pl | | Version: 1.0p | +-------------------------+ Comments: ... } {$mode objfpc}{$H+} interface uses Classes, SysUtils, Pospolite.View.Basics; type TPLViewVersionField = (vvfName, vvfVersion, vvfExVersion, vvfOS, vvfJavaScript, vvfUserAgent, vvfModules, vvfAuthor); { TPLViewVersion } TPLViewVersion = class sealed public class function GetFieldInfo(AField: TPLViewVersionField): TPLString; class function Name: TPLString; class function Version: TPLString; class function ExVersion: TPLString; class function OS: TPLString; class function JavaScript: TPLString; class function UserAgent: TPLString; class function Modules: TPLString; class function Author: TPLString; end; implementation uses sha1 {$IFDEF WINDOWS}, Windows, ActiveX, comobj{$ENDIF}; {$IFDEF WINDOWS} type TWin32_OperatingSystemInfo = record Caption, BuildNumber: Variant; end; var _Win32_OperatingSystemInfo: TWin32_OperatingSystemInfo; function GetWMIObject(const objectName: String): IDispatch; var chEaten: PULONG; BindCtx: IBindCtx; Moniker: IMoniker; begin {$if (FPC_VERSION = 3) and (FPC_RELEASE >= 2)}New(chEaten);{$endif} OleCheck(CreateBindCtx(0, bindCtx)); OleCheck(MkParseDisplayName(BindCtx, StringToOleStr(objectName), chEaten, Moniker)); OleCheck(Moniker.BindToObject(BindCtx, nil, IDispatch, Result)); {$if (FPC_VERSION = 3) and (FPC_RELEASE >= 2)}Dispose(chEaten);{$endif} end; procedure GetWin32_OperatingSystem; var objWMIService : OLEVariant; colItems : OLEVariant; colItem : OLEVariant; oEnum : IEnumvariant; iValue : LongWord; begin objWMIService := GetWMIObject('winmgmts:\\.\root\CIMV2'); colItems := objWMIService.ExecQuery('SELECT * FROM Win32_OperatingSystem', 'WQL', 0); oEnum := IUnknown(colItems._NewEnum) as IEnumVariant; if oEnum.Next(1, colItem, iValue) = 0 then with _Win32_OperatingSystemInfo do begin Caption := colItem.Caption; BuildNumber := colItem.BuildNumber; end; end; {$ENDIF} { TPLViewVersion } class function TPLViewVersion.GetFieldInfo(AField: TPLViewVersionField ): TPLString; begin Result := ''; case AField of vvfName: Result := 'Pospolite View'; vvfVersion: Result := '2022.1.' + {$I %FPCVERSION%}; vvfExVersion: Result := SHA1Print(SHA1String(Version)); vvfAuthor: Result := 'Marcin Stefanowicz (Matek)'; vvfModules: Result := '[1] Modified D2D1 Fragment From Codebot Pascal Library by Anthony Walter'; vvfJavaScript: Result := 'PospoliteJS ' + Version; vvfOS: Result := {$IFDEF WINDOWS} _Win32_OperatingSystemInfo.Caption + ' OS (Build ' + _Win32_OperatingSystemInfo.BuildNumber + ')' {$ELSE} {$IFDEF LINUX} 'Linux' {$ENDIF}{$IFDEF DARWIN} 'MacOS' {$ENDIF}{$IFDEF UNIX} 'UNIX' {$ELSE} 'Undefined' {$ENDIF} {$ENDIF}; vvfUserAgent: Result := 'Mozilla/5.0 ' + {$IFDEF WINDOWS} '(Windows NT ' + IntToStr(Win32MajorVersion) + '.' + IntToStr(Win32MinorVersion) + '; ' + {$IFDEF WIN64} 'Win64; ' {$ELSE} 'Win32; ' {$ENDIF} + {$IFDEF CPU64} 'x64' {$ELSE} 'x86' {$ENDIF} + ')' {$ELSE} '(' + OS + '; ' + {$IFDEF CPU64} 'x64' {$ELSE} 'x86' {$ENDIF} + ')' {$ENDIF} + ' PospoliteView/' + Version; end; end; class function TPLViewVersion.Name: TPLString; begin Result := GetFieldInfo(vvfName); end; class function TPLViewVersion.Version: TPLString; begin Result := GetFieldInfo(vvfVersion); end; class function TPLViewVersion.ExVersion: TPLString; begin Result := GetFieldInfo(vvfExVersion); end; class function TPLViewVersion.OS: TPLString; begin Result := GetFieldInfo(vvfOS); end; class function TPLViewVersion.JavaScript: TPLString; begin Result := GetFieldInfo(vvfJavaScript); end; class function TPLViewVersion.UserAgent: TPLString; begin Result := GetFieldInfo(vvfUserAgent); end; class function TPLViewVersion.Modules: TPLString; begin Result := GetFieldInfo(vvfModules); end; class function TPLViewVersion.Author: TPLString; begin Result := GetFieldInfo(vvfAuthor); end; {$IFDEF WINDOWS} initialization try CoInitialize(nil); try GetWin32_OperatingSystem; finally CoUninitialize; end; except on e: Exception do ; end; {$ENDIF} end.
unit WinProcess1; interface uses Windows, classes, sysutils, util1, stmDef, stmobj, stmPg, stmMemo1; function fonctionCallProcess(cmdLine: Ansistring; var list: TstmMemo): integer;pascal; implementation function fonctionCallProcess(cmdLine: AnsiString; var list: TstmMemo): integer; const g_hChildStd_IN_Rd: Thandle = 0; g_hChildStd_IN_Wr: Thandle = 0; g_hChildStd_OUT_Rd: Thandle = 0; g_hChildStd_OUT_Wr: Thandle = 0; var saAttr: SECURITY_ATTRIBUTES ; ProcInfo: PROCESS_INFORMATION ; StartInfo: TSTARTUPINFO ; bSuccess: BOOL; dwRead, dwWritten: longword; chBuf:string; code: cardinal; tot: integer; begin verifierObjet(typeUO(list)); // Set the bInheritHandle flag so pipe handles are inherited. saAttr.nLength := sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle := TRUE; saAttr.lpSecurityDescriptor := Nil; // Create a pipe for the child process's STDOUT. if not CreatePipe(g_hChildStd_OUT_Rd, g_hChildStd_OUT_Wr, @saAttr, 0) then exit; // Ensure the read handle to the pipe for STDOUT is not inherited. if not SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0) then exit; // Create a pipe for the child process's STDIN. if not CreatePipe(g_hChildStd_IN_Rd, g_hChildStd_IN_Wr, @saAttr, 0) then exit; // Ensure the read handle to the pipe for STDIN is not inherited. if not SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) then exit; // Create the child process. // Set up members of the PROCESS_INFORMATION structure. ZeroMemory( @ProcInfo, sizeof(PROCESS_INFORMATION) ); // Set up members of the STARTUPINFO structure. // This structure specifies the STDIN and STDOUT handles for redirection. ZeroMemory( @StartInfo, sizeof(TSTARTUPINFO) ); StartInfo.cb := sizeof(TSTARTUPINFO); StartInfo.hStdError := g_hChildStd_OUT_Wr; StartInfo.hStdOutput := g_hChildStd_OUT_Wr; StartInfo.hStdInput := g_hChildStd_IN_Rd; StartInfo.wShowWindow:= SW_HIDE; StartInfo.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW ; // Create the child process. bSuccess := CreateProcess(Nil, Pchar(Cmdline), // command line nil, // process security attributes nil, // primary thread security attributes TRUE, // handles are inherited 0, // creation flags nil, // use parent's environment nil, // use parent's current directory StartInfo, // STARTUPINFO pointer ProcInfo); // receives PROCESS_INFORMATION // If an error occurs, exit the application. if not bSuccess then Exit; closeHandle( g_hChildStd_IN_Rd); // Deux lignes indispensables! closeHandle( g_hChildStd_OUT_Wr); // sinon blocage tot:=0; repeat setlength(chBuf,10000); dwRead:=0; bSuccess := ReadFile( g_hChildStd_OUT_Rd, pointer(@chBuf[1])^, 10000, dwRead, nil); if bSuccess and (dwRead>0) then begin setLength(chBuf,dwRead); tot:= tot+dwRead; StatuslineTxt('Total ='+Istr(tot)); list.Addline(chBuf); if testerFinPg then break; end else break; until false; GetExitCodeProcess(procInfo.hprocess,code); result:= code; CloseHandle(ProcInfo.hProcess); CloseHandle(ProcInfo.hThread); end; end.
unit DriverAPI; // Description: // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses Windows, // Required for DWORD FreeOTFEDriverConsts; // #define CTL_CODE( DeviceType, Function, Method, Access ) ( \ // ((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \ // ) type TFreeOTFEMountSource = (fomsFile, fomsPartition, fomsUnknown); // WARNING: The definition of: // TFreeOTFESectorIVGenMethod // FreeOTFESectorIVGenMethodTitle // FreeOTFESectorIVGenMethodID // SCTRIVGEN_USES_SECTOR_ID // SCTRIVGEN_USES_HASH // *must* all be kept in sync with each other at all times TFreeOTFESectorIVGenMethod = ( foivgNone, foivg32BitSectorID, foivg64BitSectorID, foivgHash32BitSectorID, foivgHash64BitSectorID, foivgESSIV, foivgUnknown ); // This is taken from "ntdddisk.h" from the MS Windows DDK TFreeOTFEStorageMediaType = ( mtUnknown, // Format is unknown mtF5_1Pt2_512, // 5.25", 1.2MB, 512 bytes/sector mtF3_1Pt44_512, // 3.5", 1.44MB, 512 bytes/sector mtF3_2Pt88_512, // 3.5", 2.88MB, 512 bytes/sector mtF3_20Pt8_512, // 3.5", 20.8MB, 512 bytes/sector mtF3_720_512, // 3.5", 720KB, 512 bytes/sector mtF5_360_512, // 5.25", 360KB, 512 bytes/sector mtF5_320_512, // 5.25", 320KB, 512 bytes/sector mtF5_320_1024, // 5.25", 320KB, 1024 bytes/sector mtF5_180_512, // 5.25", 180KB, 512 bytes/sector mtF5_160_512, // 5.25", 160KB, 512 bytes/sector mtRemovableMedia, // Removable media other than floppy mtFixedMedia, // Fixed hard disk media mtF3_120M_512, // 3.5", 120M Floppy mtF3_640_512, // 3.5" , 640KB, 512 bytes/sector mtF5_640_512, // 5.25", 640KB, 512 bytes/sector mtF5_720_512, // 5.25", 720KB, 512 bytes/sector mtF3_1Pt2_512, // 3.5" , 1.2Mb, 512 bytes/sector mtF3_1Pt23_1024, // 3.5" , 1.23Mb, 1024 bytes/sector mtF5_1Pt23_1024, // 5.25", 1.23MB, 1024 bytes/sector mtF3_128Mb_512, // 3.5" MO 128Mb 512 bytes/sector mtF3_230Mb_512, // 3.5" MO 230Mb 512 bytes/sector mtF8_256_128, // 8", 256KB, 128 bytes/sector mtF3_200Mb_512, // 3.5", 200M Floppy (HiFD) mtF3_240M_512, // 3.5", 240Mb Floppy (HiFD) mtF3_32M_512, // 3.5", 32Mb Floppy mtDDS_4mm, // Tape - DAT DDS1,2,... (all vendors) mtMiniQic, // Tape - miniQIC Tape mtTravan, // Tape - Travan TR-1,2,3,... mtQIC, // Tape - QIC mtMP_8mm, // Tape - 8mm Exabyte Metal Particle mtAME_8mm, // Tape - 8mm Exabyte Advanced Metal Evap mtAIT1_8mm, // Tape - 8mm Sony AIT mtDLT, // Tape - DLT Compact IIIxt, IV mtNCTP, // Tape - Philips NCTP mtIBM_3480, // Tape - IBM 3480 mtIBM_3490E, // Tape - IBM 3490E mtIBM_Magstar_3590, // Tape - IBM Magstar 3590 mtIBM_Magstar_MP, // Tape - IBM Magstar MP mtSTK_DATA_D3, // Tape - STK Data D3 mtSONY_DTF, // Tape - Sony DTF mtDV_6mm, // Tape - 6mm Digital Video mtDMI, // Tape - Exabyte DMI and compatibles mtSONY_D2, // Tape - Sony D2S and D2L mtCLEANER_CARTRIDGE, // Cleaner - All Drive types that support Drive Cleaners mtCD_ROM, // Opt_Disk - CD mtCD_R, // Opt_Disk - CD-Recordable (Write Once) mtCD_RW, // Opt_Disk - CD-Rewriteable mtDVD_ROM, // Opt_Disk - DVD-ROM mtDVD_R, // Opt_Disk - DVD-Recordable (Write Once) mtDVD_RW, // Opt_Disk - DVD-Rewriteable mtMO_3_RW, // Opt_Disk - 3.5" Rewriteable MO Disk mtMO_5_WO, // Opt_Disk - MO 5.25" Write Once mtMO_5_RW, // Opt_Disk - MO 5.25" Rewriteable (not LIMDOW) mtMO_5_LIMDOW, // Opt_Disk - MO 5.25" Rewriteable (LIMDOW) mtPC_5_WO, // Opt_Disk - Phase Change 5.25" Write Once Optical mtPC_5_RW, // Opt_Disk - Phase Change 5.25" Rewriteable mtPD_5_RW, // Opt_Disk - PhaseChange Dual Rewriteable mtABL_5_WO, // Opt_Disk - Ablative 5.25" Write Once Optical mtPINNACLE_APEX_5_RW, // Opt_Disk - Pinnacle Apex 4.6GB Rewriteable Optical mtSONY_12_WO, // Opt_Disk - Sony 12" Write Once mtPHILIPS_12_WO, // Opt_Disk - Philips/LMS 12" Write Once mtHITACHI_12_WO, // Opt_Disk - Hitachi 12" Write Once mtCYGNET_12_WO, // Opt_Disk - Cygnet/ATG 12" Write Once mtKODAK_14_WO, // Opt_Disk - Kodak 14" Write Once mtMO_NFR_525, // Opt_Disk - Near Field Recording (Terastor) mtNIKON_12_RW, // Opt_Disk - Nikon 12" Rewriteable mtIOMEGA_ZIP, // Mag_Disk - Iomega Zip mtIOMEGA_JAZ, // Mag_Disk - Iomega Jaz mtSYQUEST_EZ135, // Mag_Disk - Syquest EZ135 mtSYQUEST_EZFLYER, // Mag_Disk - Syquest EzFlyer mtSYQUEST_SYJET, // Mag_Disk - Syquest SyJet mtAVATAR_F2, // Mag_Disk - 2.5" Floppy mtMP2_8mm, // Tape - 8mm Hitachi mtDST_S, // Ampex DST Small Tapes mtDST_M, // Ampex DST Medium Tapes mtDST_L, // Ampex DST Large Tapes mtVXATape_1, // Ecrix 8mm Tape mtVXATape_2, // Ecrix 8mm Tape mtSTK_9840, // STK 9840 mtLTO_Ultrium, // IBM, HP, Seagate LTO Ultrium mtLTO_Accelis, // IBM, HP, Seagate LTO Accelis mtDVD_RAM, // Opt_Disk - DVD-RAM mtAIT_8mm, // AIT2 or higher mtADR_1, // OnStream ADR Mediatypes mtADR_2 ); resourcestring RS_MOUNTSOURCE_FILE = 'File'; RS_MOUNTSOURCE_PARTITION = 'Partition'; RS_MOUNTSOURCE_UNKNOWN = 'Unknown'; const FreeOTFEMountSourceTitle : array [TFreeOTFEMountSource] of string = ( RS_MOUNTSOURCE_FILE, RS_MOUNTSOURCE_PARTITION, RS_MOUNTSOURCE_UNKNOWN ); FreeOTFEMountSourceID : array [TFreeOTFEMountSource] of integer = ( 1, // MNTSRC_FILE 2, // MNTSRC_PARTITION 9999 // MNTSRC_FILE_UNKNOWN ); resourcestring RS_SECTORIVGENMETHOD_NULL_IV = 'Null IV'; RS_SECTORIVGENMETHOD_SECTOR_ID_32 = '32 bit sector ID'; RS_SECTORIVGENMETHOD_SECTOR_ID_64 = '64 bit sector ID'; RS_SECTORIVGENMETHOD_HASHED_SECTOR_ID_32 = 'Hashed 32 bit sector ID'; RS_SECTORIVGENMETHOD_HASHED_SECTOR_ID_64 = 'Hashed 64 bit sector ID'; RS_SECTORIVGENMETHOD_ESSIV = 'ESSIV'; RS_SECTORIVGENMETHOD_UNKNOWN = 'Unknown'; const // WARNING: The definition of: // TFreeOTFESectorIVGenMethod // FreeOTFESectorIVGenMethodTitle // FreeOTFESectorIVGenMethodID // SCTRIVGEN_USES_SECTOR_ID // SCTRIVGEN_USES_HASH // *must* all be kept in sync with each other at all times FreeOTFESectorIVGenMethodTitle : array [TFreeOTFESectorIVGenMethod] of string = ( RS_SECTORIVGENMETHOD_NULL_IV, RS_SECTORIVGENMETHOD_SECTOR_ID_32, RS_SECTORIVGENMETHOD_SECTOR_ID_64, RS_SECTORIVGENMETHOD_HASHED_SECTOR_ID_32, RS_SECTORIVGENMETHOD_HASHED_SECTOR_ID_64, RS_SECTORIVGENMETHOD_ESSIV, RS_SECTORIVGENMETHOD_UNKNOWN ); // WARNING: The definition of: // TFreeOTFESectorIVGenMethod // FreeOTFESectorIVGenMethodTitle // FreeOTFESectorIVGenMethodID // SCTRIVGEN_USES_SECTOR_ID // SCTRIVGEN_USES_HASH // *must* all be kept in sync with each other at all times FreeOTFESectorIVGenMethodID : array [TFreeOTFESectorIVGenMethod] of byte = ( 0, // IVGEN_NONE 1, // IVGEN_32BIT_SECTOR_ID 2, // IVGEN_64BIT_SECTOR_ID 3, // IVGEN_HASH_32BIT_SECTOR_ID 4, // IVGEN_HASH_64BIT_SECTOR_ID 5, // IVGEN_ESSIV 255 // IVGEN_UNKNOWN ); FreeOTFEStorageMediaTypeTitle : array [TFreeOTFEStorageMediaType] of string = ( 'Format is unknown', '5.25", 1.2MB, 512 bytes/sector', '3.5", 1.44MB, 512 bytes/sector', '3.5", 2.88MB, 512 bytes/sector', '3.5", 20.8MB, 512 bytes/sector', '3.5", 720KB, 512 bytes/sector', '5.25", 360KB, 512 bytes/sector', '5.25", 320KB, 512 bytes/sector', '5.25", 320KB, 1024 bytes/sector', '5.25", 180KB, 512 bytes/sector', '5.25", 160KB, 512 bytes/sector', 'Removable media other than floppy', 'Fixed hard disk media', '3.5", 120M Floppy', '3.5" , 640KB, 512 bytes/sector', '5.25", 640KB, 512 bytes/sector', '5.25", 720KB, 512 bytes/sector', '3.5" , 1.2Mb, 512 bytes/sector', '3.5" , 1.23Mb, 1024 bytes/sector', '5.25", 1.23MB, 1024 bytes/sector', '3.5" MO 128Mb 512 bytes/sector', '3.5" MO 230Mb 512 bytes/sector', '8", 256KB, 128 bytes/sector', '3.5", 200M Floppy (HiFD)', '3.5", 240Mb Floppy (HiFD)', '3.5", 32Mb Floppy', 'Tape - DAT DDS1,2,... (all vendors)', 'Tape - miniQIC Tape', 'Tape - Travan TR-1,2,3,...', 'Tape - QIC', 'Tape - 8mm Exabyte Metal Particle', 'Tape - 8mm Exabyte Advanced Metal Evap', 'Tape - 8mm Sony AIT', 'Tape - DLT Compact IIIxt, IV', 'Tape - Philips NCTP', 'Tape - IBM 3480', 'Tape - IBM 3490E', 'Tape - IBM Magstar 3590', 'Tape - IBM Magstar MP', 'Tape - STK Data D3', 'Tape - Sony DTF', 'Tape - 6mm Digital Video', 'Tape - Exabyte DMI and compatibles', 'Tape - Sony D2S and D2L', 'Cleaner - All Drive types that support Drive Cleaners', 'Opt_Disk - CD', 'Opt_Disk - CD-Recordable (Write Once)', 'Opt_Disk - CD-Rewriteable', 'Opt_Disk - DVD-ROM', 'Opt_Disk - DVD-Recordable (Write Once)', 'Opt_Disk - DVD-Rewriteable', 'Opt_Disk - 3.5" Rewriteable MO Disk', 'Opt_Disk - MO 5.25" Write Once', 'Opt_Disk - MO 5.25" Rewriteable (not LIMDOW)', 'Opt_Disk - MO 5.25" Rewriteable (LIMDOW)', 'Opt_Disk - Phase Change 5.25" Write Once Optical', 'Opt_Disk - Phase Change 5.25" Rewriteable', 'Opt_Disk - PhaseChange Dual Rewriteable', 'Opt_Disk - Ablative 5.25" Write Once Optical', 'Opt_Disk - Pinnacle Apex 4.6GB Rewriteable Optical', 'Opt_Disk - Sony 12" Write Once', 'Opt_Disk - Philips/LMS 12" Write Once', 'Opt_Disk - Hitachi 12" Write Once', 'Opt_Disk - Cygnet/ATG 12" Write Once', 'Opt_Disk - Kodak 14" Write Once', 'Opt_Disk - Near Field Recording (Terastor)', 'Opt_Disk - Nikon 12" Rewriteable', 'Mag_Disk - Iomega Zip', 'Mag_Disk - Iomega Jaz', 'Mag_Disk - Syquest EZ135', 'Mag_Disk - Syquest EzFlyer', 'Mag_Disk - Syquest SyJet', 'Mag_Disk - 2.5" Floppy', 'Tape - 8mm Hitachi', 'Ampex DST Small Tapes', 'Ampex DST Medium Tapes', 'Ampex DST Large Tapes', 'Ecrix 8mm Tape', 'Ecrix 8mm Tape', 'STK 9840', 'IBM, HP, Seagate LTO Ultrium', 'IBM, HP, Seagate LTO Accelis', 'Opt_Disk - DVD-RAM', 'AIT2 or higher', 'OnStream ADR Mediatypes (1)', 'OnStream ADR Mediatypes (2)' ); FreeOTFEStorageMediaTypeID : array [TFreeOTFEStorageMediaType] of integer = ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, // 0x20 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91 ); type // This definition is stored here, although it would be better if it was // stored in OTFEFreeOTFE_U, so only that unit need be "used" by user // applications TFreeOTFEMACAlgorithm = (fomacHash, fomacHMAC, fomacUnknown); // This definition is stored here, although it would be better if it was // stored in OTFEFreeOTFE_U, so only that unit need be "used" by user // applications TFreeOTFEKDFAlgorithm = (fokdfHashWithSalt, fokdfPBKDF2, fokdfUnknown); const // Various version IDs returned by the main FreeOTFE driver // Unused consts are commented out //FREEOTFE_ID_v00_50_0000 = (00 * $01000000) + (50 * $00010000) + (0000 * $00000001); //FREEOTFE_ID_v00_53_0000 = (00 * $01000000) + (53 * $00010000) + (0000 * $00000001); //FREEOTFE_ID_v00_54_0000 = (00 * $01000000) + (54 * $00010000) + (0000 * $00000001); //FREEOTFE_ID_v00_56_0000 = (00 * $01000000) + (56 * $00010000) + (0000 * $00000001); //FREEOTFE_ID_v00_57_0000 = (00 * $01000000) + (57 * $00010000) + (0000 * $00000001); FREEOTFE_ID_v00_58_0000 = (00 * $01000000) + (58 * $00010000) + (0000 * $00000001); FREEOTFE_ID_v01_60_0000 = (01 * $01000000) + (60 * $00010000) + (0000 * $00000001); FREEOTFE_ID_v02_00_0000 = (02 * $01000000) + (00 * $00010000) + (0000 * $00000001); FREEOTFE_ID_v03_00_0000 = (03 * $01000000) + (00 * $00010000) + (0000 * $00000001); FREEOTFE_ID_v04_30_0000 = (04 * $01000000) + (30 * $00010000) + (0000 * $00000001); // If the version ID couldn't be determined FREEOTFE_ID_FAILURE = $FFFFFFFF; // From FreeOTFEAPI.h // Length in characters (not bytes) FREEOTFE_MAX_FILENAME_LENGTH = 1024; MAIN_DEVICE_NAME = 'FreeOTFE'; DEVICE_BASE_NAME = '\' + MAIN_DEVICE_NAME; DEVICE_FREEOTFE_ROOT = '\Device' + DEVICE_BASE_NAME; //DEVICE_SYMLINK_FREEOTFE_ROOT = '\DosDevices'; // Note: THERE IS NO TRAILING SLASH ON THIS ONE - THE NAMES WHICH GET APPENDED // ONTO THE END ALL START WITH THAT "\" DEVICE_SYMLINK_FREEOTFE_ROOT = '\\.'; // Main device DEVICE_MAIN_NAME = DEVICE_FREEOTFE_ROOT + DEVICE_BASE_NAME; DEVICE_SYMLINK_MAIN_NAME = DEVICE_SYMLINK_FREEOTFE_ROOT + DEVICE_BASE_NAME; // Disk devices DEVICE_DISK_DIR_NAME = DEVICE_FREEOTFE_ROOT + '\Disks'; DEVICE_DISK_PREFIX = DEVICE_DISK_DIR_NAME + '\Disk'; // The following is just padding to represent the number tacked onto the // end of DEVICE_DISK_PREFIX DEVICE_DISK_NUMBER = 'zzzzz'; NULL_GUID = '{00000000-0000-0000-0000-000000000000}'; // The length of the critical data section, INCLUDING ALL PADDING // If this is changed, the following functions will also probably have to be changed: // BackupVolumeCriticalData(...) // RestoreVolumeCriticalData(...) // ChangeVolumePassword(...) CRITICAL_DATA_LENGTH = 4096; // In *bits* // In bits CDB_MAX_MAC_LENGTH = 512; // Volume flags // Bit 0 unused (1) VOL_FLAGS_SECTOR_ID_ZERO_VOLSTART = 2; // Bit 1 // Bit 2 unused (4) // Bit 3 unused (8) VOL_FLAGS_NORMAL_TIMESTAMPS = 16; // Bit 4 const IOCTL_FREEOTFE_VERSION = (((FILE_DEVICE_DISK) * $10000) OR ((FILE_READ_DATA) * $4000) OR (($800) * $4) OR (METHOD_BUFFERED)); const IOCTL_FREEOTFE_CREATE = (((FILE_DEVICE_DISK) * $10000) OR ((FILE_READ_DATA) * $4000) OR (($805) * $4) OR (METHOD_BUFFERED)); const IOCTL_FREEOTFE_SET_RAW = (((FILE_DEVICE_DISK) * $10000) OR ((FILE_READ_DATA) * $4000) OR (($809) * $4) OR (METHOD_BUFFERED)); const IOCTL_FREEOTFE_GET_RAW = (((FILE_DEVICE_DISK) * $10000) OR ((FILE_READ_DATA) * $4000) OR (($80A) * $4) OR (METHOD_BUFFERED)); const IOCTL_FREEOTFE_MOUNT = (((FILE_DEVICE_DISK) * $10000) OR ((FILE_READ_DATA) * $4000) OR (($801) * $4) OR (METHOD_BUFFERED)); const IOCTL_FREEOTFE_DISMOUNT = (((FILE_DEVICE_DISK) * $10000) OR ((FILE_READ_DATA) * $4000) OR (($802) * $4) OR (METHOD_BUFFERED)); const IOCTL_FREEOTFE_DESTROY = (((FILE_DEVICE_DISK) * $10000) OR ((FILE_READ_DATA) * $4000) OR (($806) * $4) OR (METHOD_BUFFERED)); const IOCTL_FREEOTFE_GET_DISK_DEVICE_COUNT = (((FILE_DEVICE_DISK) * $10000) OR ((FILE_READ_DATA) * $4000) OR (($807) * $4) OR (METHOD_BUFFERED)); const IOCTL_FREEOTFE_GET_DISK_DEVICE_LIST = (((FILE_DEVICE_DISK) * $10000) OR ((FILE_READ_DATA) * $4000) OR (($808) * $4) OR (METHOD_BUFFERED)); const IOCTL_FREEOTFE_GET_DISK_DEVICE_STATUS = (((FILE_DEVICE_DISK) * $10000) OR ((FILE_READ_DATA) * $4000) OR (($803) * $4) OR (METHOD_BUFFERED)); const IOCTL_FREEOTFE_GET_DISK_DEVICE_METADATA = (((FILE_DEVICE_DISK) * $10000) OR ((FILE_READ_DATA) * $4000) OR (($804) * $4) OR (METHOD_BUFFERED)); // Derive a key const IOCTL_FREEOTFE_DERIVE_KEY = (((FILE_DEVICE_UNKNOWN) * $10000) OR ((FILE_READ_DATA) * $4000) OR (($810) * $4) OR (METHOD_BUFFERED)); // Generate a MAC const IOCTL_FREEOTFE_GENERATE_MAC = (((FILE_DEVICE_UNKNOWN) * $10000) OR ((FILE_READ_DATA) * $4000) OR (($811) * $4) OR (METHOD_BUFFERED)); // Encrypt a block const IOCTL_FREEOTFE_ENCRYPT_BLOCK = (((FILE_DEVICE_UNKNOWN) * $10000) OR ((FILE_READ_DATA) * $4000) OR (($812) * $4) OR (METHOD_BUFFERED)); // Decrypt a block const IOCTL_FREEOTFE_DECRYPT_BLOCK = (((FILE_DEVICE_UNKNOWN) * $10000) OR ((FILE_READ_DATA) * $4000) OR (($813) * $4) OR (METHOD_BUFFERED)); // Lock, dismount, remove, eject and unlock // Originally added for Vista, where the user can't do this if UAC is // operational, and the userspace software isn't running with escalated privs const IOCTL_FREEOTFE_LDREU = (((FILE_DEVICE_UNKNOWN) * $10000) OR ((FILE_READ_DATA) * $4000) OR (($814) * $4) OR (METHOD_BUFFERED)); // Create DOS symlink for device const IOCTL_FREEOTFE_CREATE_DOS_MOUNTPOINT = (((FILE_DEVICE_UNKNOWN) * $10000) OR ((FILE_READ_DATA) * $4000) OR (($815) * $4) OR (METHOD_BUFFERED)); // Delete DOS symlink for device const IOCTL_FREEOTFE_DELETE_DOS_MOUNTPOINT = (((FILE_DEVICE_UNKNOWN) * $10000) OR ((FILE_READ_DATA) * $4000) OR (($816) * $4) OR (METHOD_BUFFERED)); type // THIS DEPENDS ON DELPHI ALIGNING VALUES IN A RECORD ON WORD BOUNDRIES!!! // - i.e. it's not a "packed record" PDIOC_VERSION = ^TDIOC_VERSION; TDIOC_VERSION = record VersionID: DWORD; end; // THIS DEPENDS ON DELPHI ALIGNING VALUES IN A RECORD ON WORD BOUNDRIES!!! // - i.e. it's not a "packed record" PDIOC_DISK_DEVICE_CREATE = ^TDIOC_DISK_DEVICE_CREATE; TDIOC_DISK_DEVICE_CREATE = record DeviceType: DWORD; // Set to one of the system defined FILE_DEVICE_XXX // constants end; // THIS DEPENDS ON DELPHI ALIGNING VALUES IN A RECORD ON WORD BOUNDRIES!!! // - i.e. it's not a "packed record" PDIOC_DEVICE_NAME = ^TDIOC_DEVICE_NAME; TDIOC_DEVICE_NAME = record DeviceName: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of aNSIchar; end; // THIS DEPENDS ON DELPHI ALIGNING VALUES IN A RECORD ON WORD BOUNDRIES!!! // - i.e. it's not a "packed record" PDIOC_DEVICE_NAME_LIST = ^TDIOC_DEVICE_NAME_LIST; TDIOC_DEVICE_NAME_LIST = record DeviceCount: DWORD; DeviceName: array [0..0] of array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of aNSIchar; // Variable length end; // THIS DEPENDS ON DELPHI ALIGNING VALUES IN A RECORD ON WORD BOUNDRIES!!! // - i.e. it's not a "packed record" PDIOC_MOUNT_PC_DRIVER = ^TDIOC_MOUNT_PC_DRIVER; TDIOC_MOUNT_PC_DRIVER = record DiskDeviceName: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of aNSIchar; Filename: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of AnsiChar; // Start and end of encrypted data within the file // If DataEnd is zero, it will be set to the last byte in the file DataStart: int64; DataEnd: int64; IVHashDeviceName: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of AnsiChar; IVHashGUID: TGUID; IVCypherDeviceName: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of AnsiChar; IVCypherGUID: TGUID; MainCypherDeviceName: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of AnsiChar; MainCypherGUID: TGUID; ReadOnly: boolean; MountSource: integer; // An ID taken from FreeOTFEMountSourceID StorageMediaType: integer; // An ID taken from FreeOTFEMStoragemediaTypeID VolumeFlags: DWORD; SectorIVGenMethod: integer; MasterKeyLength: cardinal; // In bits VolumeIVLength: cardinal; // In bits MetaDataLength: cardinal; // In *bytes* MasterKey: array [0..0] of byte; // Variable length array VolumeIV: array [0..0] of byte; // Variable length array MetaData: array [0..0] of byte; // Variable length array end; // THIS DEPENDS ON DELPHI ALIGNING VALUES IN A RECORD ON WORD BOUNDRIES!!! // - i.e. it's not a "packed record" PDIOC_MOUNT_PC_DLL = ^TDIOC_MOUNT_PC_DLL; TDIOC_MOUNT_PC_DLL = record Filename: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of WChar; // Start and end of encrypted data within the file // If DataEnd is zero, it will be set to the last byte in the file DataStart: int64; DataEnd: int64; IVHashDeviceName: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of WChar; IVHashGUID: TGUID; IVCypherDeviceName: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of WChar; IVCypherGUID: TGUID; MainCypherDeviceName: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of WChar; MainCypherGUID: TGUID; ReadOnly: boolean; MountSource: integer; // An ID taken from FreeOTFEMountSourceID VolumeFlags: DWORD; SectorIVGenMethod: integer; MasterKeyLength: cardinal; // In bits VolumeIVLength: cardinal; // In bits MetaDataLength: cardinal; // In *bytes* MasterKey: array [0..0] of byte; // Variable length array VolumeIV: array [0..0] of byte; // Variable length array MetaData: array [0..0] of byte; // Variable length array end; // THIS DEPENDS ON DELPHI ALIGNING VALUES IN A RECORD ON WORD BOUNDRIES!!! // - i.e. it's not a "packed record" PDIOC_DISMOUNT = ^TDIOC_DISMOUNT; TDIOC_DISMOUNT = record DiskDeviceName: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of AnsiChar; Emergency: boolean; end; // THIS DEPENDS ON DELPHI ALIGNING VALUES IN A RECORD ON WORD BOUNDRIES!!! // - i.e. it's not a "packed record" PDIOC_DISK_DEVICE_COUNT = ^TDIOC_DISK_DEVICE_COUNT; TDIOC_DISK_DEVICE_COUNT = record Count: cardinal; end; PDIOC_DISK_DEVICE_STATUS_PC_DRIVER = ^TDIOC_DISK_DEVICE_STATUS_PC_DRIVER; TDIOC_DISK_DEVICE_STATUS_PC_DRIVER = packed record DiskDeviceName: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of AnsiChar; Filename: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of AnsiChar; Mounted: boolean; IVHashDeviceName: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of AnsiChar; junk_padding1: array [1..3] of byte; // Weird, but needed?! IVHashGUID: TGUID; IVCypherDeviceName: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of AnsiChar; IVCypherGUID: TGUID; MainCypherDeviceName: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of AnsiChar; MainCypherGUID: TGUID; DismountPending: boolean; ReadOnly: boolean; junk_padding3: array [1..2] of byte; VolumeFlags: DWORD; SectorIVGenMethod: integer; MetaDataLength: cardinal; // In *bytes* end; PDIOC_DISK_DEVICE_STATUS_PC_DLL = ^TDIOC_DISK_DEVICE_STATUS_PC_DLL; TDIOC_DISK_DEVICE_STATUS_PC_DLL = packed record Filename: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of WChar; IVHashDeviceName: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of WChar; IVHashGUID: TGUID; IVCypherDeviceName: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of WChar; IVCypherGUID: TGUID; MainCypherDeviceName: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of WChar; MainCypherGUID: TGUID; DismountPending: boolean; ReadOnly: boolean; junk_padding3: array [1..2] of byte; VolumeFlags: DWORD; SectorIVGenMethod: integer; MetaDataLength: cardinal; // In *bytes* end; PDIOC_DISK_DEVICE_METADATA = ^TDIOC_DISK_DEVICE_METADATA; TDIOC_DISK_DEVICE_METADATA = record MetaDataLength: cardinal; // In *bytes* MetaData: array [0..0] of byte; // Variable length array end; PDIOC_FILENAME = ^TDIOC_FILENAME; TDIOC_FILENAME = record Filename: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of AnsiChar; end; PDIOC_SET_RAW_DATA = ^TDIOC_SET_RAW_DATA; TDIOC_SET_RAW_DATA = record Filename: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of AnsiChar; Offset: int64; DataLength: integer; Data: array [0..0] of byte; end; PDIOC_GET_RAW_DATA_IN = ^TDIOC_GET_RAW_DATA_IN; TDIOC_GET_RAW_DATA_IN = record Filename: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of AnsiChar; Offset: int64; DataLength: integer; end; PDIOC_GET_RAW_DATA_OUT = ^TDIOC_GET_RAW_DATA_OUT; TDIOC_GET_RAW_DATA_OUT = record Data: array [0..0] of byte; end; PDIOC_DERIVE_KEY_IN_PC_DRIVER = ^TDIOC_DERIVE_KEY_IN_PC_DRIVER; TDIOC_DERIVE_KEY_IN_PC_DRIVER = record KDFAlgorithm: integer; HashDeviceName: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of AnsiChar; HashGUID: TGUID; CypherDeviceName: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of AnsiChar; CypherGUID: TGUID; Iterations: integer; LengthWanted: integer; // In bits - the length of the output key wanted // NOTE: THE ORDER OF THE FOLLOWING ITEMS IS SIGNIFICANT // We have the lengths first, *then* the data as this makes checking the size of the // struct easier, since these are both known-width members and can therefore // be accessed directly using "variable->SaltLength". // If the order was: "Password", "SaltLength", "Salt", then we could not access // "SaltLength" directly, and would have to take PasswordLength into account before // accessing it. PasswordLength: integer; // In bits SaltLength: integer; // In bits Password: array [0..0] of AnsiChar; // Variable length array Salt: array [0..0] of AnsiChar; // Variable length array end; PDIOC_DERIVE_KEY_IN_PC_DLL = ^TDIOC_DERIVE_KEY_IN_PC_DLL; TDIOC_DERIVE_KEY_IN_PC_DLL = record KDFAlgorithm: integer; HashDeviceName: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of WChar; HashGUID: TGUID; CypherDeviceName: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of WChar; CypherGUID: TGUID; Iterations: integer; LengthWanted: integer; // In bits - the length of the output key wanted // NOTE: THE ORDER OF THE FOLLOWING ITEMS IS SIGNIFICANT // We have the lengths first, *then* the data as this makes checking the size of the // struct easier, since these are both known-width members and can therefore // be accessed directly using "variable->SaltLength". // If the order was: "Password", "SaltLength", "Salt", then we could not access // "SaltLength" directly, and would have to take PasswordLength into account before // accessing it. PasswordLength: integer; // In bits SaltLength: integer; // In bits Password: array [0..0] of byte; // Variable length array Salt: array [0..0] of byte; // Variable length array end; PDIOC_DERIVE_KEY_OUT = ^TDIOC_DERIVE_KEY_OUT; TDIOC_DERIVE_KEY_OUT = record DerivedKeyLength: integer; // In bits DerivedKey: array [0..0] of byte; // Variable length array end; PDIOC_GENERATE_MAC_IN_PC_DRIVER = ^TDIOC_GENERATE_MAC_IN_PC_DRIVER; TDIOC_GENERATE_MAC_IN_PC_DRIVER = record MACAlgorithm: integer; HashDeviceName: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of aNSIchar; HashGUID: TGUID; CypherDeviceName: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of aNSIchar; CypherGUID: TGUID; LengthWanted: integer; // In bits - the length of the output key wanted // NOTE: THE ORDER OF THE FOLLOWING ITEMS IS SIGNIFICANT // We have the lengths first, *then* the data as this makes checking the size of the // struct easier, since these are both known-width members and can therefore // be accessed directly using "variable->SaltLength". // If the order was: "Data", "SaltLength", "Salt", then we could not access // "SaltLength" directly, and would have to take DataLength into account before // accessing it. KeyLength: integer; // In bits DataLength: integer; // In bits Key: array [0..0] of byte; // Variable length array Data: array [0..0] of byte; // Variable length array end; PDIOC_GENERATE_MAC_IN_PC_DLL = ^TDIOC_GENERATE_MAC_IN_PC_DLL; TDIOC_GENERATE_MAC_IN_PC_DLL = record MACAlgorithm: integer; HashDeviceName: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of WChar; HashGUID: TGUID; CypherDeviceName: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of WChar; CypherGUID: TGUID; LengthWanted: integer; // In bits - the length of the output key wanted // NOTE: THE ORDER OF THE FOLLOWING ITEMS IS SIGNIFICANT // We have the lengths first, *then* the data as this makes checking the size of the // struct easier, since these are both known-width members and can therefore // be accessed directly using "variable->SaltLength". // If the order was: "Data", "SaltLength", "Salt", then we could not access // "SaltLength" directly, and would have to take DataLength into account before // accessing it. KeyLength: integer; // In bits DataLength: integer; // In bits Key: array [0..0] of byte; // Variable length array Data: array [0..0] of byte; // Variable length array end; PDIOC_GENERATE_MAC_OUT = ^TDIOC_GENERATE_MAC_OUT; TDIOC_GENERATE_MAC_OUT = record MACLength: integer; // In bits MAC: array [0..0] of byte; // Variable length array end; // THIS DEPENDS ON DELPHI ALIGNING VALUES IN A RECORD ON WORD BOUNDRIES!!! // - i.e. it's not a "packed record" PDIOC_LDREU = ^TDIOC_LDREU; TDIOC_LDREU = record DriveFile: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of AnsiChar; DiskDeviceName: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of AnsiChar; Emergency: boolean; end; // THIS DEPENDS ON DELPHI ALIGNING VALUES IN A RECORD ON WORD BOUNDRIES!!! // - i.e. it's not a "packed record" PDIOC_DOS_MOUNTPOINT = ^TDIOC_DOS_MOUNTPOINT; TDIOC_DOS_MOUNTPOINT = record DiskDeviceName: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of AnsiChar; Global: boolean; Mountpoint: array [0..FREEOTFE_MAX_FILENAME_LENGTH-1] of AnsiChar; end; implementation END.
unit Edit_OrderPrintDolgn; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, ExtCtrls, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, ActnList; type TParamEdit = class ZnachDolgnost:string; ZnachNameDolgnost:string; idReport:Integer; AOwner:TComponent; end; type TFEdit = class(TForm) TextEditValue: TcxMaskEdit; Panel1: TPanel; btnOk: TcxButton; btnCancel: TcxButton; ActionList: TActionList; ActionEnter: TAction; ActionEsc: TAction; MENameDolgnost: TcxMaskEdit; procedure btnOkClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); constructor create(Param:TParamEdit) ; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure Action1Execute(Sender: TObject); procedure ActionEscExecute(Sender: TObject); private LocParam:TParamEdit; public { Public declarations } end; var FEdit: TFEdit; implementation {$R *.dfm} procedure TFEdit.btnOkClick(Sender: TObject); begin LocParam.ZnachDolgnost:=VarToStrDef(TextEditValue.EditValue,''); LocParam.ZnachNameDolgnost:=VarToStrDef(MENameDolgnost.EditValue,''); ModalResult:=mrOk; end; procedure TFEdit.btnCancelClick(Sender: TObject); begin ModalResult:=mrCancel; end; constructor TFEdit.create(Param:TParamEdit); begin inherited create(Param.AOwner); LocParam:=Param; TextEditValue.EditValue:=Param.ZnachDolgnost; MENameDolgnost.EditValue:= Param.ZnachNameDolgnost; end; procedure TFEdit.FormClose(Sender: TObject; var Action: TCloseAction); begin //Action:=caFree; end; procedure TFEdit.Action1Execute(Sender: TObject); begin if btnOk.Focused then btnOkClick(sender) else if btnCancel.Focused then btnCancelClick(Sender) else keybd_event(VK_TAB,0,0,0); end; procedure TFEdit.ActionEscExecute(Sender: TObject); begin btnCancelClick(Sender); end; end.
function DigitSum(number:integer): integer; begin number := abs(number); result := 0; while number > 0 do begin Inc(result, number mod 10); number := number div 10; end; end; begin writeln((DigitSum(ReadInteger))mod 3 = 0 ? 'yes' : 'no'); end.
unit DataModule; interface uses Windows, SysUtils, Classes, DB, ADODB, Dialogs; type Tdm = class(TDataModule) ADOConnection: TADOConnection; private { Private declarations } function getConnection: String; public { Public declarations } function getModuleInfo: TDataSet; function UpdateModuleInfo(AModuleInfo: String): boolean; function getSQLObj(ASQL: String; ACanOpen: boolean = true): TDataSet; function ApplySQL(ASQL: String): boolean; overload; function ApplySQL(ADataset: TDataSet): boolean; overload; end; var dm: Tdm; implementation uses Registry, uParamFunctions, uEncryptFunctions, uOperationSystem; {$R *.dfm} { Tdm } function Tdm.ApplySQL(ASQL: String): boolean; var qryADO: TADOQuery; begin result := false; try ADOConnection.Close; ADOConnection.ConnectionString := getConnection; qryAdo := TADOQuery.Create(nil); qryAdo.Connection := ADOConnection; try qryAdo.ExecSQL; result := true; except // end; finally freeAndNil(qryAdo); end; end; function Tdm.ApplySQL(ADataset: TDataSet): boolean; begin try ( ADataSet as TADOQuery ).ExecSQL; result := true; except result := false; end; end; function Tdm.getConnection: String; var Reg : TRegistry; buildInfo: String; sResult, sServer, sDBAlias, sUser, sPW : String; begin try //Pega as info local Reg := TRegistry.Create; if ( getOS(buildInfo) = osW7 ) then Reg.RootKey := HKEY_CURRENT_USER else Reg.RootKey := HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\AppleNet', True); sResult := DecodeServerInfo(Reg.ReadString('ServerInfo'), 'Server', CIPHER_TEXT_STEALING, FMT_UU); sServer := ParseParam(sResult, '#SRV#='); sDBAlias := ParseParam(sResult, '#DB#='); sUser := ParseParam(sResult, '#USER#='); sPW := ParseParam(sResult, '#PW#='); result := SetConnectionStr(sUser, sPw, SDBAlias, sServer); //Fechar o Registry Reg.CloseKey; Reg.Free; except ShowMessage('Connection Error !'); Abort; end; end; function Tdm.getModuleInfo: TDataSet; var sql: String; begin sql := 'Select ModuleInfo from Sys_Module'; result := getSQLObj(Sql); end; function Tdm.getSQLObj(ASQL: String; ACanOpen: boolean): TDataSet; var qryAdo: TADOQuery; begin try qryAdo := TADOQuery.Create(nil); ADOConnection.Close; ADOConnection.ConnectionString := getConnection; qryAdo.Connection := ADOConnection; qryAdo.SQL.Text := ASql; try if ( ACanOpen ) then qryAdo.Open; result := qryADO; except freeAndNil(qryAdo); end; finally // freeAndNil(qryAdo); end; end; function Tdm.UpdateModuleInfo(AModuleInfo: String): boolean; var sql: String; ds: TDataSet; begin sql := 'Update Sys_Module set ModuleInfo = :moduleinfo'; ds := getSQLObj(sql, false); ( ds as TADOQuery ).Parameters.ParamByName('moduleinfo').Value := AModuleInfo; result := ApplySQL(ds); end; end.
unit FreeOTFEExplorerCheckFilesystem; interface uses SDFilesystem_FAT; procedure CheckFilesystem(Filesystem: TSDFilesystem_FAT); implementation uses Dialogs, Forms, lcDialogs, SDUGeneral, SDUi18n; {$IFDEF _NEVER_DEFINED} // This is just a dummy const to fool dxGetText when extracting message // information // This const is never used; it's #ifdef'd out - SDUCRLF in the code refers to // picks up SDUGeneral.SDUCRLF const SDUCRLF = ''#13#10; {$ENDIF} procedure CheckFilesystem(Filesystem: TSDFilesystem_FAT); var allOK: Boolean; begin //SetStatusMsg(_('Checking filesystem...')); try allOK := Filesystem.CheckFilesystem(); finally //SetStatusMsg(''); end; if allOK then begin SDUMessageDlg(_('Filesystem OK'), mtInformation); end else begin Filesystem.ReadOnly := True; SDUMessageDlg( SDUParamSubstitute(_('Filesystem errors detected.' + SDUCRLF + SDUCRLF + 'Please mount as a normal drive, and run chkdsk to correct.' + SDUCRLF + '%1 will continue in readonly mode'), [Application.Title]), mtError ); end; end; end.
unit Solutions; {$mode tp} {$H+} interface uses SysUtils; function LargestPalindromeProduct: Int64; function LargestPrimeFactor(number: Int64): Int64; function EvenFibonacciNumbers: Int64; function MultiplesOf3And5: Int64; implementation {[Largest palindrome product](https://projecteuler.net/problem=4)} function LargestPalindromeProduct: Int64; begin {TODO: Implement the LargestPalindromeProduct method } WriteLn('TODO: Implement the LargestPalindromeProduct method'); end; {(Largest prime factor)[https://projecteuler.net/problem=3]} function LargestPrimeFactor(number: Int64): Int64; begin {TODO: Implement the LargestPrimeFactor method} WriteLn('TODO: Implement the LargestPrimeFactor method'); end; {(Even Fibonacci numbers)[https://projecteuler.net/problem=2]} function EvenFibonacciNumbers: Int64; var fibPrev, fibCurr, sum: Int64; cap: Int64; begin fibPrev := 1; fibCurr := 2; sum := 0; cap := 4000000; While fibCurr < cap do begin If (fibCurr mod 2 = 0) then sum := sum + fibCurr; fibCurr := fibCurr + fibPrev; fibPrev := fibCurr - fibPrev; end; WriteLn('Even Fibonacci Numbers - ', sum); EvenFibonacciNumbers := sum; WriteLn('TODO: Implement the EvenFibonacciNumbers method'); end; {(Multiples of 3 and 5)[https://projecteuler.net/problem=1]} function MultiplesOf3And5: Int64; var i, sum: Int64; begin sum := 0; i := 0; While i <= 999 do begin If (i mod 3 = 0) or (i mod 5 = 0) then sum := sum + i; i := i + 1; end; WriteLn('Multiples Of 3 And 5 - ', sum); MultiplesOf3And5 := sum; end; end.
{ *********************************************************************** } { } { GUI Hangman } { Version 1.0 - First release of program } { Last Revised: 27nd of July 2004 } { Copyright (c) 2004 Chris Alley } { } { *********************************************************************** } unit USplashScreen; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, Jpeg; type TSplashScreen = class(TForm) SplashScreenImage: TImage; procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; implementation {$R *.dfm} procedure TSplashScreen.FormCreate(Sender: TObject); { Loads the splash screen's image from file. } begin Self.SplashScreenImage.Picture.LoadFromFile('Images/SplashScreen.jpg'); end; end.
unit UnifiedUpdater; interface uses SysUtils, Windows, Classes, DB, ADODB, ComObj, FormLoader; type TUpdateLoader = class private shortExeName, fullExeName: TFileName; currDir: TFileName; fileDescName: TFileName; fileVersion: String; fileProductName: String; frmVisualizer: TfrmLoader; qwrCommand: TAdoQuery; /// Обновляет содержимое окна визуализации процесса загрузки procedure ProcessMessages(wnd: HWND = 0); /// Получает имя исполняемого файла запущенной программы, инициализирует поле /// fullExeName значением полного имени исполняемого файла /// а также устанавливает в поле shortExeName только имя файла без пути function GetFileName(): TFileName; /// Считывает из информации о файле значения ProductName, OriginalFilename /// и ProductVersion и записывает эти значения в поля fileProductName, /// fileDescName и fileVersion function GetFileInfo(): Boolean; /// По замыслу эта функция должна вызываться после всех обновлений /// перед запуском программы для возможности выполнения дополнительных /// действий function DoAdditionalJobs(): Boolean; /// Проверяет версию запущенного исполняемого файла программы (по номеру версии) /// и в случае необходимости загружает и заменяет необходимый файл /// Возвращает False если произошло обновление и необходим перезапуск программы /// (завершение запущенной копии) или если при обновлении произошла ошибка и /// нужно завершение программы /// Возвращает True если версия не нуждается в обновлении и необходимо /// продолжить запуск программы function CheckMainFileVersion(): Boolean; /// Проверяет версии остальных файлов имеющих в базе данных ненулловое поле /// версии, установленный флаг MainVersion и поле FileName отличное от /// OriginalFilename из информации о файле /// (пока функция не реализована) function CheckOtherProgramFiles(): Boolean; /// Проверяет по дате модификации файлы с полем File_Version равным null и в /// случае необходимости скачивает и заменяет их function CheckOtherStuffFiles(): Boolean; /// Устанавливает ProgressBar на окне визуализации загрузчика в положение Pos /// (от 0 до 100), выводит в Label значение Caption, в случае, если IsWarning /// установлено в True цвет текста Label - красный, и производит задержку в /// Delay миллисекунд procedure ShowProgressCaption(Pos: Integer; Caption: string; Delay: Integer; IsWarning: Boolean = false); protected /// По двум строковым значениям версии локального файла и версии файла в БД /// определяет необходимость обновления локального файла /// Возвращает True если обновление необходимо class function NeedUpdate(ExeVersion, DbVersion: String): Boolean; overload;static; /// Проверяет необходимость обновления файла по значению даты последней /// модификации, возвращает True если обновление необходимо class function NeedUpdate(FileName: string; DBDate: TDateTime): Boolean;overload;static; public /// Функция вызывается при старте приложения и выполняет необходимые действия /// по обновлению. /// Возвращаемые результаты: /// True - необходимо продолжить запуск программы /// False - необходимо завершить программу function InitApplication(): Boolean; /// Функция по имени файла проверяет в БД по дате последнего изменения /// необходимость обновления файла и в случае необходимости заменяет /// файл на новый. Возвращает True в случае успешного обновления и False /// в случае ошибок. Также в некоторых случаях функция выдаёт Exception /// поэтому для выявления ошибок можно использовать try ... except class function CheckFileUpdate(FileName: String): Boolean;static; constructor Create(); destructor Destroy(); end; implementation uses Graphics, ShellAPI, Variants; const conn_str = 'Provider=SQLOLEDB.1;Password=UpdateAdmin;Persist Security Info=True;User ID=UpdateAdmin;Initial Catalog=ProgramUpdate;Data Source=192.168.75.100;OLE DB Services=0'; sql_select_project = 'select ' + ' * ' + 'from ' + ' ProgramUpdate.dbo.GetFileUpdateList(:prmProjectName) ' + 'order by ' + ' DownloadPriority '; sql_select_all_other_files = 'select ' + ' * ' + 'from ' + ' ProgramUpdate.dbo.GetOtherFileUpdateListFull(:prmProjectName) ' + 'order by ' + ' DownloadPriority '; var mProgramDir: String; // Глобальные переменные для функций mProjectName: String; // отвязанных от класса { TUpdateLoader } /// Функция ищет в записях, возвращённых запросом запись с именем файла, /// соответствующим параметру OriginalFilename информации о файле class function TUpdateLoader.CheckFileUpdate(FileName: String): Boolean; var qwrCommandLocal: TAdoQuery; recordFound: Boolean; begin Result := False; // Проверка имени проекта if mProjectName = '' then begin raise Exception.Create('Не инициализирована глобальная переменная имени проекта, для инициализации необходимо хотя бы один раз создать объект класса TUpdateLoader'); Exit; end; try qwrCommandLocal := TAdoQuery.Create(nil); except raise Exception.Create('Проблемы с вызовом функции CoInitialize, возможно её следует вызвать для конкретного потока'); Exit; end; qwrCommandLocal.ConnectionString := conn_str; qwrCommandLocal.SQL.Text := sql_select_all_other_files; qwrCommandLocal.ParamCheck := True; qwrCommandLocal.Parameters.ParseSQL(qwrCommandLocal.SQL.Text,True); try qwrCommandLocal.Parameters.ParamByName('prmProjectName').Value := mProjectName; qwrCommandLocal.Open; except raise Exception.Create('Невозможно выполнить запрос в функции TUpdateLoader.CheckFileUpdate'); Exit; end; if qwrCommandLocal.RecordCount = 0 then begin Exit; end; qwrCommandLocal.First; recordFound := False; while (not qwrCommandLocal.Eof) and (not recordFound) do begin if (qwrCommandLocal.FieldByName('File_Name').AsString = FileName)and (qwrCommandLocal.FieldByName('FType').AsInteger = 1) then begin recordFound := True; if NeedUpdate(FileName,qwrCommandLocal.FieldByName('File_Date').AsDateTime) then begin /// Пиши обновление файла try TBlobField(qwrCommandLocal.FieldByName('File_Data')).SaveToFile(mProgramDir+FileName+'.new'); RenameFile(mProgramDir + FileName,mProgramDir + FileName + '.old'); MoveFile(PChar(mProgramDir + FileName + '.new'),PChar(mProgramDir + FileName)); except Exit; end; end; end; qwrCommandLocal.Next; end; if recordFound then Result := True; end; function TUpdateLoader.CheckMainFileVersion: Boolean; const B_CONTINUE = 0; B_ABORT = 1; B_NORMAL = 2; function CheckParamsExists(): Byte; begin Result := B_NORMAL; if fileDescName = '' then begin if MessageBox(0, 'Не задан параметр "OriginalFilename" в информации о файле, работа модуля обновления без данного параметра невозможна, продолжить загрузку без обновления программы?', 'Warning!', MB_YESNO or MB_ICONWARNING) = ID_NO then begin Result := B_ABORT; end else begin Result := B_CONTINUE; end; Exit; end; if fileProductName = '' then begin if MessageBox(0, 'Не задан параметр "ProductName" в информации о файле, работа модуля обновления без данного параметра невозможна, продолжить загрузку без обновления программы?', 'Warning!', MB_YESNO or MB_ICONWARNING) = ID_NO then begin Result := B_ABORT; end else begin Result := B_CONTINUE; end; Exit; end; if fileVersion = '' then begin if MessageBox(0, 'Не задан параметр "FileVersion" в информации о файле, работа модуля обновления без данного параметра невозможна, продолжить загрузку без обновления программы?', 'Warning!', MB_YESNO or MB_ICONWARNING) = ID_NO then begin Result := B_ABORT; end else begin Result := B_CONTINUE; end; Exit; end; end; var paramsExists: Byte; bRecordFound: Boolean; begin Result := false; paramsExists := CheckParamsExists(); if (paramsExists <> B_NORMAL) then begin if (paramsExists = B_CONTINUE) then Result := True; Exit; end; try qwrCommand.ParamCheck := True; qwrCommand.Parameters.ParseSQL(qwrCommand.SQL.Text, True); qwrCommand.Parameters.ParamByName('prmProjectName').Value := fileProductName; except ShowProgressCaption(100, 'Невозможно задать параметр для запроса (отладочная ошибка)', 5000, True); Exit; end; if (not qwrCommand.Active) then begin try qwrCommand.Open(); except // невозможно подключиться к БД // Нужно бы вывести это сообщение на форму ShowProgressCaption(100, 'Невозможно подключиться к БД для обновления, приложение будет закрыто' , 2000, True); Exit; end; end; qwrCommand.First; bRecordFound := false; while (not qwrCommand.Eof) and (not bRecordFound) do begin if (qwrCommand.FieldByName('File_Name').AsString = fileDescName) and (qwrCommand.FieldByName('FType').AsInteger = 0) then begin bRecordFound := True; Break; end; qwrCommand.Next; end; if (not bRecordFound) then begin if MessageBox(0, 'В базе данных не найден соответствующий файл обновления, запустить текущую версию программы?', 'Warning!!', MB_YESNO or MB_ICONWARNING) = ID_YES then begin Result := True; end; Exit; end; ShowProgressCaption(10, 'Проверка наличия обновлений', 150); if FileExists(fullExeName + '.old') then begin // Удаляем лишний файл обновления DeleteFile(PChar(fullExeName + '.old')); end; if (NeedUpdate(fileVersion, qwrCommand.FieldByName('File_Version').AsString)) then begin // Пытаемся обновиться ShowProgressCaption(25, 'Обновление найдено, скачиваем', 150); try TBlobField(qwrCommand.FieldByName('File_Data')).SaveToFile (fullExeName + '.new'); except // не удалось сохранить или скачать файл из БД if (MessageBox(0, 'Не удалось скачать файл обновления, продолжить работу со старой версией?' , 'Warning!!', MB_YESNO or MB_ICONWARNING) = ID_YES) then begin Result := True; end; Exit; end; try ShowProgressCaption(50, 'Обновляем исполняемый файл', 150); RenameFile(fullExeName, fullExeName + '.old'); MoveFile(PChar(fullExeName + '.new'), PChar(fullExeName)); except // Невозможно заменить файло ShowProgressCaption(100, 'Невозможно заменить файло на обновлённый, программа будет закрыта', 2000, True); Exit; end; ShowProgressCaption(100, 'Перезапускаем программу', 150); ShellExecute(0, 'open', PChar(fullExeName), nil, nil, SW_SHOWNORMAL); end else begin ShowProgressCaption(25, 'Обновление исполняемого файла не требуется', 150); Result := True; end; end; function TUpdateLoader.CheckOtherProgramFiles: Boolean; begin Result := True; end; function TUpdateLoader.CheckOtherStuffFiles: Boolean; const B_CONTINUE = 0; B_NORMAL = 2; function CheckParamsExists(): Byte; begin Result := B_NORMAL; if fileDescName = '' then begin Result := B_CONTINUE; Exit; end; if fileProductName = '' then begin Result := B_CONTINUE; Exit; end; if fileVersion = '' then begin Result := B_CONTINUE; Exit; end; end; begin Result := True; // По умолчанию программа возвращает положительный результат, так как // проверку остальных файлов я считаю не важной if CheckParamsExists()<> B_NORMAL then Exit; try if qwrCommand.Parameters.ParamByName('prmProjectName').Value = Null() then begin // Не заданы параметры запроса, значит проблемы qwrCommand.Parameters.ParamByName('prmProjectName').Value := fileProductName; end; except // Не созданы объекты параметров или другая проблема ShowProgressCaption(50,'Невозможно скачать из базы дополнительные файлы',1000,True); Exit; end; if (not qwrCommand.Active) then begin try qwrCommand.Open(); except // невозможно подключиться к БД // ???????? ShowProgressCaption(100,'Невозможно подключиться к БД для обновления дополнительных файлов', 2000, True); Exit; end; end; qwrCommand.First; while (not qwrCommand.Eof) do begin if (qwrCommand.FieldByName('FType').AsInteger = 1) then begin if (NeedUpdate(qwrCommand.FieldByName('File_Name').AsString,qwrCommand.FieldByName('File_Date').AsDateTime)) then begin // Обновление нужно try TBlobField(qwrCommand.FieldByName('File_Data')).SaveToFile(currDir+qwrCommand.FieldByName('File_Name').AsString+'.new'); RenameFile(currDir + qwrCommand.FieldByName('File_Name').AsString,currDir + qwrCommand.FieldByName('File_Name').AsString+'.old'); MoveFile(PChar(currDir + qwrCommand.FieldByName('File_Name').AsString+'.new'),PChar(currDir + qwrCommand.FieldByName('File_Name').AsString)); except // Ощибка при скачивании или переименовани файла Result := False; end; end; end; qwrCommand.Next; end; end; constructor TUpdateLoader.Create; begin inherited Create(); frmVisualizer := TfrmLoader.Create(nil); frmVisualizer.Show; ProcessMessages(); qwrCommand := TAdoQuery.Create(nil); qwrCommand.ConnectionString := conn_str; qwrCommand.SQL.Text := sql_select_project; GetFileName(); GetFileInfo(); end; destructor TUpdateLoader.Destroy; begin qwrCommand.Close; qwrCommand.Free; frmVisualizer.Free; inherited Destroy(); end; function TUpdateLoader.DoAdditionalJobs: Boolean; begin Result := True; end; function TUpdateLoader.GetFileInfo: Boolean; var exeName: array [0 .. 255] of WideChar; dwSize, dwReserved1: DWORD; pBuffer, pDtLang: PWord; strLang: String; pFileDescString: PChar; begin if fullExeName = '' then GetFileName(); Result := false; StrCopy(@exeName, PWideChar(fullExeName)); dwSize := GetFileVersionInfoSize(@exeName, dwReserved1); if dwSize = 0 then begin raise Exception.Create('Could not retreive info size for file'); Exit; end; try GetMem(pBuffer, dwSize); GetFileVersionInfo(@exeName, 0, dwSize, pBuffer); VerQueryValue(pBuffer, '\VarFileInfo\Translation', Pointer(pDtLang), dwReserved1); strLang := IntToHex(pDtLang^, 4); Inc(pDtLang, 1); strLang := strLang + IntToHex(pDtLang^, 4); VerQueryValue(pBuffer, PChar('\StringFileInfo\' + strLang + '\OriginalFilename'), Pointer(pFileDescString), dwReserved1); SetString(fileDescName, pFileDescString, Length(pFileDescString)); VerQueryValue(pBuffer, PChar('\StringFileInfo\' + strLang + '\ProductName'), Pointer(pFileDescString), dwReserved1); SetString(fileProductName, pFileDescString, Length(pFileDescString)); VerQueryValue(pBuffer, PChar('\StringFileInfo\' + strLang + '\FileVersion'), Pointer(pFileDescString), dwReserved1); SetString(fileVersion, pFileDescString, Length(pFileDescString)); mProjectName := fileProductName; Result := True; finally FreeMem(pBuffer, dwSize); end; end; function TUpdateLoader.GetFileName: TFileName; var buff: array [0 .. 254] of WideChar; lng: Integer; begin lng := GetModuleFileName(0, @buff, 255); if lng <= 0 then begin raise Exception.Create('Could not retreive file executable name'); Exit; end; SetString(fullExeName, PWideChar(@buff), lng); shortExeName := ExtractFileName(fullExeName); currDir := ExtractFilePath(fullExeName); mProgramDir := currDir; Result := fullExeName; end; function TUpdateLoader.InitApplication: Boolean; var mainFileCheck, otherProgFilesCheck: Boolean; begin Result := false; // Если результат функции True то программа инициализируется и стартует // а если False то завершается (в случае удачного обновления с перезапуском) try mainFileCheck := CheckMainFileVersion(); otherProgFilesCheck := CheckOtherProgramFiles(); if not (mainFileCheck and otherProgFilesCheck) then begin // Необходимо завершить программу по причине обновления или // неудачи в процессе обновления с решением пользователя не продолжать запуск // или в связи с невозможностью запуска Exit; end; except // Произошёл эксепшен в функциях поиска обновлений, вывести пользователю информацию end; Result := True; if not CheckOtherStuffFiles() then begin // Не удалось загрузить дополнительные файлы // Можно уведомить пользователя но нужно продолжить запуск программы end; ShowProgressCaption(100, 'Старт программы', 500); frmVisualizer.Free; end; class function TUpdateLoader.NeedUpdate(FileName: string; DBDate: TDateTime): Boolean; begin Result := False; FileName := mProgramDir + FileName; if (not FileExists(FileName)) then begin // такого файла не существует, нужно кочать Result := True; Exit; end else begin if FileDateToDateTime(FileAge(FileName)) < DBDate then begin Result := True; end; end; end; class function TUpdateLoader.NeedUpdate(ExeVersion, DbVersion: String): Boolean; var verListOld, verListNew: TStringList; verOld, verNew: DWORD; i: Integer; bContinue: Boolean; begin Result := false; verListOld := TStringList.Create; verListNew := TStringList.Create; verListOld.Delimiter := '.'; verListNew.Delimiter := '.'; verListOld.DelimitedText := ExeVersion; verListNew.DelimitedText := DbVersion; if verListOld.Count <> verListNew.Count then begin raise Exception.Create('Неправильный формат строки версии программы'); Exit; end; i := 0; bContinue := True; while bContinue and (i < verListOld.Count) do begin verOld := StrToInt(verListOld.Strings[i]); verNew := StrToInt(verListNew.Strings[i]); i := i + 1; if verNew <> verOld then begin if verNew > verOld then Result := True; bContinue := false; end; end; verListOld.Free; verListNew.Free; end; procedure TUpdateLoader.ProcessMessages(wnd: HWND = 0); var msg: TMsg; begin if wnd = 0 then wnd := frmVisualizer.Handle; while PeekMessage(msg, wnd, 0, 0, PM_REMOVE) do begin TranslateMessage(msg); DispatchMessage(msg); end; end; procedure TUpdateLoader.ShowProgressCaption(Pos: Integer; Caption: string; Delay: Integer; IsWarning: Boolean = false); begin frmVisualizer.pbProgress.Position := Pos; frmVisualizer.lblStasusMessage.Caption := Caption; if IsWarning then begin frmVisualizer.lblStasusMessage.Font.Color := clRed; end else begin frmVisualizer.lblStasusMessage.Font.Color := clBlack; end; ProcessMessages(); Sleep(Delay); end; initialization CoInitializeEx(nil, 0); mProgramDir := GetCurrentDir(); end.
unit Forms.Main; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AdvMemo, Vcl.StdCtrls; const DEMO_TITLE = 'FNC Core Utils - MulDiv demo'; DEMO_BUTTON = 'Execute'; type TFrmMain = class(TForm) btnExecute: TButton; txtLog: TAdvMemo; procedure btnExecuteClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } procedure DoExecute; public { Public declarations } end; var FrmMain: TFrmMain; implementation {$R *.dfm} uses System.JSON, TMSFNCUtils; procedure TFrmMain.btnExecuteClick(Sender: TObject); begin DoExecute; end; procedure TFrmMain.DoExecute; begin txtLog.Lines.Add( TTMSFNCUtils.MulDivInt( 4, 1, 2 ).ToString ); txtLog.Lines.Add( TTMSFNCUtils.MulDivSingle( 4.2, 1.1, 2.2 ).ToString ) end; procedure TFrmMain.FormCreate(Sender: TObject); begin btnExecute.Caption := DEMO_BUTTON; self.Caption := DEMO_TITLE; txtLog.Lines.Clear; end; end.
unit Objekt.DHLNativeAdress; interface uses SysUtils, Classes, geschaeftskundenversand_api_2, Objekt.DHLOrigin; type TDHLNativeAdress = class private fAdressAdditionArray: Array_Of_addressAddition; fNativeAdressTypeAPI: NativeAddressType; fStreetName: string; fStreetNumber: string; fDispatchingInformation: string; fZip: string; fCity: string; fAddressAddition: string; fDHLOrigin: TDHLOrigin; procedure setStreetName(const Value: string); procedure setStreetNumber(const Value: string); procedure setDispatchingInformation(const Value: string); procedure setZip(const Value: string); procedure setCity(const Value: string); procedure setAddressAddition(const Value: string); public constructor Create; destructor Destroy; override; function NativeAdressTypeAPI: NativeAddressType; property StreetName: string read fStreetName write setStreetName; property StreetNumber: string read fStreetNumber write setStreetNumber; property DispatchingInformation: string read fDispatchingInformation write setDispatchingInformation; property Zip: string read fZip write setZip; property City: string read fCity write setCity; property AddressAddition: string read fAddressAddition write setAddressAddition; property Origin: TDHLOrigin read fDHLOrigin write fDHLOrigin; procedure Copy(aNativeAdress: TDHLNativeAdress); end; implementation { TDHLNativeAdress } constructor TDHLNativeAdress.Create; begin fDHLOrigin := TDHLOrigin.Create; fNativeAdressTypeAPI := NativeAddressType.Create; SetLength(fAdressAdditionArray, 1); fNativeAdressTypeAPI.addressAddition := fAdressAdditionArray; fNativeAdressTypeAPI.Origin := fDHLOrigin.OriginAPI; end; destructor TDHLNativeAdress.Destroy; begin FreeAndNil(fDHLOrigin); //FreeAndNil(fNativeAdressTypeAPI); inherited; end; function TDHLNativeAdress.NativeAdressTypeAPI: NativeAddressType; begin Result := fNativeAdressTypeAPI; end; procedure TDHLNativeAdress.setAddressAddition(const Value: string); begin fAddressAddition := Value; fAdressAdditionArray[0] := Value; end; procedure TDHLNativeAdress.setCity(const Value: string); begin fCity := Value; fNativeAdressTypeAPI.city := Value; end; procedure TDHLNativeAdress.setDispatchingInformation(const Value: string); begin fDispatchingInformation := Value; fNativeAdressTypeAPI.dispatchingInformation := Value; end; procedure TDHLNativeAdress.setStreetName(const Value: string); begin fStreetName := Value; NativeAdressTypeAPI.streetName := Value; end; procedure TDHLNativeAdress.setStreetNumber(const Value: string); begin fStreetNumber := Value; fNativeAdressTypeAPI.streetNumber := Value; end; procedure TDHLNativeAdress.setZip(const Value: string); begin fZip := Value; fNativeAdressTypeAPI.zip := Value; end; procedure TDHLNativeAdress.Copy(aNativeAdress: TDHLNativeAdress); begin setStreetName(aNativeAdress.StreetName); setStreetNumber(aNativeAdress.StreetNumber); setZip(aNativeAdress.Zip); setCity(aNativeAdress.City); setDispatchingInformation(aNativeAdress.DispatchingInformation); setAddressAddition(aNativeAdress.AddressAddition); fDHLOrigin.copy(aNativeAdress.Origin); 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. //--------------------------------------------------------------------------- namespace DelphiPrismWebApp; interface uses System.Collections; type TApplicationCounter = class(TCounter) private FCount, FCountUserOn : Int32; FLastVisit: DateTime; FPages: Hashtable; method GetCount: Int32; public constructor Create; property Count : Int32 read FCount;reintroduce; property CountUserOn : Int32 read FCountUserOn; property LastVisit : DateTime read FLastVisit; method Inc;reintroduce; property Pages : Hashtable read FPages; procedure IncPages( Key : String ); procedure LoginUser; procedure LogoffUser; end; implementation constructor TApplicationCounter.Create; begin inherited Create; // TODO: Add any constructor code here FPages := Hashtable.Create; end; METHOD TApplicationCounter.Inc; begin FCount := FCount + 1; FLastVisit := DateTime.Now; end; procedure TApplicationCounter.IncPages(Key: String); begin if not FPages.ContainsKey(Key) then FPages.Add(Key, Int32(1)) else FPages.Item[Key] := Int32(FPages.Item[Key]) + 1; end; procedure TApplicationCounter.LoginUser; begin FCountUserOn := FCountUserOn + 1; end; procedure TApplicationCounter.LogoffUser; begin FCountUserOn := FCountUserOn - 1; if FCountUserOn < 0 then FCountUserOn := 0; end; method TApplicationCounter.GetCount: Int32; begin result := FCount; end; end.
unit Unit17; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdExplicitTLSClientServerBase, IdFTP, o_zpl, Vcl.ExtCtrls; type TForm17 = class(TForm) Memo1: TMemo; IdFTP1: TIdFTP; Panel1: TPanel; Button1: TButton; btn_Drucken_Stream: TButton; Button2: TButton; Button3: TButton; procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure btn_Drucken_StreamClick(Sender: TObject); procedure Button3Click(Sender: TObject); private procedure Print2Streams; procedure Drucken(aStream: TMemoryStream); public { Public-Deklarationen } end; var Form17: TForm17; implementation {$R *.dfm} uses o_BinConverter; procedure TForm17.FormCreate(Sender: TObject); begin Memo1.Clear; Memo1.Lines.Add('~WC'); { ^XA ^F050,50 ^A0N,50,50 ^FDHello World^FS ^XS } end; procedure TForm17.Print2Streams; var m1, m2, m3: TMemoryStream; begin m1 := TMemoryStream.Create; m2 := TMemoryStream.Create; m3 := TMemoryStream.Create; try Memo1.Clear; Memo1.Lines.Add('^XA'); Memo1.Lines.Add('^FO50,50^ADN,36,20^FDThomas'); Memo1.Lines.SaveToStream(m1); m1.Position := 0; Memo1.Clear; Memo1.Lines.Add('^FS'); Memo1.Lines.Add('^XZ'); Memo1.Lines.SaveToStream(m2); m2.Position := 0; m1.SaveToStream(m3); m2.SaveToStream(m3); Drucken(m3); finally FreeAndNil(m1); FreeAndNil(m2); FreeAndNil(m3); end; end; procedure TForm17.btn_Drucken_StreamClick(Sender: TObject); var m: TMemoryStream; ZPL: TZPL; begin // Print2Streams; // exit; ZPL := TZPL.Create(Self); m := TMemoryStream.Create; try Memo1.Lines.SaveToStream(m); ZPL.print('192.168.208.54', m); finally FreeAndNil(m); FreeAndNil(ZPL); end; end; procedure TForm17.Button1Click(Sender: TObject); var ZPL: TZPL; begin ZPL := TZPL.Create(Self); try ZPL.print('192.168.208.54', Memo1.Lines.Text) finally FreeAndNil(ZPL); end; end; procedure TForm17.Button2Click(Sender: TObject); var m: TMemoryStream; PrintStream: TMemoryStream; s: string; a: AnsiString; begin m := TMemoryStream.Create; PrintStream := TMemoryStream.Create; try m.LoadFromFile('d:\ZPL\KN-Signet-schwarz.bmp'); m.Position := 0; s := '^XA' + '^FO100,100^GFB,' + IntToStr(m.Size)+',' + IntToStr(151811)+',' + IntToStr(19458)+','; // + Memo1.Text; { s := '^XA' + '^FO100,100^GFA,' + IntToStr(trunc(length(Memo1.Text)/2))+',' + IntToStr(trunc(length(Memo1.Text)/2))+',' + IntToStr(80)+',' + Memo1.Text; } Memo1.Clear; Memo1.Lines.Text := s; Memo1.Lines.SaveToStream(PrintStream); m.SaveToStream(PrintStream); Memo1.Clear; Memo1.Lines.Add('^XZ'); Memo1.Lines.SaveToStream(PrintStream); Drucken(PrintStream); finally FreeAndNil(m); FreeAndNil(PrintStream); end; end; procedure TForm17.Drucken(aStream: TMemoryStream); var ZPL: TZPL; begin ZPL := TZPL.Create(Self); try ZPL.print('172.16.10.210', aStream); finally FreeAndNil(ZPL); end; end; procedure TForm17.Button3Click(Sender: TObject); begin Memo1.Lines.Text := BinFileToHexString('d:\ZPL\T.bmp'); HexStringToFile(Memo1.Lines.Text, 'd:\zpl\Test3.bmp'); end; end.
// ************************************************************************ // // The types declared in this file were generated from data read from the // WSDL File described below: // WSDL : http://srv-s4-asq.pdm.local:8000/sap/bc/srt/wsdl/flv_10002A111AD1/bndg_url/sap/bc/srt/rfc/sap/zmm_ws_goodsmvt_create_solo/400/zmm_ws_goodsmvt_create_solo/zmm_ws_goodsmvt_create_solo?sap-client=400 // Encoding : utf-8 // Codegen : [wfDebug,wfAmbiguousComplexTypesAsArray,wfUseSerializerClassForAttrs] // Version : 1.0 // (02/05/2019 02:36:34 a.m. - 1.33.2.5) // ************************************************************************ // unit zmm_ws_goodsmvt_create_solo1; interface uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns; type // ************************************************************************ // // The following types, referred to in the WSDL document are not being represented // in this file. They are either aliases[@] of other types represented or were referred // to but never[!] declared in the document. The types from the latter category // typically map to predefined/known XML or Borland types; however, they could also // indicate incorrect WSDL documents that failed to declare or import a schema type. // ************************************************************************ // // !:string - "http://www.w3.org/2001/XMLSchema" // !:decimal - "http://www.w3.org/2001/XMLSchema" // !:int - "http://www.w3.org/2001/XMLSchema" BAPI2017_GM_HEAD_01 = class; { "urn:sap-com:document:sap:rfc:functions" } BAPI2017_GM_ITEM_CREATE = class; { "urn:sap-com:document:sap:rfc:functions" } BAPIRET2 = class; { "urn:sap-com:document:sap:rfc:functions" } char1 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } char10 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } char12 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } char14 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } char15 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } char16 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } char18 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } char2 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } char20 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } char220 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } char24 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } char25 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } char3 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } char30 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } char32 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } char35 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } char4 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } char40 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } char50 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } char6 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } char8 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } date10 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } decimal23_4 = TXSDecimal; { "urn:sap-com:document:sap:rfc:functions" } decimal3_0 = TXSDecimal; { "urn:sap-com:document:sap:rfc:functions" } numeric10 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } numeric2 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } numeric3 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } numeric4 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } numeric5 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } numeric6 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } quantum13_3 = TXSDecimal; { "urn:sap-com:document:sap:rfc:functions" } unit3 = type WideString; { "urn:sap-com:document:sap:rfc:functions" } // ************************************************************************ // // Namespace : urn:sap-com:document:sap:rfc:functions // ************************************************************************ // BAPI2017_GM_HEAD_01 = class(TRemotable) private FPSTNG_DATE: date10; FDOC_DATE: date10; FREF_DOC_NO: char16; FBILL_OF_LADING: char16; FGR_GI_SLIP_NO: char10; FPR_UNAME: char12; FHEADER_TXT: char25; FVER_GR_GI_SLIP: char1; FVER_GR_GI_SLIPX: char1; FEXT_WMS: char1; FREF_DOC_NO_LONG: char35; FBILL_OF_LADING_LONG: char35; FBAR_CODE: char40; published property PSTNG_DATE: date10 read FPSTNG_DATE write FPSTNG_DATE; property DOC_DATE: date10 read FDOC_DATE write FDOC_DATE; property REF_DOC_NO: char16 read FREF_DOC_NO write FREF_DOC_NO; property BILL_OF_LADING: char16 read FBILL_OF_LADING write FBILL_OF_LADING; property GR_GI_SLIP_NO: char10 read FGR_GI_SLIP_NO write FGR_GI_SLIP_NO; property PR_UNAME: char12 read FPR_UNAME write FPR_UNAME; property HEADER_TXT: char25 read FHEADER_TXT write FHEADER_TXT; property VER_GR_GI_SLIP: char1 read FVER_GR_GI_SLIP write FVER_GR_GI_SLIP; property VER_GR_GI_SLIPX: char1 read FVER_GR_GI_SLIPX write FVER_GR_GI_SLIPX; property EXT_WMS: char1 read FEXT_WMS write FEXT_WMS; property REF_DOC_NO_LONG: char35 read FREF_DOC_NO_LONG write FREF_DOC_NO_LONG; property BILL_OF_LADING_LONG: char35 read FBILL_OF_LADING_LONG write FBILL_OF_LADING_LONG; property BAR_CODE: char40 read FBAR_CODE write FBAR_CODE; end; // ************************************************************************ // // Namespace : urn:sap-com:document:sap:rfc:functions // ************************************************************************ // BAPI2017_GM_ITEM_CREATE = class(TRemotable) private FMATERIAL: char18; FPLANT: char4; FSTGE_LOC: char4; FBATCH: char10; FMOVE_TYPE: char3; FSTCK_TYPE: char1; FSPEC_STOCK: char1; FVENDOR: char10; FCUSTOMER: char10; FSALES_ORD: char10; FS_ORD_ITEM: numeric6; FSCHED_LINE: numeric4; FVAL_TYPE: char10; FENTRY_QNT: quantum13_3; FENTRY_UOM: unit3; FENTRY_UOM_ISO: char3; FPO_PR_QNT: quantum13_3; FORDERPR_UN: unit3; FORDERPR_UN_ISO: char3; FPO_NUMBER: char10; FPO_ITEM: numeric5; FSHIPPING: char2; FCOMP_SHIP: char2; FNO_MORE_GR: char1; FITEM_TEXT: char50; FGR_RCPT: char12; FUNLOAD_PT: char25; FCOSTCENTER: char10; FORDERID: char12; FORDER_ITNO: numeric4; FCALC_MOTIVE: char2; FASSET_NO: char12; FSUB_NUMBER: char4; FRESERV_NO: numeric10; FRES_ITEM: numeric4; FRES_TYPE: char1; FWITHDRAWN: char1; FMOVE_MAT: char18; FMOVE_PLANT: char4; FMOVE_STLOC: char4; FMOVE_BATCH: char10; FMOVE_VAL_TYPE: char10; FMVT_IND: char1; FMOVE_REAS: numeric4; FRL_EST_KEY: char8; FREF_DATE: date10; FCOST_OBJ: char12; FPROFIT_SEGM_NO: numeric10; FPROFIT_CTR: char10; FWBS_ELEM: char24; FNETWORK: char12; FACTIVITY: char4; FPART_ACCT: char10; FAMOUNT_LC: decimal23_4; FAMOUNT_SV: decimal23_4; FREF_DOC_YR: numeric4; FREF_DOC: char10; FREF_DOC_IT: numeric4; FEXPIRYDATE: date10; FPROD_DATE: date10; FFUND: char10; FFUNDS_CTR: char16; FCMMT_ITEM: char14; FVAL_SALES_ORD: char10; FVAL_S_ORD_ITEM: numeric6; FVAL_WBS_ELEM: char24; FGL_ACCOUNT: char10; FIND_PROPOSE_QUANX: char1; FXSTOB: char1; FEAN_UPC: char18; FDELIV_NUMB_TO_SEARCH: char10; FDELIV_ITEM_TO_SEARCH: numeric6; FSERIALNO_AUTO_NUMBERASSIGNMENT: char1; FVENDRBATCH: char15; FSTGE_TYPE: char3; FSTGE_BIN: char10; FSU_PL_STCK_1: decimal3_0; FST_UN_QTYY_1: quantum13_3; FST_UN_QTYY_1_ISO: char3; FUNITTYPE_1: char3; FSU_PL_STCK_2: decimal3_0; FST_UN_QTYY_2: quantum13_3; FST_UN_QTYY_2_ISO: char3; FUNITTYPE_2: char3; FSTGE_TYPE_PC: char3; FSTGE_BIN_PC: char10; FNO_PST_CHGNT: char1; FGR_NUMBER: char10; FSTGE_TYPE_ST: char3; FSTGE_BIN_ST: char10; FMATDOC_TR_CANCEL: char10; FMATITEM_TR_CANCEL: numeric4; FMATYEAR_TR_CANCEL: numeric4; FNO_TRANSFER_REQ: char1; FCO_BUSPROC: char12; FACTTYPE: char6; FSUPPL_VEND: char10; FMATERIAL_EXTERNAL: char40; FMATERIAL_GUID: char32; FMATERIAL_VERSION: char10; FMOVE_MAT_EXTERNAL: char40; FMOVE_MAT_GUID: char32; FMOVE_MAT_VERSION: char10; FFUNC_AREA: char4; FTR_PART_BA: char4; FPAR_COMPCO: char4; FDELIV_NUMB: char10; FDELIV_ITEM: numeric6; FNB_SLIPS: numeric3; FNB_SLIPSX: char1; FGR_RCPTX: char1; FUNLOAD_PTX: char1; FSPEC_MVMT: char1; FGRANT_NBR: char20; FCMMT_ITEM_LONG: char24; FFUNC_AREA_LONG: char16; FLINE_ID: numeric6; FPARENT_ID: numeric6; FLINE_DEPTH: numeric2; FQUANTITY: quantum13_3; FBASE_UOM: unit3; FLONGNUM: char40; FBUDGET_PERIOD: char10; FEARMARKED_NUMBER: char10; FEARMARKED_ITEM: numeric3; FSTK_SEGMENT: char16; FMOVE_SEGMENT: char16; FMATERIAL_LONG: char40; FMOVE_MAT_LONG: char40; FSTK_SEG_LONG: char40; FMOV_SEG_LONG: char40; FCREATE_DELIVERY: char1; published property MATERIAL: char18 read FMATERIAL write FMATERIAL; property PLANT: char4 read FPLANT write FPLANT; property STGE_LOC: char4 read FSTGE_LOC write FSTGE_LOC; property BATCH: char10 read FBATCH write FBATCH; property MOVE_TYPE: char3 read FMOVE_TYPE write FMOVE_TYPE; property STCK_TYPE: char1 read FSTCK_TYPE write FSTCK_TYPE; property SPEC_STOCK: char1 read FSPEC_STOCK write FSPEC_STOCK; property VENDOR: char10 read FVENDOR write FVENDOR; property CUSTOMER: char10 read FCUSTOMER write FCUSTOMER; property SALES_ORD: char10 read FSALES_ORD write FSALES_ORD; property S_ORD_ITEM: numeric6 read FS_ORD_ITEM write FS_ORD_ITEM; property SCHED_LINE: numeric4 read FSCHED_LINE write FSCHED_LINE; property VAL_TYPE: char10 read FVAL_TYPE write FVAL_TYPE; property ENTRY_QNT: quantum13_3 read FENTRY_QNT write FENTRY_QNT; property ENTRY_UOM: unit3 read FENTRY_UOM write FENTRY_UOM; property ENTRY_UOM_ISO: char3 read FENTRY_UOM_ISO write FENTRY_UOM_ISO; property PO_PR_QNT: quantum13_3 read FPO_PR_QNT write FPO_PR_QNT; property ORDERPR_UN: unit3 read FORDERPR_UN write FORDERPR_UN; property ORDERPR_UN_ISO: char3 read FORDERPR_UN_ISO write FORDERPR_UN_ISO; property PO_NUMBER: char10 read FPO_NUMBER write FPO_NUMBER; property PO_ITEM: numeric5 read FPO_ITEM write FPO_ITEM; property SHIPPING: char2 read FSHIPPING write FSHIPPING; property COMP_SHIP: char2 read FCOMP_SHIP write FCOMP_SHIP; property NO_MORE_GR: char1 read FNO_MORE_GR write FNO_MORE_GR; property ITEM_TEXT: char50 read FITEM_TEXT write FITEM_TEXT; property GR_RCPT: char12 read FGR_RCPT write FGR_RCPT; property UNLOAD_PT: char25 read FUNLOAD_PT write FUNLOAD_PT; property COSTCENTER: char10 read FCOSTCENTER write FCOSTCENTER; property ORDERID: char12 read FORDERID write FORDERID; property ORDER_ITNO: numeric4 read FORDER_ITNO write FORDER_ITNO; property CALC_MOTIVE: char2 read FCALC_MOTIVE write FCALC_MOTIVE; property ASSET_NO: char12 read FASSET_NO write FASSET_NO; property SUB_NUMBER: char4 read FSUB_NUMBER write FSUB_NUMBER; property RESERV_NO: numeric10 read FRESERV_NO write FRESERV_NO; property RES_ITEM: numeric4 read FRES_ITEM write FRES_ITEM; property RES_TYPE: char1 read FRES_TYPE write FRES_TYPE; property WITHDRAWN: char1 read FWITHDRAWN write FWITHDRAWN; property MOVE_MAT: char18 read FMOVE_MAT write FMOVE_MAT; property MOVE_PLANT: char4 read FMOVE_PLANT write FMOVE_PLANT; property MOVE_STLOC: char4 read FMOVE_STLOC write FMOVE_STLOC; property MOVE_BATCH: char10 read FMOVE_BATCH write FMOVE_BATCH; property MOVE_VAL_TYPE: char10 read FMOVE_VAL_TYPE write FMOVE_VAL_TYPE; property MVT_IND: char1 read FMVT_IND write FMVT_IND; property MOVE_REAS: numeric4 read FMOVE_REAS write FMOVE_REAS; property RL_EST_KEY: char8 read FRL_EST_KEY write FRL_EST_KEY; property REF_DATE: date10 read FREF_DATE write FREF_DATE; property COST_OBJ: char12 read FCOST_OBJ write FCOST_OBJ; property PROFIT_SEGM_NO: numeric10 read FPROFIT_SEGM_NO write FPROFIT_SEGM_NO; property PROFIT_CTR: char10 read FPROFIT_CTR write FPROFIT_CTR; property WBS_ELEM: char24 read FWBS_ELEM write FWBS_ELEM; property NETWORK: char12 read FNETWORK write FNETWORK; property ACTIVITY: char4 read FACTIVITY write FACTIVITY; property PART_ACCT: char10 read FPART_ACCT write FPART_ACCT; property AMOUNT_LC: decimal23_4 read FAMOUNT_LC write FAMOUNT_LC; property AMOUNT_SV: decimal23_4 read FAMOUNT_SV write FAMOUNT_SV; property REF_DOC_YR: numeric4 read FREF_DOC_YR write FREF_DOC_YR; property REF_DOC: char10 read FREF_DOC write FREF_DOC; property REF_DOC_IT: numeric4 read FREF_DOC_IT write FREF_DOC_IT; property EXPIRYDATE: date10 read FEXPIRYDATE write FEXPIRYDATE; property PROD_DATE: date10 read FPROD_DATE write FPROD_DATE; property FUND: char10 read FFUND write FFUND; property FUNDS_CTR: char16 read FFUNDS_CTR write FFUNDS_CTR; property CMMT_ITEM: char14 read FCMMT_ITEM write FCMMT_ITEM; property VAL_SALES_ORD: char10 read FVAL_SALES_ORD write FVAL_SALES_ORD; property VAL_S_ORD_ITEM: numeric6 read FVAL_S_ORD_ITEM write FVAL_S_ORD_ITEM; property VAL_WBS_ELEM: char24 read FVAL_WBS_ELEM write FVAL_WBS_ELEM; property GL_ACCOUNT: char10 read FGL_ACCOUNT write FGL_ACCOUNT; property IND_PROPOSE_QUANX: char1 read FIND_PROPOSE_QUANX write FIND_PROPOSE_QUANX; property XSTOB: char1 read FXSTOB write FXSTOB; property EAN_UPC: char18 read FEAN_UPC write FEAN_UPC; property DELIV_NUMB_TO_SEARCH: char10 read FDELIV_NUMB_TO_SEARCH write FDELIV_NUMB_TO_SEARCH; property DELIV_ITEM_TO_SEARCH: numeric6 read FDELIV_ITEM_TO_SEARCH write FDELIV_ITEM_TO_SEARCH; property SERIALNO_AUTO_NUMBERASSIGNMENT: char1 read FSERIALNO_AUTO_NUMBERASSIGNMENT write FSERIALNO_AUTO_NUMBERASSIGNMENT; property VENDRBATCH: char15 read FVENDRBATCH write FVENDRBATCH; property STGE_TYPE: char3 read FSTGE_TYPE write FSTGE_TYPE; property STGE_BIN: char10 read FSTGE_BIN write FSTGE_BIN; property SU_PL_STCK_1: decimal3_0 read FSU_PL_STCK_1 write FSU_PL_STCK_1; property ST_UN_QTYY_1: quantum13_3 read FST_UN_QTYY_1 write FST_UN_QTYY_1; property ST_UN_QTYY_1_ISO: char3 read FST_UN_QTYY_1_ISO write FST_UN_QTYY_1_ISO; property UNITTYPE_1: char3 read FUNITTYPE_1 write FUNITTYPE_1; property SU_PL_STCK_2: decimal3_0 read FSU_PL_STCK_2 write FSU_PL_STCK_2; property ST_UN_QTYY_2: quantum13_3 read FST_UN_QTYY_2 write FST_UN_QTYY_2; property ST_UN_QTYY_2_ISO: char3 read FST_UN_QTYY_2_ISO write FST_UN_QTYY_2_ISO; property UNITTYPE_2: char3 read FUNITTYPE_2 write FUNITTYPE_2; property STGE_TYPE_PC: char3 read FSTGE_TYPE_PC write FSTGE_TYPE_PC; property STGE_BIN_PC: char10 read FSTGE_BIN_PC write FSTGE_BIN_PC; property NO_PST_CHGNT: char1 read FNO_PST_CHGNT write FNO_PST_CHGNT; property GR_NUMBER: char10 read FGR_NUMBER write FGR_NUMBER; property STGE_TYPE_ST: char3 read FSTGE_TYPE_ST write FSTGE_TYPE_ST; property STGE_BIN_ST: char10 read FSTGE_BIN_ST write FSTGE_BIN_ST; property MATDOC_TR_CANCEL: char10 read FMATDOC_TR_CANCEL write FMATDOC_TR_CANCEL; property MATITEM_TR_CANCEL: numeric4 read FMATITEM_TR_CANCEL write FMATITEM_TR_CANCEL; property MATYEAR_TR_CANCEL: numeric4 read FMATYEAR_TR_CANCEL write FMATYEAR_TR_CANCEL; property NO_TRANSFER_REQ: char1 read FNO_TRANSFER_REQ write FNO_TRANSFER_REQ; property CO_BUSPROC: char12 read FCO_BUSPROC write FCO_BUSPROC; property ACTTYPE: char6 read FACTTYPE write FACTTYPE; property SUPPL_VEND: char10 read FSUPPL_VEND write FSUPPL_VEND; property MATERIAL_EXTERNAL: char40 read FMATERIAL_EXTERNAL write FMATERIAL_EXTERNAL; property MATERIAL_GUID: char32 read FMATERIAL_GUID write FMATERIAL_GUID; property MATERIAL_VERSION: char10 read FMATERIAL_VERSION write FMATERIAL_VERSION; property MOVE_MAT_EXTERNAL: char40 read FMOVE_MAT_EXTERNAL write FMOVE_MAT_EXTERNAL; property MOVE_MAT_GUID: char32 read FMOVE_MAT_GUID write FMOVE_MAT_GUID; property MOVE_MAT_VERSION: char10 read FMOVE_MAT_VERSION write FMOVE_MAT_VERSION; property FUNC_AREA: char4 read FFUNC_AREA write FFUNC_AREA; property TR_PART_BA: char4 read FTR_PART_BA write FTR_PART_BA; property PAR_COMPCO: char4 read FPAR_COMPCO write FPAR_COMPCO; property DELIV_NUMB: char10 read FDELIV_NUMB write FDELIV_NUMB; property DELIV_ITEM: numeric6 read FDELIV_ITEM write FDELIV_ITEM; property NB_SLIPS: numeric3 read FNB_SLIPS write FNB_SLIPS; property NB_SLIPSX: char1 read FNB_SLIPSX write FNB_SLIPSX; property GR_RCPTX: char1 read FGR_RCPTX write FGR_RCPTX; property UNLOAD_PTX: char1 read FUNLOAD_PTX write FUNLOAD_PTX; property SPEC_MVMT: char1 read FSPEC_MVMT write FSPEC_MVMT; property GRANT_NBR: char20 read FGRANT_NBR write FGRANT_NBR; property CMMT_ITEM_LONG: char24 read FCMMT_ITEM_LONG write FCMMT_ITEM_LONG; property FUNC_AREA_LONG: char16 read FFUNC_AREA_LONG write FFUNC_AREA_LONG; property LINE_ID: numeric6 read FLINE_ID write FLINE_ID; property PARENT_ID: numeric6 read FPARENT_ID write FPARENT_ID; property LINE_DEPTH: numeric2 read FLINE_DEPTH write FLINE_DEPTH; property QUANTITY: quantum13_3 read FQUANTITY write FQUANTITY; property BASE_UOM: unit3 read FBASE_UOM write FBASE_UOM; property LONGNUM: char40 read FLONGNUM write FLONGNUM; property BUDGET_PERIOD: char10 read FBUDGET_PERIOD write FBUDGET_PERIOD; property EARMARKED_NUMBER: char10 read FEARMARKED_NUMBER write FEARMARKED_NUMBER; property EARMARKED_ITEM: numeric3 read FEARMARKED_ITEM write FEARMARKED_ITEM; property STK_SEGMENT: char16 read FSTK_SEGMENT write FSTK_SEGMENT; property MOVE_SEGMENT: char16 read FMOVE_SEGMENT write FMOVE_SEGMENT; property MATERIAL_LONG: char40 read FMATERIAL_LONG write FMATERIAL_LONG; property MOVE_MAT_LONG: char40 read FMOVE_MAT_LONG write FMOVE_MAT_LONG; property STK_SEG_LONG: char40 read FSTK_SEG_LONG write FSTK_SEG_LONG; property MOV_SEG_LONG: char40 read FMOV_SEG_LONG write FMOV_SEG_LONG; property CREATE_DELIVERY: char1 read FCREATE_DELIVERY write FCREATE_DELIVERY; end; BAPI2017_GM_ITEM_CREATE_T = array of BAPI2017_GM_ITEM_CREATE; { "urn:sap-com:document:sap:rfc:functions" } // ************************************************************************ // // Namespace : urn:sap-com:document:sap:rfc:functions // ************************************************************************ // BAPIRET2 = class(TRemotable) private FTYPE_: char1; FID: char20; FNUMBER: numeric3; FMESSAGE: char220; FLOG_NO: char20; FLOG_MSG_NO: numeric6; FMESSAGE_V1: char50; FMESSAGE_V2: char50; FMESSAGE_V3: char50; FMESSAGE_V4: char50; FPARAMETER: char32; FROW: Integer; FFIELD: char30; FSYSTEM: char10; published property TYPE_: char1 read FTYPE_ write FTYPE_; property ID: char20 read FID write FID; property NUMBER: numeric3 read FNUMBER write FNUMBER; property MESSAGE: char220 read FMESSAGE write FMESSAGE; property LOG_NO: char20 read FLOG_NO write FLOG_NO; property LOG_MSG_NO: numeric6 read FLOG_MSG_NO write FLOG_MSG_NO; property MESSAGE_V1: char50 read FMESSAGE_V1 write FMESSAGE_V1; property MESSAGE_V2: char50 read FMESSAGE_V2 write FMESSAGE_V2; property MESSAGE_V3: char50 read FMESSAGE_V3 write FMESSAGE_V3; property MESSAGE_V4: char50 read FMESSAGE_V4 write FMESSAGE_V4; property PARAMETER: char32 read FPARAMETER write FPARAMETER; property ROW: Integer read FROW write FROW; property FIELD: char30 read FFIELD write FFIELD; property SYSTEM: char10 read FSYSTEM write FSYSTEM; end; BAPIRET2_T = array of BAPIRET2; { "urn:sap-com:document:sap:rfc:functions" } // ************************************************************************ // // Namespace : urn:sap-com:document:sap:rfc:functions // soapAction: urn:sap-com:document:sap:rfc:functions:ZMM_WS_GOODSMVT_CREATE_SOLO:ZMM_GOODSMVT_CREATE_SOLORequest // transport : http://schemas.xmlsoap.org/soap/http // style : document // binding : zmm_ws_goodsmvt_create_solo // service : zmm_ws_goodsmvt_create_solo // port : zmm_ws_goodsmvt_create_solo // URL : http://srv-s4-asq.pdm.local:8000/sap/bc/srt/rfc/sap/zmm_ws_goodsmvt_create_solo/400/zmm_ws_goodsmvt_create_solo/zmm_ws_goodsmvt_create_solo // ************************************************************************ // ZMM_WS_GOODSMVT_CREATE_SOLO = interface(IInvokable) ['{741ED251-B7EA-F9ED-3736-6C22BE8A5B28}'] function ZMM_GOODSMVT_CREATE_SOLO(const FI_HEADER: BAPI2017_GM_HEAD_01; const FI_ITEM: BAPI2017_GM_ITEM_CREATE_T): BAPIRET2_T; stdcall; end; function GetZMM_WS_GOODSMVT_CREATE_SOLO(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): ZMM_WS_GOODSMVT_CREATE_SOLO; implementation function GetZMM_WS_GOODSMVT_CREATE_SOLO(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): ZMM_WS_GOODSMVT_CREATE_SOLO; const defWSDL = 'http://srv-s4-asq.pdm.local:8000/sap/bc/srt/wsdl/flv_10002A111AD1/bndg_url/sap/bc/srt/rfc/sap/zmm_ws_goodsmvt_create_solo/400/zmm_ws_goodsmvt_create_solo/zmm_ws_goodsmvt_create_solo?sap-client=400'; defURL = 'http://srv-s4-asq.pdm.local:8000/sap/bc/srt/rfc/sap/zmm_ws_goodsmvt_create_solo/400/zmm_ws_goodsmvt_create_solo/zmm_ws_goodsmvt_create_solo'; defSvc = 'zmm_ws_goodsmvt_create_solo'; defPrt = 'zmm_ws_goodsmvt_create_solo'; var RIO: THTTPRIO; begin Result := nil; if (Addr = '') then begin if UseWSDL then Addr := defWSDL else Addr := defURL; end; if HTTPRIO = nil then RIO := THTTPRIO.Create(nil) else RIO := HTTPRIO; try Result := (RIO as ZMM_WS_GOODSMVT_CREATE_SOLO); if UseWSDL then begin RIO.WSDLLocation := Addr; RIO.Service := defSvc; RIO.Port := defPrt; end else RIO.URL := Addr; finally if (Result = nil) and (HTTPRIO = nil) then RIO.Free; end; end; initialization InvRegistry.RegisterInterface(TypeInfo(ZMM_WS_GOODSMVT_CREATE_SOLO), 'urn:sap-com:document:sap:rfc:functions', 'utf-8'); InvRegistry.RegisterDefaultSOAPAction(TypeInfo(ZMM_WS_GOODSMVT_CREATE_SOLO), 'urn:sap-com:document:sap:rfc:functions:ZMM_WS_GOODSMVT_CREATE_SOLO:ZMM_GOODSMVT_CREATE_SOLORequest'); InvRegistry.RegisterInvokeOptions(TypeInfo(ZMM_WS_GOODSMVT_CREATE_SOLO), ioDocument); RemClassRegistry.RegisterXSInfo(TypeInfo(char1), 'urn:sap-com:document:sap:rfc:functions', 'char1'); RemClassRegistry.RegisterXSInfo(TypeInfo(char10), 'urn:sap-com:document:sap:rfc:functions', 'char10'); RemClassRegistry.RegisterXSInfo(TypeInfo(char12), 'urn:sap-com:document:sap:rfc:functions', 'char12'); RemClassRegistry.RegisterXSInfo(TypeInfo(char14), 'urn:sap-com:document:sap:rfc:functions', 'char14'); RemClassRegistry.RegisterXSInfo(TypeInfo(char15), 'urn:sap-com:document:sap:rfc:functions', 'char15'); RemClassRegistry.RegisterXSInfo(TypeInfo(char16), 'urn:sap-com:document:sap:rfc:functions', 'char16'); RemClassRegistry.RegisterXSInfo(TypeInfo(char18), 'urn:sap-com:document:sap:rfc:functions', 'char18'); RemClassRegistry.RegisterXSInfo(TypeInfo(char2), 'urn:sap-com:document:sap:rfc:functions', 'char2'); RemClassRegistry.RegisterXSInfo(TypeInfo(char20), 'urn:sap-com:document:sap:rfc:functions', 'char20'); RemClassRegistry.RegisterXSInfo(TypeInfo(char220), 'urn:sap-com:document:sap:rfc:functions', 'char220'); RemClassRegistry.RegisterXSInfo(TypeInfo(char24), 'urn:sap-com:document:sap:rfc:functions', 'char24'); RemClassRegistry.RegisterXSInfo(TypeInfo(char25), 'urn:sap-com:document:sap:rfc:functions', 'char25'); RemClassRegistry.RegisterXSInfo(TypeInfo(char3), 'urn:sap-com:document:sap:rfc:functions', 'char3'); RemClassRegistry.RegisterXSInfo(TypeInfo(char30), 'urn:sap-com:document:sap:rfc:functions', 'char30'); RemClassRegistry.RegisterXSInfo(TypeInfo(char32), 'urn:sap-com:document:sap:rfc:functions', 'char32'); RemClassRegistry.RegisterXSInfo(TypeInfo(char35), 'urn:sap-com:document:sap:rfc:functions', 'char35'); RemClassRegistry.RegisterXSInfo(TypeInfo(char4), 'urn:sap-com:document:sap:rfc:functions', 'char4'); RemClassRegistry.RegisterXSInfo(TypeInfo(char40), 'urn:sap-com:document:sap:rfc:functions', 'char40'); RemClassRegistry.RegisterXSInfo(TypeInfo(char50), 'urn:sap-com:document:sap:rfc:functions', 'char50'); RemClassRegistry.RegisterXSInfo(TypeInfo(char6), 'urn:sap-com:document:sap:rfc:functions', 'char6'); RemClassRegistry.RegisterXSInfo(TypeInfo(char8), 'urn:sap-com:document:sap:rfc:functions', 'char8'); RemClassRegistry.RegisterXSInfo(TypeInfo(date10), 'urn:sap-com:document:sap:rfc:functions', 'date10'); RemClassRegistry.RegisterXSInfo(TypeInfo(decimal23_4), 'urn:sap-com:document:sap:rfc:functions', 'decimal23_4', 'decimal23.4'); RemClassRegistry.RegisterXSInfo(TypeInfo(decimal3_0), 'urn:sap-com:document:sap:rfc:functions', 'decimal3_0', 'decimal3.0'); RemClassRegistry.RegisterXSInfo(TypeInfo(numeric10), 'urn:sap-com:document:sap:rfc:functions', 'numeric10'); RemClassRegistry.RegisterXSInfo(TypeInfo(numeric2), 'urn:sap-com:document:sap:rfc:functions', 'numeric2'); RemClassRegistry.RegisterXSInfo(TypeInfo(numeric3), 'urn:sap-com:document:sap:rfc:functions', 'numeric3'); RemClassRegistry.RegisterXSInfo(TypeInfo(numeric4), 'urn:sap-com:document:sap:rfc:functions', 'numeric4'); RemClassRegistry.RegisterXSInfo(TypeInfo(numeric5), 'urn:sap-com:document:sap:rfc:functions', 'numeric5'); RemClassRegistry.RegisterXSInfo(TypeInfo(numeric6), 'urn:sap-com:document:sap:rfc:functions', 'numeric6'); RemClassRegistry.RegisterXSInfo(TypeInfo(quantum13_3), 'urn:sap-com:document:sap:rfc:functions', 'quantum13_3', 'quantum13.3'); RemClassRegistry.RegisterXSInfo(TypeInfo(unit3), 'urn:sap-com:document:sap:rfc:functions', 'unit3'); RemClassRegistry.RegisterXSClass(BAPI2017_GM_HEAD_01, 'urn:sap-com:document:sap:rfc:functions', 'BAPI2017_GM_HEAD_01'); RemClassRegistry.RegisterXSClass(BAPI2017_GM_ITEM_CREATE, 'urn:sap-com:document:sap:rfc:functions', 'BAPI2017_GM_ITEM_CREATE'); RemClassRegistry.RegisterXSInfo(TypeInfo(BAPI2017_GM_ITEM_CREATE_T), 'urn:sap-com:document:sap:rfc:functions', 'BAPI2017_GM_ITEM_CREATE_T'); RemClassRegistry.RegisterXSClass(BAPIRET2, 'urn:sap-com:document:sap:rfc:functions', 'BAPIRET2'); RemClassRegistry.RegisterExternalPropName(TypeInfo(BAPIRET2), 'TYPE_', 'TYPE'); RemClassRegistry.RegisterXSInfo(TypeInfo(BAPIRET2_T), 'urn:sap-com:document:sap:rfc:functions', 'BAPIRET2_T'); end.
unit ibSHRegister; interface uses SysUtils, Classes, Controls, Forms, Dialogs, SHDesignIntf, SHDevelopIntf, ibSHDesignIntf, ibSHDriverIntf, ibSHComponent; type TibBTRegisterFactory = class(TibBTComponentFactory) public function SupportComponent(const AClassIID: TGUID): Boolean; override; function CreateComponent(const AOwnerIID, AClassIID: TGUID; const ACaption: string): TSHComponent; override; function DestroyComponent(AComponent: TSHComponent): Boolean; override; end; procedure Register(); implementation uses ibSHConsts, ibSHMessages, ibSHServer, ibSHDatabase, ibSHRegisterActions, ibSHRegisterEditors, ibSHRegisterFrm, ibSHUserConnectedFrm; procedure Register(); begin SHRegisterImage(GUIDToString(IibSHServer), 'Server.bmp'); // SHRegisterImage(GUIDToString(IfbSHServer), 'Server.bmp'); SHRegisterImage(GUIDToString(IibSHDatabase), 'Database.bmp'); // SHRegisterImage(GUIDToString(IfbSHDatabase), 'Database.bmp'); SHRegisterImage(GUIDToString(IibSHServerOptions), 'Server.bmp'); SHRegisterImage(GUIDToString(IfbSHServerOptions), 'Server.bmp'); SHRegisterImage(GUIDToString(IibSHDatabaseOptions), 'Database.bmp'); SHRegisterImage(GUIDToString(IfbSHDatabaseOptions), 'Database.bmp'); SHRegisterImage(TibSHRegisterServerAction.ClassName, 'ServerRegister.bmp'); SHRegisterImage(TibSHRegisterDatabaseAction.ClassName, 'DatabaseRegister.bmp'); SHRegisterImage(TibSHCloneServerAction.ClassName, 'ServerClone.bmp'); SHRegisterImage(TibSHCloneDatabaseAction.ClassName, 'DatabaseClone.bmp'); SHRegisterImage(TibSHUnregisterServerAction.ClassName, 'ServerUnregister.bmp'); SHRegisterImage(TibSHUnregisterDatabaseAction.ClassName, 'DatabaseUnregister.bmp'); SHRegisterImage(TibSHCreateDatabaseAction.ClassName, 'DatabaseCreate.bmp'); SHRegisterImage(TibSHDropDatabaseAction.ClassName, 'DatabaseDrop.bmp'); SHRegisterImage(TibSHAliasInfoServerAction.ClassName, 'ServerInfo.bmp'); SHRegisterImage(TibSHAliasInfoDatabaseAction.ClassName, 'DatabaseInfo.bmp'); SHRegisterImage(TibSHServerEditorRegisterDatabase.ClassName, 'DatabaseRegister.bmp'); SHRegisterImage(TibSHServerEditorCreateDatabase.ClassName, 'DatabaseCreate.bmp'); SHRegisterImage(TibSHServerEditorClone.ClassName, 'ServerClone.bmp'); SHRegisterImage(TibSHServerEditorUnregister.ClassName, 'ServerUnregister.bmp'); SHRegisterImage(TibSHServerEditorTestConnect.ClassName, 'Button_ConnectTest.bmp'); SHRegisterImage(TibSHServerEditorRegInfo.ClassName, 'ServerInfo.bmp'); SHRegisterImage(TibSHDatabaseEditorConnect.ClassName, 'Button_Connect.bmp'); SHRegisterImage(TibSHDatabaseEditorReconnect.ClassName, 'Button_Reconnect.bmp'); SHRegisterImage(TibSHDatabaseEditorDisconnect.ClassName, 'Button_Disconnect.bmp'); SHRegisterImage(TibSHDatabaseEditorRefresh.ClassName, 'Button_Refresh.bmp'); SHRegisterImage(TibSHDatabaseEditorActiveUsers.ClassName, 'User.bmp'); SHRegisterImage(TibSHDatabaseEditorOnline.ClassName, 'Online.bmp'); SHRegisterImage(TibSHDatabaseEditorShutdown.ClassName, 'Shutdown.bmp'); SHRegisterImage(TibSHDatabaseEditorClone.ClassName, 'DatabaseClone.bmp'); SHRegisterImage(TibSHDatabaseEditorUnregister.ClassName, 'DatabaseUnregister.bmp'); SHRegisterImage(TibSHDatabaseEditorDrop.ClassName, 'DatabaseDrop.bmp'); SHRegisterImage(TibSHDatabaseEditorTestConnect.ClassName, 'Button_ConnectTest.bmp'); SHRegisterImage(TibSHDatabaseEditorRegInfo.ClassName, 'DatabaseInfo.bmp'); SHRegisterActions([ // Common Register TibSHRegisterServerAction, TibSHRegisterDatabaseAction, {-} TibSHRegisterSeparatorAction, TibSHCloneServerAction, TibSHCloneDatabaseAction, {-} TibSHRegisterSeparatorAction, TibSHUnregisterServerAction, TibSHUnregisterDatabaseAction, {-} TibSHRegisterSeparatorAction, TibSHCreateDatabaseAction, TibSHDropDatabaseAction, {-} TibSHRegisterSeparatorAction, TibSHAliasInfoServerAction, TibSHAliasInfoDatabaseAction]); SHRegisterActions([ // Server TibSHServerEditorRegisterDatabase, TibSHServerEditorCreateDatabase, {-} TibSHServerSeparatorEditorAction, TibSHServerEditorClone, TibSHServerEditorUnregister, {-} TibSHServerSeparatorEditorAction, TibSHServerEditorTestConnect, TibSHServerEditorRegInfo]); SHRegisterActions([ // Database TibSHDatabaseEditorConnect, TibSHDatabaseEditorReconnect, TibSHDatabaseEditorDisconnect, TibSHDatabaseEditorRefresh, {-} TibSHDatabaseSeparatorEditorAction, TibSHDatabaseEditorActiveUsers, {-} TibSHDatabaseSeparatorEditorAction, TibSHDatabaseEditorOnline, TibSHDatabaseEditorShutdown, {-} TibSHDatabaseSeparatorEditorAction, TibSHDatabaseEditorClone, TibSHDatabaseEditorUnregister, TibSHDatabaseEditorDrop, {-} TibSHDatabaseSeparatorEditorAction, TibSHDatabaseEditorTestConnect, TibSHDatabaseEditorRegInfo]); SHRegisterComponents([TibSHServer, TibSHDatabase]); SHRegisterComponents([TibBTRegisterFactory]); SHRegisterComponents([TibSHServerOptions, TfbSHServerOptions, TibSHDatabaseOptions, TfbSHDatabaseOptions]); SHRegisterPropertyEditor(IibSHServer, SCallHost, TibBTHostPropEditor); SHRegisterPropertyEditor(IibSHDummy, SCallVersion, TibSHServerVersionPropEditor); SHRegisterPropertyEditor(IibSHDummy, SCallClientLibrary, TibBTClientLibraryPropEditor); SHRegisterPropertyEditor(IibSHDummy, SCallProtocol, TibBTProtocolPropEditor); SHRegisterPropertyEditor(IibSHDummy, SCallSecurityDatabase, TibSHDatabasePropEditor); SHRegisterPropertyEditor(IibSHDummy, SCallPassword, TibBTPasswordPropEditor); SHRegisterPropertyEditor(IibSHDummy, SCallServer, TibSHServerPropEditor); SHRegisterPropertyEditor(IibSHDatabase, SCallDatabase, TibSHDatabasePropEditor); SHRegisterPropertyEditor(IibSHDatabase, SCallPageSize, TibBTPageSizePropEditor); SHRegisterPropertyEditor(IibSHDatabase, SCallSQLDialect, TibBTSQLDialectPropEditor); SHRegisterPropertyEditor(IibSHDummy, SCallCharset, TibBTCharsetPropEditor); SHRegisterPropertyEditor(IibSHDatabase, SCallCharset, TibBTCharsetPropEditor); SHRegisterPropertyEditor(IibSHDatabase, SCallAdditionalConnectParams, TibBTAdditionalConnectParamsPropEditor); SHRegisterPropertyEditor(IibSHDatabase, 'DatabaseAliasOptions', TibSHDatabaseAliasOptionsPropEditor); SHRegisterPropertyEditor(IibSHDatabaseAliasOptions, 'Navigator', TibSHDatabaseAliasOptionsPropEditor); SHRegisterPropertyEditor(IibSHDatabaseAliasOptions, 'DDL', TibSHDatabaseAliasOptionsPropEditor); SHRegisterPropertyEditor(IibSHDatabaseAliasOptions, 'DML', TibSHDatabaseAliasOptionsPropEditor); SHRegisterPropertyEditor(IibSHDDLOptions, 'StartDomainForm', TibBTStartFromPropEditor); SHRegisterPropertyEditor(IibSHDDLOptions, 'StartTableForm', TibBTStartFromPropEditor); SHRegisterPropertyEditor(IibSHDDLOptions, 'StartIndexForm', TibBTStartFromPropEditor); SHRegisterPropertyEditor(IibSHDDLOptions, 'StartViewForm', TibBTStartFromPropEditor); SHRegisterPropertyEditor(IibSHDDLOptions, 'StartProcedureForm', TibBTStartFromPropEditor); SHRegisterPropertyEditor(IibSHDDLOptions, 'StartTriggerForm', TibBTStartFromPropEditor); SHRegisterPropertyEditor(IibSHDDLOptions, 'StartGeneratorForm', TibBTStartFromPropEditor); SHRegisterPropertyEditor(IibSHDDLOptions, 'StartExceptionForm', TibBTStartFromPropEditor); SHRegisterPropertyEditor(IibSHDDLOptions, 'StartFunctionForm', TibBTStartFromPropEditor); SHRegisterPropertyEditor(IibSHDDLOptions, 'StartFilterForm', TibBTStartFromPropEditor); SHRegisterPropertyEditor(IibSHDDLOptions, 'StartRoleForm', TibBTStartFromPropEditor); SHRegisterPropertyEditor(IibSHDMLOptions, 'ConfirmEndTransaction', TibBTConfirmEndTransaction); SHRegisterPropertyEditor(IibSHDMLOptions, 'DefaultTransactionAction', TibBTDefaultTransactionAction); SHRegisterPropertyEditor(IibSHDMLOptions, 'IsolationLevel', TibBTIsolationLevelPropEditor); SHRegisterComponentForm(IibSHDummy, SCallRegister, TibBTRegisterForm); SHRegisterComponentForm(IibSHDummy, SCallActiveUsers, TibSHUserConnectedForm); end; { TibBTRegisterFactory } function TibBTRegisterFactory.SupportComponent(const AClassIID: TGUID): Boolean; begin Result := IsEqualGUID(AClassIID, IibSHBranch) or IsEqualGUID(AClassIID, IfbSHBranch); end; function TibBTRegisterFactory.CreateComponent(const AOwnerIID, AClassIID: TGUID; const ACaption: string): TSHComponent; begin Result := nil; if IsEqualGUID(AClassIID, ISHServer) then begin Result := Designer.GetComponent(IibSHServer).Create(nil); Result.OwnerIID := AOwnerIID; Designer.ChangeNotification(Result, opInsert); end; if IsEqualGUID(AClassIID, ISHDatabase) then begin Result := Designer.GetComponent(IibSHDatabase).Create(nil); if not IsEqualGUID(AOwnerIID, IUnknown) then Result.OwnerIID := AOwnerIID; Designer.ChangeNotification(Result, opInsert); end; end; function TibBTRegisterFactory.DestroyComponent(AComponent: TSHComponent): Boolean; begin Result := Designer.ChangeNotification(AComponent, opRemove); if Result then FreeAndNil(AComponent); end; initialization Register; end.
type TEnum = (Value1,Value2,Value3, Value4); TSample<T1, T2> = class(TObject,IInterface) private FA: Integer; public procedure Method(arg1, arg2: Integer; arg3: TEnum); function Simple(a1: TEnum): TSample; function Modifiers(a, b: TEnum): TEnum; virtual; abstract; register; end; // comment procedure TSample<T1, T2>.Method(arg1, arg2: Integer; arg3: TEnum); var t1, t2: Integer; begin t1 := arg2; t2 := arg2; if t1 = t2 then t1 := t2 else t2 := t1; t2 := arg1 + arg2 + arg3 * arg1 div arg2 mod arg1; if -arg1 > arg2 then begin FA := arg1 - arg2; end else begin FA := (arg1 + -arg2); end; Method(arg1 + arg2, arg2, arg3); Simple(arg3).Simple(arg1).Simple(arg3).Simple(arg2); end; function TSample.Simple(a1: TEnum): TSample; begin a1[0] := 0; end; function NotSimple(a1: TEnum): TSample; begin a1[0] := 0; a1 := a1; end; begin end.
{ ******************************************************* } { * {* uTVDBEpisode.pas {* Delphi Implementation of the Class TVDBEpisode {* Generated by Enterprise Architect {* Created on: 09-févr.-2015 11:43:17 {* Original author: Labelleg OK {* {******************************************************* } unit xmltvdb.TVDBEpisode; interface uses System.Generics.Collections; type ITVDBEpisode = interface['{95CA74BA-EDD5-44B3-A3C6-6158DCD22E5B}'] function toString: String; function GetepisodeNumber: String; function GetfirstAired: String; function GethasImage: boolean; function GetseasonNumber: String; function Gettitle: String; procedure Assign( e:ITVDBEpisode); procedure AddMissingInfo(e: ITVDBEpisode); end; TTVDBEpisode = class(TInterfacedObject,ITVDBEpisode) strict private FepisodeNumber: String; FfirstAired: String; FhasImage: boolean; FseasonNumber: String; Ftitle: String; public function GetepisodeNumber: String; function GetfirstAired: String; function GethasImage: boolean; function GetseasonNumber: String; function Gettitle: String; function toString: String; reintroduce; procedure Assign( e:ITVDBEpisode); procedure AddMissingInfo(e: ITVDBEpisode); constructor Create(const tvdbTitle: String; const tvdbFirstAired: String;const tvdbSeasonNumber: String;const tvdbEpisodeNumber: String; const hasTVDBImage: boolean); overload; destructor Destroy; override; end; TVDBEpisodeColl = class(TList<ITVDBEpisode>) public constructor Create; overload; destructor Destroy; override; function containsAll(coll: TVDBEpisodeColl): boolean; function IsEmpty: boolean; function toString: String; reintroduce; function FindByOriginalDate(ladate:string) : ITVDBEpisode; end; implementation uses System.SysUtils; { implementation of TVDBEpisode } procedure TTVDBEpisode.AddMissingInfo(e: ITVDBEpisode); begin if Ftitle.IsEmpty and not e.Gettitle.IsEmpty then Ftitle := e.getTitle; if FseasonNumber.IsEmpty and not e.GetseasonNumber.IsEmpty then FseasonNumber := e.GetseasonNumber; if FepisodeNumber.IsEmpty and not e.GetepisodeNumber.IsEmpty then FepisodeNumber := e.GetepisodeNumber; end; procedure TTVDBEpisode.Assign(e: ITVDBEpisode); begin self.Ftitle := e.getTitle; self.FfirstAired := e.GetfirstAired; self.FseasonNumber := e.GetseasonNumber; self.FepisodeNumber := e.GetepisodeNumber; self.FhasImage := e.GethasImage; end; constructor TTVDBEpisode.Create(const tvdbTitle, tvdbFirstAired, tvdbSeasonNumber, tvdbEpisodeNumber: String; const hasTVDBImage: boolean); begin inherited Create; self.Ftitle := tvdbTitle; self.FfirstAired := tvdbFirstAired; self.FseasonNumber := tvdbSeasonNumber; self.FepisodeNumber := tvdbEpisodeNumber; self.FhasImage := hasTVDBImage; end; destructor TTVDBEpisode.Destroy; begin inherited Destroy; end; function TTVDBEpisode.GetepisodeNumber: String; begin Result := FepisodeNumber; end; function TTVDBEpisode.GetfirstAired: String; begin Result := FfirstAired; end; function TTVDBEpisode.GethasImage: boolean; begin Result := FhasImage; end; function TTVDBEpisode.GetseasonNumber: String; begin Result := FseasonNumber; end; function TTVDBEpisode.Gettitle: String; begin Result := Ftitle end; //procedure TTVDBEpisode.SetepisodeNumber(const Value: String); //begin // FepisodeNumber := Value; //end; // //procedure TTVDBEpisode.SetfirstAired(const Value: String); //begin // FfirstAired := Value; //end; // //procedure TTVDBEpisode.SethasImage(const Value: boolean); //begin // FhasImage := Value; //end; // //procedure TTVDBEpisode.SetseasonNumber(const Value: String); //begin // FseasonNumber := Value; //end; // //procedure TTVDBEpisode.Settitle(const Value: String); //begin // Ftitle := Value; //end; function TTVDBEpisode.toString: String; begin Result := FseasonNumber + 'x' + FepisodeNumber + ' - ' + Ftitle + ' (' + FfirstAired + ')'; end; { TVDBEpisodeColl } function TVDBEpisodeColl.containsAll(coll: TVDBEpisodeColl): boolean; var unElement: ITVDBEpisode; begin for unElement in coll do begin if not self.Contains(unElement) then begin Result := False; exit; end; end; Result := True; end; constructor TVDBEpisodeColl.Create; begin inherited Create(); // OwnsObjects := True; end; destructor TVDBEpisodeColl.Destroy; begin inherited Destroy; end; function TVDBEpisodeColl.FindByOriginalDate(ladate: string): ITVDBEpisode; var ep:ITVDBEpisode; begin Result := nil ; for ep in Self do begin if sameText( ep.GetfirstAired, ladate) then begin Result := ep; end; end; end; function TVDBEpisodeColl.IsEmpty: boolean; begin Result := (self.Count = 0); end; function TVDBEpisodeColl.toString: String; var item: ITVDBEpisode; begin Result := ''; for item in self do begin Result := Result + '; ' + item.toString; end; end; end.
// ################################## // ###### IT PAT 2018 ####### // ###### GrowCery ####### // ###### Tiaan van der Riel ####### // ################################## unit clsAnalyticsCalculator_u; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, TeEngine, TeeProcs, Chart, Grids, DBGrids, pngimage, Buttons, ComCtrls, Mask; type TAnalyticsCalculator = class(TObject) private fSelectedAccountID: string; fStartDate: string; fEndDate: string; public // Variables iCount: integer; rTotalSales: real; rAverageSalesValue: real; iTotalNumberOfItemsSold: integer; iAverageNumberOfItemsSold: integer; // Constructor constructor Create(sSelectedAccountID: string; sStartDate: string; sEndDate: string); // Functions function CalcTotalSales: real; function CalcAverageSales: real; function CalcTotalItemsSold: integer; function CalcAverageItemsSold: integer; // Procedure procedure BuildSQL; end; implementation uses dmDatabase_u; { TAnalyticsCalculator } { This class is used to calculate the analytics of a given account whitin a certain period of time, using a start date and a end date. The following can be calculated: 1.) Total value of the items sold 2.) Average value of the items sold for each day 3.) Total number of items sold 4.) Average number of items sold each day * This class is used by the from frmAnalytics to calcylate the analytics within a certain time period, to be displayed on panels, and a graph. * This class is also repurposed by the form frmTellerHomeScreen, to obtain the totals (nr. 1 and 2) form the current day, and the previous day. - This is done by setting the end and start dates to the same day, effectively telling the class to only calculate the analytics for that one day } // Constructor constructor TAnalyticsCalculator.Create(sSelectedAccountID, sStartDate, sEndDate: string); begin fSelectedAccountID := sSelectedAccountID; fStartDate := fStartDate; fEndDate := sEndDate; BuildSQL; end; // Builds the SQL procedure TAnalyticsCalculator.BuildSQL; begin with dmDatabase do Begin // ShowMessage(sSelectedAccountID); qryTransactions.SQL.Clear; qryTransactions.SQL.Add('SELECT TT.AccountID, TT.DateOfTransaction'); qryTransactions.SQL.Add(', SUM(Quantity) AS [Number Of Items Sold]'); qryTransactions.SQL.Add( ' ,SUM(IT.Quantity * IT.UnitPrice) AS [Total For The Day] '); qryTransactions.SQL.Add('FROM Transactions TT, ItemTransactions IT'); qryTransactions.SQL.Add(' WHERE (AccountID = ' + QuotedStr (fSelectedAccountID) + ')'); qryTransactions.SQL.Add(' AND (DateOfTransaction BETWEEN ' + QuotedStr (fStartDate) + ' AND ' + QuotedStr(fEndDate) + ') '); qryTransactions.SQL.Add(' AND TT.TransID = IT.TransID '); qryTransactions.SQL.Add(' GROUP BY TT.DateOfTransaction, TT.AccountID '); qryTransactions.Open; iCount := 0; rTotalSales := 0; iTotalNumberOfItemsSold := 0; // Runs through the query and sums up the fields while NOT qryTransactions.Eof do begin Inc(iCount); rTotalSales := rTotalSales + qryTransactions['Total For The Day']; iTotalNumberOfItemsSold := iTotalNumberOfItemsSold + qryTransactions ['Number Of Items Sold']; qryTransactions.Next; end; qryTransactions.First; End; end; // 1.) Total value of the items sold function TAnalyticsCalculator.CalcTotalSales: real; begin if rTotalSales = 0 then Begin Result := 0; End Else Begin Result := rTotalSales; End; end; // 2.) Average value of the items sold for each day function TAnalyticsCalculator.CalcAverageSales: real; begin { If no sales where made on that day. Cannot divide by 0 for average. } if rTotalSales = 0 then Begin Result := 0; End Else Begin rAverageSalesValue := rTotalSales / iCount; Result := rAverageSalesValue; end; end; // 3.) Total number of items sold function TAnalyticsCalculator.CalcTotalItemsSold: integer; begin Result := iTotalNumberOfItemsSold; end; // 4.) Average number of items sold each day function TAnalyticsCalculator.CalcAverageItemsSold: integer; begin { If no sales where made on that day. Cannot divide by 0 for average. } if iTotalNumberOfItemsSold = 0 then Begin Result := 0; End Else Begin iAverageNumberOfItemsSold := Round(iTotalNumberOfItemsSold / iCount); Result := iAverageNumberOfItemsSold; End; end; end.
// // Generated by JavaToPas v1.5 20171018 - 171146 //////////////////////////////////////////////////////////////////////////////// unit java.nio.file.SimpleFileVisitor; interface uses AndroidAPI.JNIBridge, Androidapi.JNI.JavaTypes, java.nio.file.FileVisitResult, java.nio.file.attribute.BasicFileAttributes, java.io.IOException; type JSimpleFileVisitor = interface; JSimpleFileVisitorClass = interface(JObjectClass) ['{9CA7232E-799F-4FC6-B39A-56AA0539C4E9}'] function postVisitDirectory(dir : JObject; exc : JIOException) : JFileVisitResult; cdecl;// (Ljava/lang/Object;Ljava/io/IOException;)Ljava/nio/file/FileVisitResult; A: $1 function preVisitDirectory(dir : JObject; attrs : JBasicFileAttributes) : JFileVisitResult; cdecl;// (Ljava/lang/Object;Ljava/nio/file/attribute/BasicFileAttributes;)Ljava/nio/file/FileVisitResult; A: $1 function visitFile(&file : JObject; attrs : JBasicFileAttributes) : JFileVisitResult; cdecl;// (Ljava/lang/Object;Ljava/nio/file/attribute/BasicFileAttributes;)Ljava/nio/file/FileVisitResult; A: $1 function visitFileFailed(&file : JObject; exc : JIOException) : JFileVisitResult; cdecl;// (Ljava/lang/Object;Ljava/io/IOException;)Ljava/nio/file/FileVisitResult; A: $1 end; [JavaSignature('java/nio/file/SimpleFileVisitor')] JSimpleFileVisitor = interface(JObject) ['{5078892C-3CF8-4BB2-9331-9F6AFCBA4711}'] function postVisitDirectory(dir : JObject; exc : JIOException) : JFileVisitResult; cdecl;// (Ljava/lang/Object;Ljava/io/IOException;)Ljava/nio/file/FileVisitResult; A: $1 function preVisitDirectory(dir : JObject; attrs : JBasicFileAttributes) : JFileVisitResult; cdecl;// (Ljava/lang/Object;Ljava/nio/file/attribute/BasicFileAttributes;)Ljava/nio/file/FileVisitResult; A: $1 function visitFile(&file : JObject; attrs : JBasicFileAttributes) : JFileVisitResult; cdecl;// (Ljava/lang/Object;Ljava/nio/file/attribute/BasicFileAttributes;)Ljava/nio/file/FileVisitResult; A: $1 function visitFileFailed(&file : JObject; exc : JIOException) : JFileVisitResult; cdecl;// (Ljava/lang/Object;Ljava/io/IOException;)Ljava/nio/file/FileVisitResult; A: $1 end; TJSimpleFileVisitor = class(TJavaGenericImport<JSimpleFileVisitorClass, JSimpleFileVisitor>) end; implementation end.
{ publish with BSD Licence. Copyright (c) Terry Lao } unit anaFilters; {$MODE Delphi} interface uses iLBC_define,C2Delphi_header; {----------------------------------------------------------------* * LP analysis filter. *---------------------------------------------------------------} procedure anaFilter( nIn:pareal; { (i) Signal to be filtered } a:pareal; { (i) LP parameters } len:integer;{ (i) Length of signal } nOut:pareal; { (o) Filtered signal } mem:pareal { (i/o) Filter state } ); implementation procedure anaFilter( nIn:pareal; { (i) Signal to be filtered } a:pareal; { (i) LP parameters } len:integer;{ (i) Length of signal } nOut:pareal; { (o) Filtered signal } mem:pareal { (i/o) Filter state } ); var i,j:integer; po, pi, pm, pa:^real; begin po := @nOut[0]; { Filter first part using memory from past } for i:=0 to LPC_FILTERORDER-1 do begin pi:=@(nIn[i]); pm:=@(mem[LPC_FILTERORDER-1]); pa:=@a[0]; po^:=0.0; for j:=0 to i do begin po^:=po^+pa^*pi^; inc(pa); dec(pi); end; for j:=i+1 to LPC_FILTERORDER do begin po^:=po^+pa^*pm^; inc(pa); dec(pm) end; inc(po); end; { Filter last part where the state is entirely in the input vector } for i:=LPC_FILTERORDER to len-1 do begin pi:=@(nIn[i]); pa:=@a[0]; po^:=0.0; for j:=0 to LPC_FILTERORDER do begin po^:=po^+pa^*pi^; inc(pa); dec(pi); end; inc(po); end; { Update state vector } Move( nIn[len-LPC_FILTERORDER],mem[0], LPC_FILTERORDER*sizeof(real)); end; end.
unit MVVM.Services.Platform.FMX; interface uses FMX.Platform, System.Classes, System.SysUtils, System.UITypes, System.Diagnostics, System.TimeSpan, MVVM.Interfaces; type TFMXPlatformServices = class(TPlatformServicesBase) private class var Reference: TStopwatch; protected class constructor CreateC; class destructor DestroyC; public function CreatePlatformEmptyForm: TComponent; override; procedure AssignParent(AChild, AParent: TComponent); override; function MessageDlg(const ATitulo: string; const ATexto: String): Boolean; override; procedure ShowFormView(AComponent: TComponent); override; procedure ShowModalFormView(AComponent: TComponent; const AResultProc: TProc<TModalResult>); override; function IsMainThreadUI: Boolean; override; function LoadBitmap(const AFileName: String): TObject; overload; override; function LoadBitmap(const AStream: TStream): TObject; overload; override; function LoadBitmap(const AData: TBytes): TObject; overload; override; function LoadBitmap(const AMemory: Pointer; const ASize: Integer): TObject; overload; override; function ElapsedMiliseconds: Int64; override; function ElapsedTicks: Int64; override; function GetTimeStamp: Int64; override; function Elapsed: TTimeSpan; override; function GetReferenceTime: Double; override; end; procedure InitializePlatform; implementation uses FMX.Forms, FMX.Controls, FMX.Dialogs, FMX.Graphics, MVVM.Core; { TFMXServicioDialogo } procedure TFMXPlatformServices.AssignParent(AChild, AParent: TComponent); begin if AParent is TForm then TControl(AChild).Parent := TForm(AParent) else TControl(AChild).Parent := TControl(AParent) end; class constructor TFMXPlatformServices.CreateC; begin Reference := TStopwatch.Create; Reference.Start; end; function TFMXPlatformServices.CreatePlatformEmptyForm: TComponent; begin Result := TForm.Create(nil); end; class destructor TFMXPlatformServices.DestroyC; begin // end; function TFMXPlatformServices.Elapsed: TTimeSpan; begin Result := Reference.Elapsed; end; function TFMXPlatformServices.ElapsedTicks: Int64; begin Result := Reference.ElapsedTicks; end; function TFMXPlatformServices.ElapsedMiliseconds: Int64; begin Result := Reference.ElapsedMilliseconds; end; function TFMXPlatformServices.GetReferenceTime: Double; begin Result := TStopwatch.GetTimeStamp / TStopwatch.Frequency; end; function TFMXPlatformServices.GetTimeStamp: Int64; begin Result := Reference.GetTimeStamp end; function TFMXPlatformServices.IsMainThreadUI: Boolean; begin Result := TThread.Current.ThreadID = MainThreadID; end; function TFMXPlatformServices.LoadBitmap(const AFileName: String): TObject; var Stream: TFileStream; begin Stream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite); try Result := TBitmap.CreateFromStream(Stream); finally Stream.Free; end; end; function TFMXPlatformServices.LoadBitmap(const AStream: TStream): TObject; begin Result := TBitmap.CreateFromStream(AStream); end; function TFMXPlatformServices.LoadBitmap(const AData: TBytes): TObject; var Stream: TBytesStream; begin Stream := TBytesStream.Create(AData); try Result := TBitmap.CreateFromStream(Stream); finally Stream.Free; end; end; function TFMXPlatformServices.LoadBitmap(const AMemory: Pointer; const ASize: Integer): TObject; var Stream: TMemoryStream; begin Stream := TMemoryStream.Create; try Stream.WriteBuffer(AMemory^, ASize); Stream.Position := 0; Result := TBitmap.CreateFromStream(Stream); finally Stream.Free; end; end; function TFMXPlatformServices.MessageDlg(const ATitulo, ATexto: String): Boolean; begin Result := FMX.Dialogs.MessageDlg(ATitulo, TMsgDlgType.mtConfirmation, [TMsgDlgBtn.mbYes, TMsgDlgBtn.mbNo], 0) = mrYes end; procedure TFMXPlatformServices.ShowFormView(AComponent: TComponent); begin if not (AComponent.InheritsFrom(TForm)) then raise Exception.Create('The component ' + AComponent.QualifiedClassName + ' must inherit from TForm'); TForm(AComponent).Show; end; procedure TFMXPlatformServices.ShowModalFormView(AComponent: TComponent; const AResultProc: TProc<TModalResult>); begin TForm(AComponent).ShowModal(AResultProc); end; procedure InitializePlatform; begin; end; initialization MVVMCore.RegisterPlatformServices(TFMXPlatformServices); end.
{**************************************************************************************} { } { CCR Exif - Delphi class library for reading and writing image metadata } { Version 1.5.2 beta } { } { The contents of this file are subject to the Mozilla Public License Version 1.1 } { (the "License"); you may not use this file except in compliance with the License. } { You may obtain a copy of the License at http://www.mozilla.org/MPL/ } { } { Software distributed under the License is distributed on an "AS IS" basis, WITHOUT } { WARRANTY OF ANY KIND, either express or implied. See the License for the specific } { language governing rights and limitations under the License. } { } { The Original Code is CCR.Exif.TagIDs.pas. } { } { The Initial Developer of the Original Code is Chris Rolliston. Portions created by } { Chris Rolliston are Copyright (C) 2009-2012 Chris Rolliston. All Rights Reserved. } { } {**************************************************************************************} unit CCR.Exif.TagIDs; interface const { TIFF/Exif main directory tags } ttImageDescription = $010E; ttMake = $010F; ttModel = $0110; ttOrientation = $0112; ttXResolution = $011A; ttYResolution = $011B; ttResolutionUnit = $0128; ttSoftware = $0131; ttDateTime = $0132; ttArtist = $013B; ttWhitePoint = $013E; ttPrimaryChromaticities = $013F; ttYCbCrCoefficients = $0211; ttYCbCrPositioning = $0213; ttReferenceBlackWhite = $0214; ttXMP = $02BC; //should be tdByte according to the XMP spec, with the packet itself UTF-8 encoded ttCopyright = $8298; ttIPTC = $83BB; ttExifOffset = $8769; ttGPSOffset = $8825; ttPrintIM = $C4A5; { Additional Exif main directory tags supported by Windows Explorer - for all but ttWindowsRating, the data type is tdByte and the content null-terminated UTF16LE, even when the Exif block as a whole is big endian. } ttWindowsTitle = $9C9B; ttWindowsComments = $9C9C; ttWindowsAuthor = $9C9D; //Vista's Windows Explorer will check for ttArtist too, though only sets this ttWindowsKeywords = $9C9E; //'Tags' in the UI ttWindowsSubject = $9C9F; ttWindowsRating = $4746; //word value, despite being out of 5 { Padding tag patented (!) by MS (http://www.freepatentsonline.com/7421451.html) } ttWindowsPadding = $EA1C; { Exif sub-directory tags } ttExposureTime = $829A; ttFNumber = $829D; ttExposureProgram = $8822; //1 = manual, 2 = normal, 3 = aperture priority, 4 = shutter priority, 5 = creative, 6 = action, 7 = portrait mode, 8 = landscape mode ttSpectralSensitivity = $8824; ttISOSpeedRatings = $8827; ttExifVersion = $9000; ttDateTimeOriginal = $9003; ttDateTimeDigitized = $9004; ttComponentsConfiguration = $9101; ttCompressedBitsPerPixel = $9102; ttShutterSpeedValue = $9201; ttApertureValue = $9202; ttBrightnessValue = $9203; ttExposureBiasValue = $9204; ttMaxApertureValue = $9205; ttSubjectDistance = $9206; ttMeteringMode = $9207; ttLightSource = $9208; ttFlash = $9209; //0 = didn't fire, 1 = fired, 2 = fired but strobe return light not detected, 7 = flash fired and strobe return light detected ttFocalLength = $920A; //in millimetres ttSubjectArea = $9214; ttMakerNote = $927C; ttUserComment = $9286; ttSubsecTime = $9290; ttSubsecTimeOriginal = $9291; ttSubsecTimeDigitized = $9292; ttFlashPixVersion = $A000; ttColorSpace = $A001; ttExifImageWidth = $A002; ttExifImageHeight = $A003; ttRelatedSoundFile = $A004; ttInteropOffset = $A005; ttFlashEnergy = $A20B; ttSpatialFrequencyResponse = $A20C; ttFocalPlaneXResolution = $A20E; ttFocalPlaneYResolution = $A20F; ttFocalPlaneResolutionUnit = $A210; ttSubjectLocation = $A214; ttExposureIndex = $A215; ttSensingMethod = $A217; ttFileSource = $A300; //$03 = digital still camera ttSceneType = $A301; //$01 = directly photographed ttCFAPattern = $A302; ttCustomRendered = $A401; ttExposureMode = $A402; ttWhiteBalance = $A403; ttDigitalZoomRatio = $A404; ttFocalLengthIn35mmFilm = $A405; ttSceneCaptureType = $A406; ttGainControl = $A407; ttContrast = $A408; ttSaturation = $A409; ttSharpness = $A40A; ttDeviceSettingDescription = $A40B; ttSubjectDistanceRange = $A40C; ttImageUniqueID = $A420; ttCameraOwnerName = $A430; ttBodySerialNumber = $A431; ttLensSpecification = $A432; ttLensMake = $A433; ttLensModel = $A434; ttLensSerialNumber = $A435; { MakerNote tag data offset relative to where it originally was; tag defined by MS } ttOffsetSchema = $EA1D; { Exif interoperability sub-directory tags } ttInteropIndex = $0001; ttInteropVersion = $0002; ttRelatedImageFileFormat = $1000; ttRelatedImageWidth = $1001; ttRelatedImageLength = $1002; { GPS sub-directory tags } ttGPSVersionID = $0000; ttGPSLatitudeRef = $0001; ttGPSLatitude = $0002; ttGPSLongitudeRef = $0003; ttGPSLongitude = $0004; ttGPSAltitudeRef = $0005; ttGPSAltitude = $0006; ttGPSTimeStamp = $0007; ttGPSSatellites = $0008; ttGPSStatus = $0009; ttGPSMeasureMode = $000A; ttGPSDOP = $000B; ttGPSSpeedRef = $000C; ttGPSSpeed = $000D; ttGPSTrackRef = $000E; ttGPSTrack = $000F; ttGPSImgDirectionRef = $0010; ttGPSImgDirection = $0011; ttGPSMapDatum = $0012; ttGPSDestLatitudeRef = $0013; ttGPSDestLatitude = $0014; ttGPSDestLongitudeRef = $0015; ttGPSDestLongitude = $0016; ttGPSDestBearingRef = $0017; ttGPSDestBearing = $0018; ttGPSDestDistanceRef = $0019; ttGPSDestDistance = $001A; ttGPSProcessingMethod = $001B; ttGPSAreaInformation = $001C; ttGPSDateStamp = $001D; ttGPSDifferential = $001E; { Exif thumbnail directory tags } ttImageWidth = $0100; //shouldn't be used for a JPEG thumbnail ttImageHeight = $0101; //shouldn't be used for a JPEG thumbnail ttBitsPerSample = $0102; //shouldn't be used for a JPEG thumbnail ttCompression = $0103; //value should be 6 for JPEG (1 = uncompressed TIFF ttPhotometricInterp = $0106; //1=b/w, 2 = RGB, 6 = YCbCr; shouldn't be used for a JPEG thumbnail ttStripOffsets = $0111; //for when thumbnail is a TIFF ttSamplesPerPixel = $0115; //shouldn't be used for a JPEG thumbnail ttRowsPerStrip = $0116; //shouldn't be used for a JPEG thumbnail ttStripByteCounts = $0117; //for when thumbnail is a TIFF ttPlanarConfiguration = $011C; //shouldn't be used for a JPEG thumbnail ttTileOffsets = $0144; //shouldn't be used for a JPEG thumbnail ttTileByteCounts = $0145; //shouldn't be used for a JPEG thumbnail ttJPEGProc = $0200; //for old-style TIFF-JPEG ttJPEGIFOffset = $0201; ttJPEGIFByteCount = $0202; ttThumbnailOffset = ttJPEGIFOffset; ttThumbnailSize = ttJPEGIFByteCount; { Cannon MakerNote tags } ttCanonCameraSettings = $0001; ttCanonFocalLength = $0002; ttCanonFlashInfo = $0003; ttCanonShotInfo = $0004; ttCanonPanorama = $0005; ttCanonImageType = $0006; //tdAscii ttCanonFirmwareVersion = $0007; //tdAscii ttCanonFileNumber = $0008; //tdLongWord ttCanonOwnerName = $0009; //tdAscii ttCanonSerialNumber = $000C; //tdLongWord ttCanonCameraInfo = $000D; ttCanonFileLength = $000E; //tdLongWord ttCanonFunctions = $000F; ttCanonModelID = $0010; //tdLongWord ttCanonAFInfo = $0012; ttCanonValidThumbnailArea = $0013; //tdWord x 4; all zeros for full frame ttCanonSerialNumberFormat = $0015; //tdLongWord ttCanonSuperMacro = $001A; //tdWord (0 = off, 1 = on (1) 2 = on (2) ttCanonDateStampMode = $001C; //tdWord (0 = off, 1 = date, 2 = date and time ttCanonMyColors = $001D; ttCanonFirmwareRevision = $001E; //tdLongWord ttCanonCategories = $0023; //tdLongWord x 2 (first value always 8) { Kodak MakerNote tags } ttKodakImageWidth = $0005; ttKodakYear = $0006; { Nikon Type 3 MakerNote tags } ttNikonType3Version = $0001; ttNikonType3ISOSpeed = $0002; ttNikonType3ColorMode = $0003; ttNikonType3Quality = $0004; ttNikonType3WhiteBalance = $0005; ttNikonType3Sharpening = $0006; ttNikonType3FocusMode = $0007; ttNikonType3FlashSetting = $0008; ttNikonType3AutoFlashMode = $0009; ttNikonType3MiscRatio = $000A; ttNikonType3WhiteBalanceBias = $000B; ttNikonType3WB_RBLevels = $000C; ttNikonType3ProgramShift = $000D; ttNikonType3ExposureDiff = $000E; ttNikonType3ISOSelection = $000F; ttNikonType3DataDump = $0010; ttNikonType3Preview = $0011; ttNikonType3FlashComp = $0012; ttNikonType3ISOSettings = $0013; ttNikonType3ImageBoundary = $0016; ttNikonType3FlashExposureComp = $0017; ttNikonType3FlashBracketComp = $0018; ttNikonType3AutoExposureBracketComp = $0019; ttNikonType3ImageProcessing = $001A; ttNikonType3CropHiSpeed = $001B; ttNikonType3ExposureTuning = $001C; ttNikonType3SerialNumber = $001D; ttNikonType3ColorSpace = $001E; ttNikonType3VRInfo = $001F; ttNikonType3ImageAuthentication = $0020; ttNikonType3ActiveDLighting = $0022; ttNikonType3PictureControl = $0023; ttNikonType3WorldTime = $0024; ttNikonType3ISOInfo = $0025; ttNikonType3VignetteControl = $002A; ttNikonType3ImageAdjustment = $0080; ttNikonType3ToneComp = $0081; ttNikonType3AuxiliaryLens = $0082; ttNikonType3LensType = $0083; ttNikonType3Lens = $0084; ttNikonType3FocusDistance = $0085; ttNikonType3DigitalZoom = $0086; ttNikonType3FlashMode = $0087; ttNikonType3AFInfo = $0088; ttNikonType3ShootingMode = $0089; ttNikonType3AutoBracketRelease = $008A; ttNikonType3LensFStops = $008B; ttNikonType3ContrastCurve = $008C; ttNikonType3ColorHue = $008D; ttNikonType3SceneMode = $008F; ttNikonType3LightSource = $0090; ttNikonType3ShotInfo = $0091; ttNikonType3HueAdjustment = $0092; ttNikonType3NEFCompression = $0093; ttNikonType3Saturation = $0094; ttNikonType3NoiseReduction = $0095; ttNikonType3LinearizationTable = $0096; ttNikonType3ColorBalance = $0097; ttNikonType3LensData = $0098; ttNikonType3RawImageCenter = $0099; ttNikonType3SensorPixelSize = $009A; ttNikonType3SceneAssist = $009C; ttNikonType3RetouchHistory = $009E; ttNikonType3CameraSerialNumber = $00A0; ttNikonType3ImageDataSize = $00A2; ttNikonType3ImageCount = $00A5; ttNikonType3DeletedImageCount = $00A6; ttNikonType3ShutterCount = $00A7; ttNikonType3FlashInfo = $00A8; ttNikonType3ImageOptimization = $00A9; ttNikonType3SaturationText = $00AA; ttNikonType3DigitalVarProg = $00AB; ttNikonType3ImageStabilization = $00AC; ttNikonType3AFResponse = $00AD; ttNikonType3MultiExposure = $00B0; ttNikonType3HighISONoiseReduction = $00B1; ttNikonType3ToningEffect = $00B3; ttNikonType3AFInfo2 = $00B7; ttNikonType3FileInfo = $00B8; ttNikonType3PrintIM = $0E00; ttNikonType3CaptureData = $0E01; ttNikonType3CaptureVersion = $0E09; ttNikonType3CaptureOffsets = $0E0E; ttNikonType3ScanIFD = $0E10; ttNikonType3ICCProfile = $0E1D; ttNikonType3CaptureOutput = $0E1E; ttNikonType3First = ttNikonType3Version; ttNikonType3Last = ttNikonType3CaptureOutput; { Panasonic MakerNote tags } ttPanasonicImageQuality = $0001; ttPanasonicFirmwareVersion = $0002; ttPanasonicWhiteBalance = $0003; ttPanasonicFocusMode = $0007; ttPanasonicSpotMode = $000F; ttPanasonicImageStabilizer = $001A; ttPanasonicMacroMode = $001C; ttPanasonicShootingMode = $001F; ttPanasonicAudio = $0020; ttPanasonicDataDump = $0021; ttPanasonicWhiteBalanceBias = $0023; ttPanasonicFlashBias = $0024; ttPanasonicInternalSerialNum = $0025; ttPanasonicExifVersion = $0026; ttPanasonicColorEffect = $0028; ttPanasonicTimeSincePowerOn = $0029; ttPanasonicBurstMode = $002A; ttPanasonicSequenceNumber = $002B; ttPanasonicContrastMode = $002C; ttPanasonicNoiseReduction = $002D; ttPanasonicSelfTimer = $002E; ttPanasonicRotation = $0030; ttPanasonicAFAssistLamp = $0031; ttPanasonicColorMode = $0032; ttPanasonicBabyOrPetAge1 = $0033; ttPanasonicOpticalZoomMode = $0034; ttPanasonicConversionLens = $0035; ttPanasonicTravelDay = $0036; ttPanasonicWorldTimeLocation = $003A; ttPanasonicTextStamp1 = $003B; ttPanasonicProgramISO = $003C; ttPanasonicSaturation = $0040; ttPanasonicSharpness = $0041; ttPanasonicFilmMode = $0042; ttPanasonicWBAdjustAB = $0046; ttPanasonicWBAdjustGM = $0047; ttPanasonicLensType = $0051; ttPanasonicLensSerialNumber = $0052; ttPanasonicAccessoryType = $0053; ttPanasonicMakerNoteVersion = $8000; ttPanasonicSceneMode = $8001; ttPanasonicWBRedLevel = $8004; ttPanasonicWBGreenLevel = $8005; ttPanasonicWBBlueLevel = $8006; ttPanasonicTextStamp2 = $8008; ttPanasonicTextStamp3 = $8009; ttPanasonicBabyOrPetAge2 = $8010; { IPTC record IDs } isEnvelope = 1; isApplication = 2; { IPTC record 1 tags } itModelVersion = 0; itDestination = 5; itFileFormat = 20; itFileFormatVersion = 22; itServiceIdentifier = 30; itEnvelopeNumber = 40; itProductID = 50; itEnvelopePriority = 60; //1=most urgent, 5=normal, 8=least, 9=user defined itDateSent = 70; //CCYYMMDD itTimeSent = 80; //HHMMSS±HHMM itCodedCharset = 90; itUNO = 100; itARMIdentifier = 120; itARMVersion = 122; { IPTC record 2 tags } itRecordVersion = 0; //word value; should be 4 itObjectTypeRef = 3; itObjectAttributeRef = 4; //repeatable itObjectName = 5; //e.g. 'Ferry Sinks' (nice and blunt then...) itEditStatus = 7; //e.g. 'Lead', 'CORRECTION' itEditorialUpdate = 8; itUrgency = 10; itSubjectRef = 12; //repeatable itCategory = 15; itSupplementaryCategory = 20; //repeatable itFixtureIdentifier = 22; itKeyword = 25; //repeatable (one keyword per instance) itContentLocationCode = 26; //repeatable with the next tag as a pair itContentLocationName = 27; //repeatable with the previous tag as a pair itReleaseDate = 30; //CCYYMMDD itReleaseTime = 35; //HHMMSS±HHMM itExpirationDate = 37; //CCYYMMDD itExpirationTime = 38; //HHMMSS±HHMM itSpecialInstructions = 40; itActionAdvised = 42; //'01', '02', '03' or '04'; itReferenceService = 45; //repeatable with next two tags in sequence itReferenceDate = 47; itReferenceNumber = 50; itDateCreated = 55; //CCYYMMDD; 'to designate the date the intellectual content of the objectdata was created rather than the date of the creation of the physical representation' (IPTC spec) itTimeCreated = 60; //HHMMSS±HHMM itDigitalCreationDate = 62; //CCYYMMDD itDigitalCreationTime = 63; //HHMMSS±HHMM itOriginatingProgram = 65; itProgramVersion = 70; //string itObjectCycle = 75; //'a'=morning, 'p'=evening, 'b'=both itByline = 80; //repeatable itBylineTitle = 85; //e.g. 'Staff Photographer'; repeatable itCity = 90; itSubLocation = 92; itProvinceOrState = 95; itCountryCode = 100; //three-letter code itCountryName = 101; //three-letter code itOriginalTransmissionRef = 103; itHeadline = 105; itCredit = 110; itSource = 115; itCopyrightNotice = 116; itContact = 118; //repeatable itCaptionOrAbstract = 120; itWriterOrEditor = 122; //repeatable itRasterizedCaption = 125; //binary itImageType = 130; //two character code itImageOrientation = 131; //'P' = portrait, 'L' = landscape, 'S' = sqaure itLanguageIdentifier = 135; //2 or 3 character code itAudioType = 150; //2 character code itAudioSamplingRate = 151; //six digit string of numbers (includes leading zero) itAudioSamplingResolution = 152; //e.g. '08' for 8 bit, '24' for 24 bit itAudioDuration = 153; //HHMMSS itAudioAutocue = 154; //e.g. '... better as a team', 'fades', '...Jean Krause Paris' itObjectDataPreviewFileFormat = 200; //binary word number itObjectDataPreviewFileFormatVersion = 201; //binary word number itObjectDataPreviewData = 202; { IPTC record 7 tags } itSizeMode = 10; itMaxSubFileSize = 20; itObjectDataSizeAnnounced = 90; itMaxObjectDataSize = 95; { IPTC record 8 tags } itSubfile = 10; { IPTC record 9 tags } itConfirmedObjectDataSize = 10; implementation end.
unit Sp_Privileges_Zarplata; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, cxLookAndFeels, dxBar, dxBarExtItems, SpPrivilegesZarplataControl, ActnList, Ztypes, FIBQuery, pFIBQuery, pFIBStoredProc, FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet, IBase, ZProc, Kernel, cxTextEdit, cxCalendar, Unit_ZGlobal_Consts, dxStatusBar, zMessages; type TFZ_Sp_Privileges = class(TForm) Grid: TcxGrid; GridDBTableView1: TcxGridDBTableView; GridClKod: TcxGridDBColumn; GridClName: TcxGridDBColumn; GridClMin: TcxGridDBColumn; GridClMax: TcxGridDBColumn; GridClKoefficient: TcxGridDBColumn; GridClDateBeg: TcxGridDBColumn; GridClDateEnd: TcxGridDBColumn; GridLevel1: TcxGridLevel; BarManager: TdxBarManager; UpdateBtn: TdxBarLargeButton; DeleteBtn: TdxBarLargeButton; SelectBtn: TdxBarLargeButton; RefreshBtn: TdxBarLargeButton; InsertBtn: TdxBarLargeButton; ExitBtn: TdxBarLargeButton; DSource: TDataSource; DB: TpFIBDatabase; DSet: TpFIBDataSet; ReadTransaction: TpFIBTransaction; WriteTransaction: TpFIBTransaction; StoredProc: TpFIBStoredProc; StatusBar: TdxStatusBar; DetailBtn: TdxBarLargeButton; Styles: 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; GridTableViewStyleSheetDevExpress: TcxGridTableViewStyleSheet; GridClKodPriv1DF: TcxGridDBColumn; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure InsertBtnClick(Sender: TObject); procedure RefreshBtnClick(Sender: TObject); procedure ExitBtnClick(Sender: TObject); procedure UpdateBtnClick(Sender: TObject); procedure DeleteBtnClick(Sender: TObject); procedure SelectBtnClick(Sender: TObject); procedure GridDBTableView1CustomDrawCell( Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean); procedure GridDBTableView1FocusedRecordChanged( Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); procedure ButtonsUpdate(Sender:TObject); procedure FormCreate(Sender: TObject); procedure GridDBTableView1DblClick(Sender: TObject); procedure FormResize(Sender: TObject); procedure DetailBtnClick(Sender: TObject); private Ins_Resault: Variant; Ins_ZFormStyle:TZFormStyle; PLanguageIndex:byte; public constructor Create(ComeComponent:TComponent;ComeDB:TISC_DB_HANDLE;ComeFormStyle:TZFormStyle=zfsChild);reintroduce; property ZFormStyle:TZFormStyle read Ins_ZFormStyle; property Resault:Variant read Ins_Resault; end; function View_FZ_Privileges_Sp(AOwner : TComponent;DB:TISC_DB_HANDLE;ComeFormStyle:TZFormStyle):Variant;stdcall; exports View_FZ_Privileges_Sp; implementation uses Math; {$R *.dfm} function View_FZ_Privileges_Sp(AOwner : TComponent;DB:TISC_DB_HANDLE;ComeFormStyle:TZFormStyle):Variant; var ViewForm: TFZ_Sp_Privileges; Res:Variant; begin case ComeFormStyle of zfsChild: begin if not IsMDIChildFormShow(TFZ_Sp_Privileges) then ViewForm := TFZ_Sp_Privileges.Create(AOwner, DB, zfsChild); res :=NULL; end; zfsNormal: begin ViewForm := TFZ_Sp_Privileges.Create(AOwner, DB, zfsNormal); ViewForm.ShowModal; res:=NULL; ViewForm.Free; end; zfsModal: begin ViewForm := TFZ_Sp_Privileges.Create(AOwner, DB, zfsModal); ViewForm.ShowModal; if (ViewForm.ModalResult=mrOk) then res:=ViewForm.Resault else res:=NULL; ViewForm.Free; end; end; View_FZ_Privileges_Sp:=res; end; constructor TFZ_Sp_Privileges.Create(ComeComponent:TComponent;ComeDB:TISC_DB_HANDLE;ComeFormStyle:TZFormStyle=zfsChild); begin inherited Create(ComeComponent); PLanguageIndex:=LanguageIndex; self.Caption := ZSp_Privilege_Caption[PLanguageIndex]; case ComeFormStyle of zfsModal: begin self.FormStyle := fsNormal; self.BorderStyle := bsDialog; self.SelectBtn.Visible := ivAlways; self.InsertBtn.Visible := ivNever; self.UpdateBtn.Visible := ivNever; self.DeleteBtn.Visible := ivNever; self.DetailBtn.Visible := ivNever; self.Position := poOwnerFormCenter; StatusBar.Panels[0].Text := SelectBtn_Hint[PLanguageIndex]; StatusBar.Panels[1].Text := RefreshBtn_Hint[PLanguageIndex]; StatusBar.Panels[2].Text := ExitBtn_Hint[PLanguageIndex]; StatusBar.Panels[5].Destroy; StatusBar.Panels[4].Destroy; StatusBar.Panels[3].Destroy; end; zfsChild: begin self.FormStyle := fsMDIChild; self.BorderStyle := bsSizeable; self.SelectBtn.Visible := ivNever; self.Position := poMainFormCenter; StatusBar.Panels[0].Text := InsertBtn_Hint[PLanguageIndex]; StatusBar.Panels[1].Text := UpdateBtn_Hint[PLanguageIndex]; StatusBar.Panels[2].Text := DeleteBtn_Hint[PLanguageIndex]; StatusBar.Panels[3].Text := DetailBtn_Hint[PLanguageIndex]; StatusBar.Panels[4].Text := RefreshBtn_Hint[PLanguageIndex]; StatusBar.Panels[5].Text := ExitBtn_Hint[PLanguageIndex]; end; zfsNormal: begin self.FormStyle := fsNormal; self.BorderStyle := bsDialog; self.SelectBtn.Visible := ivNever; self.Position := poOwnerFormCenter; StatusBar.Panels[0].Text := InsertBtn_Hint[PLanguageIndex]; StatusBar.Panels[1].Text := UpdateBtn_Hint[PLanguageIndex]; StatusBar.Panels[2].Text := DeleteBtn_Hint[PLanguageIndex]; StatusBar.Panels[3].Text := DetailBtn_Hint[PLanguageIndex]; StatusBar.Panels[4].Text := RefreshBtn_Hint[PLanguageIndex]; StatusBar.Panels[5].Text := ExitBtn_Hint[PLanguageIndex]; end; end; Ins_ZFormStyle:=ComeFormStyle; Ins_Resault := VarArrayCreate([0,7],varVariant); DB.Handle := ComeDB; self.InsertBtn.Caption := InsertBtn_Caption[PLanguageIndex]; self.UpdateBtn.Caption := UpdateBtn_Caption[PLanguageIndex]; self.DeleteBtn.Caption := DeleteBtn_Caption[PLanguageIndex]; self.DetailBtn.Caption := DetailBtn_Caption[PLanguageIndex]; self.RefreshBtn.Caption := 'Відновити'; //RefreshBtn_Caption[PLanguageIndex]; self.SelectBtn.Caption := SelectBtn_Caption[PLanguageIndex]; self.ExitBtn.Caption := ExitBtn_Caption[PLanguageIndex]; self.GridClKod.DataBinding.FieldName := 'KOD_PRIV'; self.GridClName.DataBinding.FieldName := 'NAME_PRIV'; self.GridClMin.DataBinding.FieldName := 'MIN_AMOUNT_PRIV'; self.GridClMax.DataBinding.FieldName := 'MAX_AMOUNT_PRIV'; self.GridClKoefficient.DataBinding.FieldName := 'KOEFFICIENT_PRIV'; self.GridClDateBeg.DataBinding.FieldName := 'DATE_BEG'; self.GridClDateEnd.DataBinding.FieldName := 'DATE_END'; self.GridClKodPriv1DF.DataBinding.FieldName := 'KOD_PRIV_1DF'; self.GridClKod.Caption := GridClKod_Caption[PLanguageIndex]; self.GridClName.Caption := GridClName_Caption[PLanguageIndex]; self.GridClMin.Caption := GridClMinAmount_Caption[PLanguageIndex]; self.GridClMax.Caption := GridClMaxAmount_Caption[PLanguageIndex]; self.GridClKoefficient.Caption := GridClKoefficicent_Caption[PLanguageIndex]; self.GridClDateBeg.Caption := GridClBegPeriod_Caption[PLanguageIndex]; self.GridClDateEnd.Caption := GridClEndPeriod_Caption[PLanguageIndex]; self.GridClKodPriv1DF.Caption := GridClKod1DF_Caption[PLanguageIndex]; GridDBTableView1.DataController.DataSource := DSource; DSet.SQLs.SelectSQL.Text := 'SELECT * FROM Z_SP_PRIVILEGES_SELECT'; DSet.Open; FormResize(Self); end; procedure TFZ_Sp_Privileges.FormClose(Sender: TObject; var Action: TCloseAction); begin ReadTransaction.Commit; Action:=caFree; end; procedure TFZ_Sp_Privileges.InsertBtnClick(Sender: TObject); var InsertForm:TFormSp_PrivilegesControl; Id_Priv:Integer; begin InsertForm := TFormSp_PrivilegesControl.Create(self); InsertForm.Caption := ZSp_Privilege_Caption_Insert[PLanguageIndex]; InsertForm.DateEnd.Date := StrToDate('31.12.2050'); InsertForm.DateEnd.Enabled:=False; InsertForm.ShowModal; If InsertForm.ModalResult=mrYes then try StoredProc.Database := DB; StoredProc.Transaction := WriteTransaction; StoredProc.Transaction.StartTransaction; StoredProc.StoredProcName := 'Z_SP_PRIVILEGES_INSERT'; StoredProc.Prepare; StoredProc.ParamByName('KOD_PRIV').AsInteger := StrToInt(InsertForm.KodEdit.Text); StoredProc.ParamByName('NAME_PRIV').AsString := InsertForm.NameEdit.Text; StoredProc.ParamByName('MIN_AMOUNT_PRIV').AsInteger := StrToInt(InsertForm.MinSpinEdit.Text); StoredProc.ParamByName('MAX_AMOUNT_PRIV').AsInteger := StrToInt(InsertForm.MaxSpinEdit.Text); StoredProc.ParamByName('KOEFFICIENT_PRIV').AsFloat := StrToFloat(InsertForm.KoefficientEdit.Text); StoredProc.ParamByName('DATE_BEG').AsDate := InsertForm.DateBeg.Date; StoredProc.ParamByName('DATE_END').AsDate := InsertForm.DateEnd.Date; StoredProc.ParamByName('KOD_PRIV_1DF').AsInteger := StrToInt(InsertForm.MaskEditKodPriv1DF.Text); StoredProc.ExecProc; Id_Priv:=StoredProc.ParamByName('ID_PRIV').AsInteger; WriteTransaction.Commit; DSet.CloseOpen(True); DSet.Locate('ID_PRIV',Id_Priv,[loCaseInsensitive,loPartialKey]); except on E: Exception do begin ZShowMessage(Error_Caption[PLanguageIndex],E.Message,mtError,[mbOK]); WriteTransaction.Rollback; end; end; InsertForm.Free; end; procedure TFZ_Sp_Privileges.RefreshBtnClick(Sender: TObject); begin DataSetCloseOpen(DSet, 'ID_PRIV'); end; procedure TFZ_Sp_Privileges.ExitBtnClick(Sender: TObject); begin if Ins_ZFormStyle=zfsModal then ModalResult:=mrNo else Close; end; procedure TFZ_Sp_Privileges.UpdateBtnClick(Sender: TObject); var UpdateForm:TFormSp_PrivilegesControl; RecInfo:RECORD_INFO_STRUCTURE; // ResultInfo:RESULT_STRUCTURE; begin try StoredProc.Database := DB; StoredProc.Transaction := WriteTransaction; StoredProc.Transaction.StartTransaction; RecInfo.TRHANDLE := WriteTransaction.Handle; RecInfo.DBHANDLE := DB.Handle; RecInfo.ID_RECORD := VarArrayOf([DSet.FieldValues['ID_PRIV']]); RecInfo.PK_FIELD_NAME := VarArrayOf(['ID_PRIV']); RecInfo.TABLE_NAME := 'Z_SP_PRIVILEGES'; RecInfo.RAISE_FLAG := True; LockRecord(@RecInfo); UpdateForm := TFormSp_PrivilegesControl.Create(self); UpdateForm.Caption := ZSp_Privilege_Caption_Update[PLanguageIndex]; UpdateForm.KodEdit.Text := IntToStr(DSet.FieldValues['KOD_PRIV']); UpdateForm.NameEdit.Text := DSet.FieldValues['NAME_PRIV']; UpdateForm.KoefficientEdit.Text := DSet.FieldValues['KOEFFICIENT_PRIV']; UpdateForm.MinSpinEdit.Value := DSet.FieldValues['MIN_AMOUNT_PRIV']; UpdateForm.MaxSpinEdit.Value := DSet.FieldValues['MAX_AMOUNT_PRIV']; UpdateForm.DateBeg.Date := DSet.FieldValues['DATE_BEG']; UpdateForm.DateEnd.Date := DSet.FieldValues['DATE_END']; UpdateForm.MaskEditKodPriv1DF.Text:= IntToStr(DSet.FieldValues['KOD_PRIV_1DF']); UpdateForm.DateEnd.Enabled := False; UpdateForm.ShowModal; If UpdateForm.ModalResult=mrYes then begin StoredProc.Database := DB; StoredProc.Transaction := WriteTransaction; StoredProc.Transaction.StartTransaction; StoredProc.StoredProcName := 'Z_SP_PRIVILEGES_UPDATE'; StoredProc.Prepare; StoredProc.ParamByName('ID_PRIV').AsInteger := DSet.FieldValues['ID_PRIV']; StoredProc.ParamByName('KOD_PRIV').AsInteger := StrToInt(UpdateForm.KodEdit.Text); StoredProc.ParamByName('NAME_PRIV').AsString := UpdateForm.NameEdit.Text; StoredProc.ParamByName('MIN_AMOUNT_PRIV').AsInteger := StrToInt(UpdateForm.MinSpinEdit.Text); StoredProc.ParamByName('MAX_AMOUNT_PRIV').AsInteger := StrToInt(UpdateForm.MaxSpinEdit.Text); StoredProc.ParamByName('KOEFFICIENT_PRIV').AsFloat := StrToFloat(UpdateForm.KoefficientEdit.Text); StoredProc.ParamByName('DATE_BEG').AsDate := UpdateForm.DateBeg.Date; StoredProc.ParamByName('DATE_END').AsDate := UpdateForm.DateEnd.Date; StoredProc.ParamByName('KOD_PRIV_1DF').AsInteger := StrToInt(UpdateForm.MaskEditKodPriv1DF.Text); StoredProc.ExecProc; end; WriteTransaction.Commit; If UpdateForm.ModalResult=mrYes then DataSetCloseOpen(DSet,'ID_PRIV'); UpdateForm.Free; except on E: Exception do begin ZShowMessage(Error_Caption[PLanguageIndex],E.Message,mtError,[mbOK]); WriteTransaction.Rollback; end; end; end; procedure TFZ_Sp_Privileges.DeleteBtnClick(Sender: TObject); var CloseRecordForm:TFormSp_PrivilegesControl; begin CloseRecordForm := TFormSp_PrivilegesControl.Create(self); CloseRecordForm.Caption := ZSp_Privilege_Caption_Delete[PLanguageIndex]; CloseRecordForm.KodEdit.Text := IntToStr(DSet.FieldValues['KOD_PRIV']); CloseRecordForm.NameEdit.Text := DSet.FieldValues['NAME_PRIV']; CloseRecordForm.KoefficientEdit.Text := DSet.FieldValues['KOEFFICIENT_PRIV']; CloseRecordForm.MinSpinEdit.Value := DSet.FieldValues['MIN_AMOUNT_PRIV']; CloseRecordForm.MaxSpinEdit.Value := DSet.FieldValues['MAX_AMOUNT_PRIV']; CloseRecordForm.DateBeg.Date := DSet.FieldValues['DATE_BEG']; CloseRecordForm.DateEnd.Date := DSet.FieldValues['DATE_END']; CloseRecordForm.MaskEditKodPriv1DF.Text := IntToStr(DSet.FieldValues['KOD_PRIV_1DF']); CloseRecordForm.MaskEditKodPriv1DF.Enabled := False; CloseRecordForm.KodEdit.Enabled := False; CloseRecordForm.NameEdit.Enabled := False; CloseRecordForm.KoefficientEdit.Enabled := False; CloseRecordForm.MinSpinEdit.Enabled := False; CloseRecordForm.MaxSpinEdit.Enabled := False; CloseRecordForm.DateBeg.Enabled := False; CloseRecordForm.ShowModal; If CloseRecordForm.ModalResult=mrYes then try StoredProc.Database := DB; StoredProc.Transaction := WriteTransaction; StoredProc.Transaction.StartTransaction; StoredProc.StoredProcName := 'Z_SP_PRIVILEGES_CLOSERECORD'; StoredProc.Prepare; StoredProc.ParamByName('ID_PRIV').AsInteger := DSet.FieldValues['ID_PRIV']; StoredProc.ParamByName('DATE_END').AsDate := CloseRecordForm.DateEnd.Date; StoredProc.ExecProc; WriteTransaction.Commit; DataSetCloseOpen(DSet); except on E: Exception do begin ZShowMessage(Error_Caption[PLanguageIndex],E.Message,mtError,[mbOK]); WriteTransaction.Rollback; end; end; CloseRecordForm.Free; end; procedure TFZ_Sp_Privileges.SelectBtnClick(Sender: TObject); begin Ins_Resault[0] := DSet['ID_PRIV']; Ins_Resault[1] := DSet['NAME_PRIV']; Ins_Resault[2] := DSet['MIN_AMOUNT_PRIV']; Ins_Resault[3] := DSet['MAX_AMOUNT_PRIV']; Ins_Resault[4] := DSet['DATE_BEG']; Ins_Resault[5] := DSet['DATE_END']; Ins_Resault[6] := DSet['KOD_PRIV']; Ins_Resault[7] := DSet['KOD_PRIV_1DF']; self.ModalResult:=mrOk; end; procedure TFZ_Sp_Privileges.GridDBTableView1CustomDrawCell( Sender: TcxCustomGridTableView; ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean); begin if (AViewInfo.GridRecord.Values[6]<Date) and (AviewInfo.GridRecord.Focused=False) then begin ACanvas.Font.Style := [fsStrikeOut]; ACanvas.Brush.Color := clSilver; //$00E2EFF1;//$0047D5FE; end; end; procedure TFZ_Sp_Privileges.GridDBTableView1FocusedRecordChanged( Sender: TcxCustomGridTableView; APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord; ANewItemRecordFocusingChanged: Boolean); begin If AFocusedRecord<>nil then If AFocusedRecord.Values[6]<Date then begin UpdateBtn.Enabled:=False; DeleteBtn.Enabled:=False; end else begin UpdateBtn.Enabled:=True; DeleteBtn.Enabled:=True; end else begin UpdateBtn.Enabled:=False; DeleteBtn.Enabled:=False; end; end; procedure TFZ_Sp_Privileges.ButtonsUpdate(Sender: Tobject); begin if DSet.VisibleRecordCount=0 then begin UpdateBtn.Enabled:=False; DeleteBtn.Enabled:=False; end else begin UpdateBtn.Enabled:=True; DeleteBtn.Enabled:=True; end; end; procedure TFZ_Sp_Privileges.FormCreate(Sender: TObject); begin ButtonsUpdate(Sender); GridDBTableView1FocusedRecordChanged(GridDBTableView1,GridDBTableView1.Controller.FocusedRecord, GridDBTableView1.Controller.FocusedRecord,false); end; procedure TFZ_Sp_Privileges.GridDBTableView1DblClick(Sender: TObject); begin if (SelectBtn.Visible = ivAlways) and (SelectBtn.Enabled) and (GridDBTableView1.Controller.FocusedRecord<>nil) then SelectBtnClick(sender); end; procedure TFZ_Sp_Privileges.FormResize(Sender: TObject); var i:byte; begin if StatusBar.Panels.Count=0 then Exit; for i:=0 to StatusBar.Panels.Count-1 do StatusBar.Panels[i].Width := StatusBar.Width div StatusBar.Panels.Count; end; procedure TFZ_Sp_Privileges.DetailBtnClick(Sender: TObject); var ViewForm:TFormSp_PrivilegesControl; begin ViewForm := TFormSp_PrivilegesControl.Create(self); ViewForm.Caption := ZSp_Privilege_Caption_Detail[PLanguageIndex]; ViewForm.KodEdit.Text := IntToStr(DSet.FieldValues['KOD_PRIV']); ViewForm.NameEdit.Text := DSet.FieldValues['NAME_PRIV']; ViewForm.KoefficientEdit.Text := DSet.FieldValues['KOEFFICIENT_PRIV']; ViewForm.MinSpinEdit.Value := DSet.FieldValues['MIN_AMOUNT_PRIV']; ViewForm.MaxSpinEdit.Value := DSet.FieldValues['MAX_AMOUNT_PRIV']; ViewForm.DateBeg.Date := DSet.FieldValues['DATE_BEG']; ViewForm.DateEnd.Date := DSet.FieldValues['DATE_END']; ViewForm.MaskEditKodPriv1DF.Text := IntToStr(DSet.FieldValues['KOD_PRIV_1DF']); ViewForm.IdentificationBox.Enabled := False; ViewForm.OptionsBox.Enabled := False; ViewForm.PeriodBox.Enabled := False; ViewForm.YesBtn.Visible := False; ViewForm.CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex]; ViewForm.ShowModal; ViewForm.Free; end; end.
unit OTFEFreeOTFE_InstructionRichEdit; // Description: Password Richedit // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // // This control jsut sets some default values and sets them differently at design time - DO NOT USE. use TRichEdit instead interface uses Windows, Messages, Classes, StdCtrls, ComCtrls, // Required for definition of TRichEdit Forms, // Required for bsNone Graphics, Controls; type TOTFEFreeOTFE_InstructionRichEdit = class (TRichEdit) public constructor Create(AOwner: TComponent); override; destructor Destroy(); override; procedure ResetDisplay(); published { property BorderStyle default bsNone; property TabStop default FALSE; property PlainText default TRUE; property ReadOnly default TRUE; property Color default clBtnFace; property ParentColor default TRUE; } end; procedure Register; implementation uses RichEdit; procedure Register; begin RegisterComponents('FreeOTFE', [TOTFEFreeOTFE_InstructionRichEdit]); end; constructor TOTFEFreeOTFE_InstructionRichEdit.Create(AOwner: TComponent); begin inherited Create(AOwner); // We don't set these at design-time, as it makes it easier to see where the // components are if not (csDesigning in ComponentState) then begin ResetDisplay(); end; end; destructor TOTFEFreeOTFE_InstructionRichEdit.Destroy(); begin inherited; end; procedure TOTFEFreeOTFE_InstructionRichEdit.ResetDisplay(); begin inherited; // Restore various properties suitable for instructions display... self.BorderStyle := bsNone; self.TabStop := False; self.PlainText := True; self.ReadOnly := True; self.ParentColor := True; end; end.
unit RandomNumberGenerator; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, FunctionManager; type TformRandomNumberGenerator = class(TForm) listBoxGeneratedNumbers: TListBox; btnGenerateNumbers: TButton; editNumbersToGenerate: TEdit; lblRandomNumberList: TLabel; procedure btnGenerateNumbersClick(Sender: TObject); procedure editNumbersToGenerateKeyPress(Sender: TObject; var Key: Char); private functionManager: TFunctionManager; { Private declarations } public { Public declarations } end; var formRandomNumberGenerator: TformRandomNumberGenerator; implementation {$R *.dfm} procedure TformRandomNumberGenerator.btnGenerateNumbersClick(Sender: TObject); begin listBoxGeneratedNumbers.Clear; functionManager.GenerateAddRandomNumbers(editNumbersToGenerate.Text, listBoxGeneratedNumbers.Items); end; procedure TformRandomNumberGenerator.editNumbersToGenerateKeyPress(Sender: TObject; var Key: Char); begin if not(charinset(Key, [#8, '0' .. '9', '-']) and not(ord(Key) = VK_RETURN)) and not(Key = ^C) then begin Application.MessageBox('Invalid key. Only numbers are valid for input', 'Invalid key entered', MB_OK Or MB_ICONEXCLAMATION); Key := #0; end; end; end.
unit frmSickLeave; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, dbfunc, uKernel; type TfSickLeave = class(TForm) Panel1: TPanel; cmbPedagogue: TComboBox; cmbAcademicYear: TComboBox; Label3: TLabel; Label1: TLabel; lvSickLeave: TListView; bAddSickLeave: TButton; Button3: TButton; bDeleteSickLeave: TButton; Panel2: TPanel; cmbAcademicYear2: TComboBox; cmbPedagogue2: TComboBox; Label5: TLabel; Label6: TLabel; dtpDateBegining: TDateTimePicker; dtpDateEnding: TDateTimePicker; Label2: TLabel; Label4: TLabel; bSaveSickLeave: TButton; bChange: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); procedure Button3Click(Sender: TObject); procedure bAddSickLeaveClick(Sender: TObject); procedure bSaveSickLeaveClick(Sender: TObject); procedure lvSickLeaveSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure bDeleteSickLeaveClick(Sender: TObject); procedure cmbPedagogueChange(Sender: TObject); procedure cmbAcademicYearChange(Sender: TObject); procedure bChangeClick(Sender: TObject); private IDSickLeave: integer; AcademicYear: TResultTable; PedagogueSurnameNP: TResultTable; SickLeave: TResultTable; FStrPedagogue: string; FIDPedagogue: integer; FStrAcademicYear: string; FIDAcademicYear: integer; procedure SetStrPedagogue(const Value: string); procedure SetIDPedagogue(const Value: integer); procedure SetStrAcademicYear(const Value: string); procedure SetIDAcademicYear(const Value: integer); procedure ShowSickLeaveList; public property IDAcademicYear: integer read FIDAcademicYear write SetIDAcademicYear; property IDPedagogue: integer read FIDPedagogue write SetIDPedagogue; property StrAcademicYear: string read FStrAcademicYear write SetStrAcademicYear; property StrPedagogue: string read FStrPedagogue write SetStrPedagogue; end; var fSickLeave: TfSickLeave; implementation {$R *.dfm} { TfSickLeave } procedure TfSickLeave.bAddSickLeaveClick(Sender: TObject); begin // Kernel.ChooseComboBoxItemIndex(cmbPedagogue, PedagogueSurnameNP, true, // 'ID_OUT', IDPedagogue); // Kernel.ChooseComboBoxItemIndex(cmbAcademicYear, AcademicYear, true, 'ID', // IDAcademicYear); cmbPedagogue2.ItemIndex := -1; // cmbAcademicYear2.ItemIndex := -1; Kernel.ChooseComboBoxItemIndex(cmbAcademicYear2, AcademicYear, false, 'ID', IDAcademicYear); dtpDateBegining.Date := Date; dtpDateEnding.Date := Date; IDSickLeave := -1; bChange.Enabled := false; bDeleteSickLeave.Enabled := false; bSaveSickLeave.Enabled := true; end; procedure TfSickLeave.bChangeClick(Sender: TObject); begin bChange.Enabled := true; bDeleteSickLeave.Enabled := true; // надо подумать, мож false bSaveSickLeave.Enabled := true; end; procedure TfSickLeave.bDeleteSickLeaveClick(Sender: TObject); begin if Kernel.DeleteSickLeave([IDSickLeave]) then begin ShowMessage('Запись удалена!'); // МОЖЕТ НЕ СТОИТ ВЫВОДИТЬ ЭТО СООБЩЕНИЕ!!??? end else ShowMessage('Ошибка при удалении записи!'); ShowSickLeaveList; end; procedure TfSickLeave.bSaveSickLeaveClick(Sender: TObject); var i1, i2: integer; s1, s2: string; begin if (cmbPedagogue2.ItemIndex = -1) or (cmbAcademicYear2.ItemIndex = -1) then begin ShowMessage('Выберите педагога и учебный год!'); Exit; end; i1 := AcademicYear[cmbAcademicYear2.ItemIndex].ValueByName('ID'); i2 := PedagogueSurnameNP[cmbPedagogue2.ItemIndex].ValueByName('ID_OUT'); s1 := dateToStr(dtpDateBegining.Date); s2 := dateToStr(dtpDateEnding.Date); if Kernel.SaveSickLeave([IDSickLeave, AcademicYear[cmbAcademicYear2.ItemIndex] .ValueByName('ID'), PedagogueSurnameNP[cmbPedagogue2.ItemIndex] .ValueByName('ID_OUT'), dateToStr(dtpDateBegining.Date), dateToStr(dtpDateEnding.Date)]) then ShowMessage('Сохранение выполнено!') else ShowMessage('Ошибка при сохранении!'); ShowSickLeaveList; end; procedure TfSickLeave.Button3Click(Sender: TObject); begin Close; end; procedure TfSickLeave.cmbAcademicYearChange(Sender: TObject); begin ShowSickLeaveList; end; procedure TfSickLeave.cmbPedagogueChange(Sender: TObject); begin ShowSickLeaveList; end; procedure TfSickLeave.FormCreate(Sender: TObject); begin AcademicYear := nil; PedagogueSurnameNP := nil; SickLeave := nil; end; procedure TfSickLeave.FormDestroy(Sender: TObject); begin if Assigned(AcademicYear) then FreeAndNil(AcademicYear); if Assigned(PedagogueSurnameNP) then FreeAndNil(PedagogueSurnameNP); if Assigned(SickLeave) then FreeAndNil(SickLeave); end; procedure TfSickLeave.FormShow(Sender: TObject); var i: integer; begin if not Assigned(AcademicYear) then AcademicYear := Kernel.GetAcademicYear; Kernel.FillingComboBox(cmbAcademicYear, AcademicYear, 'NAME', true); Kernel.ChooseComboBoxItemIndex(cmbAcademicYear, AcademicYear, true, 'ID', IDAcademicYear); Kernel.FillingComboBox(cmbAcademicYear2, AcademicYear, 'NAME', false); Kernel.ChooseComboBoxItemIndex(cmbAcademicYear2, AcademicYear, false, 'ID', IDAcademicYear); if not Assigned(PedagogueSurnameNP) then PedagogueSurnameNP := Kernel.GetPedagogueSurnameNP; Kernel.FillingComboBox(cmbPedagogue, PedagogueSurnameNP, 'SurnameNP', true); // Kernel.ChooseComboBoxItemIndex(cmbPedagogue, PedagogueSurnameNP, true, // 'ID_OUT', IDPedagogue); cmbPedagogue.ItemIndex := 0; Kernel.FillingComboBox(cmbPedagogue2, PedagogueSurnameNP, 'SurnameNP', false); // Kernel.ChooseComboBoxItemIndex(cmbPedagogue2, PedagogueSurnameNP, false, // 'ID_OUT', IDPedagogue); cmbPedagogue2.ItemIndex := -1; dtpDateBegining.Date := Date; dtpDateEnding.Date := Date; ShowSickLeaveList; Panel1.Caption := 'Педагог: ' + StrPedagogue + ', ' + StrAcademicYear + ' учебный год.'; end; procedure TfSickLeave.lvSickLeaveSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); var i: integer; begin if SickLeave.Count > 0 then with SickLeave[Item.Index] do begin IDSickLeave := ValueByName('ID_OUT'); dtpDateBegining.Date := ValueByName('DATE_BEGINING'); dtpDateEnding.Date := ValueByName('DATE_ENDING'); for i := 0 to AcademicYear.Count - 1 do if cmbAcademicYear2.Items[i] = ValueStrByName('ACADEMIC_YEAR') then cmbAcademicYear2.ItemIndex := i; for i := 0 to PedagogueSurnameNP.Count - 1 do if cmbPedagogue2.Items[i] = ValueStrByName('SURNAMENP') then cmbPedagogue2.ItemIndex := i; end; // bDeleteSickLeave.Enabled := false; // bSaveSickLeave.Enabled := false; end; procedure TfSickLeave.SetIDAcademicYear(const Value: integer); begin if FIDAcademicYear <> Value then FIDAcademicYear := Value; end; procedure TfSickLeave.SetIDPedagogue(const Value: integer); begin if FIDPedagogue <> Value then FIDPedagogue := Value; end; procedure TfSickLeave.SetStrAcademicYear(const Value: string); begin if FStrAcademicYear <> Value then FStrAcademicYear := Value; end; procedure TfSickLeave.SetStrPedagogue(const Value: string); begin if FStrPedagogue <> Value then FStrPedagogue := Value; end; procedure TfSickLeave.ShowSickLeaveList; var id_academic_year, id_pedagogue: integer; begin if cmbPedagogue.ItemIndex = 0 then id_pedagogue := 0 else id_pedagogue := PedagogueSurnameNP[cmbPedagogue.ItemIndex - 1] .ValueByName('ID_OUT'); if cmbAcademicYear.ItemIndex = 0 then id_academic_year := 0 else id_academic_year := AcademicYear[cmbAcademicYear.ItemIndex - 1] .ValueByName('ID'); if Assigned(SickLeave) then FreeAndNil(SickLeave); SickLeave := Kernel.GetSickLeave(id_pedagogue, id_academic_year); Kernel.GetLVSickLeave(lvSickLeave, SickLeave); if lvSickLeave.Items.Count > 0 then begin lvSickLeave.ItemIndex := 0; bChange.Enabled := true; bDeleteSickLeave.Enabled := true; bSaveSickLeave.Enabled := false; end else begin IDSickLeave := -1; bChange.Enabled := false; bDeleteSickLeave.Enabled := false; bSaveSickLeave.Enabled := false; end; end; end.
unit frmWizardChangePasswordCreateKeyfile; // Description: // By Sarah Dean // Email: sdean12@sdean12.org // WWW: http://www.SDean12.org/ // // ----------------------------------------------------------------------------- // interface uses Classes, ComCtrls, Controls, Dialogs, ExtCtrls, Forms, Graphics, Messages, MouseRNG, PasswordRichEdit, Spin64, StdCtrls, SysUtils, Windows, //sdu lcDialogs, sdurandpool, SDUStdCtrls, SDUGeneral, fmeDiskPartitionsPanel, //LibreCrypt DriverAPI, // Required for CRITICAL_DATA_LEN fmeSelectPartition, frmWizard, OTFEFreeOTFE_InstructionRichEdit, OTFEFreeOTFE_PasswordRichEdit, OTFEFreeOTFE_U, OTFEFreeOTFEBase_U, fmeSDUBlocks, fmeSDUDiskPartitions, SDUForms, SDUFrames, SDUSpin64Units, SDUDialogs, fmeNewPassword; type TChangePasswordCreateKeyfile = (opChangePassword, opCreateKeyfile); TfrmWizardChangePasswordCreateKeyfile = class (TfrmWizard) tsSrcDetails: TTabSheet; tsDestDetails: TTabSheet; reInstructSrcDetails: TLabel; tsRNGMouseMovement: TTabSheet; reInstructRNGMouseMovement: TLabel; MouseRNG: TMouseRNG; lblMouseRNGBits: TLabel; tsDestFile: TTabSheet; reInstructDestFile: TLabel; tsRNGGPG: TTabSheet; reInstructRNGGPG: TLabel; GroupBox5: TGroupBox; lblGPGFilename: TSDUFilenameLabel; pbBrowseGPG: TButton; OpenDialog: TSDUOpenDialog; SaveDialog: TSDUSaveDialog; GPGOpenDialog: TSDUOpenDialog; tsRNGSelect: TTabSheet; reInstructRNGSelect1: TLabel; Label9: TLabel; Label1: TLabel; Label4: TLabel; Label6: TLabel; preSrcUserKey: TOTFEFreeOTFE_PasswordRichEdit; seSrcSaltLength: TSpinEdit64; Label5: TLabel; seDestSaltLength: TSpinEdit64; Label7: TLabel; cbDestDriveLetter: TComboBox; Label12: TLabel; gbKeyFile: TGroupBox; lblDestFilename: TSDUFilenameLabel; pbBrowseDest: TButton; tsSrcFile: TTabSheet; reInstructSrcFile: TLabel; GroupBox2: TGroupBox; lblSrcFilename: TSDUFilenameLabel; pbBrowseSrc: TButton; tsFileOrPartition: TTabSheet; tsPartitionSelect: TTabSheet; rgFileOrPartition: TRadioGroup; reInstructFileOrPartition: TLabel; reInstructPartitionSelect: TLabel; Label21: TLabel; seDestKeyIterations: TSpinEdit64; Label8: TLabel; seSrcKeyIterations: TSpinEdit64; Label11: TLabel; gbRNG: TGroupBox; ckRNGMouseMovement: TCheckBox; ckRNGCryptoAPI: TCheckBox; ckRNGcryptlib: TCheckBox; ckRNGGPG: TCheckBox; ckRNGPKCS11: TCheckBox; tsRNGPKCS11: TTabSheet; reInstructRNGPKCS11: TLabel; cbToken: TComboBox; lblToken: TLabel; pbRefresh: TButton; fmeSelectPartition: TfmeSelectPartition; se64UnitOffset: TSDUSpin64Unit_Storage; TSDUDiskPartitionsPanel1: TfmeDiskPartitionsPanel; frmeNewPassword: TfrmeNewPassword; lblInstructDestDetails: TLabel; reInstructRNGSelect2: TLabel; reInstructRNGSelect3: TLabel; reInstructRNGSelect4: TLabel; procedure FormShow(Sender: TObject); procedure edSrcFilenameChange(Sender: TObject); procedure se64OffsetChange(Sender: TObject); procedure seSaltLengthChange(Sender: TObject); procedure ckRNGClick(Sender: TObject); procedure MouseRNGByteGenerated(Sender: TObject; random: Byte); procedure pbBrowseGPGClick(Sender: TObject); procedure pbFinishClick(Sender: TObject); procedure pbBrowseDestClick(Sender: TObject); procedure pbBrowseSrcClick(Sender: TObject); procedure rgFileOrPartitionClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure pbRefreshClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure frmeNewPasswordChange(Sender: TObject); procedure preSrcUserKeyChange(Sender: TObject); private // fCombinedRandomData: Ansistring; deviceList: TStringList; deviceTitle: TStringList; FPKCS11TokensAvailable: Boolean; function GetRNGSet(): TRNGSet; function GetIsPartition(): Boolean; function GetSrcFilename(): String; function GetOffset(): Int64; function GetSrcUserKey(): TSDUBytes; function GetSrcSaltLength(): Integer; function GetSrcKeyIterations(): Integer; function GetDestFilename(): String; procedure SetDestFilename(filename: String); function GetDestUserKey(): TSDUBytes; function GetDestSaltLength(): Integer; function GetDestKeyIterations(): Integer; function GetDestRequestedDriveLetter(): DriveLetterChar; // function GetRandomData(): Ansistring; procedure PopulatePKCS11Tokens(); procedure SetupInstructionsCreateKeyfile(); procedure SetSrcFilename(const Value: String); procedure SetDestUserKey(const Value: TSDUBytes); procedure SetIsPartition(const Value: Boolean); procedure SetSrcUserKey(const Value: TSDUBytes); protected fsilent: Boolean; fsilentResult: TModalResult; procedure SetupInstructions(); override; procedure EnableDisableControls(); override; function IsTabSkipped(tabSheet: TTabSheet): Boolean; override; procedure FormWizardStepChanged(Sender: TObject); function IsTabComplete(checkTab: TTabSheet): Boolean; override; public fChangePasswordCreateKeyfile: TChangePasswordCreateKeyfile; procedure fmeSelectPartitionChanged(Sender: TObject); published property silent: Boolean Read fsilent Write fsilent; property IsPartition: Boolean Read GetIsPartition Write SetIsPartition; property SrcFilename: String Read GetSrcFilename Write SetSrcFilename; { property Offset: Int64 Read GetOffset;} property SrcUserKey: TSDUBytes Read GetSrcUserKey Write SetSrcUserKey; { property SrcSaltLength: Integer Read GetSrcSaltLength; property SrcKeyIterations: Integer Read GetSrcKeyIterations; property DestFilename: String Read GetDestFilename Write SetDestFilename;} property DestUserKey: TSDUBytes Read GetDestUserKey Write SetDestUserKey; { property DestSaltLength: Integer Read GetDestSaltLength; property DestKeyIterations: Integer Read GetDestKeyIterations; property DestRequestedDriveLetter: ansichar Read GetDestRequestedDriveLetter; } // property RandomData: Ansistring Read GetRandomData; end; implementation {$R *.DFM} uses MSCryptoAPI, PKCS11Lib, OTFEFreeOTFEDLL_U, SDUi18n; {$IFDEF _NEVER_DEFINED} // This is just a dummy const to fool dxGetText when extracting message // information // This const is never used; it's #ifdef'd out - SDUCRLF in the code refers to // picks up SDUGeneral.SDUCRLF const SDUCRLF = ''#13#10; {$ENDIF} resourcestring FILEORPART_OPT_VOLUME_FILE = 'File'; FILEORPART_OPT_PARTITION = 'Partition'; { TODO 2 -otdk -crefactor : this uses a lot of same code and GUI as create volume - turn into frames } function TfrmWizardChangePasswordCreateKeyfile.GetSrcFilename(): String; begin if GetIsPartition() then begin Result := fmeSelectPartition.SelectedDevice; end else begin Result := lblSrcFilename.Caption; end; end; procedure TfrmWizardChangePasswordCreateKeyfile.SetSrcFilename(const Value: String); begin if GetIsPartition() then begin // fmeSelectPartition.SelectedDevice := Value; assert(False, 'this feature not supported'); end else begin lblSrcFilename.Caption := Value; end; end; function TfrmWizardChangePasswordCreateKeyfile.GetOffset(): Int64; begin Result := se64UnitOffset.Value; end; function TfrmWizardChangePasswordCreateKeyfile.GetSrcUserKey(): TSDUBytes; begin { TODO 1 -otdk -cfix : warn user - no unicode } Result := SDUStringToSDUBytes(preSrcUserKey.Text); end; procedure TfrmWizardChangePasswordCreateKeyfile.SetSrcUserKey(const Value: TSDUBytes); begin preSrcUserKey.Text := SDUBytesToString(Value); end; function TfrmWizardChangePasswordCreateKeyfile.GetSrcSaltLength(): Integer; begin Result := seSrcSaltLength.Value; end; function TfrmWizardChangePasswordCreateKeyfile.GetDestFilename(): String; begin Result := lblDestFilename.Caption; end; procedure TfrmWizardChangePasswordCreateKeyfile.SetDestFilename(filename: String); begin lblDestFilename.Caption := filename; end; function TfrmWizardChangePasswordCreateKeyfile.GetDestUserKey(): TSDUBytes; begin Result := frmeNewPassword.GetKeyPhrase; { TODO 1 -otdk -cfix : warn user - no unicode } end; procedure TfrmWizardChangePasswordCreateKeyfile.SetDestUserKey(const Value: TSDUBytes); begin frmeNewPassword.SetKeyPhrase(Value); end; function TfrmWizardChangePasswordCreateKeyfile.GetDestSaltLength(): Integer; begin Result := seDestSaltLength.Value; { TODO 1 -otdk -cfix : warn user - no unicode } end; function TfrmWizardChangePasswordCreateKeyfile.GetSrcKeyIterations(): Integer; begin Result := seSrcKeyIterations.Value; end; function TfrmWizardChangePasswordCreateKeyfile.GetDestKeyIterations(): Integer; begin Result := seDestKeyIterations.Value; end; function TfrmWizardChangePasswordCreateKeyfile.GetDestRequestedDriveLetter(): DriveLetterChar; begin Result := #0; if (cbDestDriveLetter.ItemIndex > 0) then begin Result := cbDestDriveLetter.Items[cbDestDriveLetter.ItemIndex][1]; end; end; //function TfrmWizardChangePasswordCreateKeyfile.GetRandomData(): Ansistring; //begin // Result := fCombinedRandomData; //end; // Returns TRUE if the specified tab should be skipped in 'next' progression, otherwise FALSE function TfrmWizardChangePasswordCreateKeyfile.IsTabSkipped(tabSheet: TTabSheet): Boolean; begin Result := inherited IsTabSkipped(tabSheet); // DLL doesn't currently support partitions if (tabSheet = tsFileOrPartition) then begin Result := (GetFreeOTFEBase() is TOTFEFreeOTFEDLL); end; // If the user isn't creating a volume within a volume file, skip that tab if (tabSheet = tsSrcFile) then begin Result := GetIsPartition(); end; // If the user isn't creating a volume on a partition, skip that tab if (tabSheet = tsPartitionSelect) then begin Result := not (GetIsPartition()); end; // If the user isn't creating a keyfile, skip the destination keyfile tabsheet if (tabSheet = tsDestFile) then Result := (fChangePasswordCreateKeyfile <> opCreateKeyfile); // If the user *isn't* using the mouse movement RNG, skip the tsRNGMouseMovement tabsheet if (tabSheet = tsRNGMouseMovement) then Result := not (rngMouseMovement in GetRNGSet()); // If the user *isn't* using the PKCS#11 token RNG, skip the tsRNGPKCS11 tabsheet if (tabSheet = tsRNGPKCS11) then Result := not (rngPKCS11 in GetRNGSet()); // If the user *isn't* using the GPG RNG, skip the tsRNGGPG tabsheet if (tabSheet = tsRNGGPG) then begin Result := not (rngGPG in GetRNGSet()); end; end; procedure TfrmWizardChangePasswordCreateKeyfile.EnableDisableControls(); begin inherited; // (No wizard specific code for *this* wizard.) end; // This procedure will check to see if all items on the current tabsheet have // been successfully completed function TfrmWizardChangePasswordCreateKeyfile.IsTabComplete(checkTab: TTabSheet): Boolean; var randomBitsGenerated: Integer; begin inherited; Result := False; if (checkTab = tsFileOrPartition) then begin // Ensure one option has been selected Result := (rgFileOrPartition.ItemIndex >= 0); end else if (checkTab = tsSrcFile) then begin // Flag tabsheet complete if a valid filename has been specified if (GetIsPartition()) then begin Result := True; end else begin Result := FileExists(GetSrcFilename()); end; end else if (checkTab = tsPartitionSelect) then begin // If we're creating a volume on a partition, one must be selected if (not (GetIsPartition())) then begin Result := True; end else begin Result := (fmeSelectPartition.SelectedDevice <> ''); end; end else if (checkTab = tsSrcDetails) then begin // Check that the number entered is less than the max size... if (GetIsPartition()) then begin Result := (GetOffset() >= 0); end else begin Result := (GetOffset() < SDUGetFileSize(GetSrcFilename())) and (GetOffset() >= 0); end; // Check that the number entered is less than the size of the file... // Src salt length >= 0 // Note that the password *can* be blank - e.g. with the NULL encryption // cypher Result := Result and (GetSrcSaltLength() >= 0) and (GetSrcKeyIterations() > 0); end else if (checkTab = tsDestFile) then begin // Dest filename entered Result := (GetDestFilename() <> ''); // Sanity check - if we're creating a keyfile, ensure user's not trying to // overwrite the original volume file! if (fChangePasswordCreateKeyfile = opCreateKeyfile) then Result := Result and (GetSrcFilename() <> GetDestFilename()); end else if (checkTab = tsDestDetails) then begin // Check that user password is confirmed // Note that RNG is always set to something, and others always default // Note that the password *can* be blank - e.g. with the NULL encryption // cypher Result := (frmeNewPassword.IsPasswordValid) and (GetDestSaltLength() >= 0) and (GetDestKeyIterations() > 0); end else if (checkTab = tsRNGSelect) then begin // Must have at least one RNG selected Result := (GetRNGSet() <> []); end else if (checkTab = tsRNGMouseMovement) then begin // This is a good place to update the display of the number of random bits // generated... randomBitsGenerated := CountMouseRNGData(); lblMouseRNGBits.Caption := SDUParamSubstitute(_('Random bits generated: %1/%2'), [randomBitsGenerated, CRITICAL_DATA_LENGTH]); Result := (randomBitsGenerated >= CRITICAL_DATA_LENGTH); MouseRNG.Enabled := not (Result); if MouseRNG.Enabled then begin MouseRNG.Color := clWindow; end else begin MouseRNG.Color := clBtnFace; end; end else if (checkTab = tsRNGPKCS11) then begin // Must have at least one RNG selected Result := (FPKCS11TokensAvailable and (cbToken.ItemIndex >= 0)); end else if (checkTab = tsRNGGPG) then begin // Flag tabsheet complete if a GPG executable has been specified Result := (lblGPGFilename.Caption <> ''); end; end; procedure TfrmWizardChangePasswordCreateKeyfile.FormShow(Sender: TObject); var i: Integer; dl: Char; begin inherited; //SDUInitAndZeroBuffer(0,fCombinedRandomData); // fCombinedRandomData := ''; { TODO -otdk -crefactor : this should all be in formcreate - but need to have global TOTFEFreeOTFEBase object first } // tsSrcFile if not fsilent then lblSrcFilename.Caption := ''; seSrcKeyIterations.MinValue := 1; seSrcKeyIterations.MaxValue := 999999; // Need *some* upper value, otherwise setting MinValue won't work properly seSrcKeyIterations.Increment := DEFAULT_KEY_ITERATIONS_INCREMENT; seSrcKeyIterations.Value := DEFAULT_KEY_ITERATIONS; // tsPartitionSelect // Setup and make sure nothing is selected // fmeSelectPartition.FreeOTFEObj := fFreeOTFEObj; // Only list CDROMs if we're creating a keyfile // - CDROMs can't have their passwords changed fmeSelectPartition.AllowCDROM := (fChangePasswordCreateKeyfile = opCreateKeyfile); fmeSelectPartition.OnChange := fmeSelectPartitionChanged; fmeSelectPartition.Tag := 1; // fmeSelectPartition.Initialize(); // tsSrcDetails preSrcUserKey.Plaintext := True; // FreeOTFE volumes CAN have newlines in the user's password preSrcUserKey.WantReturns := True; preSrcUserKey.WordWrap := True; if not fsilent then preSrcUserKey.Lines.Clear(); preSrcUserKey.PasswordChar := GetFreeOTFEBase().PasswordChar; preSrcUserKey.WantReturns := GetFreeOTFEBase().AllowNewlinesInPasswords; preSrcUserKey.WantTabs := GetFreeOTFEBase().AllowTabsInPasswords; se64UnitOffset.Value := 0; seSrcSaltLength.Increment := 8; seSrcSaltLength.Value := DEFAULT_SALT_LENGTH; // tsDestFile lblDestFilename.Caption := ''; // tsDestDetails // // if not fsilent then // preDestUserKey1.Lines.Clear(); // // if not fsilent then // preDestUserKey2.Lines.Clear(); seDestSaltLength.Increment := 8; seDestSaltLength.Value := DEFAULT_SALT_LENGTH; seDestKeyIterations.MinValue := 1; seDestKeyIterations.MaxValue := 999999; // Need *some* upper value, otherwise setting MinValue won't work properly seDestKeyIterations.Increment := DEFAULT_KEY_ITERATIONS_INCREMENT; seDestKeyIterations.Value := DEFAULT_KEY_ITERATIONS; cbDestDriveLetter.Items.Clear(); cbDestDriveLetter.Items.Add(_('Use default')); // for dl:='C' to 'Z' do for dl := 'A' to 'Z' do cbDestDriveLetter.Items.Add(dl + ':'); // Autoselect the "default" (first) entry cbDestDriveLetter.ItemIndex := 0; // tsRNGSelect ckRNGCryptoAPI.Checked := True; ckRNGcryptlib.Enabled := GetRandPool().CanUseCryptlib; if ckRNGcryptlib.Enabled then ckRNGcryptlib.Checked := True; ckRNGPKCS11.Enabled := PKCS11LibraryReady(GetFreeOTFEBase().PKCS11Library); // tsRNGMouseMovement InitMouseRNGData(); // tsRNGPKCS11 PopulatePKCS11Tokens(); // tsRNGGPG lblGPGFilename.Caption := ''; // Set all tabs to show that they have not yet been completed for i := 0 to (pcWizard.PageCount - 1) do begin pcWizard.Pages[i].TabVisible := False; // Each tabsheet's tag indicates if that tab has been completed or not; 1 for // completed, 0 for not yet complete pcWizard.Pages[i].Tag := 0; end; // BECAUSE WE DEFAULTED TO USING A VOLUME *FILE*, WE MUST SET THE PARTITION // SELECT PAGE TO "DONE" HERE (otherwise, it'll never be flagged as complete // if the user doens't switch) tsPartitionSelect.Tag := 1; // BECAUSE WE DEFAULTED TO USING THE MOUSERNG, WE MUST SET THE GPG PAGE TO // "DONE" HERE (otherwise, it'll never be flagged as complete if the user // doens't switch RNGs) tsRNGGPG.Tag := 1; // Select the first tab // Yes, this is required; get an access violation if this isn't done pcWizard.ActivePageIndex := 0; // DLL doesn't currently support partitions if (GetFreeOTFEBase() is TOTFEFreeOTFEDLL) then begin pcWizard.ActivePageIndex := 1; // Mark as completed tsFileOrPartition.Tag := 1; end; UpdateUIAfterChangeOnCurrentTab(); if fSilent then begin ModalResult := mrCancel; pbFinishClick(self); FSilentResult := ModalResult; // if testing and no errors, then close dlg if ModalResult = mrOk then PostMessage(Handle, WM_CLOSE, 0, 0); end; //tag is used as flag if translated already if self.tag = 0 then self.Caption := SDUTranslate(self.Caption); self.tag := 1; SDUTranslateComp(reInstructSrcFile); SDUTranslateComp(reInstructFileOrPartition); SDUTranslateComp(reInstructSrcDetails); SDUTranslateComp(reInstructDestFile); SDUTranslateComp(reInstructRNGSelect1); SDUTranslateComp(reInstructRNGSelect2); SDUTranslateComp(reInstructRNGSelect3); SDUTranslateComp(reInstructRNGSelect4); SDUTranslateComp(reInstructDestFile); SDUTranslateComp(reInstructRNGMouseMovement); SDUTranslateComp(reInstructRNGGPG); SDUTranslateComp(reInstructRNGPKCS11); end; procedure TfrmWizardChangePasswordCreateKeyfile.edSrcFilenameChange(Sender: TObject); begin if (fChangePasswordCreateKeyfile = opChangePassword) then SetDestFilename(GetSrcFilename()); UpdateUIAfterChangeOnCurrentTab(); end; procedure TfrmWizardChangePasswordCreateKeyfile.se64OffsetChange(Sender: TObject); begin UpdateUIAfterChangeOnCurrentTab(); end; procedure TfrmWizardChangePasswordCreateKeyfile.frmeNewPasswordChange(Sender: TObject); begin UpdateUIAfterChangeOnCurrentTab(); end; procedure TfrmWizardChangePasswordCreateKeyfile.seSaltLengthChange(Sender: TObject); begin UpdateUIAfterChangeOnCurrentTab(); end; procedure TfrmWizardChangePasswordCreateKeyfile.ckRNGClick(Sender: TObject); begin InitMouseRNGData(); // Set unused tabsheets as complete // ...RNG mouse movement tsRNGMouseMovement.Tag := 1; if ckRNGMouseMovement.Checked then begin tsRNGMouseMovement.Tag := 0; end; // ...RNG GPG tsRNGGPG.Tag := 1; if ckRNGGPG.Checked then begin if (lblGPGFilename.Caption = '') then begin tsRNGGPG.Tag := 0; end; end; // ...RNG PKCS#11 token tsRNGPKCS11.Tag := 1; if ckRNGPKCS11.Checked then begin if not (FPKCS11TokensAvailable and (cbToken.ItemIndex >= 0)) then begin tsRNGPKCS11.Tag := 0; end; end; UpdateUIAfterChangeOnCurrentTab(); end; procedure TfrmWizardChangePasswordCreateKeyfile.MouseRNGByteGenerated(Sender: TObject; random: Byte); begin // Note: This is correct; if it's *less than* CRITICAL_DATA_LEN, then store it if (CountMouseRNGData() < CRITICAL_DATA_LENGTH) then begin AddToMouseRNGData(random); end; UpdateUIAfterChangeOnCurrentTab(); end; procedure TfrmWizardChangePasswordCreateKeyfile.pbBrowseGPGClick(Sender: TObject); begin GPGOpenDialog.Filter := FILE_FILTER_FLT_KEYFILES; GPGOpenDialog.DefaultExt := FILE_FILTER_DFLT_KEYFILES; GPGOpenDialog.Options := GPGOpenDialog.Options + [ofDontAddToRecent]; SDUOpenSaveDialogSetup(GPGOpenDialog, lblGPGFilename.Caption); if GPGOpenDialog.Execute then begin lblGPGFilename.Caption := GPGOpenDialog.Filename; end; UpdateUIAfterChangeOnCurrentTab(); end; function TfrmWizardChangePasswordCreateKeyfile.GetRNGSet(): TRNGSet; begin Result := []; if ckRNGCryptoAPI.Checked then begin Result := Result + [rngCryptoAPI]; end; if ckRNGMouseMovement.Checked then begin Result := Result + [rngMouseMovement]; end; if ckRNGcryptlib.Checked then begin Result := Result + [rngcryptlib]; end; if ckRNGPKCS11.Checked then begin Result := Result + [rngPKCS11]; end; if ckRNGGPG.Checked then begin Result := Result + [rngGPG]; end; end; procedure TfrmWizardChangePasswordCreateKeyfile.pbFinishClick(Sender: TObject); var allOK: Boolean; saltBytes: TSDUBytes; // salt: Ansistring; begin inherited; GetRandPool.SetUpRandPool(GetRNGSet(), PKCS11TokenListSelected(cbToken), lblGPGFilename.Caption); try // Grab 'n' bytes from the random pool to use as the salt GetRandPool.GetRandomData(GetDestSaltLength() div 8, saltBytes); // salt := SDUBytesToString(saltBytes); if (fChangePasswordCreateKeyfile = opChangePassword) then begin allOK := GetFreeOTFEBase().ChangeVolumePassword(GetSrcFilename(), GetOffset(), GetSrcUserKey(), GetSrcSaltLength(), // In bits GetSrcKeyIterations(), GetDestUserKey(), saltBytes, GetDestKeyIterations(), GetDestRequestedDriveLetter()); end else begin allOK := GetFreeOTFEBase().CreateKeyfile(GetSrcFilename(), GetOffset(), GetSrcUserKey(), GetSrcSaltLength(), // In bits GetSrcKeyIterations(), GetDestFilename(), GetDestUserKey(), saltBytes, GetDestKeyIterations(), GetDestRequestedDriveLetter()); end; except on E: EInsufficientRandom do begin allOK := False; SDUMessageDlg( _('Insufficient random data generated: ' + E.message) + SDUCRLF + SDUCRLF + PLEASE_REPORT_TO_FREEOTFE_DOC_ADDR, mtError ); end; end; if (allOK) then begin if not fsilent then SDUMessageDlg(_('Completed successfully.'), mtInformation); ModalResult := mrOk; end else begin SDUMessageDlg( _('Unable to complete requested operation: please ensure that your container is not already open or otherwise in use, and that the keyphrase, salt and offset entered are correct.'), mtError ); end; { TODO 1 -otdk -ccleanup : whats this for? } (* for i := 1 to length(saltBytes) do begin saltBytes[i] := AnsiChar(i); end;*) SDUInitAndZeroBuffer(0, saltBytes); end; procedure TfrmWizardChangePasswordCreateKeyfile.SetupInstructionsCreateKeyfile(); begin self.Caption := _('Create Keyphrase for container'); reInstructFileOrPartition.Caption := _('Please specify whether the container you wish to create a keyfile for is file or partition based.'); reInstructSrcFile.Caption := _('Please enter the full path and filename of either:' + SDUCRLF + SDUCRLF + '1) A container containing a CDB, or' + SDUCRLF + '2) An existing keyfile' + SDUCRLF + SDUCRLF + 'for the container you wish to create a keyfile for.' + SDUCRLF + SDUCRLF + 'If you wish to update a "hidden" container which is inside another container, and your hidden container includes a CDB, please specify the filename of the outer container which stores your hidden container.'); reInstructSrcDetails.Caption := _('Please enter the full details of the container you wish to create a keyfile for.' + SDUCRLF + SDUCRLF + 'If you wish to update a "hidden" container which is inside another container, and your hidden container includes a CDB, please specify the offset within the outer container where your hidden container is located.'); SDUTranslateComp(lblInstructDestDetails); // reInstructRNGSelect.Caption := // _('In order to create a new keyfile, a certain amount of random data is required.' + // SDUCRLF + SDUCRLF + 'This data will be used for the following:' + SDUCRLF + // SDUCRLF + '1) Password salting' + SDUCRLF + '2) Random padding data' + // SDUCRLF + SDUCRLF + // 'In order to generate this data, please select which random number generators you wish to use from the options below.'); end; procedure TfrmWizardChangePasswordCreateKeyfile.SetupInstructions(); begin inherited; if not (fChangePasswordCreateKeyfile = opChangePassword) then SetupInstructionsCreateKeyfile(); end; procedure TfrmWizardChangePasswordCreateKeyfile.pbBrowseDestClick(Sender: TObject); begin SaveDialog.Filter := FILE_FILTER_FLT_KEYFILES; SaveDialog.DefaultExt := FILE_FILTER_DFLT_KEYFILES; SaveDialog.Options := SaveDialog.Options + [ofDontAddToRecent]; SDUOpenSaveDialogSetup(SaveDialog, lblDestFilename.Caption); if SaveDialog.Execute() then begin if (FileExists(SaveDialog.Filename)) then begin SDUMessageDlg( _('A file with the filename you specified already exists.' + SDUCRLF + SDUCRLF + 'For safety reasons, you must specify a file which doesn''t already exist.' + SDUCRLF + SDUCRLF + 'Please either delete the existing file, or specify a new filename.'), mtError ); end else begin lblDestFilename.Caption := SaveDialog.Filename; end; end; UpdateUIAfterChangeOnCurrentTab(); end; procedure TfrmWizardChangePasswordCreateKeyfile.pbBrowseSrcClick(Sender: TObject); begin OpenDialog.Filter := FILE_FILTER_FLT_VOLUMESANDKEYFILES; OpenDialog.DefaultExt := FILE_FILTER_DFLT_VOLUMESANDKEYFILES; OpenDialog.Options := OpenDialog.Options + [ofDontAddToRecent]; SDUOpenSaveDialogSetup(OpenDialog, lblSrcFilename.Caption); if OpenDialog.Execute() then begin lblSrcFilename.Caption := OpenDialog.Filename; end; UpdateUIAfterChangeOnCurrentTab(); end; procedure TfrmWizardChangePasswordCreateKeyfile.rgFileOrPartitionClick(Sender: TObject); begin UpdateUIAfterChangeOnCurrentTab(); end; function TfrmWizardChangePasswordCreateKeyfile.GetIsPartition(): Boolean; begin Result := (rgFileOrPartition.ItemIndex = rgFileOrPartition.Items.IndexOf( FILEORPART_OPT_PARTITION)); end; procedure TfrmWizardChangePasswordCreateKeyfile.SetIsPartition(const Value: Boolean); begin if Value then rgFileOrPartition.ItemIndex := rgFileOrPartition.Items.IndexOf(FILEORPART_OPT_PARTITION) else rgFileOrPartition.ItemIndex := rgFileOrPartition.Items.IndexOf(FILEORPART_OPT_VOLUME_FILE); end; procedure TfrmWizardChangePasswordCreateKeyfile.FormWizardStepChanged(Sender: TObject); begin inherited; if (pcWizard.ActivePage = tsPartitionSelect) then begin // This shouldn't be needed, but without it, controls on this frame which // are set to "Visible := FALSE" by the frame remain visible. // Only call Initialize(...) the first time the tab is moved onto if (fmeSelectPartition.Tag = 1) then begin fmeSelectPartition.Initialize(); fmeSelectPartition.Tag := 0; end; end; end; procedure TfrmWizardChangePasswordCreateKeyfile.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; // Posting WM_CLOSE causes Delphi to reset ModalResult to mrCancel. // As a result, we reset ModalResult here, note will only close automatically if mr = mrok anyway if fsilent then begin ModalResult := FSilentResult; end; end; procedure TfrmWizardChangePasswordCreateKeyfile.FormCreate(Sender: TObject); begin deviceList := TStringList.Create(); deviceTitle := TStringList.Create(); fmeSelectPartition.OnChange := fmeSelectPartitionChanged; OnWizardStepChanged := FormWizardStepChanged; { done -otdk -crefactor : populate in designer } // tsFileOrPartition rgFileOrPartition.Items.Clear(); rgFileOrPartition.Items.Add(FILEORPART_OPT_VOLUME_FILE); rgFileOrPartition.Items.Add(FILEORPART_OPT_PARTITION); rgFileOrPartition.ItemIndex := rgFileOrPartition.Items.IndexOf(FILEORPART_OPT_VOLUME_FILE); frmeNewPassword.OnChange := frmeNewPasswordChange; end; procedure TfrmWizardChangePasswordCreateKeyfile.FormDestroy(Sender: TObject); begin deviceList.Free(); deviceTitle.Free(); PurgeMouseRNGData(); end; procedure TfrmWizardChangePasswordCreateKeyfile.PopulatePKCS11Tokens(); begin FPKCS11TokensAvailable := (PKCS11PopulateTokenList(GetFreeOTFEBase().PKCS11Library, cbToken) > 0); end; procedure TfrmWizardChangePasswordCreateKeyfile.preSrcUserKeyChange( Sender: TObject); begin inherited; UpdateUIAfterChangeOnCurrentTab(); end; procedure TfrmWizardChangePasswordCreateKeyfile.pbRefreshClick(Sender: TObject); begin PopulatePKCS11Tokens(); end; procedure TfrmWizardChangePasswordCreateKeyfile.fmeSelectPartitionChanged(Sender: TObject); begin UpdateUIAfterChangeOnCurrentTab(); end; end.
{$A+,B-,D+,E-,F+,G+,I+,L+,N+,O-,P-,Q-,R-,S+,T-,V-,X+,Y+} {-[■]------------------------------------------------------------------------ Some stack objects Copyright (c) 1997 by Alexander Demin ---------------------------------------------------------------------------- } Unit Stacks; Interface Const { Maximum size of If/Else/Endif, Do/EndDo, For/Loop stacks } MaxCnt = 10000; { Maximus size of Store/Restore stack } MaxSty = 10; Type Method = function : word; TIntStack = object Data : array [ 1..MaxCnt ] of word; Ptr : word; Count : word; constructor Init; function Push : word; function Pop : word; function Top : word; end; TStrStack = object Data : array [ 1..MaxSty ] of string; Ptr : word; constructor Init; function Push( S : string ) : string; function Pop : string; function Top : string; end; implementation Constructor TIntStack.Init; begin Ptr:=0; Count:=0; end; function TIntStack.Push; begin inc( Ptr ); Data[ Ptr ]:=Count; Push:=Count; inc( Count ); end; function TIntStack.Top : word; begin Top:=Data[ Ptr ]; end; function TIntStack.Pop : word; begin Pop:=Data[ Ptr ]; Dec( Ptr ); end; Constructor TStrStack.Init; begin Ptr:=0; end; function TStrStack.Push; begin inc( Ptr ); Data[ Ptr ]:=S; Push:=S; end; function TStrStack.Top; begin Top:=Data[ Ptr ]; end; function TStrStack.Pop; begin Pop:=Data[ Ptr ]; Dec( Ptr ); end; end.
unit utils; interface uses Windows, Messages, SysUtils; const MAX_ADAPTER_NAME_LENGTH = 256; MAX_ADAPTER_DESCRIPTION_LENGTH = 128; MAX_ADAPTER_ADDRESS_LENGTH = 8; type TOSVersion = (osUnknown, os95, os98, osME, osNT3, osNT4, os2K, osXP, os2K3); TIPAddressString = Array[0..4*4-1] of Char; PIPAddrString = ^TIPAddrString; TIPAddrString = Record Next : PIPAddrString; IPAddress : TIPAddressString; IPMask : TIPAddressString; Context : Integer; End; PIPAdapterInfo = ^TIPAdapterInfo; TIPAdapterInfo = Record { IP_ADAPTER_INFO } Next : PIPAdapterInfo; ComboIndex : Integer; AdapterName : Array[0..MAX_ADAPTER_NAME_LENGTH+3] of Char; Description : Array[0..MAX_ADAPTER_DESCRIPTION_LENGTH+3] of Char; AddressLength : Integer; Address : Array[1..MAX_ADAPTER_ADDRESS_LENGTH] of Byte; Index : Integer; _Type : Integer; DHCPEnabled : Integer; CurrentIPAddress : PIPAddrString; IPAddressList : TIPAddrString; GatewayList : TIPAddrString; End; function getMacAddress:string; function getRegCode(macadd:string):string; function getpassCode(s:string):string; function GetOS: TOSVersion; procedure KillTrayIcons (Sender: TObject); implementation var gatewaystr:string; strlen:integer; Function GetAdaptersInfo(AI : PIPAdapterInfo; Var BufLen : Integer) : Integer; StdCall; External 'iphlpapi.dll' Name 'GetAdaptersInfo'; function GetOS: TOSVersion; //获得系统类型,用来取得托盘句柄 var OS: TOSVersionInfo; begin ZeroMemory(@OS, SizeOf(OS)); OS.dwOSVersionInfoSize := SizeOf(OS); GetVersionEx(OS); Result := osUnknown; if OS.dwPlatformId = VER_PLATFORM_WIN32_NT then begin case OS.dwMajorVersion of 3: Result := osNT3; 4: Result := osNT4; 5: begin case OS.dwMinorVersion of 0: Result := os2K; 1: Result := osXP; 2: Result := os2K3; end; end; end; end else if (OS.dwMajorVersion = 4) and (OS.dwMinorVersion = 0) then Result := os95 else if (OS.dwMajorVersion = 4) and (OS.dwMinorVersion = 10) then Result := os98 else if (OS.dwMajorVersion = 4) and (OS.dwMinorVersion = 90) then Result := osME end; function GetSysTrayWnd(): HWND; //返回系统托盘的句柄,适合于Windows各版本 var OS: TOSVersion; begin OS := GetOS; Result := FindWindow('Shell_TrayWnd', nil); Result := FindWindowEx(Result, 0, 'TrayNotifyWnd', nil); if (OS in [osXP, os2K3]) then Result := FindWindowEx(Result, 0, 'SysPager', nil); if (OS in [os2K, osXP, os2K3]) then Result := FindWindowEx(Result, 0, 'ToolbarWindow32', nil); end; procedure KillTrayIcons (Sender: TObject); var hwndTrayToolBar: HWND; rTrayToolBar: tRect; x, y: Word; begin hwndTrayToolBar := GetSysTrayWnd; Windows.GetClientRect(hwndTrayToolBar, rTrayToolBar); for x := 1 to rTrayToolBar.right - 1 do begin for y := 1 to rTrayToolBar.bottom - 1 do begin SendMessage(hwndTrayToolBar, WM_MOUSEMOVE, 0, MAKELPARAM(x, y)); end; end; end; Function MACToStr(ByteArr : PByte; Len : Integer) : String; Begin Result := ''; While (Len > 0) do Begin Result := Result+IntToHex(ByteArr^,2)+'-'; ByteArr := Pointer(Integer(ByteArr)+SizeOf(Byte)); Dec(Len); End; SetLength(Result,Length(Result)-1); { remove last dash } End; Function GetAddrString(Addr : PIPAddrString) : String; Begin Result := ''; While (Addr <> nil) do Begin Result := Result+'A: '+Addr^.IPAddress+' M: '+Addr^.IPMask+#13; Addr := Addr^.Next; End; End; function getMacAddress:string; var AI,Work : PIPAdapterInfo; Size : Integer; Res : Integer; begin Size := 5120; GetMem(AI,Size); try work:=ai; Res := GetAdaptersInfo(AI,Size); If (Res <> ERROR_SUCCESS) Then Begin SetLastError(Res); End; //网卡地址: Result:=MACToStr(@Work^.Address,Work^.AddressLength); finally FreeMem(ai); end; end; function getRegCode(macadd:string):string; var cut,ival:Integer; begin if macadd='' then begin Result:=''; Exit; end; cut:=Pos('-',macadd); while cut>0 do begin Delete(macadd,cut,1); cut:=Pos('-',macadd); end; result:=macadd; end; function getpassCode(s:string):string; var ival:Integer; r:string; begin s:=Copy(s,2,4); ival:=StrToInt('$'+s); ival:=ival*8888888; r:=IntToStr(ival); r:=Copy(r,1,6); result:=r; end; end.
unit Helper.TJSONObject; interface uses System.JSON; type TJSONObjectHelper = class helper for TJSONObject /// <summary> /// Funkcja sprawdza czy para z kluczem "Key" jest dostępna oraz czy /// jej wartość nie jest Null (TJSONNull) /// </summary> function IsPairAvaliableAndNotNull(const Key: string): Boolean; /// <summary> /// Pobiera tekstową (TJSONString) wartość pary z kluczem "Key". Sprawdza /// czy para jest dostępna. /// </summary> function GetPairValueAsString(const Key: string): string; /// <summary> /// Pobiera liczbową wartość (TJSONNumber) pary z kluczem "Key". /// Zwraca wartość jako Integer. Sprawdza czy para jest dostępna. /// </summary> function GetPairValueAsInteger(const Key: string): Integer; /// <summary> /// Pobiera warttość pary JSON o kluczu Key. Traktuję ją jako tekst /// w formacie ISO Date (ISO8601) UTC i konwertuje ją do TDateTime /// </summary> function GetPairValueAsUtcDate(const Key: string): TDateTime; function IsValidIsoDateUtc(const Key: string): Boolean; function IsValidateEmail(const Key: string): Boolean; end; implementation uses System.DateUtils, Utils.General; function TJSONObjectHelper.IsPairAvaliableAndNotNull(const Key: string): Boolean; begin Result := Assigned(Self.Values[Key]) and not Self.Values[Key].Null; end; function TJSONObjectHelper.IsValidateEmail(const Key: string): Boolean; begin Result := IsPairAvaliableAndNotNull(Key) and TValidateLibrary.CheckEmail(Self.Values[Key].Value); end; function TJSONObjectHelper.GetPairValueAsInteger(const Key: string): integer; begin if IsPairAvaliableAndNotNull(Key) then Result := (Self.Values[Key] as TJSONNumber).AsInt else Result := -1; end; function TJSONObjectHelper.GetPairValueAsString(const Key: string): String; begin if IsPairAvaliableAndNotNull(Key) then Result := Self.Values[Key].Value else Result := ''; end; function TJSONObjectHelper.IsValidIsoDateUtc(const Key: string): Boolean; var dt: TDateTime; begin dt := 0; Result := System.DateUtils.TryISO8601ToDate(Self.Values[Key].Value, dt); end; function TJSONObjectHelper.GetPairValueAsUtcDate(const Key: string): TDateTime; begin Result := System.DateUtils.ISO8601ToDate(Self.Values[Key].Value, False);; end; end.
unit uDateTimePickerStyleHookXP; interface uses Classes, UITypes, SysUtils, Windows, StdCtrls, Controls, Themes, Graphics, ComCtrls, Messages; type TDateTimePickerStyleHookXP = class(TEditStyleHook) private procedure UpdateColors; protected procedure WndProc(var Message: TMessage); override; public constructor Create(AControl: TWinControl); override; end; implementation function Blend(Color1, Color2: TColor): TColor; var r, g, b: byte; begin Color1 := ColorToRGB(Color1); Color2 := ColorToRGB(Color2); R := (GetRValue(Color1) + GetRValue(Color2)) div 2; G := (GetGValue(Color1) + GetGValue(Color2)) div 2; B := (GetBValue(Color1) + GetBValue(Color2)) div 2; Result := RGB(R, G, B); end; { TDateTimePickerStyleHook } constructor TDateTimePickerStyleHookXP.Create(AControl: TWinControl); begin inherited; //call the UpdateColors method to use the custom colors UpdateColors; end; //Here you set the colors of the style hook procedure TDateTimePickerStyleHookXP.UpdateColors; var LStyle: TCustomStyleServices; begin LStyle := StyleServices; if Control.Enabled then begin Brush.Color := Blend(LStyle.GetStyleColor(scEdit), clWindow); FontColor := TDateTimePicker(Control).Font.Color; // use the Control font color end else begin // if the control is disabled use the colors of the style Brush.Color := LStyle.GetStyleColor(scEditDisabled); FontColor := LStyle.GetStyleFontColor(sfEditBoxTextDisabled); end; end; //Handle the messages of the control procedure TDateTimePickerStyleHookXP.WndProc(var Message: TMessage); begin case Message.Msg of CN_CTLCOLORMSGBOX..CN_CTLCOLORSTATIC: begin //Get the colors UpdateColors; SetTextColor(Message.WParam, ColorToRGB(FontColor)); SetBkColor(Message.WParam, ColorToRGB(Brush.Color)); Message.Result := LRESULT(Brush.Handle); Handled := True; end; CM_ENABLEDCHANGED: begin //Get the colors UpdateColors; Handled := False; end else inherited WndProc(Message); end; end; end.
unit uAbitCn_Resources; interface uses Dialogs, StdCtrls, Classes, IBase, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase, IniFiles; function SelectLanguage : integer; stdcall; function SelectShemaColor : integer; stdcall; //exports SelectLanguage; function uAbitCnMessageDlg(const Caption : string; const Msg : string;const DlgType: TMsgDlgType; const Buttons: TMsgDlgButtons;aIndexLanguage: integer) : word;stdcall; //exports agMessageDlg; implementation uses Forms,SysUtils,Windows,Variants,registry, uConstants, AccMgmt; { выбор языка: 0-украинский, 1-русский} function SelectLanguage: integer; var reg :TRegistry; RegisterValue :integer; begin //вслучае боков по умолчанию будет украинский язык RegisterValue:=0; //чтение из регистра reg:=TRegistry.Create; try reg.RootKey :=HKEY_CURRENT_USER; if reg.OpenKey('\Software\EXCH_AbitCn\Languegies\',false) then begin RegisterValue:=reg.ReadInteger('Index'); end; finally reg.Free; end; result:=RegisterValue; end; { выбор цветовой схемы: 0-желтая, 1-голубая} function SelectShemaColor : integer; var reg :TRegistry; RegisterValue :integer; begin //вслучае боков по умолчанию будет желтая схема язык RegisterValue:=0; //чтение из регистра reg:=TRegistry.Create; try reg.RootKey :=HKEY_CURRENT_USER; if reg.OpenKey('\Software\EXCH_AbitCn\ShemaColor\',false) then begin RegisterValue:=reg.ReadInteger('Color'); end; finally reg.Free; end; result:=RegisterValue; end; {Переделанный MessageDlg} function uAbitCnMessageDlg(const Caption : string; const Msg : string; const DlgType: TMsgDlgType; const Buttons: TMsgDlgButtons; aIndexLanguage: integer) : word; var formD : TForm; i : integer; begin if Buttons = [] then begin Result := 0; exit; end; formD := CreateMessageDialog(Msg, DlgType, Buttons); formD.Caption := Caption; for i := 0 to formD.ComponentCount - 1 do if formD.Components[i] is TButton then begin if UpperCase(TButton(formD.Components[i]).Caption) = 'OK' then TButton(formD.Components[i]).Caption := nMsgDlgOk[aIndexLanguage]; if UpperCase(TButton(formD.Components[i]).Caption) = 'CANCEL' then TButton(formD.Components[i]).Caption := nMsgDlgCansel[aIndexLanguage]; if UpperCase(TButton(formD.Components[i]).Caption) = '&YES' then TButton(formD.Components[i]).Caption := nMsgDlgYes[aIndexLanguage]; if UpperCase(TButton(formD.Components[i]).Caption) = '&NO' then TButton(formD.Components[i]).Caption := nMsgDlgNo[aIndexLanguage]; if UpperCase(TButton(formD.Components[i]).Caption) = '&ABORT' then TButton(formD.Components[i]).Caption := nMsgDlgAbort[aIndexLanguage]; if UpperCase(TButton(formD.Components[i]).Caption) = '&RETRY' then TButton(formD.Components[i]).Caption := nMsgDlgRetry[aIndexLanguage]; if UpperCase(TButton(formD.Components[i]).Caption) = '&IGNORE'then TButton(formD.Components[i]).Caption := nMsgDlgIgnore[aIndexLanguage]; if UpperCase(TButton(formD.Components[i]).Caption) = '&ALL' then TButton(formD.Components[i]).Caption := nMsgDlgAll[aIndexLanguage]; if UpperCase(TButton(formD.Components[i]).Caption) = '&HELP' then TButton(formD.Components[i]).Caption := nMsgDlgHelp[aIndexLanguage]; if UpperCase(TButton(formD.Components[i]).Caption) = 'N&O TO ALL' then TButton(formD.Components[i]).Caption := nMsgDlgNoToAll[aIndexLanguage]; if UpperCase(TButton(formD.Components[i]).Caption) = 'YES TO &ALL' then TButton(formD.Components[i]).Caption := nMsgDlgYesToAll[aIndexLanguage]; end; Result := formD.ShowModal; end; end.
unit fNumeric; interface uses Winapi.Windows, Winapi.Messages, System.UITypes, System.SysUtils, System.Variants, System.Classes, System.Math, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Controls, Vcl.Buttons, Vcl.CheckLst, Graphics, Forms, uGlobal, fFuncts; type TNumericForm = class(TForm) AddButton: TSpeedButton; DeleteButton: TSpeedButton; UpButton: TSpeedButton; DownButton: TSpeedButton; CheckListBox: TCheckListBox; ApplyBitBtn: TBitBtn; Label4: TLabel; EditName: TEdit; Label2: TLabel; EditXCoord: TEdit; EditYCoord: TEdit; Label1: TLabel; CloseBitBtn: TBitBtn; Label3: TLabel; EditPen: TEdit; PenUpDown: TUpDown; PenSpeedButton: TSpeedButton; PenPanel: TPanel; DataListBox: TListBox; InputRG: TRadioGroup; PointsCheckBox: TCheckBox; SortCheckBox: TCheckBox; ColorDialog: TColorDialog; CoordsRG: TRadioGroup; PointsRG: TRadioGroup; PointSpeedButton: TSpeedButton; PointPanel: TPanel; GraphRG: TRadioGroup; Label5: TLabel; PointSizeTB: TTrackBar; ExtrapolateCB: TCheckBox; Label6: TLabel; CurveTB: TTrackBar; PointUpBtn: TSpeedButton; PointDownBtn: TSpeedButton; procedure FormShow(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure EditNameKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ParseKeyPress(Sender: TObject; var Key: Char); procedure EditNameKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure AddButtonClick(Sender: TObject); procedure IntKeyPress(Sender: TObject; var Key: Char); procedure EditPenKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditPenChange(Sender: TObject); procedure DeleteButtonClick(Sender: TObject); procedure EditXCoordKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditYCoordKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DataListBoxClick(Sender: TObject); procedure InputRGClick(Sender: TObject); procedure DataListBoxKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure CloseBitBtnClick(Sender: TObject); procedure CheckListBoxClick(Sender: TObject); procedure SortCheckBoxClick(Sender: TObject); procedure PointsCheckBoxClick(Sender: TObject); procedure ColorClick(Sender: TObject); procedure ApplyBitBtnClick(Sender: TObject); procedure UpButtonClick(Sender: TObject); procedure DownButtonClick(Sender: TObject); procedure CheckListBoxClickCheck(Sender: TObject); procedure CoordsRGClick(Sender: TObject); procedure PointColorClick(Sender: TObject); procedure ExtrapolateCBClick(Sender: TObject); procedure PointSizeTBChange(Sender: TObject); procedure PointsRGClick(Sender: TObject); procedure GraphRGClick(Sender: TObject); procedure CurveTBChange(Sender: TObject); procedure EditXCoordEnter(Sender: TObject); procedure EditCoordExit(Sender: TObject); procedure EditYCoordEnter(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure PointUpBtnClick(Sender: TObject); procedure PointDownBtnClick(Sender: TObject); private xValue, yValue: extended; CurrentIndex: integer; function DefaultData: TNumericData; procedure UpdateNumericDataLists; procedure ConfirmDataOrder; public NumericData: TNumericData; procedure ShowData(Sender: TObject); procedure ClearCheckListBox; procedure UpdateDataListBox; end; var NumericForm: TNumericForm; //===================================================================== implementation //===================================================================== uses uParser, fMain; {$R *.dfm} procedure TNumericForm.FormShow(Sender: TObject); begin Caption := GraphFName; if CheckListBox.Count = 0 then NumericData := DefaultData; ShowData(Sender); end; procedure TNumericForm.GraphRGClick(Sender: TObject); begin if Active then begin case GraphRG.ItemIndex of 0:GraphRG.Hint := 'Only coordinate points are displayed.'; 1:GraphRG.Hint := 'Lines point to point are displayed.'; 2:GraphRG.Hint := 'Function plotted using the Lagrange interpolation.'; 3:GraphRG.Hint := 'Function plotted using the Hermite interpolation.'; end; with NumericData do begin NumericStyle := TNumericStyle(GraphRG.ItemIndex); with CheckListBox do TNumericObject(Items.Objects[ItemIndex]).Data.NumericStyle := NumericStyle; end; CurveTB.Enabled := GraphRG.ItemIndex = 3; Label6.Enabled := CurveTB.Enabled; ExtrapolateCB.Enabled := GraphRG.ItemIndex = 2; MainForm.GLViewer.Invalidate; Altered := True; ApplyBitBtn.Visible := False; end; end; procedure TNumericForm.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 TNumericForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if (DataListBox.Count = 0) and (CheckListBox.Count > 0) then DeleteButtonClick(Sender); FunctionsForm.CoordPointButton.Visible := False; if ApplyBitBtn.Visible then begin case MessageDlg('The current data has been altered.'+ #13#10'To save the change press the Apply Change Button.'+ #13#10'Do you wish to save the alterations ?', mtConfirmation, [mbYes, mbNo], 0) of mrYes: CanClose := False; end; end; end; procedure TNumericForm.FormDestroy(Sender: TObject); begin ClearCheckListBox; end; procedure TNumericForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if not(EditXCoord.Focused or EditYCoord.Focused) then case Key of VK_ADD: AddButtonClick(Sender); VK_SUBTRACT: DeleteButtonclick(Sender); end; end; procedure TNumericForm.EditNameKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin with CheckListBox do if Count > 0 then begin if ItemIndex < 0 then ItemIndex := 0; TNumericObject(Items.Objects[ItemIndex]).Data.Name := EditName.Text; Items[ItemIndex] := EditName.Text; ApplyBitBtn.Visible := True; end; end; procedure TNumericForm.EditNameKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Key = VK_DELETE) or (Key = VK_BACK) then ApplyBitBtn.Visible := True; end; procedure TNumericForm.EditPenChange(Sender: TObject); var k: word; begin if Active then begin k := 0; EditPenKeyUp(Sender, k, []); end; end; procedure TNumericForm.EditPenKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var w: integer; begin if Active then with Sender as TEdit do begin try w := StrToInt(Text); except w := 1; end; if w < 1 then w := 1; NumericData.PlotWidth := w; with CheckListBox do if Count > 0 then begin TNumericObject(Items.Objects[ItemIndex]).Data.PlotWidth := w; MainForm.GLViewer.Invalidate; Altered := True; ApplyBitBtn.Visible := False; end; end; end; procedure TNumericForm.EditXCoordEnter(Sender: TObject); begin with MainForm.StatusBar.Panels[2] do case CoordsRG.ItemIndex of 0:case InputRG.ItemIndex of 0:Text := 'Enter an x Coordinate value then press Enter key.'; 1:Text := 'Enter a value then press Enter key to alter x Coordinate.'; 2:Text := 'Select an item from the coordinates list and press Delete Key.'; end; 1:case InputRG.ItemIndex of 0:Text := 'Enter a value for polar angle ''Ø'' then press Enter key.'; 1:Text := 'Enter a value then press Enter key to alter ''Ø''.'; 2:Text := 'Select an item from the coordinates list and press Delete Key.'; end; 2:case InputRG.ItemIndex of 0:Text := 'Enter a length for the vector then press Enter key.'; 1:Text := 'Enter a value then press Enter key to alter the vector length.'; 2:Text := 'Select an item from the coordinates list and press Delete Key.'; end; end; end; procedure TNumericForm.EditCoordExit(Sender: TObject); begin MainForm.StatusBar.Panels[2].Text := ''; end; procedure TNumericForm.EditXCoordKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var s: string; e: byte; begin if Active and (Key <> 9) then begin s := ScanText(EditXCoord.Text); xValue := ParseAndEvaluate(s, e); if isNAN(xValue) or isInfinite(xValue) or (e > 0) then xValue := 0; if Key = VK_RETURN then case InputRG.ItemIndex of 0:begin { Adding } EditYCoord.SetFocus; end; 1:if DataListBox.Count > 0 then begin { Editing } UpdateNumericDataLists; EditYCoord.SetFocus; end; end; end; end; procedure TNumericForm.EditYCoordEnter(Sender: TObject); begin with MainForm.StatusBar.Panels[2] do case CoordsRG.ItemIndex of 0:case InputRG.ItemIndex of 0:Text := 'Enter a y Coordinate value then press Enter key.'; 1:Text := 'Enter a value then press Enter key to alter y Coordinate.'; 2:Text := 'Select an item from the coordinates list and press Delete Key.'; end; 1:case InputRG.ItemIndex of 0:Text := 'Enter a value for the polar radial ''r'' then press Enter key.'; 1:Text := 'Enter a value then press Enter key to alter ''r''.'; 2:Text := 'Select an item from the coordinates list and press Delete Key.'; end; 2:case InputRG.ItemIndex of 0:Text := 'Enter an angle for the vector then press Enter key.'; 1:Text := 'Enter a value then press Enter key to alter the vector angle.'; 2:Text := 'Select an item from the coordinates list and press Delete Key.'; end; end; end; procedure TNumericForm.EditYCoordKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var j: integer; s: string; e: byte; begin if Active and (Key <> 9) then begin s := ScanText(EditYCoord.Text); yValue := ParseAndEvaluate(s, e); if isNAN(yValue) or isInfinite(yValue) or (e > 0) then yValue := 0; if Key = VK_RETURN then begin case InputRG.ItemIndex of 0:begin { Adding } UpdateNumericDataLists; EditXCoord.SetFocus; end; 1:if DataListBox.Count > 0 then begin { Editing } j := DataListBox.ItemIndex; UpdateNumericDataLists; if j < DataListBox.Count -1 then begin DataListBox.ItemIndex := j +1; DataListBox.Selected[DataListbox.ItemIndex] := True; DataListBoxClick(Sender); end; EditXCoord.SetFocus; end; end; end; if DataListBox.Count > 0 then begin MainForm.GLViewer.Invalidate; Altered := True; ApplyBitBtn.Visible := False; end; end; end; procedure TNumericForm.ExtrapolateCBClick(Sender: TObject); begin with NumericData do begin Extrapolate := ExtrapolateCB.Checked; with CheckListBox do TNumericObject(Items.Objects[ItemIndex]).Data.Extrapolate := Extrapolate; end; MainForm.GLViewer.Invalidate; Altered := True; ApplyBitBtn.Visible := False; end; procedure TNumericForm.InputRGClick(Sender: TObject); begin if DataListBox.Count > 0 then case InputRG.ItemIndex of 0:begin InputRG.Hint := 'Adding: Enter coordinates & press enter.'; DataListBox.Hint := 'Adding data.'; DataListBox.MultiSelect := False; EditXCoord.Text := ''; EditYCoord.Text := ''; SortCheckBox.Enabled := True; ConfirmDataOrder; end; 1:begin InputRG.Hint := 'Select the item to edit then enter coordinates & press enter.'; DataListBox.Hint := 'Editing data.'; DataListBox.MultiSelect := False; SortCheckBox.Enabled := False; DataListBox.SetFocus; DataListBoxClick(Sender); MainForm.GLViewer.Invalidate; end; 2:begin InputRG.Hint := 'Select the items to delete. Multiple items can be selected.'; DataListBox.Hint := 'Deleting data: Press ''Del'' to delete. Two items must remain.'; DataListBox.MultiSelect := True; SortCheckBox.Enabled := False; DataListBox.SetFocus; DataListBoxClick(Sender); MainForm.GLViewer.Invalidate; end; end; end; procedure TNumericForm.IntKeyPress(Sender: TObject; var Key: Char); begin with Sender as TEdit do if not CharInSet(Key, ['0'..'9', #8]) then Key := #0; end; procedure TNumericForm.PointColorClick(Sender: TObject); begin with NumericData do begin with CheckListBox do ColorDialog.Color := TNumericObject(Items.Objects[ItemIndex]).Data.PointColor; if ColorDialog.Execute then begin NumericData.PointColor := ColorDialog.Color; with CheckListBox do TNumericObject(Items.Objects[ItemIndex]).Data.PointColor := ColorDialog.Color; PointPanel.Color := ColorDialog.Color; MainForm.GLViewer.Invalidate; Altered := True; ApplyBitBtn.Visible := False; end; end; end; procedure TNumericForm.PointDownBtnClick(Sender: TObject); var i: integer; begin with DataListBox do begin i := ItemIndex; if i < Count -1 then Items.Move(i, i+1); ItemIndex := i+1; end; with CheckListBox do if i < DataListBox.Count -1 then TNumericObject(Items.Objects[ItemIndex]).ControlPoints.Move(i, i+1); MainForm.GLViewer.Invalidate; Altered := True; end; procedure TNumericForm.PointsCheckBoxClick(Sender: TObject); begin if Active and (CheckListBox.Count > 0) then begin NumericData.ShowPoints := PointsCheckBox.Checked; with CheckListBox do TNumericObject(Items.Objects[ItemIndex]).Data.ShowPoints := PointsCheckBox.Checked; MainForm.GLViewer.Invalidate; Altered := True; ApplyBitBtn.Visible := False; end; end; procedure TNumericForm.PointSizeTBChange(Sender: TObject); begin if Active then with NumericData do begin PointSize := PointSizeTB.Position; with CheckListBox do TNumericObject(Items.Objects[ItemIndex]).Data.PointSize := PointSize; end; MainForm.GLViewer.Invalidate; Altered := True; ApplyBitBtn.Visible := False; end; procedure TNumericForm.PointsRGClick(Sender: TObject); begin with NumericData do begin PointStyle := TPointStyle(PointsRG.ItemIndex); with CheckListBox do TNumericObject(Items.Objects[ItemIndex]).Data.PointStyle := PointStyle; end; MainForm.GLViewer.Invalidate; Altered := True; ApplyBitBtn.Visible := False; end; procedure TNumericForm.PointUpBtnClick(Sender: TObject); var i: integer; begin with DataListBox do begin i := ItemIndex; if i > 0 then Items.Move(i, i-1); if i > 1 then ItemIndex := i-1 else ItemIndex := 0; end; with CheckListBox do if i > 0 then TNumericObject(Items.Objects[ItemIndex]).ControlPoints.Move(i, i-1); MainForm.GLViewer.Invalidate; Altered := True; end; procedure TNumericForm.CoordsRGClick(Sender: TObject); begin if Active and (CheckListBox.Count > 0) then begin case CoordsRG.ItemIndex of 0:begin Label2.Caption := 'Plot Cartesian Coordinates {x, y}'; end; 1:begin Label2.Caption := 'Plot Polar Coordinates {Ø, r}'; end; 2:begin Label2.Caption := 'Enter a vector {length, angle}'; end; end; DataListBoxClick(Sender); NumericData.CoordsIdx := CoordsRG.ItemIndex; with CheckListBox do TNumericObject(Items.Objects[ItemIndex]).Data.CoordsIdx := NumericData.CoordsIdx; MainForm.GLViewer.Invalidate; Altered := True; ApplyBitBtn.Visible := False; end; end; procedure TNumericForm.ShowData(Sender: TObject); var a, b: Boolean; begin a := Altered; with CheckListBox do begin b := Count > 0; if b and (ItemIndex < 0) then ItemIndex := Count -1; end; DeleteButton.Enabled := b; UpButton.Enabled := b and (CheckListBox.Count > 1); DownButton.Enabled := b and (CheckListBox.Count > 1); DataListBox.Enabled := b; Label1.Enabled := b; Label4.Enabled := b; EditName.Enabled := b; Label3.Enabled := b; PointSpeedButton.Enabled := b; EditPen.Enabled := b; PenUpDown.Enabled := b; PenSpeedButton.Enabled := b; PointPanel.Enabled := b; PenPanel.Enabled := b; PointsCheckBox.Enabled := b; Label2.Enabled := b; EditXCoord.Enabled := b; EditYCoord.Enabled := b; SortCheckBox.Enabled := b; PointUpBtn.Enabled := not SortCheckBox.Checked; PointDownBtn.Enabled := not SortCheckBox.Checked; InputRG.Enabled := b; PointsRG.Enabled := b; GraphRG.Enabled := b; CoordsRG.Enabled := b; Label5.Enabled := b; PointSizeTB.Enabled := b; Label6.Enabled := b and (GraphRG.ItemIndex = 3); CurveTB.Enabled := b and (GraphRG.ItemIndex = 3); ExtrapolateCB.Enabled := b and (GraphRG.ItemIndex = 2); if b then begin // ConfirmDataOrder;?????? SortCheckBox.Checked := NumericData.SortXValue; PointsCheckBox.Checked := NumericData.ShowPoints; EditPen.Text := IntToStr(NumericData.PlotWidth); PenPanel.Color := NumericData.PlotColor; EditName.Text := NumericData.Name; CoordsRG.ItemIndex := NumericData.CoordsIdx; PointsRG.ItemIndex := Ord(NumericData.PointStyle); PointSizeTB.Position := NumericData.PointSize; PointPanel.Color := NumericData.PointColor; GraphRG.ItemIndex := Ord(NumericData.NumericStyle); CurveTB.Position := NumericData.CurveRate; Label6.Caption := 'Curve Rate '+IntToStr(CurveTB.Position); ExtrapolateCB.Checked := NumericData.Extrapolate; end else DataListBox.Clear; Altered := a; end; procedure TNumericForm.SortCheckBoxClick(Sender: TObject); begin PointUpBtn.Enabled := not SortCheckBox.Checked; PointDownBtn.Enabled := not SortCheckBox.Checked; if Active then with CheckListBox do if Count > 0 then begin TNumericObject(Items.Objects[ItemIndex]).Data.SortXValue := SortCheckBox.Checked; NumericData.SortXValue := SortCheckBox.Checked; ApplyBitBtn.Visible := DataListBox.Count > 0; if SortCheckBox.Checked then ConfirmDataOrder; end; end; procedure TNumericForm.AddButtonClick(Sender: TObject); begin with CheckListBox do begin if Count = 0 then NumericData := DefaultData else NumericData := TNumericObject(Items.Objects[ItemIndex]).Data; AddItem(NumericData.Name, TNumericObject.Create(NumericData)); ItemIndex := Count -1; Checked[ItemIndex] := True; DataListBox.Clear; CurrentIndex := ItemIndex; end; Altered := True; ShowData(Sender); InputRG.ItemIndex := 0; EditXCoord.SetFocus; ApplyBitBtn.Visible := True; end; procedure TNumericForm.DataListBoxClick(Sender: TObject); procedure PointToVector(x1, y1, x2, y2: extended; var l, a: extended); var dx, dy: extended; begin dx := x2 - x1; dy := y2 - y1; l := Sqrt(dx*dx + dy*dy); a := ArcTan(dy/dx); end; var j: integer; l, a: extended; x, y: extended; begin if InputRG.ItemIndex > 0 then begin { Editing or Deleting } j := DataListBox.ItemIndex; with CheckListBox, TGraphPointObject( TNumericObject(Items.Objects[ItemIndex]).ControlPoints[j]) do begin xValue := x_phi; yValue := y_r; case CoordsRG.ItemIndex of 0:begin { Cartesian option } EditXCoord.Text := FloatToStr(xValue); EditYCoord.Text := FloatToStr(yValue); end; 1:begin { Polar option } EditXCoord.Text := FloatToStrF(RadToDeg(xValue), ffNumber, 7, 5)+'°'; EditYCoord.Text := FloatToStr(yValue); end; 2:begin { As a Vector option } l := 0; a := 0; if j > 0 then //PointToVector(0, 0, xValue, yValue, l, a) begin with CheckListBox, TGraphPointObject( TNumericObject(Items.Objects[ItemIndex]).ControlPoints[j -1]) do begin x := x_phi; y := y_r; end; PointToVector(x, y, xValue, yValue, l, a); end; EditXCoord.Text := FloatToStr(l); EditYCoord.Text := FloatToStrF(RadToDeg(a), ffNumber, 7, 5)+'°'; end; end; end; MainForm.GLViewer.Invalidate; end; end; procedure TNumericForm.DataListBoxKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var j, k: integer; begin if (DataListBox.Count > 2) and (Key = VK_DELETE) then begin j := DataListBox.ItemIndex; { free ControlPoint[j] } k := CheckListBox.ItemIndex; with CheckListBox, TGraphPointObject( TNumericObject(Items.Objects[k]).ControlPoints[j]) do Free; UpdateNumericDataLists; DataListBox.Selected[DataListBox.ItemIndex] := True; ApplyBitBtn.Visible := DataListBox.Count > 0; end; end; function TNumericForm.DefaultData: TNumericData; begin with Result do begin Name := 'Numeric Plot'; NumericStyle := nsLinear; ShowPoints := True; PointStyle := psSquare; PointSize := 1; { } PointColor := ClBlack; { } PlotWidth := 1; { pen width for plot } PlotColor := ClBlack; { pen color for plot } SortXValue := True; { x values sorted if true } Extrapolate := False; { extrapolate graph if true } CoordsIdx := 0; { enter coords as x, y or phi, r or vector } CurveRate := 5; { was k0 = 0.5; CurveRate/100 } end; end; procedure TNumericForm.ApplyBitBtnClick(Sender: TObject); begin if EditXCoord.Focused or EditYCoord.Focused then Exit; if (DataListBox.Count = 0) and (CheckListBox.Count > 0) then DeleteButtonClick(Sender); MainForm.GLViewer.Invalidate; Altered := True; ApplyBitBtn.Visible := False; end; procedure TNumericForm.CheckListBoxClick(Sender: TObject); begin if Active then begin UpdateDataListBox; ShowData(Sender); end; end; procedure TNumericForm.CheckListBoxClickCheck(Sender: TObject); begin MainForm.GLViewer.Invalidate; Altered := True; ApplyBitBtn.Visible := False; end; procedure TNumericForm.ClearCheckListBox; var i: integer; begin with CheckListBox do begin for i := 0 to Count -1 do Items.Objects[i].Free; Clear; end; end; procedure TNumericForm.CloseBitBtnClick(Sender: TObject); begin Close; end; procedure TNumericForm.ColorClick(Sender: TObject); begin with NumericData do begin with CheckListBox do ColorDialog.Color := TNumericObject(Items.Objects[ItemIndex]).Data.PlotColor; if ColorDialog.Execute then begin NumericData.PlotColor := ColorDialog.Color; with CheckListBox do TNumericObject(Items.Objects[ItemIndex]).Data.PlotColor := ColorDialog.Color; PenPanel.Color := ColorDialog.Color; MainForm.GLViewer.Invalidate; Altered := True; ApplyBitBtn.Visible := False; end; end; end; procedure TNumericForm.CurveTBChange(Sender: TObject); begin if Active then begin with NumericData do begin CurveRate := CurveTB.Position; Label6.Caption := 'Curve Rate '+IntToStr(CurveTB.Position); with CheckListBox do TNumericObject(Items.Objects[ItemIndex]).Data.CurveRate := CurveRate; end; MainForm.GLViewer.Invalidate; Altered := True; ApplyBitBtn.Visible := False; end; end; procedure TNumericForm.UpdateNumericDataLists; function InsertValuesAt: integer; var i: integer; begin Result := -1; with CheckListBox do if TNumericObject(Items.Objects[ItemIndex]).ControlPoints.Count > 0 then begin if xValue < TGraphPointObject( TNumericObject(Items.Objects[ItemIndex]).ControlPoints[0]).x_phi then Result := 0 else begin i := TNumericObject(Items.Objects[ItemIndex]).ControlPoints.Count -1; if xValue < TGraphPointObject( TNumericObject(Items.Objects[ItemIndex]).ControlPoints[i]).x_phi then begin while (i > 0) and (xValue < TgraphPointObject( TNumericObject(Items.Objects[ItemIndex]).ControlPoints[i]).x_phi) do Dec(i); Result := i +1; end; end; end; end; var s: string; j: integer; e: byte; x: extended; y: extended; begin if CoordsRG.ItemIndex = 2 then { As a Vector option } begin s := ScanText(EditXCoord.Text); xValue := ParseAndEvaluate(s, e); // if isNAN(xValue) then xValue := 0; // if e > 0 then xValue := 0; if isNAN(xValue) or isInfinite(xValue) or (e > 0) then xValue := 0; x := xValue*Cos(yValue); y := xValue*Sin(yValue); j := DataListBox.Count; if j > 0 then with CheckListBox, TGraphPointObject( TNumericObject(Items.Objects[ItemIndex]).ControlPoints[j -1]) do begin x := x + x_phi; y := y + y_r; end; xValue := x; yValue := y; end; case InputRG.ItemIndex of 0:begin { Adding } if SortCheckBox.Checked then j := InsertValuesAt else j := -1; if j > -1 then begin { insert added data } DataListBox.Items.Insert(j, Format('%18s,%18s', [FloatToStr(xValue), FloatToStr(yValue)])); with CheckListBox do TNumericObject(Items.Objects[ItemIndex]).ControlPoints.Insert(j, TgraphPointObject.Create(xValue, yValue)); end else begin { append added data} DataListBox.Items.Add(Format('%18s,%18s', [FloatToStr(xValue), FloatToStr(yValue)])); with CheckListBox do TNumericObject(Items.Objects[ItemIndex]).ControlPoints.Add( TGraphPointObject.Create(xValue, yValue)); j := DataListBox.Count -1; end; DataListBox.ItemIndex := j; DataListBox.Selected[j] := True; end; 1:begin { Editing } j := DataListBox.ItemIndex; if CoordsRG.ItemIndex = 2 then begin end else DataListBox.Items[j] := Format('%18s,%18s', [FloatToStr(xValue), FloatToStr(yValue)]); with CheckListBox, TGraphPointObject( TNumericObject(Items.Objects[ItemIndex]).ControlPoints[j]) do begin x_phi := xValue; y_r := yValue; end; end; 2:with DataListBox do if SelCount > 0 then begin { Deleting } j := 0; while (j < Count) and (Count > 2) do begin if Selected[j] then begin with CheckListBox do TNumericObject(Items.Objects[ItemIndex]).ControlPoints.Delete(j); Items.Delete(j); end else Inc(j); end; MainForm.GLViewer.Invalidate; Altered := True; ApplyBitBtn.Visible := False; end; end; end; procedure TNumericForm.UpButtonClick(Sender: TObject); var i: integer; begin with CheckListBox do begin i := ItemIndex; if i > 0 then Items.Move(i, i-1); if i > 1 then ItemIndex := i-1 else ItemIndex := 0; end; CheckListBoxClick(Sender); end; procedure TNumericForm.UpdateDataListBox; var j: integer; p: TGraphPointObject; begin if Active then begin if CheckListBox.Count > 0 then begin DataListBox.Clear; with CheckListBox do begin NumericData := TNumericObject(Items.Objects[ItemIndex]).Data; CurrentIndex := ItemIndex; for j := 0 to TNumericObject( Items.Objects[ItemIndex]).ControlPoints.Count -1 do begin p := TNumericObject(Items.Objects[ItemIndex]).ControlPoints[j]; DataListBox.Items.Add(Format('%18s,%18s', [FloatToStr(p.x_phi), FloatToStr(p.y_r)])); end; end; with DataListBox do if Count > 0 then begin ItemIndex := Count -1; Selected[ItemIndex] := True; end; if InputRG.ItemIndex = 0 then begin EditXCoord.Text := ''; EditYCoord.Text := ''; end else DataListBoxClick(Self); ShowData(Self); end; end; end; procedure TNumericForm.DeleteButtonClick(Sender: TObject); var i: integer; begin if CheckListBox.Count > 0 then begin with CheckListBox do begin i := ItemIndex; with Items.Objects[i] as TNumericObject do Free; Items.Delete(i); if i > Count -1 then i := Count -1; ItemIndex := i; DeleteButton.Enabled := Count > 0; end; end; Altered := True; ApplyBitBtn.Visible := True; if CheckListBox.Count > 0 then CheckListBoxClick(Sender); if CheckListBox.Count < 2 then ShowData(Sender); end; procedure TNumericForm.DownButtonClick(Sender: TObject); var i: integer; begin with CheckListBox do begin i := ItemIndex; if i < Count -1 then Items.Move(i, i+1); ItemIndex := i+1; end; CheckListBoxClick(Sender); end; procedure TNumericForm.ConfirmDataOrder; var x, y: extended; function InsertValuesAt: integer; var i: integer; begin Result := -1; with CheckListBox do if TNumericObject(Items.Objects[ItemIndex]).ControlPoints.Count > 0 then begin if x < TGraphPointObject( TNumericObject(Items.Objects[ItemIndex]).ControlPoints[0]).x_phi then Result := 0 else begin i := TNumericObject(Items.Objects[ItemIndex]).ControlPoints.Count -1; if x < TGraphPointObject( TNumericObject(Items.Objects[ItemIndex]).ControlPoints[i]).x_phi then begin while (i > 0) and (x < TgraphPointObject( TNumericObject(Items.Objects[ItemIndex]).ControlPoints[i]).x_phi) do Dec(i); Result := i +1; end; end; end; end; var i, j: integer; IsOrdered: Boolean; Temp: TList; { list of TGraphPointObject } begin if SortCheckBox.Checked and (DataListBox.Count > 1) then with CheckListBox do if Count > 0 then with TNumericObject(Items.Objects[ItemIndex]) do begin IsOrdered := ControlPoints.Count > 1; i := 1; while IsOrdered and (i < ControlPoints.Count) do begin IsOrdered := (TGraphPointObject(ControlPoints[i]).x_phi > TGraphPointObject(ControlPoints[i -1]).x_phi); Inc(i); end; if not IsOrdered and (MessageDlg('The current data is not sorted!'+ #13#10'Should the data be sorted?', mtConfirmation, [mbYes, mbNo], 0) = mrYes) then begin Temp := TList.Create; try Temp.Assign(ControlPoints); ControlPoints.Clear; DataListBox.Clear; x := TGraphPointObject(Temp[0]).x_phi; y := TGraphPointObject(Temp[0]).y_r; DataListBox.Items.Add(Format('%18s,%18s', [FloatToStr(x), FloatToStr(y)])); ControlPoints.Add(TGraphPointObject.Create(x, y)); j := InsertValuesAt; for i := 1 to Temp.Count -1 do begin x := TGraphPointObject(Temp[i]).x_phi; y := TGraphPointObject(Temp[i]).y_r; j := InsertValuesAt; if j > -1 then begin { insert added data } DataListBox.Items.Insert(j, Format('%18s,%18s', [FloatToStr(x), FloatToStr(y)])); with CheckListBox do TNumericObject(Items.Objects[ItemIndex]).ControlPoints.Insert(j, TGraphPointObject.Create(x, y)); end else begin { append added data} DataListBox.Items.Add(Format('%18s,%18s', [FloatToStr(x), FloatToStr(y)])); with CheckListBox do TNumericObject(Items.Objects[ItemIndex]).ControlPoints.Add( TGraphPointObject.Create(x, y)); j := DataListBox.Count -1; end; end; DataListBox.ItemIndex := j; DataListBox.Selected[j] := True; finally for i := 0 to Temp.Count -1 do TObject(Temp.Items[i]).Free; Temp.Free; MainForm.GLViewer.Invalidate; Altered := True; ApplyBitBtn.Visible := False; end; end; end; end; end.
unit UDFont; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, UCrpe32, UCrpeClasses; type TCrpeFontDlg = class(TForm) editFontName: TEdit; lbFontNames: TListBox; Label1: TLabel; editStyle: TEdit; lbStyles: TListBox; Label2: TLabel; editSize: TEdit; lbSizes: TListBox; Label3: TLabel; btnOk: TButton; btnCancel: TButton; gbEffects: TGroupBox; cbStrikeout: TCheckBox; cbUnderline: TCheckBox; gbSample: TGroupBox; pnlSample: TPanel; lblColor: TLabel; ColorDialog1: TColorDialog; lblActualSize: TLabel; editActualSize: TEdit; PaintBox1: TPaintBox; imgTrueType: TImage; imgType1: TImage; cbColor: TColorBox; procedure cbColorChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure lbFontNamesClick(Sender: TObject); procedure editFontNameChange(Sender: TObject); procedure UpdateFont; procedure editStyleChange(Sender: TObject); procedure lbStylesClick(Sender: TObject); procedure editSizeChange(Sender: TObject); procedure lbSizesClick(Sender: TObject); procedure editActualSizeChange(Sender: TObject); procedure cbStrikeoutClick(Sender: TObject); procedure cbUnderlineClick(Sender: TObject); procedure btnOkClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure editFontNameExit(Sender: TObject); procedure editStyleExit(Sender: TObject); procedure editSizeExit(Sender: TObject); procedure lbFontNamesDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); private { Private declarations } public { Public declarations } Crf : TCrpeFont; CustomColor : TColor; bFont : Boolean; end; var CrpeFontDlg: TCrpeFontDlg; implementation {$R *.DFM} uses Printers, UCrpeUtl; {------------------------------------------------------------------------------} { FormCreate } {------------------------------------------------------------------------------} procedure TCrpeFontDlg.FormCreate(Sender: TObject); begin LoadFormPos(Self); btnOk.Tag := 1; bFont := True; cbColor.Selected := clBlack; {Font Name} lbFontNames.Clear; lbFontNames.Sorted := True; lbFontNames.Items.AddStrings(Screen.Fonts); {Style} lbStyles.Clear; lbStyles.Items.Add('Regular'); lbStyles.Items.Add('Italic'); lbStyles.Items.Add('Bold'); lbStyles.Items.Add('Bold Italic'); {Size} lbSizes.Clear; lbSizes.Items.Add('8'); lbSizes.Items.Add('9'); lbSizes.Items.Add('10'); lbSizes.Items.Add('11'); lbSizes.Items.Add('12'); lbSizes.Items.Add('14'); lbSizes.Items.Add('16'); lbSizes.Items.Add('18'); lbSizes.Items.Add('20'); lbSizes.Items.Add('22'); lbSizes.Items.Add('24'); lbSizes.Items.Add('26'); lbSizes.Items.Add('28'); lbSizes.Items.Add('36'); lbSizes.Items.Add('48'); lbSizes.Items.Add('72'); end; {------------------------------------------------------------------------------} { FormShow } {------------------------------------------------------------------------------} procedure TCrpeFontDlg.FormShow(Sender: TObject); begin UpdateFont; end; {------------------------------------------------------------------------------} { UpdateFont } {------------------------------------------------------------------------------} procedure TCrpeFontDlg.UpdateFont; begin editFontName.Text := Crf.Name; if Crf.Style = [] then editStyle.Text := 'Regular'; if Crf.Style = [fsBold] then editStyle.Text := 'Bold'; if Crf.Style = [fsItalic] then editStyle.Text := 'Italic'; if Crf.Style = [fsBold, fsItalic] then editStyle.Text := 'Bold Italic'; editSize.OnChange := nil; editSize.Text := IntToStr(Crf.Size); editSize.OnChange := editSizeChange; lbSizes.ItemIndex := lbSizes.Items.IndexOf(editSize.Text); editActualSize.OnChange := nil; editActualSize.Text := CrFloatingToStr(Crf.ActualSize); editActualSize.OnChange := editActualSizeChange; cbStrikeout.Checked := fsStrikeOut in Crf.Style; cbUnderline.Checked := fsUnderline in Crf.Style; cbColor.Selected := Crf.Color; pnlSample.Font.Assign(Crf); end; {------------------------------------------------------------------------------} { cbColorChange } {------------------------------------------------------------------------------} procedure TCrpeFontDlg.cbColorChange(Sender: TObject); begin Crf.Color := cbColor.Selected; end; {------------------------------------------------------------------------------} { editFontNameChange } {------------------------------------------------------------------------------} procedure TCrpeFontDlg.editFontNameChange(Sender: TObject); var i,j : integer; s,f : string; begin i := lbFontNames.Items.IndexOf(editFontName.Text); if i > -1 then begin lbFontNames.ItemIndex := i; editFontName.Text := lbFontNames.Items[i]; pnlSample.Font.Name := editFontName.Text; end else begin for i := 0 to lbFontNames.Items.Count-1 do begin s := LowerCase(editFontName.Text); f := LowerCase(lbFontNames.Items[i]); j := Pos(s, f); if j = 1 then begin lbFontNames.ItemIndex := i; Exit; end; end; end; end; {------------------------------------------------------------------------------} { editFontNameExit } {------------------------------------------------------------------------------} procedure TCrpeFontDlg.editFontNameExit(Sender: TObject); var i : integer; begin i := lbFontNames.Items.IndexOf(editFontName.Text); if i = -1 then begin if lbFontNames.ItemIndex < 0 then lbFontNames.ItemIndex := 0; lbFontNamesClick(Self); end; end; {------------------------------------------------------------------------------} { lbFontNamesClick } {------------------------------------------------------------------------------} procedure TCrpeFontDlg.lbFontNamesClick(Sender: TObject); begin editFontName.OnChange := nil; editFontName.Text := lbFontNames.Items[lbFontNames.ItemIndex]; editFontName.OnChange := editFontNameChange; pnlSample.Font.Name := lbFontNames.Items[lbFontNames.ItemIndex]; end; {------------------------------------------------------------------------------} { lbFontNamesDrawItem } {------------------------------------------------------------------------------} procedure TCrpeFontDlg.lbFontNamesDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); var ColorR : TRect; TextR : TRect; FontInfo : TTextMetric; g : TBitmap; begin ColorR.Left := Rect.Left + 1; ColorR.Top := Rect.Top + 1; ColorR.Right := Rect.Left + 14{ColorWidth} - 1; ColorR.Bottom := Rect.Top + lbFontNames.ItemHeight - 1; TextR.Left := Rect.Left + 14{ColorWidth} + 4; TextR.Top := Rect.Top + 1; TextR.Right := Rect.Right; TextR.Bottom := Rect.Bottom - 1; with lbFontNames.Canvas do begin FillRect(Rect); { clear the rectangle } PaintBox1.Canvas.Font.Name := lbFontNames.Items[Index]; GetTextMetrics(PaintBox1.Canvas.Handle, FontInfo); if ((FontInfo.tmPitchAndFamily and $0F) and TMPF_TRUETYPE) = TMPF_TRUETYPE then begin g := TBitmap.Create; g.Assign(imgTrueType.Picture.Bitmap); Draw(ColorR.Left, ColorR.Top, g); g.Free; end else if ((FontInfo.tmPitchAndFamily and $0F) and TMPF_VECTOR) = TMPF_VECTOR then begin g := TBitmap.Create; g.Assign(imgType1.Picture.Bitmap); Draw(ColorR.Left, ColorR.Top, g); g.Free; end; DrawText(Handle, PChar(lbFontNames.Items[Index]), -1, TextR, DT_VCENTER or DT_SINGLELINE); end; end; {------------------------------------------------------------------------------} { editStyleChange } {------------------------------------------------------------------------------} procedure TCrpeFontDlg.editStyleChange(Sender: TObject); var i : integer; begin i := lbStyles.Items.IndexOf(editStyle.Text); if i > -1 then begin lbStyles.ItemIndex := i; editStyle.Text := lbStyles.Items[lbStyles.ItemIndex]; if editStyle.Text = 'Regular' then pnlSample.Font.Style := []; if editStyle.Text = 'Italic' then pnlSample.Font.Style := [fsItalic]; if editStyle.Text = 'Bold' then pnlSample.Font.Style := [fsBold]; if editStyle.Text = 'Bold Italic' then pnlSample.Font.Style := [fsBold, fsItalic]; end; end; {------------------------------------------------------------------------------} { lbStylesClick } {------------------------------------------------------------------------------} procedure TCrpeFontDlg.lbStylesClick(Sender: TObject); begin editStyle.OnChange := nil; editStyle.Text := lbStyles.Items[lbStyles.ItemIndex]; editStyle.OnChange := editStyleChange; if editStyle.Text = 'Regular' then pnlSample.Font.Style := []; if editStyle.Text = 'Italic' then pnlSample.Font.Style := [fsItalic]; if editStyle.Text = 'Bold' then pnlSample.Font.Style := [fsBold]; if editStyle.Text = 'Bold Italic' then pnlSample.Font.Style := [fsBold, fsItalic]; end; {------------------------------------------------------------------------------} { editStyleExit } {------------------------------------------------------------------------------} procedure TCrpeFontDlg.editStyleExit(Sender: TObject); var i : integer; begin i := lbStyles.Items.IndexOf(editStyle.Text); if i = -1 then begin if lbStyles.ItemIndex < 0 then lbStyles.ItemIndex := 0; lbStylesClick(Self); end; end; {------------------------------------------------------------------------------} { editSizeChange } {------------------------------------------------------------------------------} procedure TCrpeFontDlg.editSizeChange(Sender: TObject); var i : integer; begin i := lbSizes.Items.IndexOf(editSize.Text); if i > -1 then begin lbSizes.ItemIndex := i; pnlSample.Font.Size := i; end else begin if IsNumeric(editSize.Text) then begin i := StrToInt(editSize.Text); editActualSize.Text := editSize.Text; pnlSample.Font.Size := i; end; end; end; {------------------------------------------------------------------------------} { lbSizesClick } {------------------------------------------------------------------------------} procedure TCrpeFontDlg.lbSizesClick(Sender: TObject); begin editSize.OnChange := nil; editSize.Text := lbSizes.Items[lbSizes.ItemIndex]; editSize.OnChange := editSizeChange; pnlSample.Font.Size := StrToInt(lbSizes.Items[lbSizes.ItemIndex]); editActualSize.Text := lbSizes.Items[lbSizes.ItemIndex]; end; {------------------------------------------------------------------------------} { editSizeExit } {------------------------------------------------------------------------------} procedure TCrpeFontDlg.editSizeExit(Sender: TObject); var i : integer; begin i := lbSizes.Items.IndexOf(editSize.Text); if i = -1 then begin if lbSizes.ItemIndex < 0 then lbSizes.ItemIndex := 0; lbSizesClick(Self); end; end; {------------------------------------------------------------------------------} { editActualSizeChange } {------------------------------------------------------------------------------} procedure TCrpeFontDlg.editActualSizeChange(Sender: TObject); var i : integer; d : double; begin if IsFloating(editActualSize.Text) then begin d := CrStrToFloating(editActualSize.Text); i := Round(d); editSize.Text := IntToStr(i); {Attempt to show the difference but it doesn't really work since Pixels and Points are very similar measurements...however the fraction will be converted to Twips when sent to the Print Engine, which is more accurate} i := Round(d * 100); i := (i * pnlSample.Font.PixelsPerInch); i := i div 72; i := i div 100; pnlSample.Font.Height := -i; end; end; {------------------------------------------------------------------------------} { cbStrikeoutClick } {------------------------------------------------------------------------------} procedure TCrpeFontDlg.cbStrikeoutClick(Sender: TObject); begin if cbStrikeout.Checked then pnlSample.Font.Style := pnlSample.Font.Style + [fsStrikeOut] else pnlSample.Font.Style := pnlSample.Font.Style - [fsStrikeOut]; end; {------------------------------------------------------------------------------} { cbUnderlineClick } {------------------------------------------------------------------------------} procedure TCrpeFontDlg.cbUnderlineClick(Sender: TObject); begin if cbUnderline.Checked then pnlSample.Font.Style := pnlSample.Font.Style + [fsUnderline] else pnlSample.Font.Style := pnlSample.Font.Style - [fsUnderline]; end; {------------------------------------------------------------------------------} { btnOkClick } {------------------------------------------------------------------------------} procedure TCrpeFontDlg.btnOkClick(Sender: TObject); begin editFontNameExit(Self); editStyleExit(Self); Crf.Name := editFontName.Text; if editStyle.Text = 'Regular' then Crf.Style := []; if editStyle.Text = 'Bold' then Crf.Style := [fsBold]; if editStyle.Text = 'Italic' then Crf.Style := [fsItalic]; if editStyle.Text = 'Bold Italic' then Crf.Style := [fsBold, fsItalic]; if IsNumeric(editSize.Text) then Crf.Size := StrToInt(editSize.Text); if IsFloating(editActualSize.Text) then Crf.ActualSize := CrStrToFloating(editActualSize.Text); if cbStrikeout.Checked then Crf.Style := (Crf.Style + [fsStrikeOut]) else Crf.Style := (Crf.Style - [fsStrikeOut]); if cbUnderline.Checked then Crf.Style := (Crf.Style + [fsUnderline]) else Crf.Style := (Crf.Style - [fsUnderline]); Crf.Color := cbColor.Selected; SaveFormPos(Self); Close; end; {------------------------------------------------------------------------------} { btnCancelClick } {------------------------------------------------------------------------------} procedure TCrpeFontDlg.btnCancelClick(Sender: TObject); begin // end; {------------------------------------------------------------------------------} { FormClose } {------------------------------------------------------------------------------} procedure TCrpeFontDlg.FormClose(Sender: TObject; var Action: TCloseAction); begin bFont := False; Release; end; end.
namespace LinqToXML; interface uses System.Drawing, System.Collections, System.Collections.Generic, System.Linq, System.Xml, System.Xml.Linq, System.Windows.Forms, System.ComponentModel; type /// <summary> /// Summary description for MainForm. /// </summary> MainForm = partial class(System.Windows.Forms.Form) private method button1_Click(sender: System.Object; e: System.EventArgs); protected method Dispose(disposing: Boolean); override; public constructor; end; implementation {$REGION Construction and Disposition} constructor MainForm; begin // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // end; method MainForm.Dispose(disposing: Boolean); begin if disposing then begin if assigned(components) then components.Dispose(); // // TODO: Add custom disposition code here // end; inherited Dispose(disposing); end; {$ENDREGION} method MainForm.button1_Click(sender: System.Object; e: System.EventArgs); var books : Array of Books := [ new Books('Programming and Problem Solving with Delphi', 'Mitchell C. Kerman', 2008), new Books('Delphi 2009', 'Marco Cantu', 2008), new Books('Learn Object Pascal with Delphi', 'Rachele, Warren', 2008), new Books('RSS and Atom in Action', 'Manning', 2006)]; xml : XElement; begin xml := new XElement('books', from book in books where book.Year = 2008 select new XElement( 'book', new XAttribute('title',book.Title), new XAttribute('publisher', book.Publisher) ) ); tbXML.Text := xml.ToString end; end.
unit GLDPlaneParamsFrame; interface uses Classes, Controls, Forms, StdCtrls, ComCtrls, GL, GLDTypes, GLDSystem, GLDPlane, GLDNameAndColorFrame, GLDUpDown; type TGLDPlaneParamsFrame = class(TFrame) NameAndColor: TGLDNameAndColorFrame; GB_Params: TGroupBox; L_Length: TLabel; L_Width: TLabel; L_LengthSegs: TLabel; L_WidthSegs: TLabel; E_Length: TEdit; E_Width: TEdit; E_LengthSegs: TEdit; E_WidthSegs: TEdit; UD_Length: TGLDUpDown; UD_Width: TGLDUpDown; UD_LengthSegs: TUpDown; UD_WidthSegs: TUpDown; procedure SizeChangeUD(Sender: TObject); procedure SegmentsChangeUD(Sender: TObject; Button: TUDBtnType); procedure EditEnter(Sender: TObject); private FDrawer: TGLDDrawer; procedure SetDrawer(Value: TGLDDrawer); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function HavePlane: GLboolean; function GetParams: TGLDPlaneParams; procedure SetParams(const Name: string; const Color: TGLDColor3ub; const Length, Width: GLfloat; const LengthSegs, WidthSegs: GLushort); procedure SetParamsFrom(Plane: TGLDPlane); procedure ApplyParams; property Drawer: TGLDDrawer read FDrawer write SetDrawer; end; procedure Register; implementation {$R *.dfm} uses SysUtils, GLDConst, GLDX; constructor TGLDPlaneParamsFrame.Create(AOwner: TComponent); begin inherited Create(AOwner); FDrawer := nil; end; destructor TGLDPlaneParamsFrame.Destroy; begin if Assigned(FDrawer) then if FDrawer.IOFrame = Self then FDrawer.IOFrame := nil; inherited Destroy; end; function TGLDPlaneParamsFrame.HavePlane: GLboolean; begin Result := False; if Assigned(FDrawer) and Assigned(FDrawer.EditedObject) and (FDrawer.EditedObject is TGLDPlane) then Result := True; end; function TGLDPlaneParamsFrame.GetParams: TGLDPlaneParams; begin if HavePlane then with TGLDPlane(FDrawer.EditedObject) do begin Result.Position := Position.Vector3f; Result.Rotation := Rotation.Params; end else begin Result.Position := GLD_VECTOR3F_ZERO; Result.Rotation := GLD_ROTATION3D_ZERO; end; Result.Color := NameAndColor.ColorParam; Result.Length := UD_Length.Position; Result.Width := UD_Width.Position; Result.LengthSegs := UD_LengthSegs.Position; Result.WidthSegs := UD_WidthSegs.Position; end; procedure TGLDPlaneParamsFrame.SetParams(const Name: string; const Color: TGLDColor3ub; const Length, Width: GLfloat; const LengthSegs, WidthSegs: GLushort); begin NameAndColor.NameParam := Name; NameAndColor.ColorParam := Color; UD_Length.Position := Length; UD_Width.Position := Width; UD_LengthSegs.Position := LengthSegs; UD_WidthSegs.Position := WidthSegs; end; procedure TGLDPlaneParamsFrame.SetParamsFrom(Plane: TGLDPlane); begin if not Assigned(Plane) then Exit; with Plane do SetParams(Name, Color.Color3ub, Length, Width, LengthSegs, WidthSegs); end; procedure TGLDPlaneParamsFrame.ApplyParams; begin if HavePlane then TGLDPlane(FDrawer.EditedObject).Params := GetParams; end; procedure TGLDPlaneParamsFrame.SizeChangeUD(Sender: TObject); begin if HavePlane then with TGLDPlane(FDrawer.EditedObject) do if Sender = UD_Length then Length := UD_Length.Position else if Sender = UD_Width then Width := UD_Width.Position; end; procedure TGLDPlaneParamsFrame.SegmentsChangeUD(Sender: TObject; Button: TUDBtnType); begin if HavePlane then with TGLDPlane(FDrawer.EditedObject) do if Sender = UD_LengthSegs then LengthSegs := UD_LengthSegs.Position else if Sender = UD_WidthSegs then WidthSegs := UD_WidthSegs.Position; end; procedure TGLDPlaneParamsFrame.EditEnter(Sender: TObject); begin ApplyParams; end; procedure TGLDPlaneParamsFrame.Notification(AComponent: TComponent; Operation: TOperation); begin if Assigned(FDrawer) and (AComponent = FDrawer.Owner) and (Operation = opRemove) then FDrawer := nil; inherited Notification(AComponent, Operation); end; procedure TGLDPlaneParamsFrame.SetDrawer(Value: TGLDDrawer); begin FDrawer := Value; NameAndColor.Drawer := FDrawer; end; procedure Register; begin //RegisterComponents('GLDraw', [TGLDPlaneParamsFrame]); end; end.
// Sorting demo {$APPTYPE CONSOLE} program Sort; type TValue = Integer; TCompareFunc = function(x, y: TValue): Boolean; procedure Swap(var x, y: TValue); var buf: TValue; begin buf := x; x := y; y := buf; end; procedure QuickSort(var data: array of TValue; len: Integer; Ordered: TCompareFunc); function Partition(var data: array of TValue; low, high: Integer; Ordered: TCompareFunc): Integer; var pivot: TValue; pivotIndex, i: Integer; begin pivot := data[high]; pivotIndex := low; for i := low to high - 1 do if not Ordered(data[i], pivot) then begin Swap(data[pivotIndex], data[i]); Inc(pivotIndex); end; // if Swap(data[high], data[pivotIndex]); Result := pivotIndex; end; procedure Sort(var data: array of TValue; low, high: Integer; Ordered: TCompareFunc); var pivotIndex: Integer; begin if high > low then begin pivotIndex := Partition(data, low, high, Ordered); Sort(data, low, pivotIndex - 1, Ordered); Sort(data, pivotIndex + 1, high, Ordered); end; // if end; begin Sort(data, 0, len - 1, Ordered); end; procedure BubbleSort(var data: array of TValue; len: Integer; Ordered: TCompareFunc); var changed: Boolean; i: Integer; begin repeat changed := FALSE; for i := 0 to len - 2 do if not Ordered(data[i + 1], data[i]) then begin Swap(data[i + 1], data[i]); changed := TRUE; end; until not changed; end; procedure SelectionSort(var data: array of TValue; len: Integer; Ordered: TCompareFunc); var i, j, extrIndex: Integer; extr: TValue; begin for i := 0 to len - 1 do begin extr := data[i]; extrIndex := i; for j := i + 1 to len - 1 do if not Ordered(data[j], extr) then begin extr := data[j]; extrIndex := j; end; Swap(data[i], data[extrIndex]); end; // for end; function Sorted(var data: array of TValue; len: Integer; Ordered: TCompareFunc): Boolean; var i: Integer; begin Result := TRUE; for i := 0 to len - 2 do if not Ordered(data[i + 1], data[i]) then begin Result := FALSE; Break; end; end; function OrderedAscending(y, x: TValue): Boolean; begin Result := y >= x; end; function OrderedDescending(y, x: TValue): Boolean; begin Result := y <= x; end; const DataLength = 600; var RandomData: array [1..DataLength] of TValue; i: Integer; Ordered: TCompareFunc; Order, Method: Char; begin WriteLn; WriteLn('Sorting demo'); WriteLn; WriteLn('Initial array: '); WriteLn; Randomize; for i := 1 to DataLength do begin RandomData[i] := Round((Random - 0.5) * 1000000); Write(RandomData[i]: 8); if i mod 6 = 0 then WriteLn; end; WriteLn; WriteLn; Write('Select order (A - ascending, D - descending): '); ReadLn(Order); WriteLn; case Order of 'A', 'a': begin WriteLn('Ascending order'); Ordered := @OrderedAscending; end; 'D', 'd': begin WriteLn('Descending order'); Ordered := @OrderedDescending; end else WriteLn('Order is not selected.'); Ordered := nil; ReadLn; Halt; end; WriteLn; Write('Select method (Q - quick, B - bubble, S - selection): '); ReadLn(Method); WriteLn; case Method of 'Q', 'q': begin WriteLn('Quick sorting'); QuickSort(RandomData, DataLength, Ordered); end; 'B', 'b': begin WriteLn('Bubble sorting'); BubbleSort(RandomData, DataLength, Ordered); end; 'S', 's': begin WriteLn('Selection sorting'); SelectionSort(RandomData, DataLength, Ordered); end else WriteLn('Sorting method is not selected.'); ReadLn; Halt; end; WriteLn; WriteLn('Sorted array: '); WriteLn; for i := 1 to DataLength do begin Write(RandomData[i]: 8); if i mod 6 = 0 then WriteLn; end; WriteLn; WriteLn('Sorted: ', Sorted(RandomData, DataLength, Ordered)); WriteLn('Done.'); ReadLn; end.
//~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ // // Programa: MultiFind // // Propósito Modulo Archivo: // El proposito de este modulo de Archivo, es el de encapsular en una clase las // acciones de manipulación de la shell de windows sobre el archivo seleccionado. // Esto nos permite una mayor claridad del código fuente y responde a los esquemas // habituales de encapsulamiento de estructuras y código. // El diseño se hace basado en la interfaz (IArchivo) que representa a todos aquellos // objetos que tienen la capacidad de manipular archivos. // //~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ unit Archivo; interface type // // Se define el interfaz IArchivo que representa todas aquellas acciones que se // podrán realizar con el archivo // IArchivo = interface(IUnknown) function Eliminar: integer; function Abrir: integer; function AbrirCarpeta: integer; function ExplorarCarpeta: integer; function CopiarAlPortapapeles: integer; function MostrarPropiedades: integer; end; // // Se define una clase que haga una implementación concreta de IArchivo. // Además, esta clase desciende de TInterfacedObject, por lo que no será necesario // liberar los objetos creados, ya que se liberan solos. // TArchivo = class(TInterfacedObject, IArchivo) private FRuta: string; FNombre: string; procedure SetNombre(const value: string); function GetNombreCompleto: string; property NombreCompleto: string read GetNombreCompleto; public constructor Create(filename: string); function Eliminar: integer; function Abrir: integer; function AbrirCarpeta: integer; function ExplorarCarpeta: integer; function CopiarAlPortapapeles: integer; function MostrarPropiedades: integer; property Nombre: string read FNombre write SetNombre; end; implementation uses Windows, ShellAPI, Forms, SysUtils; // // Se incluye un módulo donde se definen funciones para compatibilidad. // {$I compatible.inc} // Proc/Fun : constructor Create // // Valor retorno: vacio // Parametros : filename: string // // Comentarios : Constructor de la clase // constructor TArchivo.Create(filename: string); begin inherited Create; FRuta := IncludeTrailingBackSlash(ExtractFilePath(filename)); FNombre := ExtractFileName(filename); end; // Proc/Fun : procedure SetNombre // // Valor retorno: vacio // Parametros : const value: string // // Comentarios : Procedimiento de edición del nombre del archivo // Acción cambiar nombre // procedure TArchivo.SetNombre(const value: string); var SHFileOp: TSHFileOpStruct; ret: integer; begin if FNombre <> value then begin shFileOp.Wnd := application.MainForm.Handle; //manejador de la ventana sobre la que se realiza la operacion shFileOp.wFunc := FO_RENAME; //tipo de operacion // ojo: no olvidar #0 ya que si no genera error puesto que gracias al caracter //nulo "imagino" que se distingue origen-destino shFileOp.pFrom := PChar(NombreCompleto + #0); //ruta nombre a cambiar; ojo: si no existe ruta supone GetCurrentDir() shFileOp.pTo := PChar(FRuta + value); //ruta + nuevo nombre ojo: si no existe ruta supone GetCurrentDir() //opciones de operacion shFileOp.fFlags:= FOF_RENAMEONCOLLISION or FOF_NOCONFIRMMKDIR; ret := SHFileOperation(shFileOp); if ret <> 0 then raise Exception.CreateFmt('Error renombrando archivo "%s"', [NombreCompleto]); end; end; // Proc/Fun : function GetNombreCompleto // // Valor retorno: string // Parametros : vacio // // Comentarios : Propiedad Nombre Completo. Función de lectura. // function TArchivo.GetNombreCompleto: string; begin result := FRuta + FNombre; end; // Proc/Fun : function Eliminar // // Valor retorno: Integer // Parametros : Vacio // // Comentarios : Acción de eliminar un archivo. // No eliminamos de forma directa. Enviamos a la papelera y dejamos // que se le comunique al usuario la intención del borrado. // Si es cancelada la acción lo comunica devolviendo -1. // function TArchivo.Eliminar: integer; var SHFileOp: TSHFileOpStruct; begin shFileOp.Wnd:= application.MainForm.Handle; //manejador de la ventana sobre la que se realiza la operacion shFileOp.wFunc:= FO_DELETE; //tipo de operacion shFileOp.pFrom:= PChar(NombreCompleto+#0); shFileOp.pTo:= #0; //opciones de operacion shFileOp.fFlags:= FOF_ALLOWUNDO; Result:= SHFileOperation(shFileOp); //si la operación ha sido cancelada por el usuario if shFileOp.fAnyOperationsAborted then result:= -1; end; // Proc/Fun : function Abrir // // Valor retorno: Integer // Parametros : Vacio // // Comentarios : Ejecutar el archivo seleccionado. Si tiene exito devuelve 0. En // caso contrario devuelve el error // function TArchivo.Abrir: integer; var ret: HINST; begin ret := ShellExecute(application.MainForm.handle, nil, PChar(NombreCompleto), nil, nil, SW_NORMAL); if ret >= HINSTANCE_ERROR then result := -1 else result := 0; end; // Proc/Fun : function AbrirCarpeta // // Valor retorno: Integer // Parametros : Vacio // // Comentarios : Abrir en una ventana distinta de la shell, la carpeta que contiene // el archivo seleccionado. Si tiene exito devuelve 0 en caso contrario // el error // function TArchivo.AbrirCarpeta: integer; var ret: HINST; begin ret := ShellExecute(application.MainForm.handle, nil, PChar(FRuta), nil, nil, SW_NORMAL); if ret >= HINSTANCE_ERROR then result := -1 else result := 0; end; // Proc/Fun : function ExplorarCarpeta // // Valor retorno: Integer // Parametros : Vacio // // Comentarios : Abrir en una ventana del explorador de la shell, la carpeta que contiene // el archivo seleccionado. Si tiene exito devuelve 0 en caso contrario // el error // function TArchivo.ExplorarCarpeta: integer; var ret: HINST; cmd: string; begin cmd := '/n, /e, "' + ExcludeTrailingBackSlash(FRuta) + '"'; ret := ShellExecute(application.MainForm.Handle, nil, 'explorer.exe', PChar(cmd), nil, SW_NORMAL); if ret >= HINSTANCE_ERROR then result := -1 else result := 0; end; // Proc/Fun : function CopiarAlPortapapeles // // Valor retorno: Integer // Parametros : Vacio // // Comentarios : Acción de copiar un archivo al portapapeles // Adaptado a Delphi sobre una idea de James Crowley en // Visual Basic, en un foro de VB en Internet. // function TArchivo.CopiarAlPortapapeles: integer; const gmem_c = GMEM_MOVEABLE OR GMEM_ZEROINIT; type TDROPFILES = record pFiles: DWORD; pt: TPOINT; fNC: LongBool; fWide: LongBool; end; var s: String; i, j: Integer; hh: LongInt; phh: ^LongInt; df: TDROPFILES; begin FillChar(df, SizeOf(df), #0); result := -1; if OpenClipBoard(0) then try EmptyClipBoard; s:= NombreCompleto + #0#0; i := length(s); j := SizeOf(df); hh:= GlobalAlloc(gmem_c, i + j); if hh <> 0 then begin try phh:= GlobalLock(hh); try df.pFiles := j; CopyMemory(phh, @df, j); phh := Pointer(LongInt(phh) + j); CopyMemory(phh, PChar(s), i); finally GlobalUnlock(hh); end; if SetClipBoardData(CF_HDROP, hh) <> 0 then result := 0; finally GlobalFree(hh); end; end; finally CloseClipBoard; end; end; // Proc/Fun : function MostrarPropiedades // // Valor retorno: Integer // Parametros : Vacío // // Comentarios : Lanzamos el cuadro de propiedades del archivo seleccionado // function TArchivo.MostrarPropiedades: integer; var s: String; shExInfo: TShellExecuteInfo; begin s:= NombreCompleto + #0; FillChar(shExInfo, SizeOf(shExInfo), #0); shExInfo.cbSize := SizeOf(TShellExecuteInfo); shExInfo.fMask := SEE_MASK_INVOKEIDLIST; shExInfo.Wnd := application.MainForm.Handle; shExInfo.lpVerb := 'properties'; shExInfo.lpFile := PChar(s); if ShellExecuteEx(@shExInfo) then result := 0 else result := -1; end; end.
unit UntFuncionarioForm; interface uses Forms, UntBaseForm, UntBaseCadastroForm, Data, StdCtrls, Buttons, Text, Controls, Classes, ExtCtrls, Windows; type TFuncionarioForm = class(TBaseCadastroForm) PanHeader: TPanel; lblCodig_Func: TLabel; txtCodig_Func: TText; PanContent: TPanel; lblNomeF_Func: TLabel; txtNomeF_Func: TText; lblDtAdm_Func: TLabel; txtDtAdm_Func: TData; lblDtAfa_Func: TLabel; txtDtAfa_Func: TData; btnGravar: TBitBtn; btnCancelar: TBitBtn; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure txtCodig_FuncKeyPress(Sender: TObject; var Key: Char); procedure btnGravarClick(Sender: TObject); procedure btnCancelarClick(Sender: TObject); private procedure LimparCampos; override; procedure HabilitarCampos(habilitar: boolean = true); override; procedure CarregarCampos; function ValidarFormulario: boolean; procedure GravarCampos; end; var FuncionarioForm: TFuncionarioForm; implementation {$R *.dfm} uses SysUtils, UntFuncionario, UntFuncionarioDAO, UntSessionManager; procedure TFuncionarioForm.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; Action := caFree; FuncionarioForm := nil; end; procedure TFuncionarioForm.txtCodig_FuncKeyPress(Sender: TObject; var Key: Char); begin inherited; if key = #13 then begin key := #0; if StrToIntDef(txtCodig_Func.Text, 0) > 0 then CarregarCampos; end; end; procedure TFuncionarioForm.btnGravarClick(Sender: TObject); begin inherited; if ValidarFormulario then GravarCampos; end; procedure TFuncionarioForm.btnCancelarClick(Sender: TObject); begin inherited; Close; end; procedure TFuncionarioForm.LimparCampos; begin inherited; if txtCodig_Func.CanFocus then txtCodig_Func.SetFocus; end; procedure TFuncionarioForm.HabilitarCampos(habilitar: boolean); begin inherited HabilitarCampos(habilitar); txtCodig_Func.Enabled := not habilitar; if habilitar then begin if txtCodig_Func.CanFocus then txtCodig_Func.SetFocus; end else begin if txtNomeF_Func.CanFocus then txtNomeF_Func.SetFocus; end; end; procedure TFuncionarioForm.CarregarCampos; var obj: TFuncionario; dao: TFuncionarioDAO; begin dao := TFuncionarioDAO.Create; try obj := dao.Obter(StrToInt(txtCodig_Func.Text)); if obj <> nil then begin HabilitarCampos; ParseObjectToForm(obj); end; finally dao.Free; end; end; function TFuncionarioForm.ValidarFormulario: boolean; begin result := false; result := true; end; procedure TFuncionarioForm.GravarCampos; var obj: TFuncionario; dao: TFuncionarioDAO; begin dao := TFuncionarioDAO.Create; try obj := TFuncionario.Create; HabilitarCampos(false); ParseFormToObject(obj); obj.Empre_Func := TSessionManager.Session.Codig_Empr; if dao.Gravar(obj) then Application.MessageBox('Registro salvo com sucesso!', 'Parabéns!', MB_OK + MB_ICONINFORMATION); finally dao.Free; end; end; end.
(* Category: SWAG Title: SORTING ROUTINES Original name: 0038.PAS Description: Linked list sort Author: IAN LIN Date: 11-02-93 06:21 *) (* IAN LIN > Can someone show me an example of how to properly dispose of a linked list? I was just as bad when I started in February. :) Anyhow, use mark and release. They're 2 new things I've discovered and love much more than dispose or freemem. Use MARK(ram) where VAR RAM:POINTER {an untyped pointer}. This will save the state of the heap. NOW, when you are done, do this: release(ram) and it's back the way it was. No freemem, no dispose, just RELEASE! I REALLY love it. :) Need to allocate and deallocate some times in between the beginning and the end? Use more untyped pointers (eg. RAM2, RAM3, etc.) and you get the picture. Gotta love it. :) Look for a message from me in here about linked list sorting. I wrote an entire program that does this (to replace DOS's sort. Mine's faster and can use more than 64k RAM). Here it is. Some of it is maybe too hard for you but then you can ignore that part and just see how I used mark and release. *) type pstring = ^string; prec = ^rec; rec = record s : pstring; n : prec; end; Var dash : byte; err : word; {max, c : word;} list, list2, node, node2 : prec; {ram, ram2, ram3 : pointer;} tf : text; f : file; procedure dodash; begin case dash of 1 : write('-'); 2 : write('\'); 3 : write('|'); 4 : write('/'); end; write(#8, ' ', #8); dash := dash mod 4 + 1; end; procedure TheEnd; begin writeln('Assassin Technologies, NetRunner.'); halt(err); end; procedure showhelp; begin writeln('Heavy duty sorter. Syntax: NSORT <INFILE> <OUTFILE>.'); writeln('Exit codes: 0-normal; 1-not enough RAM; 2-can''t open infile;'); writeln('3-outfile can''t be created'); halt; end; procedure noram; begin {release(ram);} assign(f, paramstr(1)); {writeln('Not enough RAM. ', memavail div 1024, 'k; file: ', filesize(f));} err := 1; halt; end; procedure newnode(var pntr : prec); begin {if sizeof(prec) > maxavail then begin close(tf); noram; end;} new(pntr); dodash; pntr^.n := nil; end; procedure getln(var ln : pstring); var line : string; size : word; begin readln(tf, line); size := succ(length(line)); {if size > maxavail then noram;} getmem(ln, size); move(line, ln^, succ(length(line))); dodash; end; begin err := 0; exitproc := @TheEnd; if paramcount = 0 then showhelp; assign(tf, paramstr(1)); reset(tf); if ioresult <> 0 then begin writeln('Can''t open "', paramstr(1), '".'); err := 2; halt; end; {mark(ram);} newnode(list); if not eof(tf) then begin getln(list^.s); node := list; while not eof(tf) do begin newnode(node^.n); node := node^.n; getln(node^.s); end; close(tf); newnode(list2); list2^.n := list; list := list^.n; list2^.n^.n := nil; while list <> nil do begin dodash; node := list; list := list^.n; node2 := list2; while (node2^.n <> nil) and (node^.s^ > node2^.n^.s^) do node2 := node2^.n; node^.n := node2^.n; node2^.n := node; dodash; end; list := list2^.n; assign(tf, paramstr(2)); rewrite(tf); if ioresult <> 0 then begin writeln('Can''t create "', paramstr(2), '"'); err := 3; end; node := list; while node <> nil do begin writeln(tf, node^.s^); node := node^.n; dodash; end; writeln; close(tf); {release(ram);} end; end.
program textures; {$mode objfpc}{$H+} uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} Classes, SysUtils, glfw31, gl, GLext, shader_s, FPImage, FPReadJPEG; const // settings SCR_WIDTH = 800; SCR_HEIGHT = 600; type // FPImage code to load jpeg image (not flipped like in orginal c++ example) // ------------------------------------------------------------------------- TMyRGB8BitImage = class(TFPCompactImgRGB8Bit) public property Data : PFPCompactImgRGB8BitValue read FData; end; function LoadJpegImage(ImageFile: string): TMyRGB8BitImage; var MyImage: TMyRGB8BitImage; Reader: TFPReaderJPEG; begin MyImage := nil; Reader := nil; try try MyImage := TMyRGB8BitImage.Create(0, 0); Reader := TFPReaderJPEG.Create; MyImage.LoadFromFile(ImageFile, Reader); except on E: Exception do begin FreeAndNil(MyImage); WriteLn('Failed to load texture: '+ E.Message); end; end; finally FreeAndNil(Reader); end; Result := MyImage; end; // process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly // --------------------------------------------------------------------------------------------------------- procedure processInput(window: pGLFWwindow); cdecl; begin if glfwGetKey(window, GLFW_KEY_ESCAPE) = GLFW_PRESS then begin glfwSetWindowShouldClose(window, GLFW_TRUE); end; end; // glfw: whenever the window size changed (by OS or user resize) this callback function executes // --------------------------------------------------------------------------------------------- procedure framebuffer_size_callback(window: pGLFWwindow; width, height: Integer); cdecl; begin // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); end; procedure showError(error: GLFW_INT; description: PChar); cdecl; begin Writeln(description); end; var window: pGLFWwindow; ourShader :TShader; // set up vertex data // ------------------ vertices: array [0..31] of GLfloat = ( // positions // colors // texture coords 0.5, 0.5, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, // top right 0.5, -0.5, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, // bottom right -0.5, -0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, // bottom left -0.5, 0.5, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0 // top left ); indices: array [0..5] of GLuint = ( 0, 1, 3, // first triangle 1, 2, 3 // second triangle ); VBO, VAO, EBO: GLuint; texture: GLuint; FImage: TMyRGB8BitImage; begin // glfw: initialize and configure // ------------------------------ glfwInit; glfwSetErrorCallback(@showError); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); {$ifdef DARWIN} glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); {$endif} // glfw window creation // -------------------- window := glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, 'LearnOpenGL', nil, nil); if window = nil then begin Writeln('Failed to create GLFW window'); glfwTerminate; Exit; end; glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, @framebuffer_size_callback); // GLext: load all OpenGL function pointers // ---------------------------------------- if Load_GL_version_3_3_CORE = false then begin Writeln('OpenGL 3.3 is not supported!'); glfwTerminate; Exit; end; // build and compile our shader zprogram // ------------------------------------- ourShader := TShader.Create('4.1.texture.vs', '4.1.texture.fs'); // set up buffer(s) and configure vertex attributes // ------------------------------------------------ glGenVertexArrays(1, @VAO); glGenBuffers(1, @VBO); glGenBuffers(1, @EBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), @vertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), @indices, GL_STATIC_DRAW); // position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), PGLvoid(0)); glEnableVertexAttribArray(0); // color attribute glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), PGLvoid(3 * sizeof(GLfloat))); glEnableVertexAttribArray(1); // texture coord attribute glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), PGLvoid(6 * sizeof(GLfloat))); glEnableVertexAttribArray(2); // load and create a texture // ------------------------- glGenTextures(1, @texture); glBindTexture(GL_TEXTURE_2D, texture); // all upcoming GL_TEXTURE_2D operations now have effect on this texture object // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // load image, create texture and generate mipmaps FImage := LoadJpegImage('../../../resources/textures/container.jpg'); try if FImage<> nil then begin glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, FImage.Width, FImage.Height, 0, GL_RGB, GL_UNSIGNED_BYTE, FImage.Data); glGenerateMipmap(GL_TEXTURE_2D); end; finally FreeAndNil(FImage); end; // render loop // ----------- while glfwWindowShouldClose(window) = GLFW_FALSE do begin // input // ----- processInput(window); // render // ------ glClearColor(0.2, 0.3, 0.3, 1.0); glClear(GL_COLOR_BUFFER_BIT); // bind Texture glBindTexture(GL_TEXTURE_2D, texture); // render container ourShader.use(); glBindVertexArray(VAO); // seeing as we only have a single VAO there's no need to bind it every time, but we'll do so to keep things a bit more organized glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nil); //glBindVertexArray(0); // no need to unbind it every time // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents; end; // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ glDeleteVertexArrays(1, @VAO); glDeleteBuffers(1, @VBO); glDeleteBuffers(1, @EBO); FreeAndNil(ourShader); // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate; end.
unit TestUCnae; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, System.Variants, Winapi.Windows, Generics.Collections, Vcl.Dialogs, Vcl.Grids, Vcl.Forms, UtelaCadastro, Vcl.ExtCtrls, Vcl.Controls, UCnae, System.Classes, System.SysUtils, Winapi.Messages, Vcl.DBGrids, Vcl.Graphics, Vcl.Mask, Vcl.StdCtrls, Vcl.Buttons, Vcl.ComCtrls; type // Test methods for class TFTelaCadastroCnae TestTFTelaCadastroCnae = class(TTestCase) strict private FFTelaCadastroCnae: TFTelaCadastroCnae; public procedure SetUp; override; procedure TearDown; override; published procedure TestMontaFiltro; procedure TestFormCreate; procedure TestValidarTela; procedure TestDoSalvar; procedure TestDoExcluir; procedure TestDoConsultar; procedure TestCarregaObjetoSelecionado; procedure TestBitBtnNovoClick; procedure TestGridParaEdits; // procedure TestEditsToObject; end; implementation procedure TestTFTelaCadastroCnae.SetUp; begin FFTelaCadastroCnae := TFTelaCadastroCnae.Create; end; procedure TestTFTelaCadastroCnae.TearDown; begin FFTelaCadastroCnae.Free; FFTelaCadastroCnae := nil; end; procedure TestTFTelaCadastroCnae.TestMontaFiltro; var ReturnValue: string; begin ReturnValue := FFTelaCadastroCnae.MontaFiltro; // TODO: Validate method results end; procedure TestTFTelaCadastroCnae.TestFormCreate; var Sender: TObject; begin // TODO: Setup method call parameters FFTelaCadastroCnae.FormCreate(Sender); // TODO: Validate method results end; procedure TestTFTelaCadastroCnae.TestValidarTela; var ReturnValue: Boolean; begin ReturnValue := FFTelaCadastroCnae.ValidarTela; // TODO: Validate method results end; procedure TestTFTelaCadastroCnae.TestDoSalvar; var ReturnValue: Boolean; begin ReturnValue := FFTelaCadastroCnae.DoSalvar; // TODO: Validate method results end; procedure TestTFTelaCadastroCnae.TestDoExcluir; var ReturnValue: Boolean; begin ReturnValue := FFTelaCadastroCnae.DoExcluir; // TODO: Validate method results end; procedure TestTFTelaCadastroCnae.TestDoConsultar; begin FFTelaCadastroCnae.DoConsultar; // TODO: Validate method results end; procedure TestTFTelaCadastroCnae.TestCarregaObjetoSelecionado; begin FFTelaCadastroCnae.CarregaObjetoSelecionado; // TODO: Validate method results end; procedure TestTFTelaCadastroCnae.TestBitBtnNovoClick; var Sender: TObject; begin // TODO: Setup method call parameters FFTelaCadastroCnae.BitBtnNovoClick(Sender); // TODO: Validate method results end; procedure TestTFTelaCadastroCnae.TestGridParaEdits; begin FFTelaCadastroCnae.GridParaEdits; // TODO: Validate method results end; //procedure TestTFTelaCadastroCnae.TestEditsToObject; //var // ReturnValue: TCnaeVO; // Cnae: TCnaeVO; //begin // TODO: Setup method call parameters // ReturnValue := FFTelaCadastroCnae.EditsToObject(Cnae); // TODO: Validate method results //end; initialization // Register any test cases with the test runner RegisterTest(TestTFTelaCadastroCnae.Suite); end.
unit uCrypt; { Скомпонован и дописан 13.10.2004 Предоставляет две функции Encrypt и Decrypt для шифровки и дешифровки текстов Как параметры передаются тип шифровки и список того, что нужно зашифровать в виде массива вариантов. Например, если нужно зашифровать одну строку с типом crtVersionKey, то вызов процедуры будет в виде res:=Encrypt(crtVersionKey,[str]); ВНИМАНИЕ РАЗРАБОТЧИКАМ!!! При появлении нового алгоритма шифрования поступить нужно следующим образом: 1. Добавить в тип TOilCryptType константу, которая соответствует новому типу 2. Поместить в этот модуль функцию/функции, которые осуществляют шифровку/дешифровку по новому алгоритму. Не помещать их в интерфейсную часть, они не должны непосредственно вызываться из других модулей 3. Изменить функции Encrypt и Decrypt так, чтобы они обрабатывали новый тип шифрования вызывая при этом добавленные в пункте 2 функции. Заранее спасибо за следование этим правилам. (Ю.Должиков) } interface uses uCommonForm, sysutils,ExFunc,uOilQuery,Ora, uOilStoredProc; type TOilCryptType=( crtTestLaunch, // тип пароля, использующийся в основном в Чехуновских проверках crtVersionKey, // тип пароля, шифрующий изначально VERSION_KEY, а в последнствии нашедший еще несколько применений crtSmart, // очень универсальная и классная система шифтования crtOrgKey // шифровка даты и инста в код, использующийся как пароль; расшифровки нет ); type TOilPasswordType=( pwtOrg, // пароль при замене текущей организации и т.д. и т.п. (полученный Чехуновским кейгеном) pwtPart, // пароль для синхронизации партий pwtCrash, // пароль, вводимый при вводе сбоя pwtTestLaunch, // пароль, вводимый при запуске, который зависит от даты инста и списка проверок pwtWagon // пароль, который нужно ввести при внесении сбоя по вагонам ); function Encrypt( p_Type: TOilCryptType; p_List: array of variant ): string; function Decrypt( p_Type: TOilCryptType; p_List: array of variant ): string; function GetPassword(p_Type : TOilPasswordType;p_List: array of variant): string; function TruncPasswId(p_Passw: string) : string; implementation Uses Dialogs, Windows, Messages, Classes, Graphics, Controls, Forms, Buttons, StdCtrls, Db, DBTables, Grids, DBGrids, ExtCtrls, ComObj, StrUtils; var KEY1: string = 'Да здравствует программа OIL - самая гуманная программа в мире!'; ALFA1: string = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_!'; st2: array[0..7] of integer=(1,2,4,8,16,32,64,128); vDay,vMonth,vYear : word; //============================================================================== // ************* Жуткие процедуры на ассемблере *********************** // ************* взяты из левых источников :-) *********************** //------------------------------------------------------------------------------ procedure EnCipher(var Source: AnsiString); asm Push ESI //Save the good stuff Push EDI Or EAX,EAX Jz @Done Push EAX Call UniqueString Pop EAX Mov ESI,[EAX] //String address into ESI Or ESI,ESI Jz @Done Mov ECX,[ESI-4] //String Length into ECX Jecxz @Done //Abort on null string Mov EDX,ECX //initialize EDX with length Lea EDI,@ECTbl //Table address into EDI Cld //make sure we go forward @L1: Xor EAX,EAX Lodsb //Load a byte from string Sub AX,32 //Adjust to zero base Js @Next //Ignore if control char. Cmp AX,95 Jg @Next //Ignore if high order char. Mov AL,[EDI+EAX] //get the table value Test CX,3 //screw it up some Jz @L2 Rol EDX,3 @L2: And DL,31 Xor AL,DL Add EDX,ECX Add EDX,EAX Add AL,32 //adjust to output range Mov [ESI-1],AL //write it back into string @Next: Dec ECX Jnz @L1 // Loop @L1 //do it again if necessary @Done: Pop EDI Pop ESI Jmp @Exit // Ret //this does not work with Delphi 3 - EFD 971022 @ECTbl: //The encipher table DB 75,85,86,92,93,95,74,76,84,87,91,94 DB 63,73,77,83,88,90,62,64,72,78,82,89 DB 51,61,65,71,79,81,50,52,60,66,70,80 DB 39,49,53,59,67,69,38,40,48,54,58,68 DB 27,37,41,47,55,57,26,28,36,42,46,56 DB 15,25,29,35,43,45,14,16,24,30,34,44 DB 06,13,17,23,31,33,05,07,12,18,22,32 DB 01,04,08,11,19,21,00,02,03,09,10,20 @Exit: end; //Тоже самое только на паскале Procedure PasEnChiper(var p_Str:ANSIString); const Tbl:array[0..95] of byte = ( 75,85,86,92,93,95,74,76,84,87,91,94, 63,73,77,83,88,90,62,64,72,78,82,89, 51,61,65,71,79,81,50,52,60,66,70,80, 39,49,53,59,67,69,38,40,48,54,58,68, 27,37,41,47,55,57,26,28,36,42,46,56, 15,25,29,35,43,45,14,16,24,30,34,44, 06,13,17,23,31,33,05,07,12,18,22,32, 01,04,08,11,19,21,00,02,03,09,10,20 ); var A,C,D,cnt:integer; ch:char; function L(p_val:integer):integer; begin result:= p_val and 255; end; procedure AssignL(var p_var:integer; const p_val:integer); begin p_var := p_var and (not 255); p_var := p_var or p_val; p_var := p_var; end; begin C := Length(p_Str); D := C; If(p_Str='')or(Length(p_Str)=0)then exit; cnt := 1; while not(C = 0)do begin ch := p_Str[cnt]; A := ord(ch); A := A - 32; if(A >= 95)then continue; A := Tbl[A]; if C <> 4 then D := D shl 3; //d * 2*2*2 AssignL(D,L(D) and 31); AssignL(A,L(A) xor L(D)); D := D + C + A; AssignL(A,L(A) + 32); p_Str[cnt] := chr(L(A)); dec(C); inc(cnt); end; end; //============================================================================== procedure DeCipher(var Source: AnsiString); {Decrypts a string previously encrypted with EnCipher.} asm Push ESI //Save the good stuff Push EDI Push EBX Or EAX,EAX Jz @Done Push EAX Call UniqueString Pop EAX Mov ESI,[EAX] //String address into ESI Or ESI,ESI Jz @Done Mov ECX,[ESI-4] //String Length into ECX Jecxz @Done //Abort on null string Mov EDX,ECX //Initialize EDX with length Lea EDI,@DCTbl //Table address into EDI Cld //make sure we go forward @L1: Xor EAX,EAX Lodsb //Load a byte from string Sub AX,32 //Adjust to zero base Js @Next //Ignore if control char. Cmp AX,95 Jg @Next //Ignore if high order char. Mov EBX,EAX //save to accumulate below Test CX,3 //unscrew it Jz @L2 Rol EDX,3 @L2: And DL,31 Xor AL,DL Add EDX,ECX Add EDX,EBX Mov AL,[EDI+EAX] //get the table value Add AL,32 //adjust to output range Mov [ESI-1],AL //store it back in string @Next: Dec ECX Jnz @L1 // Loop @L1 //do it again if necessary @Done: Pop EBX Pop EDI Pop ESI Jmp @Exit // Ret Does not work with Delphi3 - EFD 971022 @DCTbl: //The decryption table DB 90,84,91,92,85,78,72,79,86,93,94,87 DB 80,73,66,60,67,74,81,88,95,89,82,75 DB 68,61,54,48,55,62,69,76,83,77,70,63 DB 56,49,42,36,43,50,57,64,71,65,58,51 DB 44,37,30,24,31,38,45,52,59,53,46,39 DB 32,25,18,12,19,26,33,40,47,41,34,27 DB 20,13,06,00,07,14,21,28,35,29,22,15 DB 08,01,02,09,16,23,17,10,03,04,11,05 @Exit: end; //============================================================================== procedure Crypt(var Source: Ansistring; const Key: AnsiString); { Шифровка и дешифровка строк, с использованием расширенной XOR технологии, типа S-Coder (DDJ, Явнварь 1990). Для дешифровки просто примените повторно эту процедуру используя тот же самый ключ. Этот алгоритм достаточно надежен сам по себе, но если вы хотите сделать его еще более надежным, вы можете сделать следующее: 1) Используйте длинные ключи, которые нельзя легко угадать 2) Дважды или трижди шифруйте строку с разными ключами. При дешифровке применяйте ключи в обратном порядке 3) Используйте EnCipher перед Crypt. При дешифровке после Crypt используйте DeCipher. 4) Любая комбинация вышеперечисленного Примечание: результат может содержать любые символы от 0 до 255. (Перевод Должикова) (Encrypt AND decrypt strings using an enhanced XOR technique similar to S-Coder (DDJ, Jan. 1990). To decrypt, simply re-apply the procedure using the same password key. This algorithm is reasonably secure on it's own; however,there are steps you can take to make it even more secure. 1) Use a long key that is not easily guessed. 2) Double or triple encrypt the string using different keys. To decrypt, re-apply the passwords in reverse order. 3) Use EnCipher before using Crypt. To decrypt, re-apply Crypt first then use DeCipher. 4) Some unique combination of the above NOTE: The resultant string may contain any character, 0..255.} asm Push ESI //Save the good stuff Push EDI Push EBX Or EAX,EAX Jz @Done Push EAX Push EDX Call UniqueString Pop EDX Pop EAX Mov EDI,[EAX] //String address into EDI Or EDI,EDI Jz @Done Mov ECX,[EDI-4] //String Length into ECX Jecxz @Done //Abort on null string Mov ESI,EDX //Key address into ESI Or ESI,ESI Jz @Done Mov EDX,[ESI-4] //Key Length into EDX Dec EDX //make zero based Js @Done //abort if zero key length Mov EBX,EDX //use EBX for rotation offset Mov AH,DL //seed with key length Cld //make sure we go forward @L1: Test AH,8 //build stream char. Jnz @L3 Xor AH,1 @L3: Not AH Ror AH,1 Mov AL,[ESI+EBX] //Get next char. from Key Xor AL,AH //XOR key with stream to make pseudo-key Xor AL,[EDI] //XOR pseudo-key with Source Stosb //store it back Dec EBX //less than zero ? Jns @L2 //no, then skip Mov EBX,EDX //re-initialize Key offset @L2: Dec ECX Jnz @L1 @Done: Pop EBX //restore the world Pop EDI Pop ESI end; //тоже самое только на паскале procedure PasCrypt(var Source: Ansistring; const Key: AnsiString); const numbH=65280;// 00000000 00000000 11111111 00000000 numbL=255; // 00000000 00000000 00000000 11111111 var A,B,C,D,cntDI:integer; S,EDI:Ansistring; stop : boolean; function L(p_val:integer):integer; begin result := p_val and 255; end; function H(p_val:integer):integer; begin result := p_val and numbH; end; function HfromL(p_val:integer):integer; begin result := p_val shl 8; end; function LfromH(p_val:integer):integer; begin result := p_val shr 8; end; procedure AssignL(var p_var:integer; const p_val:integer); begin p_var := p_var and (not 255); p_var := p_var or p_val; p_var := p_var; end; procedure AssignH(var p_var:integer; const p_val:integer); begin p_var := p_var and (not numbH); p_var := p_var or p_val; p_var := p_var; end; Procedure Hshift(var p_var:integer;p_count:integer;turn:char); var tmp_var,tmp_var_1,tmp_var_2,tmp_var_3,tmp_var_4:integer; begin tmp_var := p_var and numbH; tmp_var_1 := tmp_var shl 8; tmp_var_2 := tmp_var shl 16; tmp_var_3 := tmp_var; tmp_var_4 := tmp_var shr 8; tmp_var := 0; tmp_var := tmp_var or tmp_var_1; tmp_var := tmp_var or tmp_var_2; tmp_var := tmp_var or tmp_var_3; tmp_var := tmp_var or tmp_var_4; case turn of 'r','R': tmp_var := tmp_var shr p_count; 'l','L': tmp_var := tmp_var shl p_count; end; tmp_var := tmp_var and numbH; p_var := p_var and (not numbH); p_var := p_var or tmp_var; end; begin EDI := Source; if EDI = '' then exit; C := Length(Source); if C = 0 then exit; S := Key; if S = '' then exit; D := Length(Key); dec(D); if D<0 then exit; B := D; cntDI := 3; AssignH(A,HfromL(L(D))); stop := false; while not(stop)do begin if 0 = (A and 2048)then //test AH, 8 AssignH(A,H(H(A) xor HFromL(1))); // Xor AH,1 AssignH(A,H(not H(A))); // Not AH Hshift(A,1,'r'); // Ror AH,1 AssignL(A,ord(S[B+1])); // Mov AL, [ESI+EBX] AssignL(A,L(A) xor LfromH(H(A))); // Xor AL,AH AssignL(A,L(A) xor ord(Source[cntDI-2])); // Xor AL,[EDI] Source[cntDI-2] := chr(L(A)); // Stosb inc(cntDI); dec(B); // Dec EBX if B<0 then B := D; dec(C); if C = 0 then stop := true; end; end; //============================================================================== //******** Интерфейсные функции к тем жутким наворотам на Ассемблере *********** //******** соответствуют типу crtSmart *********** //------------------------------------------------------------------------------ function EncryptSmart(p_Str: ANSIstring; p_Key: string = ''): ANSIstring; var i,n: integer; begin EnCipher(p_Str); if p_Key='' then p_Key:=KEY1; Crypt(p_Str,p_Key); result:='@!001!'+IntToStr(length(p_Str) mod 3); if length(p_Str) mod 3=1 then p_Str:=p_Str+#0#0 else if length(p_Str) mod 3=2 then p_Str:=p_Str+#0; for i:=0 to length(p_Str) div 3 -1 do begin n:=ord(p_Str[i*3+1])*256*256+ord(p_Str[i*3+2])*256+ord(p_Str[i*3+3]); result:=result+ALFA1[n div (64*64*64) + 1]; n:=n mod (64*64*64); result:=result+ALFA1[n div (64*64) + 1]; n:=n mod (64*64); result:=result+ALFA1[n div 64 + 1]+ALFA1[n mod 64 + 1]; end; end; //============================================================================== function DecryptSmart(p_Str: ANSIstring; p_Key: String=''): ANSIstring; var i,n,k: integer; //**************************************************************************** function Val(n: integer): integer; begin result:=pos(p_Str[n],ALFA1)-1; end; //**************************************************************************** begin if copy(p_Str,1,6)<>'@!001!' then raise exception.Create(TranslateText('Decrypt1: неверный заголовок входящей строки!')); k:=StrToInt(p_Str[7]); p_Str:=copy(p_Str,8,length(p_Str)); if length(p_Str) mod 4 <> 0 then raise exception.Create(TranslateText('Decrypt1: неверная длина входящей строки!')); result:=''; for i:=0 to length(p_Str) div 4 - 1 do begin n:=Val(i*4+1)*64*64*64+Val(i*4+2)*64*64+Val(i*4+3)*64+Val(i*4+4); result:=result+chr(n div (256*256)); n:=n mod (256*256); result:=result+chr(n div 256)+chr(n mod 256); end; if k<>0 then SetLength(result,length(result)-3+k); if p_Key='' then p_Key:=KEY1; Crypt(result,p_Key); DeCipher(result); end; //============================================================================== function FormatDateTime2(S : String; D : TDateTime) : String; begin if D = 0 then Result := ' ' else Result := FormatDateTime(S, D); end; //============================================================================== //************ Чехуновские функции для проверок и блокировок ******************* //************ соответствуют типу crtTestLaunch ******************* //============================================================================== { Функции EnCoder и DeCoder Str - строка, которая будет шифроваться (пока должны быть символы только с двузначным кодом) Параметры: Inst - число-строка CheckUp_ID - число-строка KeyDate - дата Key - строка-число (необязательный параметр) Возможны варианты: 1. Хоть один из параметров Inst, CheckUp_ID, KeyDate не пустой - из них формируется зависимый ключ. 2. Три параметра пустые и Key не задан - строка будет зашифрована с ключом '81943' 3. Если просто надо зашифровать со своим ключом - параметры Inst, CheckUp_ID, KeyDate установить пустыми (Inst='', CheckUp_ID='', KeyDate=0), и задать свой Key. } function EnCoder(Str, Inst, CheckUp_ID :string; KeyDate:TDateTime; Key:string='81943'):string; var InStr, TempStr, s : string; i, j : integer; {$IFDEF VER150} function ReplaceStr(const S, Srch, Replace: string): string; var I: Integer; Source: string; begin Source := S; Result := ''; repeat I := Pos(Srch, Source); if I > 0 then begin Result := Result + Copy(Source, 1, I - 1) + Replace; Source := Copy(Source, I + Length(Srch), MaxInt); end else Result := Result + Source; until I <= 0; end; {$ENDIF} begin // ВНИМАНИЕ !!! Данная версия функции может шифровать только строки, // которые состоят из символов с двузначными кодами ! result := ''; if length(Str)=0 then exit; TempStr := ''; // За ключ(ключ-цифровой) берем строку из инста и кода проверки для непереносимости // зашифрованной строки между базами if Inst + CheckUp_ID + ReplaceStr(FormatDateTime2('ddmm',KeyDate),' ','')<>'' then Key := Inst + CheckUp_ID + ReplaceStr(FormatDateTime2('ddmm',KeyDate),' ',''); InStr := Str; // Если кодируется слишком маленькая строка - дополнить ее ('_'+циферки) до 10 симв. if Length(Str)<4 then begin InStr := InStr + '_'+IntToStr((ord(InStr[1])*2+1) mod 10); while Length(InStr)<10 do InStr := InStr +IntToStr((StrToInt(InStr[Length(InStr)])*2+1) mod 10) end; // Формируем строку из кодов символов входящей строки и складываем с ключом for i :=1 to Length(InStr) do TempStr := TempStr + IntToStr(ord(InStr[i])); InStr := TempStr; j:=1; s:=''; for i:=1 to Length(InStr) do begin s:=s+IntToStr((StrToInt(InStr[i])+StrToInt(Key[j])) mod 10); inc(j); if j>Length(Key) then j:=1; end; InStr := s; // Делим строку на блоки по 6 символом, над каждым блоком проворачиваем // перестановку и слепляем в строку-результат i:=1; while i<length(InStr) do begin s:= Copy(InStr,i,6); if Length(s)<6 then Result := Result +s else Result:=Result+s[3]+s[1]+s[6]+s[2]+s[4]+s[5]; inc(i,6); end; End; //============================================================================== function DeCoder(Str, Inst, CheckUp_ID :string;KeyDate:TDateTime; Key:string='81943'):string; var InStr, TempStr, s : string; i, j : integer; {$IFDEF VER150} function ReplaceStr(const S, Srch, Replace: string): string; var I: Integer; Source: string; begin Source := S; Result := ''; repeat I := Pos(Srch, Source); if I > 0 then begin Result := Result + Copy(Source, 1, I - 1) + Replace; Source := Copy(Source, I + Length(Srch), MaxInt); end else Result := Result + Source; until I <= 0; end; {$ENDIF} begin // Обратная перестановка блоков result := ''; i:=1; InStr := ''; while i<length(Str) do begin s:= Copy(Str,i,6); if Length(s)<6 then InStr := InStr +s else InStr := InStr +s[2]+s[4]+s[1]+s[5]+s[6]+s[3]; inc(i,6); end; // Отнимаем ключ if Inst + CheckUp_ID + ReplaceStr(FormatDateTime2('ddmm',KeyDate),' ','')<>'' then Key := Inst + CheckUp_ID + ReplaceStr(FormatDateTime2('ddmm',KeyDate),' ',''); j:=1; TempStr:=''; for i:=1 to Length(InStr) do begin TempStr := TempStr +IntToStr((StrToInt(InStr[i])+10-StrToInt(Key[j])) mod 10); inc(j); if j>Length(Key) then j:=1; end; // Переводим в символы i:=1; InStr := TempStr; while i<Length(InStr) do begin Result := Result + chr(StrToInt(Copy(InStr,i,2))); inc(i,2); end; if Pos('_',Result)>0 then Result := Copy(Result,1,Pos('_',Result)-1); End; //============================================================================== //********* Функции Должикова для кодирования VERSION_KEY и еще разного ******** //********* соответствуют типу crtVersionKey ******** //============================================================================== const Shifr='1234567890.ABCDEFGHIJKLMNOPRSTUVWXYZabcdefghijklmnoprstuvwxyz'; function Coding(s:string; seed: integer = 0):string; var sm,i,n:integer; res:string; begin if seed=0 then sm:=random(length(Shifr))+1 else sm:=seed mod length(Shifr)+1; res:=Shifr[sm]; for i:=1 to length(s) do begin n:=pos(s[i],Shifr); if n=0 then Raise Exception.Create(TranslateText('Coding: Не найден символ ')+s[i]); n:=(n+sm*i) mod length(Shifr)+1; res:=res+Shifr[n]; end; result:=res; end; //============================================================================== function Decoding(s:string):string; var sm,i,n:integer; res:string; begin sm:=pos(s[1],Shifr); res:=''; for i:=2 to length(s) do begin n:=pos(s[i],Shifr); if n=0 then Raise Exception.Create(TranslateText('Decoding: Не найден символ ')+s[i]); n:=n-sm*(i-1)+length(Shifr)*i-2; n:=n mod length(Shifr)+1; res:=res+Shifr[n]; end; result:=res; end; //============================================================================== function GetKey(CurrDate:TDateTime;inst:integer):string; const days :array[1..7] of string = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'); var dd, mon, year : word; temp, str_dd : integer; begin DecodeDate(CurrDate, Year, mon, dd); str_dd := DayOfWeek(CurrDate); Temp := ((inst*101) mod (dd+mon))*99999+str_dd*9999+((dd+mon)*(str_dd+inst))*999*inst+(dd-mon-inst)*99-dd-mon-inst; result := IntToStr(Temp)+days[str_dd][inst*dd mod 6 + 1]; insert(days[str_dd][ABS(dd+mon-inst)*str_dd mod 6 + 1],result,(str_dd*str_dd+inst+dd) mod 8 + 1); insert(days[str_dd][(inst+mon) mod 6 + 1],result,(dd*mon+inst+str_dd) mod 8 + 1); while Pos('-',result)<>0 do delete(result,Pos('-',result),1); end; //============================================================================== //************** ГЛАВНЫЕ ИНТЕРФЕЙСНЫЕ ФУНКЦИИ ***************************** //------------------------------------------------------------------------------ procedure GetTestLaunchArgs( p_List: array of variant; p_Len: integer; var pp_Inst,pp_Checkup_id: string; var pp_KeyDate: TDateTime; var pp_Key: string); begin if p_Len>1 then pp_Inst:=p_List[1] else pp_Inst:=''; if p_Len>2 then pp_Checkup_Id:=p_List[2] else pp_Checkup_Id:=''; if p_Len>3 then pp_KeyDate:=p_List[3] else pp_KeyDate:=0; if p_Len>4 then pp_Key:=p_List[4] else pp_Key:='81943'; end; function Encrypt( p_Type: TOilCryptType; p_List: array of variant ): string; var vInst,vCheckup_Id,vKey: string; vKeyDate:TDateTime; len,sid: integer; begin try len:=length(p_List); if len<=0 then raise exception.create( TranslateText('недостаточно аргументов')); case p_Type of crtTestLaunch: begin GetTestLaunchArgs(p_List,len,vInst,vCheckup_Id,vKeyDate,vKey); result:=EnCoder(p_List[0],vInst,vCheckup_Id,vKeyDate,vKey); end; crtVersionKey: if len=1 then result:=Coding(p_List[0]) else result:=Coding(p_List[0],p_List[1]); crtSmart: begin {если вторым членом p_List идет ключ то использовать его иначе ключ по умолчанию} if len=1 then result:=EncryptSmart(p_List[0]) else result:=EncryptSmart(p_List[0],p_List[1]); end; crtOrgKey: begin if len<2 then raise exception.create( TranslateText('Недостаточно аргументов для вызова с типом crtOrgKey')); result:=GetKey(p_List[0],p_List[1]); end; end; except on E:Exception do raise exception.create('Encrypt: '+E.Message); end; end; //============================================================================== function Decrypt( p_Type: TOilCryptType; p_List: array of variant ): string; var vInst,vCheckup_Id,vKey: string; vKeyDate:TDateTime; len: integer; begin try len:=length(p_List); if len<=0 then raise exception.create( TranslateText('Decrypt: недостаточно аргументов')); case p_Type of crtTestLaunch: begin GetTestLaunchArgs(p_List,len,vInst,vCheckup_Id,vKeyDate,vKey); result:=DeCoder(p_List[0],vInst,vCheckup_Id,vKeyDate,vKey); end; crtVersionKey: result:=Decoding(p_List[0]); crtSmart: begin {если вторым членом p_List идет ключ то использовать его иначе ключ по умолчанию} if len=1 then result:=DecryptSmart(p_List[0]) else result:=DecryptSmart(p_List[0],p_List[1]); end; crtOrgKey: raise exception.create( TranslateText('Decrypt: отсутствует алгоритм расшифровки с типом crtOrgKey')); end; except on E: Exception do raise exception.create('Decrypt: '+E.Message); end; end; //============================================================================== function GetPassword(p_Type : TOilPasswordType;p_List: array of variant): string; var SPassw,SStr : string; begin case p_Type of pwtTestLaunch: begin try DecodeDate(p_List[2],vYear,vMonth,vDay); SStr := IntToStr(p_List[1])+ p_List[3]+ FormatDateTime('md',p_List[2])+ p_List[0] ; SPassw := Encrypt( crtSmart, [FormatDateTime('mmddyy',p_List[2]), SStr ] ); Result := TruncPasswId(SPassw); except on E:Exception do ShowMessage(TranslateText('Ошибка в GetPassword.pwtTestLaunch:')+E.Message); end; end; pwtOrg : result:=GetKey(p_List[0],p_List[1]); pwtWagon: result:=Encrypt(crtVersionKey,[Integer(p_List[0])+p_List[1],Integer(p_List[0])]); else raise Exception.Create(TranslateText('Задан неведомый тип пароля. Если появился новый, нужно добавить в uCrypt.GetPassword')); end; end; //============================================================================== function TruncPasswId(p_Passw: string) : string; begin Result := Copy(p_Passw,Pos('@!001!',p_Passw)+6,length(p_Passw)); end; //============================================================================== end.
//****************************************************************************** // TSunTime v.2.0 -- Calculates times of sunrise, sunset. // // The algorithm is derived from noaa code : // http://www.srrb.noaa.gov/highlights/sunrise/sunrise.html // Adapted and ported on Free Pascal by bb - sdtp - may 2021 // Properties // Sundate (TDateTime) : Selected day // TimeZone (Double) : Time offset in hours // Latitude (Double) : Latitude in decimal degrees (N : positive, S : negative) // Longitude (Double) : Longitude in decimal degrees (E : positive, W : negative) // Altitude (Integer) : Not yet implemented // TypeSun (TSunrise) : Sunrise/sunset type: standard, civil, nautic ou astro // // Sunrise (TDateTime) : Sunrise at the selected date (Sundate) // Sunset (TDateTime) : Sunset // SunNoon (TDateTime) : Noon // Infos // ZenithDistance : angular distance of a celestial body from the zenith. // 90° minus the body's altitude above the horizon // Todo : Altitude/Elevation : adding -2.076*sqrt(elevation in metres)/60 //****************************************************************************** unit Suntime; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, math, dateUtils; type // Type of value needed TSunrise = (standard, civil, nautic, astro, none); TSuntime = class(TComponent) private fVersion: String; fSundate: TDateTime; fTimeZone: Double; fLatitude: Double; fLongitude: Double; fAltitude: Integer; fSunrise: TDateTime; fSunset: TDateTime; fSunNoon: TDateTime; fTypeSun: TSunrise; fOnchange: TNotifyEvent; procedure ParametersChanged(Sender: TObject); procedure SetTypeSun(value: TSunRise); procedure SetSundate(Value: TDateTime); procedure SetTimeZone(Value: Double); procedure SetLatitude(Value: Double); procedure SetLongitude(Value: Double); procedure SetAltitude(Value: Integer); function calcSunrise(index: Integer): TDateTime; function calcSolNoonUTC(t, longitude: double): double; function calcTimeJulianCent(jd: double): double; function calcJDFromJulianCent(t: double): double; function calcEquationOfTime(t: double): double; function calcObliquityCorrection(t: double):double; function calcMeanObliquityOfEcliptic(t: double): double; function calcGeomMeanLongSun(t: double): double; function calcEccentricityEarthOrbit(t: double): double; function calcGeomMeanAnomalySun(t: double): double; function calcSunDeclination(t: double): double; function calcSunApparentLong(t: double): double; function calcSunTrueLong(t: double): double; function calcSunEqOfCenter(t: double): double; function calcHourAngleSunrise(lat, solarDec: double; TypeSun: TSunRise=standard): double; function UTCMinutesToUTCTime(const Minutes: Double): TDateTime; protected public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Version: String read fVersion; property Sunrise: TDateTime read fSunrise;//calcSunrise; property Sunset: TDateTime read fSunset; property SunNoon: TDateTime read fSunNoon; published property Sundate: TDateTime read fSundate write SetSundate; property TimeZone: Double read fTimeZone write SetTimeZone; property Latitude: Double read fLatitude write SetLatitude; property Longitude: Double read fLongitude write SetLongitude; property Altitude: Integer read fAltitude write SetAltitude; // Not yet implemented property TypeSun: TSunrise read fTypeSun write SetTypeSun; end; procedure Register; implementation procedure Register; begin {$I suntime_icon.lrs} RegisterComponents('lazbbAstroComponents',[TSuntime]); end; constructor TSuntime.Create(AOwner: TComponent); begin inherited Create(AOwner); fVersion:= '2.0'; fTypeSun:= standard; end; destructor TSuntime.Destroy; begin inherited Destroy; end; procedure TSuntime.SetTypeSun(value: TSunRise); begin if fTypeSun <> Value then begin fTypeSun:= Value; ParametersChanged(nil); end; end; procedure TSuntime.SetSundate(Value: TDateTime); begin if fsundate <> Value then begin fSundate := Value; ParametersChanged(nil); end; end; procedure TSuntime.SetTimeZone(Value: Double); begin if (fTimeZone <> Value) and (Value >= -12) and (Value <= +12) then begin fTimeZone := Value; ParametersChanged(nil); end; end; procedure TSuntime.SetLatitude(Value: Double); begin if fLatitude<>value then begin fLatitude:= Value; ParametersChanged(nil); end; end; procedure TSuntime.SetLongitude(Value: Double); begin if fLongitude<>value then begin fLongitude:= Value; ParametersChanged(nil); end; end; procedure TSuntime.SetAltitude(Value: Integer); begin if fAltitude<>value then begin fAltitude:= Value; ParametersChanged(nil); end; end; procedure TSuntime.ParametersChanged(Sender: TObject); begin fSunrise:= calcSunrise(0); fSunset:= calcSunrise(1); fSunNoon:= calcSunrise(2); if Assigned(FOnChange) then FOnChange(Self); end; //***********************************************************************/ // calcSunrise : calculate the local time of sunrise/sunset // index 0 sunrise, 1 sunset and 2 noon // Return value: local time //***********************************************************************/ function TSuntime.calcSunrise(index: Integer): TDateTime; var r: integer; JD, t: double; noonmin, tnoon, eqTime, solarDec, hourAngle: double; delta, timeDiff,timeUTC, newt : double; hr, mn, y, m, d : Integer; longit: Double; begin // longitudes are inversed (east negative) longit:= -1*flongitude; JD:= DateTimeToJulianDate(fSundate); t:= calcTimeJulianCent(JD); noonmin:= calcSolNoonUTC(t, longit); // Find the time of solar noon at the location if index=2 then begin result:= UTCMinutesToUTCTime(noonmin)+fTimeZone/24; // update noon value exit; end; tnoon:= calcTimeJulianCent (JD+noonmin/1440.0); // *** First pass to approximate sunrise or sunset (using solar noon) // check if sunrise or sunset if index= 0 then r:= 1 else r:= -1; eqTime:= calcEquationOfTime(tnoon); solarDec:= calcSunDeclination(tnoon); hourAngle:= calcHourAngleSunrise(flatitude, solarDec, fTypeSun)*r; delta:= longit - radToDeg(hourAngle); timeDiff:= 4 * delta; // in minutes of time timeUTC:= 720 + timeDiff - eqTime; // in minutes // *** Second pass includes fractional jday in gamma calc newt:= calcTimeJulianCent(calcJDFromJulianCent(t) + timeUTC/1440.0); eqTime:= calcEquationOfTime(newt); solarDec:= calcSunDeclination(newt); hourAngle:= calcHourAngleSunrise(flatitude, solarDec, fTypeSun)*r; delta:= longit - radToDeg(hourAngle); timeDiff:= 4 * delta; timeUTC:= 720 + timeDiff - eqTime; // in minutes hr:= floor(timeUTC /60); mn:= floor(timeUTC- hr*60); y:= YearOf(fSundate); m:= MonthOf(fSundate); d:= DayOfTheMonth(fSundate); result:= EncodeDateTime(y,m,d,hr,mn,0,0)+fTimeZone/24; end; //*********************************************************************** // calcSolNoonUTC // calculate the Universal Coordinated Time (UTC) of solar // noon for the given day at the given location on earth // t : number of Julian centuries since J2000.0 // longitude : longitude of observer in degrees // Return value: time in minutes from zero Z //***********************************************************************/ function TSuntime.calcSolNoonUTC(t, longitude: double): double; var tnoon, eqTime, solNoonUTC, newt: double; begin //First pass uses approximate solar noon to calculate eqtime tnoon:= calcTimeJulianCent(calcJDFromJulianCent(t) + longitude/360.0); eqTime:= calcEquationOfTime(tnoon); solNoonUTC:= 720 + (longitude * 4) - eqTime; // min newt:= calcTimeJulianCent(calcJDFromJulianCent(t) -0.5 + solNoonUTC/1440.0); eqTime:= calcEquationOfTime(newt); // var solarNoonDec = calcSunDeclination(newt); solNoonUTC:= 720 + (longitude * 4) - eqTime; // min result:= solNoonUTC; end; //***********************************************************************/ //* Name: calcTimeJulianCent //* Type: Function //* Purpose: convert Julian Day to centuries since J2000.0. //* Arguments: //* jd : the Julian Day to convert //* Return value: //* the T value corresponding to the Julian Day //***********************************************************************/ function TSuntime.calcTimeJulianCent(jd: double): double; begin result:= (jd-2451545.0)/36525.0; end; //***********************************************************************/ //* Name: calcJDFromJulianCent //* Type: Function //* Purpose: convert centuries since J2000.0 to Julian Day. //* Arguments: //* t : number of Julian centuries since J2000.0 //* Return value: //* the Julian Day corresponding to the t value //***********************************************************************/ function TSuntime.calcJDFromJulianCent(t: double): double; var JD: double; begin JD:= (t*36525.0) + 2451545.0; result:= JD; end; //***********************************************************************/ //* Name: calcEquationOfTime //* Type: Function //* Purpose: calculate the difference between true solar time and mean solar time //* Arguments: //* t : number of Julian centuries since J2000.0 //* Return value: //* equation of time in minutes of time //***********************************************************************/ function TSuntime.calcEquationOfTime(t: double): double; var epsilon, l0, e, m, y : double; sin2l0, sinm, cos2l0, sin4l0, sin2m : double; Etime: Double; begin epsilon:= calcObliquityCorrection(t); l0:= calcGeomMeanLongSun(t); e:= calcEccentricityEarthOrbit(t); m:= calcGeomMeanAnomalySun(t); y:= sqr(tan(degToRad(epsilon)/2.0)); sin2l0:= sin(2.0 * degToRad(l0)); sinm:= sin(degToRad(m)); cos2l0:= cos(2.0 * degToRad(l0)); sin4l0:= sin(4.0 * degToRad(l0)); sin2m:= sin(2.0 * degToRad(m)); Etime:= y * sin2l0 - 2.0 * e * sinm + 4.0 * e * y * sinm * cos2l0 - 0.5 * y * y * sin4l0 - 1.25 * e * e * sin2m; result:= radToDeg(Etime)*4.0; // in minutes of time end; //***********************************************************************/ //* Name: calcObliquityCorrection //* Type: Function //* Purpose: calculate the corrected obliquity of the ecliptic //* Arguments: //* t : number of Julian centuries since J2000.0 //* Return value: //* corrected obliquity in degrees //***********************************************************************/ function TSuntime.calcObliquityCorrection(t: double):double; var e0, omega, e: double; begin e0:= calcMeanObliquityOfEcliptic(t); omega:= 125.04 - 1934.136 * t; e:= e0 + 0.00256 * cos(degToRad(omega)); result:= e; // in degrees end; //***********************************************************************/ //* Name: calcMeanObliquityOfEcliptic //* Type: Function //* Purpose: calculate the mean obliquity of the ecliptic //* Arguments: //* t : number of Julian centuries since J2000.0 //* Return value: //* mean obliquity in degrees //***********************************************************************/ function TSuntime.calcMeanObliquityOfEcliptic(t: double): double; var seconds, e0 : double; begin seconds:= 21.448 - t*(46.8150 + t*(0.00059 - t*(0.001813))); e0:= 23.0 + (26.0 + (seconds/60.0))/60.0; result:= e0; //in degrees end; //***********************************************************************/ //* Name: calGeomMeanLongSun //* Type: Function //* Purpose: calculate the Geometric Mean Longitude of the Sun //* Arguments: //* t : number of Julian centuries since J2000.0 //* Return value: //* the Geometric Mean Longitude of the Sun in degrees //***********************************************************************/ function TSuntime.calcGeomMeanLongSun(t: double): double; var L0: double; begin L0:= 280.46646 + t * (36000.76983 + 0.0003032 * t); while(L0 > 360.0) do L0:= L0 - 360.0; while(L0 < 0.0) do L0:= L0 + 360.0; result:= L0; // in degrees end; //***********************************************************************/ //* Name: calcEccentricityEarthOrbit //* Type: Function //* Purpose: calculate the eccentricity of earth's orbit //* Arguments: //* t : number of Julian centuries since J2000.0 //* Return value: //* the unitless eccentricity //***********************************************************************/ function TSuntime.calcEccentricityEarthOrbit(t: double): double; var e: double; begin e:= 0.016708634 - t * (0.000042037 + 0.0000001267 * t); result:= e; // unitless end; //***********************************************************************/ //* Name: calGeomAnomalySun //* Type: Function //* Purpose: calculate the Geometric Mean Anomaly of the Sun //* Arguments: //* t : number of Julian centuries since J2000.0 //* Return value: //* the Geometric Mean Anomaly of the Sun in degrees //***********************************************************************/ function TSuntime.calcGeomMeanAnomalySun(t: double): double; var M: double; begin M:= 357.52911 + t * (35999.05029 - 0.0001537 * t); result:= M; // in degrees end; //***********************************************************************/ //* Name: calcSunDeclination //* Type: Function //* Purpose: calculate the declination of the sun //* Arguments: //* t : number of Julian centuries since J2000.0 //* Return value: //* sun's declination in degrees //***********************************************************************/ function TSuntime.calcSunDeclination(t: double): double; var e, lambda, sint, theta: double; begin e:= calcObliquityCorrection(t); lambda:= calcSunApparentLong(t); sint:= sin(degToRad(e)) * sin(degToRad(lambda)); theta:= radToDeg(arcsin(sint)); result:= theta; // in degrees end; //***********************************************************************/ //* Name: calcSunApparentLong //* Type: Function //* Purpose: calculate the apparent longitude of the sun //* Arguments: //* t : number of Julian centuries since J2000.0 //* Return value: //* sun's apparent longitude in degrees //***********************************************************************/ function TSuntime.calcSunApparentLong(t: double): double; var o, omega, lambda: double; begin o:= calcSunTrueLong(t); omega:= 125.04 - 1934.136 * t; lambda:= o - 0.00569 - 0.00478 * sin(degToRad(omega)); result:= lambda; // in degrees end; //***********************************************************************/ //* Name: calcSunTrueLong //* Type: Function //* Purpose: calculate the true longitude of the sun //* Arguments: //* t : number of Julian centuries since J2000.0 //* Return value: //* sun's true longitude in degrees //***********************************************************************/ function TSuntime.calcSunTrueLong(t: double): double; var l0, c, O: double; begin l0:= calcGeomMeanLongSun(t); c:= calcSunEqOfCenter(t); O:= l0 + c; result:= O; // in degrees end; //***********************************************************************/ //* Name: calcSunEqOfCenter //* Type: Function //* Purpose: calculate the equation of center for the sun //* Arguments: //* t : number of Julian centuries since J2000.0 //* Return value: //* in degrees //***********************************************************************/ function TSuntime.calcSunEqOfCenter(t: double): double; var m, mrad, sinm, sin2m, sin3m, C : double; begin m:= calcGeomMeanAnomalySun(t); mrad:= degToRad(m); sinm:= sin(mrad); sin2m:= sin(mrad+mrad); sin3m:= sin(mrad+mrad+mrad); C:= sinm * (1.914602 - t * (0.004817 + 0.000014 * t)) + sin2m * (0.019993 - 0.000101 * t) + sin3m * 0.000289; Result:= C; // in degrees end; //***********************************************************************/ //* Name: calcHourAngleSunrise //* Purpose: calculate the hour angle of the sun at sunrise for the latitude //* Arguments: //* lat : latitude of observer in degrees //* solarDec : declination angle of sun in degrees //* TypSun : standard, civil, nautic, astro //* Return value: //* hour angle of sunrise in radians //***********************************************************************/ function TSuntime.calcHourAngleSunrise(lat, solarDec: double; TypeSun: TSunRise=standard): double; var latRad, sdRad, HA: double; ZenithDistance: Double; const aSunTypDeg: array [0..4] of Double = (90.83333, 96, 102, 108, 90); begin try ZenithDistance:= aSunTypDeg[Ord(TypeSun)]; except ZenithDistance:= 90.83333; end; latRad:= degToRad(lat); sdRad:= degToRad(solarDec); HA:= (arccos(cos(degToRad(ZenithDistance))/(cos(latRad)*cos(sdRad))-tan(latRad) * tan(sdRad))); Result:= HA; // in radians end; function TSuntime.UTCMinutesToUTCTime(const Minutes: Double): TDateTime; begin Result := Trunc(fSundate) + (Minutes / 60 ) / 24; end; end.
unit GameTactics; interface uses GameLogic, Classes, Dialogs; procedure LoadLib(FileName: string= ''); procedure SaveLib(FileName: string = ''); function FormatPosition(const Position: TPosition): string; function SelectMove(var Board: TPosition; MaxBufLen: Integer; var CurrentEstimate: Integer): Integer; var Lib: TStringList; implementation uses Windows, SysUtils, MainUnit; var MySide: ShortInt; Deep: Integer; MaxBufferLen: Integer; CurrentN: Integer; const NO_MOVES = 1; SingleCosts: array[0..31] of Integer = ( 7, 11, 13, 10, 10, 12, 11, 10, 8, 12, 12, 11, 11, 13, 15, 11, 10, 16, 10, 9, 11, 13, 16, 11, 10, 10, 10, 10, 0, 0, 0, 0); MamCosts: array[0..31] of Integer = (12, 11, 10, 13, 13, 10, 13, 13, 11, 14, 14, 13, 10, 15, 14, 10, 11, 14, 15, 10, 13, 14, 14, 11, 13, 13, 10, 13, 13, 11, 11, 12); Diag: array[0..31] of Integer = ( 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1 ); function LibPosition(const Position: TPosition; var Estimate: Integer): Boolean; var Index: Integer; PositionStr: string; begin PositionStr := FormatPosition(Position); Index := Lib.IndexOf(PositionStr); Result := Index <> -1; if Result then Estimate := Integer(Lib.Objects[Index]); end; function Estimate(const Board: TPosition): Integer; var I: Integer; C: Integer; WS, BS, WM, BM: Integer; WhiteDiag: Boolean; BlackDiag: Boolean; begin Result := 0; WS := 0; BS := 0; WM := 0; BM := 0; WhiteDiag := False; BlackDiag := False; C := 0; for I := 0 to 31 do begin case Board.Field[I] of brWhiteSingle: begin C := SingleCosts[I]; WS := WS + 1; end; brBlackSingle: begin C := SingleCosts[31-I]; BS := BS + 1; end; brWhiteMam: begin C := MamCosts[I]; WM := WM + 1; if Diag[I] = 1 then WhiteDiag := True; end; brBlackMam: begin C := MamCosts[31-I]; BM := BM + 1; if Diag[I] = 1 then BlackDiag := True; end; else Continue end; Result := Result + C*Board.Field[I]; end; if (BM <> 0) and (WS <> 0) then Result := Result div 2; if (WS=0) and (BS=0) then begin if (WM=1) and (BM=1) then Result := 0; if (WM=2) and (BM=1) then Result := 0; if (WM=1) and (BM=2) then Result := 0; if (WM=3) and (BM=1) and BlackDiag then Result := 0; if (WM=1) and (BM=3) and WhiteDiag then Result := 0; end; if WhiteDiag then Result := Result + 100; if BlackDiag then Result := Result - 100; end; // Beta tested 20.02.2002 function RecurseEstimate(var Position: TPosition): Integer; var SaveCurrentN: Integer; PositionCount: Integer; I: Integer; Temp: Integer; Board: TPosition; begin Board := Position; if CurrentN > MaxBufferLen then begin Result := Estimate(Board); Exit; end; Deep := Deep + 20; SaveCurrentN := CurrentN; if Board.Active = ActiveWhite then PositionCount := GetMovesWhite(SaveCurrentN, Board) else PositionCount := GetMovesBlack(SaveCurrentN, Board); CurrentN := CurrentN + PositionCount; if PositionCount = 0 then begin if Board.Active = ActiveWhite then Result := -100000 + Deep else Result := +100000 - Deep; end else if PositionCount = 1 then begin Result := RecurseEstimate(Buffer[SaveCurrentN]); end else begin // Обычная рекурсивная оценка Result := RecurseEstimate(Buffer[SaveCurrentN]); for I := SaveCurrentN+1 to CurrentN - 1 do begin Temp := RecurseEstimate(Buffer[I]); if (Board.Active = ActiveWhite) then begin if Temp > Result then Result := Temp; end else begin if Temp < Result then Result := Temp; end; end; end; Deep := Deep - 20; CurrentN := SaveCurrentN; end; procedure WaitAnimation; begin while SendMessage(MainForm.Handle, MM_IS_ANIMATION, 0, 0) = 1 do Sleep(30); end; // Beta tested 20.05.2002 function SelectMove(var Board: TPosition; MaxBufLen: Integer; var CurrentEstimate: Integer): Integer; var I: Integer; CurrentIndex: Integer; Temp: Integer; begin try MySide := Board.Active; MaxBufferLen := MaxBufLen; CurrentN := 0; Deep := 0; if Board.Active = ActiveWhite then CurrentN := Abs(GetMovesWhite(0, Board)) else CurrentN := Abs(GetMovesBlack(0, Board)); if CurrentN = 0 then begin Result := NO_MOVES; Exit; end; if CurrentN = 1 then begin Board := Buffer[0]; Result := 0; Exit; end; SendMessage(MainForm.Handle, MM_DEBUG, 0, 0); if not LibPosition(Buffer[0], CurrentEstimate) then CurrentEstimate := RecurseEstimate(Buffer[0]); SendMessage(MainForm.Handle, MM_DEBUG, Integer(@Buffer[0]), CurrentEstimate); CurrentEstimate := CurrentEstimate + Random(101) - 50; CurrentIndex := 0; for I := 1 to CurrentN - 1 do begin if not LibPosition(Buffer[I], Temp) then Temp := RecurseEstimate(Buffer[I]); SendMessage(MainForm.Handle, MM_DEBUG, Integer(@Buffer[I]), Temp); Temp := Temp + Random(21) - 10; if MySide = ActiveWhite then begin if Temp > CurrentEstimate then begin CurrentEstimate := Temp; CurrentIndex := I; end; end else begin if Temp < CurrentEstimate then begin CurrentEstimate := Temp; CurrentIndex := I; end; end; end; Board := Buffer[CurrentIndex]; Result := 0; finally WaitAnimation; end; end; function DefaultFileName: string; begin Result := IncludeTrailingBackslash(ExtractFilePath(ParamStr(0))) + 'WinDraught.lib' end; procedure LoadLib(FileName: string= ''); var Temp: TStringList; I: Integer; No: Integer; begin if Trim(FileName) = '' then FileName := DefaultFileName; try Temp := TStringList.Create; try Temp.LoadFromFile(FileName); for I := 0 to Temp.Count-1 do begin if Length(Trim(Temp[I])) <> 6 + 33 then Continue; No := StrToIntDef(Copy(Trim(Temp[I]), 1, 6), -$7FFFFFFF); if No = -$7FFFFFFF then Continue; Lib.AddObject(Copy(Trim(Temp[I]), 7, 33), TObject(No)); end; Lib.Sorted := True; finally Temp.Free; end; except MessageDlg(Format('Error loading file "%s"', [FileName]), mtWarning, [mbOk], 0); end; end; procedure SaveLib(FileName: string = ''); var I: Integer; Estimate: Integer; Temp: TStringList; begin if Trim(FileName) = '' then FileName := DefaultFileName; Temp := TStringList.Create; try for I := 0 to Lib.Count-1 do begin Estimate := Integer(Lib.Objects[I]); if Estimate < 0 then Temp.Add('-' + FormatFloat('00000', -Estimate) + Lib[I]) else Temp.Add('+' + FormatFloat('00000', Estimate) + Lib[I]); end; Temp.SaveToFile(FileName); finally Temp.Free; end; end; function FormatPosition(const Position: TPosition): string; var I: Integer; begin SetLength(Result, 33); if Position.Active = ActiveWhite then Result[1] := '+' else Result[1] := '-'; for I := 0 to 31 do case Position.Field[I] of brWhiteSingle: Result[I+2] := 'w'; brBlackSingle: Result[I+2] := 'b'; brWhiteMam: Result[I+2] := 'W'; brBlackMam: Result[I+2] := 'B' else Result[I+2] := '.' end; end; initialization Randomize; Lib := TStringList.Create; finalization Lib.Free; end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [CONTABIL_CONTA] 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 ContabilContaVO; {$mode objfpc}{$H+} interface uses VO, Classes, SysUtils, FGL, PlanoContaVO, PlanoContaRefSpedVO; type TContabilContaVO = class(TVO) private FID: Integer; FID_PLANO_CONTA: Integer; FID_CONTABIL_CONTA: Integer; FID_PLANO_CONTA_REF_SPED: Integer; FCLASSIFICACAO: String; FTIPO: String; FDESCRICAO: String; FDATA_INCLUSAO: TDateTime; FSITUACAO: String; FNATUREZA: String; FPATRIMONIO_RESULTADO: String; FLIVRO_CAIXA: String; FDFC: String; FORDEM: String; FCODIGO_REDUZIDO: String; FCODIGO_EFD: String; FPlanoContaNome: String; FPlanoContaSpedDescricao: String; FContabilContaPai: String; FPlanoContaVO: TPlanoContaVO; FPlanoContaRefSpedVO: TPlanoContaRefSpedVO; FContabilContaPaiVO: TContabilContaVO; published constructor Create; override; destructor Destroy; override; property Id: Integer read FID write FID; property IdPlanoConta: Integer read FID_PLANO_CONTA write FID_PLANO_CONTA; property PlanoContaNome: String read FPlanoContaNome write FPlanoContaNome; property IdContabilConta: Integer read FID_CONTABIL_CONTA write FID_CONTABIL_CONTA; property ContabilContaPai: String read FContabilContaPai write FContabilContaPai; property IdPlanoContaRefSped: Integer read FID_PLANO_CONTA_REF_SPED write FID_PLANO_CONTA_REF_SPED; property PlanoContaSpedDescricao: String read FPlanoContaSpedDescricao write FPlanoContaSpedDescricao; property Classificacao: String read FCLASSIFICACAO write FCLASSIFICACAO; property Tipo: String read FTIPO write FTIPO; property Descricao: String read FDESCRICAO write FDESCRICAO; property DataInclusao: TDateTime read FDATA_INCLUSAO write FDATA_INCLUSAO; property Situacao: String read FSITUACAO write FSITUACAO; property Natureza: String read FNATUREZA write FNATUREZA; property PatrimonioResultado: String read FPATRIMONIO_RESULTADO write FPATRIMONIO_RESULTADO; property LivroCaixa: String read FLIVRO_CAIXA write FLIVRO_CAIXA; property Dfc: String read FDFC write FDFC; property Ordem: String read FORDEM write FORDEM; property CodigoReduzido: String read FCODIGO_REDUZIDO write FCODIGO_REDUZIDO; property CodigoEfd: String read FCODIGO_EFD write FCODIGO_EFD; property PlanoContaVO: TPlanoContaVO read FPlanoContaVO write FPlanoContaVO; property PlanoContaRefSpedVO: TPlanoContaRefSpedVO read FPlanoContaRefSpedVO write FPlanoContaRefSpedVO; property ContabilContaPaiVO: TContabilContaVO read FContabilContaPaiVO write FContabilContaPaiVO; end; TListaContabilContaVO = specialize TFPGObjectList<TContabilContaVO>; implementation constructor TContabilContaVO.Create; begin inherited; FPlanoContaVO := TPlanoContaVO.Create; FPlanoContaRefSpedVO := TPlanoContaRefSpedVO.Create; /// EXERCICIO /// se nós criamos o objeto abaixo teremos um estouro de pilha. /// ocorre que temos um auto-relacionamento aqui. caso o objeto abaixo /// seja criado ele tentará criar outro do mesmo tipo num laço infinito /// até estourar a pilha. Pense em como resolver esse problema. //FContabilContaPaiVO := TContabilContaVO.Create; end; destructor TContabilContaVO.Destroy; begin FreeAndNil(FPlanoContaVO); FreeAndNil(FPlanoContaRefSpedVO); FreeAndNil(FContabilContaPaiVO); inherited; end; initialization Classes.RegisterClass(TContabilContaVO); finalization Classes.UnRegisterClass(TContabilContaVO); end.
unit uAviao; interface uses Windows, SysUtils, uIAeroNave; type TAviao = Class(TInterfacedObject, IAeroNave) private FNome:String; public function GetNome:string; procedure Decolar; procedure Pousar; property Nome:String read GetNome; constructor Create(); end; implementation {TAviao} constructor TAviao.Create(); begin FNome := self.ClassName; end; function TAviao.GetNome:string; begin result := FNome; end; procedure TAviao.Decolar; begin WriteLn('Ligar turbinas'); WriteLn('Pagar velocidade'); WriteLn('Subir'); end; procedure TAviao.Pousar; begin WriteLn('Diminuir velocidade'); WriteLn('Ligar trem de pouso'); WriteLn('Parar'); end; end.
// Linked list operations demo {$APPTYPE CONSOLE} program List; type PPerson = ^TPerson; TPerson = record Next: PPerson; Name, Surname: string [40]; Born: SmallInt; end; var Head, Node, NewNode: PPerson; ch: Char; begin WriteLn; WriteLn('Linked list operations demo'); WriteLn; New(Node); Node^.Next := nil; Head := Node; // Fill the list repeat Write('Add new record? (Y/N): '); ReadLn(ch); WriteLn; if (ch = 'y') or (ch = 'Y') then begin New(NewNode); Node^.Next := NewNode; Node := NewNode; Node^.Next := nil; Write('Name : '); ReadLn(Node^.Name); Write('Surname : '); ReadLn(Node^.Surname); Write('Born in : '); ReadLn(Node^.Born); WriteLn; end; until (ch = 'n') or (ch = 'N'); WriteLn; WriteLn('Record list: '); WriteLn; // Traverse the list Node := Head^.Next; while Node <> nil do begin WriteLn(Node^.Name, ' ', Node^.Surname, ', b. ', Node^.Born); Node := Node^.Next; end; // Clear the list Node := Head; while Node <> nil do begin NewNode := Node^.Next; Dispose(Node); Node := NewNode; end; WriteLn; WriteLn('Done.'); ReadLn; end.
unit Chapter05._01_Solution1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, AI.ListNode; // 206. Reverse Linked List // https://leetcode.com/problems/reverse-linked-list/description/ // 时间复杂度: O(n) // 空间复杂度: O(1) type TSolution = class(TObject) public function reverseList(var head: TListNode): TListNode; end; implementation { TSolution } function TSolution.reverseList(var head: TListNode): TListNode; var pre, cur, Next: TListNode; begin pre := nil; cur := head; while cur <> nil do begin Next := cur.Next; cur.Next := pre; pre := cur; cur := Next; end; head := pre; Result := pre; end; end.
{------------------------------------------------------------------------- Copyright by Haeger + Busch, Germany / >>>>>>>>> /----- Ingenieurbuero fuer Kommunikationsloesungen / <<<<<<<<< / ----------------------------------------------------/ >>>>>>>>> / Homepage : http://www.hbTapi.com EMail : info@hbTapi.com Package : hbTapi Components Version : 10.2 -------------------------------------------------------------------------} unit hbCommUtils; interface uses classes, windows; procedure EnumSerialPorts (PortList: TStrings); function CommEventToStr(Event: DWORD): String; function CommEventsToStr (Event: DWORD; Separator: String): String; function CommSignalToStr (Signal: DWORD): String; function CommErrorsToStr (Errors: DWORD; Separator: String): String; function StrToParity (Parity: String): Byte; function ParityToStr (Parity: Byte): String; function StrToStopbits (Stopbits: String): Byte; function StopBitsToStr (Stopbits: Byte): String; implementation uses sysutils, hbComm; {*****************************************************************************} procedure AddStr(var S1: String; S2, Separator: String); begin if S1 = '' then S1 := S2 else S1 := S1 + Separator + S2; end; {*****************************************************************************} procedure EnumSerialPorts(PortList: TStrings); var istr: string; isize, i: dword; p : PChar; x : Integer; b : TBits; cc : TCommConfig; ccSize : DWord; begin PortList.Clear; if Win32Platform = VER_PLATFORM_WIN32_NT then begin Setlength(istr, $FFFF); isize := QueryDosDevice(nil, @istr[1], $FFFF); p := @iStr[1]; b := TBits.Create; try b.Size := 256; for i := 1 to isize do begin if istr[i] = #0 then begin if StrPos(p, 'COM') = p then begin inc(p,3); x := StrToIntDef(String(p),0); b[x] := True; end; p := @iStr[i+1]; end; end; for i := 1 to b.size-1 do begin if b[i] then PortList.Add('COM'+IntToStr(i)); end; finally b.Free; end; end else begin for i := 1 to 255 do begin ccSize := sizeof(cc); iStr := 'COM'+IntToStr(i); if GetDefaultCommConfig(PChar(iStr), cc, ccSize) then PortList.Add(iStr); end; end; end; {*****************************************************************************} function CommEventToStr(Event: DWORD): String; begin case Event of EV_RXCHAR : result := 'RXCHAR'; { Any Character received } EV_RXFLAG : result := 'RXFLAG'; { The event character was received } EV_TXEMPTY : result := 'TXEMPTY'; { Transmitt Queue Empty } EV_CTS : result := 'CTS'; { CTS changed state } EV_DSR : result := 'DSR'; { DSR changed state } EV_RLSD : result := 'RLSD'; { RLSD changed state } EV_BREAK : result := 'BREAK'; { BREAK received } EV_ERR : result := 'ERR'; { Line status error occurred } EV_RING : result := 'RING'; { Ring signal detected } EV_PERR : result := 'PERR'; { Printer error occured } EV_RX80FULL : result := 'RX80FULL'; { Receive buffer is 80 percent full } EV_EVENT1 : result := 'EVENT1'; { Provider specific event 1 } EV_EVENT2 : result := 'EVENT2'; { Provider specific event 2 } else result := Format('$%x', [Event]); end; end; {*****************************************************************************} function CommEventsToStr(Event: DWORD; Separator: String): String; begin result := ''; if Event and EV_RXCHAR > 0 then AddStr(result, 'RXCHAR', Separator); { Any Character received } if Event and EV_RXFLAG > 0 then AddStr(result, 'RXFLAG', Separator); { The event character was received } if Event and EV_TXEMPTY > 0 then AddStr(result, 'TXEMPTY', Separator); { Transmitt Queue Empty } if Event and EV_CTS > 0 then AddStr(result, 'CTS', Separator); { CTS changed state } if Event and EV_DSR > 0 then AddStr(result, 'DSR', Separator); { DSR changed state } if Event and EV_RLSD > 0 then AddStr(result, 'RLSD', Separator); { RLSD changed state } if Event and EV_BREAK > 0 then AddStr(result, 'BREAK', Separator); { BREAK received } if Event and EV_ERR > 0 then AddStr(result, 'ERR', Separator); { Line status error occurred } if Event and EV_RING > 0 then AddStr(result, 'RING', Separator); { Ring signal detected } if Event and EV_PERR > 0 then AddStr(result, 'PERR', Separator); { Printer error occured } if Event and EV_RX80FULL > 0 then AddStr(result, 'RX80FULL',Separator); { Receive buffer is 80 percent full } if Event and EV_EVENT1 > 0 then AddStr(result, 'EVENT1', Separator); { Provider specific event 1 } if Event and EV_EVENT2 > 0 then AddStr(result, 'EVENT2', Separator); { Provider specific event 2 } end; {*****************************************************************************} function CommSignalToStr(Signal: DWORD): String; begin case Signal of COMPORTSIGNAL_NONE: result := 'NONE'; COMPORTSIGNAL_DTR : result := 'DTR'; COMPORTSIGNAL_DSR : result := 'DSR'; COMPORTSIGNAL_RTS : result := 'RTS'; COMPORTSIGNAL_CTS : result := 'CTS'; COMPORTSIGNAL_RING: result := 'RING'; COMPORTSIGNAL_DCD : result := 'DCD'; COMPORTSIGNAL_TXD : result := 'TXD'; COMPORTSIGNAL_RXD : result := 'RXD'; else result := Format('$%x', [Signal]); end; end; {*****************************************************************************} function CommErrorsToStr(Errors: DWORD; Separator: String) : String; begin result := ''; if (Errors and CE_RXOVER) > 0 then AddStr(result, 'RXOVER', Separator); if (Errors and CE_OVERRUN) > 0 then AddStr(result, 'OVERRUN', Separator); if (Errors and CE_RXPARITY) > 0 then AddStr(result, 'RXPARITY', Separator); if (Errors and CE_FRAME) > 0 then AddStr(result, 'FRAME', Separator); if (Errors and CE_BREAK) > 0 then AddStr(result, 'BREAK', Separator); if (Errors and CE_TXFULL) > 0 then AddStr(result, 'TXFULLTX', Separator); end; function StrToParity(Parity: String): Byte; begin if (Parity = '') or (CompareText(Parity, 'NONE') = 0) or (CompareText(Parity, 'N') = 0) then result := NOPARITY else if (CompareText(Parity, 'EVEN') = 0) or (CompareText(Parity, 'E') = 0) then result := EVENPARITY else if (CompareText(Parity, 'ODD') = 0) or (CompareText(Parity, 'O') = 0) then result := ODDPARITY else if (CompareText(Parity, 'MARK') = 0) or (CompareText(Parity, 'M') = 0) then result := MARKPARITY else if (CompareText(Parity, 'SPACE') = 0) or (CompareText(Parity, 'S') = 0) then result := SPACEPARITY else result := NOPARITY; end; function ParityToStr(Parity: Byte): String; begin case Parity of EVENPARITY : result := 'E'; ODDPARITY : result := 'O'; MARKPARITY : result := 'M'; SPACEPARITY : result := 'S'; else result := 'N'; // NOPARITY end; end; function StrToStopbits(Stopbits: String): Byte; begin if (CompareText(Stopbits, 'ONE') = 0) or (CompareText(Stopbits, '1') = 0) then result := ONESTOPBIT else if (CompareText(Stopbits, 'TWO') = 0) or (CompareText(Stopbits, '2') = 0) then result := TWOSTOPBITS else if (CompareText(Stopbits, 'ONE5') = 0) or (CompareText(Stopbits, '1.5') = 0) then result := ONE5STOPBITS else result := ONESTOPBIT; end; function StopbitsToStr(Stopbits: Byte): String; begin case Stopbits of ONE5STOPBITS : result := '1.5'; TWOSTOPBITS : result := '2'; else result := '1'; // ONESTOPBIT end; end; end.
unit Abstract2DImageData; interface uses Windows, Graphics, BasicFunctions, BasicDataTypes, AbstractDataSet, dglOpenGL; type TAbstract2DImageData = class protected FData: TAbstractDataSet; FXSize, FYSize: integer; FName: string; // Constructors and Destructors procedure Initialize; virtual; // I/O procedure LoadBitmap(const _Bitmap:TBitmap); // Gets function GetXSize: integer; function GetYSize: integer; function GetMaxX: integer; function GetMaxY: integer; function GetBitmapPixelColor(_Position: longword):longword; virtual; abstract; function GetRPixelColor(_Position: longword):byte; virtual; abstract; function GetGPixelColor(_Position: longword):byte; virtual; abstract; function GetBPixelColor(_Position: longword):byte; virtual; abstract; function GetAPixelColor(_Position: longword):byte; virtual; abstract; function GetRedPixelColor(_x,_y: integer):single; virtual; abstract; function GetGreenPixelColor(_x,_y: integer):single; virtual; abstract; function GetBluePixelColor(_x,_y: integer):single; virtual; abstract; function GetAlphaPixelColor(_x,_y: integer):single; virtual; abstract; function GetName: String; // Sets procedure SetDataLength(_Size: longword); virtual; procedure SetBitmapPixelColor(_Position, _Color: longword); virtual; abstract; procedure SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte); virtual; abstract; procedure SetRedPixelColor(_x,_y: integer; _value:single); virtual; abstract; procedure SetGreenPixelColor(_x,_y: integer; _value:single); virtual; abstract; procedure SetBluePixelColor(_x,_y: integer; _value:single); virtual; abstract; procedure SetAlphaPixelColor(_x,_y: integer; _value:single); virtual; abstract; procedure SetName(const _Name:String); public // constructors and destructors constructor Create(_XSize, _YSize: integer); overload; constructor CreateFromBitmap(const _Bitmap:TBitmap); constructor Create(const _Source: TAbstract2DImageData); overload; constructor CreateFromRGBA(const _Data:Pointer; _Width, _Height: integer); constructor CreateFromGL_RGBA(const _Data:Pointer; _Width, _Height: integer); destructor Destroy; override; procedure Clear; // I/O procedure LoadFromBitmap(const _Bitmap:TBitmap); procedure LoadRGBA(const _Data:Pointer; _Width, _Height: integer); procedure LoadGL_RGBA(const _Data:Pointer; _Width, _Height: integer); function SaveToBitmap:TBitmap; function SaveToRGBA:AUInt32; function SaveToGL_RGBA:AUInt32; // Gets function isPixelValid(_x, _y: integer):boolean; function GetOpenGLFormat:TGLInt; virtual; // Copies procedure Assign(const _Source: TAbstract2DImageData); virtual; // Misc procedure ScaleBy(_Value: single); virtual; abstract; procedure Invert; virtual; abstract; // properties property XSize:integer read GetXSize; property YSize:integer read GetYSize; property MaxX:integer read GetMaxX; property MaxY:integer read GetMaxY; property Name:String read GetName write SetName; property Red[_x,_y: integer]:single read GetRedPixelColor write SetRedPixelColor; property Green[_x,_y: integer]:single read GetGreenPixelColor write SetGreenPixelColor; property Blue[_x,_y: integer]:single read GetBluePixelColor write SetBluePixelColor; property Alpha[_x,_y: integer]:single read GetAlphaPixelColor write SetAlphaPixelColor; end; implementation constructor TAbstract2DImageData.Create(_XSize: Integer; _YSize: Integer); begin Initialize; FXSize := _XSize; FYSize := _YSize; SetDataLength(FXSize*FYSize); end; constructor TAbstract2DImageData.CreateFromBitmap(const _Bitmap: TBitmap); begin Initialize; LoadBitmap(_Bitmap); end; constructor TAbstract2DImageData.Create(const _Source: TAbstract2DImageData); begin Initialize; Assign(_Source); end; constructor TAbstract2DImageData.CreateFromRGBA(const _Data:Pointer; _Width, _Height: integer); begin Initialize; LoadRGBA(_Data,_Width,_Height); end; constructor TAbstract2DImageData.CreateFromGL_RGBA(const _Data:Pointer; _Width, _Height: integer); begin Initialize; LoadGL_RGBA(_Data,_Width,_Height); end; destructor TAbstract2DImageData.Destroy; begin FData.Free; inherited Destroy; end; procedure TAbstract2DImageData.Clear; begin SetDataLength(0); FXSize := 0; FYSize := 0; end; procedure TAbstract2DImageData.Initialize; begin FData := TAbstractDataSet.Create; end; // I/O procedure TAbstract2DImageData.LoadFromBitmap(const _Bitmap:TBitmap); begin Clear; LoadBitmap(_Bitmap); end; procedure TAbstract2DImageData.LoadBitmap(const _Bitmap:TBitmap); var x, y: integer; Value,Position: Longword; Line: Pointer; begin if (_Bitmap <> nil) then begin FXSize := _Bitmap.Width; FYSize := _Bitmap.Height; SetDataLength(FXSize*FYSize); _Bitmap.PixelFormat := pf32bit; for y := 0 to FYSize - 1 do begin Line := _Bitmap.ScanLine[y]; Position := (y * FXSize); for x := 0 to FXSize - 1 do begin Value := Longword(Line^); SetBitmapPixelColor(Position,Value); Line := Pointer(longword(Line) + 4); inc(Position); end; end; end else begin FXSize := 0; FYSize := 0; SetDataLength(0); end; end; procedure TAbstract2DImageData.LoadRGBA(const _Data:Pointer; _Width, _Height: integer); var x, DataLength, Position: integer; Data,GData,BData,AData: PByte; begin if Assigned(_Data) then begin FXSize := _Width; FYSize := _Height; DataLength := FXSize*FYSize; SetDataLength(DataLength); Position := 0; Data := _Data; for x := 1 to DataLength do begin GData := PByte(Cardinal(Data) + 1); BData := PByte(Cardinal(Data) + 2); AData := PByte(Cardinal(Data) + 3); SetRGBAPixelColor(Position,Data^,GData^,BData^,AData^); inc(Position); Data := PByte(Cardinal(Data) + 4); end; end else begin FXSize := 0; FYSize := 0; SetDataLength(0); end; end; // Same as the previous function, except that it swaps Y. procedure TAbstract2DImageData.LoadGL_RGBA(const _Data:Pointer; _Width, _Height: integer); var x, y, Position: integer; Data,GData,BData,AData: PByte; begin if Assigned(_Data) then begin FXSize := _Width; FYSize := _Height; SetDataLength(FXSize*FYSize); Data := _Data; for y := FYSize - 1 downto 0 do begin Position := (y * FXSize); for x := 0 to FXSize - 1 do begin GData := PByte(Cardinal(Data) + 1); BData := PByte(Cardinal(Data) + 2); AData := PByte(Cardinal(Data) + 3); SetRGBAPixelColor(Position,Data^,GData^,BData^,AData^); inc(Position); Data := PByte(Cardinal(Data) + 4); end; end; end else begin FXSize := 0; FYSize := 0; SetDataLength(0); end; end; function TAbstract2DImageData.SaveToBitmap:TBitmap; var x, y: integer; Position: Longword; Line: ^Longword; begin Result := TBitmap.Create; Result.Width := FXSize; Result.Height := FYSize; Result.PixelFormat := pf32bit; for y := 0 to FYSize - 1 do begin Line := Result.ScanLine[y]; Position := (y * FXSize); for x := 0 to FXSize - 1 do begin Line^ := GetBitmapPixelColor(Position); inc(Line); inc(Position); end; end; end; function TAbstract2DImageData.SaveToRGBA:AUInt32; var DataLength, x : Integer; begin DataLength := FXSize*FYSize; SetLength(Result,DataLength); for x := 0 to High(Result) do begin Result[x] := GetRPixelColor(x) + (GetGPixelColor(x) shl 8) + (GetBPixelColor(x) shl 16) + (GetAPixelColor(x) shl 24); end; end; function TAbstract2DImageData.SaveToGL_RGBA:AUInt32; var DataLength, x,y,yRes, PositionImg,PositionRes : Integer; begin DataLength := FXSize*FYSize; SetLength(Result,DataLength); yRes := 0; for y := (FYSize - 1) downto 0 do begin PositionImg := y * FXSize; PositionRes := yRes * FXSize; for x := 0 to FXSize - 1 do begin Result[PositionRes] := GetRPixelColor(PositionImg) + (GetGPixelColor(PositionImg) shl 8) + (GetBPixelColor(PositionImg) shl 16) + (GetAPixelColor(PositionImg) shl 24); inc(PositionImg); inc(PositionRes); end; inc(yRes); end; end; // Gets function TAbstract2DImageData.GetXSize: integer; begin Result := FXSize; end; function TAbstract2DImageData.GetYSize: integer; begin Result := FYSize; end; function TAbstract2DImageData.GetMaxX: integer; begin Result := FXSize - 1; end; function TAbstract2DImageData.GetMaxY: integer; begin Result := FYSize - 1; end; function TAbstract2DImageData.GetName: String; begin Result := FName; end; function TAbstract2DImageData.GetOpenGLFormat:TGLInt; begin Result := GL_RGBA; end; function TAbstract2DImageData.isPixelValid(_x, _y: integer):boolean; begin if (_x >= 0) and (_y >= 0) and (_x < FXSize) and (_y < FYSize) then begin Result := true; end else begin Result := false; end; end; // Sets procedure TAbstract2DImageData.SetName(const _Name:String); begin FName := CopyString(_Name); end; procedure TAbstract2DImageData.SetDataLength(_Size: Cardinal); begin FData.Length := _Size; end; // Copies procedure TAbstract2DImageData.Assign(const _Source: TAbstract2DImageData); begin Clear; FXSize := _Source.GetXSize; FYSize := _Source.GetYSize; FName := CopyString(_Source.FName); FData.Assign(_Source.FData); end; end.
unit UnitFileRenamerForm; interface uses Windows, Messages, SysUtils, Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.Grids, Vcl.ValEdit, Vcl.StdCtrls, Vcl.Menus, Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnPopup, Vcl.Samples.Spin, Data.DB, Dmitry.Utils.Files, Dmitry.Controls.Base, Dmitry.Controls.WebLink, UnitDBDeclare, uConstants, uMemory, uDBForm, uStringUtils, uProgramStatInfo, uShellIntegration, uDBBaseTypes, uDBUtils, uDBManager, uSettings, uCollectionEvents; type TFormFastFileRenamer = class(TDBForm) ValueListEditor1: TValueListEditor; Panel1: TPanel; Panel2: TPanel; LblTitle: TLabel; pmSort: TPopupActionBar; SortbyFileName1: TMenuItem; SortbyFileSize1: TMenuItem; BtnHelp: TButton; Panel3: TPanel; BtnOK: TButton; BtnCancel: TButton; CheckBox1: TCheckBox; Label2: TLabel; CmMaskList: TComboBox; BtAdd: TButton; BtDelete: TButton; SortbyFileNumber1: TMenuItem; SortbyModified1: TMenuItem; SortbyFileType1: TMenuItem; WebLinkWarning: TWebLink; SedStartN: TSpinEdit; procedure FormCreate(Sender: TObject); procedure BtnCancelClick(Sender: TObject); procedure Edit1Change(Sender: TObject); procedure BtnOKClick(Sender: TObject); procedure BtnHelpClick(Sender: TObject); procedure SortbyFileName1Click(Sender: TObject); procedure SortbyFileSize1Click(Sender: TObject); procedure SortbyFileNumber1Click(Sender: TObject); procedure SortbyFileType1Click(Sender: TObject); procedure SortbyModified1Click(Sender: TObject); procedure BtAddClick(Sender: TObject); procedure BtDeleteClick(Sender: TObject); procedure WebLinkWarningClick(Sender: TObject); procedure KernelEventCallBack(ID: Integer; Params: TEventFields; Value: TEventValues); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } protected function GetFormID : string; override; procedure SaveSettings; public { Public declarations } FFiles: TStrings; FIDS: TArInteger; procedure SetFiles(Files: TStrings; IDS: TArInteger); procedure SetFilesA; procedure LoadLanguage; procedure DoCalculateRename; procedure DoRename; function CheckConflictFileNames: Boolean; end; procedure FastRenameManyFiles(Files : TStrings; IDS : TArInteger); implementation {$R *.dfm} procedure FastRenameManyFiles(Files : TStrings; IDS : TArInteger); var FormFastFileRenamer: TFormFastFileRenamer; begin Application.CreateForm(TFormFastFileRenamer, FormFastFileRenamer); try FormFastFileRenamer.SetFiles(Files, IDS); FormFastFileRenamer.ShowModal; finally FormFastFileRenamer.Release; end; end; { TFormFastFileRenamer } procedure TFormFastFileRenamer.SaveSettings; var I: Integer; begin AppSettings.DeleteValues('Renamer'); for I := 0 to CmMaskList.Items.Count - 1 do AppSettings.WriteString('Renamer', 'val' + IntToStr(I + 1), CmMaskList.Items[I]); AppSettings.WriteString('Options', 'RenameText', CmMaskList.Text); end; procedure TFormFastFileRenamer.SetFiles(Files: TStrings; IDS: TArInteger); begin FFiles := Files; FIDS := IDS; SetFilesA; end; procedure TFormFastFileRenamer.FormClose(Sender: TObject; var Action: TCloseAction); begin SaveSettings; end; procedure TFormFastFileRenamer.FormCreate(Sender: TObject); var List: TStrings; I: Integer; begin LoadLanguage; List := AppSettings.ReadValues('Renamer'); try CmMaskList.Items.Clear; for I := 0 to List.Count - 1 do CmMaskList.Items.Add(AppSettings.ReadString('Renamer', List[I])); CmMaskList.Text := AppSettings.ReadString('Options', 'RenameText'); finally F(List); end; if CmMaskList.Text = '' then CmMaskList.Text := L('Image #%3d [%date]'); WebLinkWarning.Visible := False; ValueListEditor1.ColWidths[0] := ValueListEditor1.Width div 2; end; procedure TFormFastFileRenamer.LoadLanguage; begin BeginTranslate; try Caption := L('File renamer'); ValueListEditor1.TitleCaptions[0] := L('Original file name'); ValueListEditor1.TitleCaptions[1] := L('New file name'); BtnCancel.Caption := L('Cancel'); BtnOk.Caption := L('Ok'); LblTitle.Caption := L('Mask for files'); SortbyFileName1.Caption := L('Sort by file name'); SortbyFileSize1.Caption := L('Sort by file size'); SortbyFileNumber1.Caption := L('Sort by file number'); SortbyModified1.Caption := L('Sort by modified date'); SortbyFileType1.Caption := L('Sort by file type'); CheckBox1.Caption := L('Change extension'); Label2.Caption := L('From number'); BtAdd.Caption := L('Add'); BtDelete.Caption := L('Delete'); WebLinkWarning.Text := L('Conflict in file names!'); finally EndTranslate; end; end; procedure TFormFastFileRenamer.DoCalculateRename; var I, N: Integer; S: string; begin for I := 1 to ValueListEditor1.Strings.Count do begin N := SedStartN.Value - 1 + I; S := CmMaskList.Text; S := StringReplace(S, '%fn', GetFileNameWithoutExt(ExtractFileName(ValueListEditor1.Cells[0, I])), [RfReplaceAll, RfIgnoreCase]); S := StringReplace(S, '%date', DateToStr(Now), [RfReplaceAll, RfIgnoreCase]); S := StringReplace(S, '%d', Format('%d', [N]), [RfReplaceAll, RfIgnoreCase]); S := StringReplace(S, '%1d', Format('%.1d', [N]), [RfReplaceAll, RfIgnoreCase]); S := StringReplace(S, '%2d', Format('%.2d', [N]), [RfReplaceAll, RfIgnoreCase]); S := StringReplace(S, '%3d', Format('%.3d', [N]), [RfReplaceAll, RfIgnoreCase]); S := StringReplace(S, '%4d', Format('%.4d', [N]), [RfReplaceAll, RfIgnoreCase]); S := StringReplace(S, '%5d', Format('%.5d', [N]), [RfReplaceAll, RfIgnoreCase]); S := StringReplace(S, '%6d', Format('%.6d', [N]), [RfReplaceAll, RfIgnoreCase]); S := StringReplace(S, '%h', IntToHex(N, 0), [RfReplaceAll, RfIgnoreCase]); S := StringReplace(S, '%1h', IntToHex(N, 1), [RfReplaceAll, RfIgnoreCase]); S := StringReplace(S, '%2h', IntToHex(N, 2), [RfReplaceAll, RfIgnoreCase]); S := StringReplace(S, '%3h', IntToHex(N, 3), [RfReplaceAll, RfIgnoreCase]); S := StringReplace(S, '%4h', IntToHex(N, 4), [RfReplaceAll, RfIgnoreCase]); S := StringReplace(S, '%5h', IntToHex(N, 5), [RfReplaceAll, RfIgnoreCase]); S := StringReplace(S, '%6h', IntToHex(N, 6), [RfReplaceAll, RfIgnoreCase]); if not CheckBox1.Checked then begin if GetExt(ValueListEditor1.Cells[0, I]) <> '' then S := S + '.' + AnsiLowerCase(GetExt(ValueListEditor1.Cells[0, I])); end; ValueListEditor1.Cells[1, I] := S; end; end; procedure TFormFastFileRenamer.BtnCancelClick(Sender: TObject); begin Close; end; procedure TFormFastFileRenamer.Edit1Change(Sender: TObject); begin DoCalculateRename; WebLinkWarning.Visible := False; end; procedure TFormFastFileRenamer.DoRename; var I: Integer; OldFile, NewFile: string; begin for I := 1 to ValueListEditor1.Strings.Count do try OldFile := ExtractFilePath(FFiles[I - 1]) + ValueListEditor1.Cells[0, I]; NewFile := ExtractFilePath(FFiles[I - 1]) + ValueListEditor1.Cells[1, I]; RenamefileWithDB(DBManager.DBContext, KernelEventCallBack, OldFile, NewFile, FIDS[I - 1], False); except on E: Exception do MessageBoxDB(Handle, Format(L('An error occurred while renaming file "%s" to "%s"! Error message: %s'), [OldFile, NewFile, E.message]), L('Error'), TD_BUTTON_OK, TD_ICON_ERROR); end; end; procedure TFormFastFileRenamer.BtnOKClick(Sender: TObject); begin ProgramStatistics.MassRenameUsed; if CheckConflictFileNames then begin WebLinkWarning.Visible := True; MessageBoxDB(Handle, L('Conflict in file names!'), L('Error'), TD_BUTTON_OK, TD_ICON_ERROR); Exit; end; DoRename; Close; end; procedure TFormFastFileRenamer.BtnHelpClick(Sender: TObject); var Info : string; begin info := L('File mask: replace %d to number, %date - current date, %fn - original file name (without extension)'); MessageBoxDB(Handle, info, L('Info'), TD_BUTTON_OK, TD_ICON_INFORMATION); end; procedure TFormFastFileRenamer.SortbyFileName1Click(Sender: TObject); var I, K: Integer; B: Boolean; S: string; begin repeat B := False; for I := 1 to ValueListEditor1.Strings.Count - 1 do begin if AnsiCompareStr(FFiles[I - 1], FFiles[I]) > 0 then begin S := FFiles[I - 1]; FFiles[I - 1] := FFiles[I]; FFiles[I] := S; K := FIDS[I - 1]; FIDS[I - 1] := FIDS[I]; FIDS[I] := K; B := True; end; end; until not B; SetFilesA; end; procedure TFormFastFileRenamer.SetFilesA; var I: Integer; begin ValueListEditor1.Strings.Clear; for I := 1 to FFiles.Count do begin ValueListEditor1.Strings.Add(ExtractFileName(FFiles[I - 1])); ValueListEditor1.Keys[I] := ExtractFileName(FFiles[I - 1]); end; DoCalculateRename; end; procedure TFormFastFileRenamer.SortbyFileSize1Click(Sender: TObject); var I, K: Integer; B: Boolean; S: string; X: array of Integer; begin Setlength(X, ValueListEditor1.Strings.Count); for I := 1 to ValueListEditor1.Strings.Count - 1 do X[I - 1] := GetFileSizeByName(FFiles[I - 1]); repeat B := False; for I := 1 to ValueListEditor1.Strings.Count - 1 do begin if X[I - 1] < X[I] then begin S := FFiles[I - 1]; FFiles[I - 1] := FFiles[I]; FFiles[I] := S; K := X[I - 1]; X[I - 1] := X[I]; X[I] := K; K := FIDs[I - 1]; FIDs[I - 1] := FIDs[I]; FIDs[I] := K; B := True; end; end; until not B; SetFilesA; end; procedure TFormFastFileRenamer.SortbyFileNumber1Click(Sender: TObject); var I, K: Integer; B: Boolean; S: string; begin repeat B := False; for I := 1 to ValueListEditor1.Strings.Count - 1 do begin if AnsiCompareTextWithNum(FFiles[I - 1], FFiles[I]) > 0 then begin S := FFiles[I - 1]; FFiles[I - 1] := FFiles[I]; FFiles[I] := S; K := FIDS[I - 1]; FIDS[I - 1] := FIDS[I]; FIDS[I] := K; B := True; end; end; until not B; SetFilesA; end; procedure TFormFastFileRenamer.SortbyFileType1Click(Sender: TObject); var I, K: Integer; B: Boolean; S: string; begin repeat B := False; for I := 1 to ValueListEditor1.Strings.Count - 1 do begin if AnsiCompareStr(GetExt(FFiles[I - 1]), GetExt(FFiles[I])) > 0 then begin S := FFiles[I - 1]; FFiles[I - 1] := FFiles[I]; FFiles[I] := S; K := FIDS[I - 1]; FIDS[I - 1] := FIDS[I]; FIDS[I] := K; B := True; end; end; until not B; SetFilesA; end; procedure TFormFastFileRenamer.SortbyModified1Click(Sender: TObject); var I, N: Integer; K: TDateTime; B: Boolean; S: string; X: array of TDateTime; begin Setlength(X, ValueListEditor1.Strings.Count); for I := 1 to ValueListEditor1.Strings.Count - 1 do X[I - 1] := DateModify(FFiles[I - 1]); repeat B := False; for I := 1 to ValueListEditor1.Strings.Count - 1 do begin if X[I - 1] < X[I] then begin S := FFiles[I - 1]; FFiles[I - 1] := FFiles[I]; FFiles[I] := S; K := X[I - 1]; X[I - 1] := X[I]; X[I] := K; N := FIDs[I - 1]; FIDs[I - 1] := FIDs[I]; FIDs[I] := N; B := True; end; end; until not B; SetFilesA; end; procedure TFormFastFileRenamer.BtAddClick(Sender: TObject); var I: Integer; begin for I := 0 to CmMaskList.Items.Count - 1 do if AnsiLowerCase(CmMaskList.Items[I]) = AnsiLowerCase(CmMaskList.Text) then Exit; CmMaskList.Items.Add(CmMaskList.Text) end; procedure TFormFastFileRenamer.BtDeleteClick(Sender: TObject); var I: Integer; begin for I := 0 to CmMaskList.Items.Count - 1 do if AnsiLowerCase(CmMaskList.Items[I]) = AnsiLowerCase(CmMaskList.Text) then begin CmMaskList.Items.Delete(I); Exit; end; end; procedure TFormFastFileRenamer.WebLinkWarningClick(Sender: TObject); begin if CheckConflictFileNames then begin MessageBoxDB(Handle, L('Conflict in file names!'), L('Error'), TD_BUTTON_OK, TD_ICON_ERROR); Exit; end; WebLinkWarning.Visible := False; end; function TFormFastFileRenamer.GetFormID: string; begin Result := 'FileRenamer'; end; procedure TFormFastFileRenamer.KernelEventCallBack(ID: Integer; Params: TEventFields; Value: TEventValues); begin CollectionEvents.DoIDEvent(Self, ID, Params, Value); end; function TFormFastFileRenamer.CheckConflictFileNames: boolean; var I, J: Integer; Dir: string; OldFiles: TArStrings; OldDirFiles: TArStrings; NewFiles: TArStrings; begin Result := False; Dir := ExtractFilePath(FFiles[0]); OldDirFiles := TArStrings(GetDirListing(Dir, '||')); SetLength(OldFiles, ValueListEditor1.Strings.Count); for I := 1 to ValueListEditor1.Strings.Count do OldFiles[I - 1] := ExtractFilePath(FFiles[I - 1]) + ValueListEditor1.Cells[0, I]; SetLength(NewFiles, ValueListEditor1.Strings.Count); for I := 1 to ValueListEditor1.Strings.Count do NewFiles[I - 1] := ExtractFilePath(FFiles[I - 1]) + ValueListEditor1.Cells[1, I]; for I := 0 to Length(OldFiles) - 1 do for J := 0 to Length(NewFiles) - 1 do if AnsiLowerCase(OldFiles[I]) = AnsiLowerCase(NewFiles[J]) then begin Result := True; Break; end; for I := 0 to Length(OldDirFiles) - 1 do for J := 0 to Length(NewFiles) - 1 do if AnsiLowerCase(OldDirFiles[I]) = AnsiLowerCase(NewFiles[J]) then begin Result := True; Break; end; for I := 0 to Length(NewFiles) - 1 do for J := I + 1 to Length(NewFiles) - 1 do if AnsiLowerCase(NewFiles[I]) = AnsiLowerCase(NewFiles[J]) then begin Result := True; Break; end; end; end.
unit ThItemHistory; interface uses System.Generics.Collections, FMX.Types, ThItem; type TThItemHistoryData = record Parent: TFmxObject; Index: Integer; Children: TThItems; end; TThItemHistory = class(TList<TThItemHistoryData>) private FStackIndex: Integer; function GetBeforeIndex: Integer; function GetBeforeParent: TFmxObject; public constructor Crate; destructor Destroy; override; procedure Push(AParent: TFmxObject; AIndex: Integer; AChildren: TThItems); procedure Undo; procedure Redo; property BeforeParent: TFmxObject read GetBeforeParent; property BeforeIndex: Integer read GetBeforeIndex; end; implementation { TThItemHistory } constructor TThItemHistory.Crate; begin inherited; FStackIndex := -1; end; destructor TThItemHistory.Destroy; var Data: TThItemHistoryData; begin for Data in List do begin if Assigned(Data.Children) then Data.Children.Free; end; inherited; end; function TThItemHistory.GetBeforeIndex: Integer; begin Result := -1; if (FStackIndex > -1) and (Count > FStackIndex) then Result := List[FStackIndex].Index; end; function TThItemHistory.GetBeforeParent: TFmxObject; begin Result := nil; if (FStackIndex > -1) and (Count > FStackIndex) then Result := List[FStackIndex].Parent; end; procedure TThItemHistory.Push(AParent: TFmxObject; AIndex: Integer; AChildren: TThItems); var Data: TThItemHistoryData; begin Data.Parent := AParent; Data.Index := AIndex; if Assigned(AChildren) then Data.Children := TThItems.Create(AChildren); Add(Data); end; procedure TThItemHistory.Undo; begin end; procedure TThItemHistory.Redo; begin end; end.
unit Lib.JSONFormat; interface uses System.SysUtils, System.JSON; function ToJSON(jsValue: TJSONValue; ValuesJSONFormat: Boolean): string; implementation function JSONIsSimpleValue(jsValue: TJSONValue): Boolean; begin Result:=jsValue is TJSONNumber; end; function JSONIsSimpleArray(jsArray: TJSONArray): Boolean; var jsItem: TJSONValue; begin Result:=True; for jsItem in jsArray do if not JSONIsSimpleValue(jsItem) then Exit(False); end; function JSONToString(jsValue: TJSONValue; ValuesJSONFormat: Boolean): string; begin if ValuesJSONFormat then Result:=jsValue.ToJSON else Result:=jsValue.ToString; end; const CRLF=#13#10; CRLF2=CRLF+CRLF; INDENT=' '; function JSONFormatValue(jsValue: TJSONValue; const IndentValue: string; ValuesJSONFormat: Boolean): string; var jsPair: TJSONPair; jsItem: TJSONValue; begin if jsValue is TJSONObject then begin Result:=''; for jsPair in TJSONObject(jsValue) do Result:=Result+IndentValue+INDENT+JSONToString(jsPair.JsonString,ValuesJSONFormat)+': '+ JSONFormatValue(jsPair.JsonValue,IndentValue+INDENT,ValuesJSONFormat)+','+CRLF; Result:=Result.Remove(Result.Length-CRLF.Length-1); if Result.Length>0 then Result:=CRLF+Result+CRLF+IndentValue; Result:='{'+Result+'}'; end else if jsValue is TJSONArray then begin Result:=''; if JSONIsSimpleArray(TJSONArray(jsValue)) then begin for jsItem in TJSONArray(jsValue) do Result:=Result+JSONToString(jsItem,ValuesJSONFormat)+','; Result:='['+Result.Remove(Result.Length-1)+']'; end else begin for jsItem in TJSONArray(jsValue) do Result:=Result+IndentValue+INDENT+ JSONFormatValue(jsItem,IndentValue+INDENT,ValuesJSONFormat)+','+CRLF; Result:=Result.Remove(Result.Length-CRLF.Length-1); if Result.Length>0 then Result:=CRLF+Result+CRLF; Result:='['+Result+IndentValue+']'; end; end else Result:=JSONToString(jsValue,ValuesJSONFormat); end; function ToJSON(jsValue: TJSONValue; ValuesJSONFormat: Boolean): string; begin Result:=JSONFormatValue(jsValue,'',ValuesJSONFormat); end; end.
unit DPM.IDE.ToolsAPI; interface uses ToolsApi, System.Classes, Vcl.Forms; type TToolsApiUtils = class class procedure RegisterFormClassForTheming(const AFormClass : TCustomFormClass; const Component : TComponent = nil);static; class function FindProjectInGroup(const projectGroup : IOTAProjectGroup; const projectName : string) : IOTAProject; end; implementation uses System.SysUtils; { TToolsApiUtils } {$IF CompilerVersion >= 24.0} //XE3 {$LEGACYIFEND ON} {$IFEND} class function TToolsApiUtils.FindProjectInGroup(const projectGroup: IOTAProjectGroup; const projectName: string): IOTAProject; {$IF CompilerVersion < 24.0} //XE3 var i : integer; {$IFEND} begin result := nil; if projectGroup = nil then exit; {$IF CompilerVersion < 24.0} //XE3 for i := 0 to projectGroup.ProjectCount -1 do begin if SameText(projectGroup.Projects[i].FileName, projectName) then exit(projectGroup.Projects[i]); end; {$ELSE} result := projectGroup.FindProject(projectName); {$IFEND} end; class procedure TToolsApiUtils.RegisterFormClassForTheming(const AFormClass: TCustomFormClass; const Component: TComponent); {$IF CompilerVersion >= 32.0} //10.2 Var {$IF CompilerVersion = 34.0} //10.4 // Breaking change to the Open Tools API - They fixed the wrongly defined interface ITS : IOTAIDEThemingServices; {$ELSE} ITS : IOTAIDEThemingServices250; {$IFEND} {$IFEND} Begin {$IF CompilerVersion >= 32.0} //10.2 {$IF CompilerVersion = 34.0} //10.4 If Supports(BorlandIDEServices, IOTAIDEThemingServices, ITS) Then {$ELSE} If Supports(BorlandIDEServices, IOTAIDEThemingServices250, ITS) Then {$IFEND} If ITS.IDEThemingEnabled Then Begin ITS.RegisterFormClass(AFormClass); If Assigned(Component) Then ITS.ApplyTheme(Component); End; {$IFEND} end; end.
{ *************************************************************************** Copyright (c) 2016-2022 Kike Pérez Unit : Quick.Logger.Provider.Memory Description : Log memory Provider Author : Kike Pérez Version : 1.23 Created : 02/10/2017 Modified : 10/02/2022 This file is part of QuickLogger: https://github.com/exilon/QuickLogger *************************************************************************** Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************** } unit Quick.Logger.Provider.Memory; interface {$i QuickLib.inc} uses Classes, {$IFDEF MSWINDOWS} Windows, {$IFDEF DELPHIXE8_UP} Quick.Json.Serializer, {$ENDIF} {$ENDIF} {$IFDEF DELPHILINUX} Quick.SyncObjs.Linux.Compatibility, {$ENDIF} SysUtils, Generics.Collections, Quick.Commons, Quick.Logger; type TMemLog = TObjectList<TLogItem>; TLogMemoryProvider = class (TLogProviderBase) private fMemLog : TMemLog; fMaxSize : Int64; public constructor Create; override; destructor Destroy; override; {$IFDEF DELPHIXE8_UP}[TNotSerializableProperty]{$ENDIF} property MemLog : TMemLog read fMemLog write fMemLog; property MaxSize : Int64 read fMaxSize write fMaxSize; procedure Init; override; procedure Restart; override; procedure WriteLog(cLogItem : TLogItem); override; function AsStrings : TStrings; function AsString : string; procedure Clear; end; var GlobalLogMemoryProvider : TLogMemoryProvider; implementation var CS : TRTLCriticalSection; constructor TLogMemoryProvider.Create; begin inherited; LogLevel := LOG_ALL; fMaxSize := 0; end; destructor TLogMemoryProvider.Destroy; begin EnterCriticalSection(CS); try if Assigned(fMemLog) then fMemLog.Free; finally LeaveCriticalSection(CS); end; inherited; end; procedure TLogMemoryProvider.Init; begin fMemLog := TMemLog.Create(True); inherited; end; procedure TLogMemoryProvider.Restart; begin Stop; EnterCriticalSection(CS); try if Assigned(fMemLog) then fMemLog.Free; finally LeaveCriticalSection(CS); end; Init; end; procedure TLogMemoryProvider.WriteLog(cLogItem : TLogItem); begin EnterCriticalSection(CS); try if fMaxSize > 0 then begin while fMemLog.Count >= fMaxSize do fMemLog.Delete(0); end; fMemLog.Add(cLogItem.Clone); finally LeaveCriticalSection(CS); end; end; function TLogMemoryProvider.AsStrings : TStrings; var lItem : TLogItem; begin Result := TStringList.Create; if not Assigned(fMemLog) then Exit; EnterCriticalSection(CS); try for lItem in fMemLog do Result.Add(LogItemToLine(lItem,True,True)); finally LeaveCriticalSection(CS); end; end; function TLogMemoryProvider.AsString : string; var sl : TStrings; begin sl := AsStrings; try Result := sl.Text; finally sl.Free; end; end; procedure TLogMemoryProvider.Clear; begin EnterCriticalSection(CS); try fMemLog.Clear; finally LeaveCriticalSection(CS); end; end; initialization {$IF Defined(MSWINDOWS) OR Defined(DELPHILINUX)} InitializeCriticalSection(CS); {$ELSE} InitCriticalSection(CS); {$ENDIF} GlobalLogMemoryProvider := TLogMemoryProvider.Create; finalization if Assigned(GlobalLogMemoryProvider) and (GlobalLogMemoryProvider.RefCount = 0) then GlobalLogMemoryProvider.Free; {$IF Defined(MSWINDOWS) OR Defined(DELPHILINUX)} DeleteCriticalSection(CS); {$ELSE} DoneCriticalsection(CS); {$ENDIF} end.
unit uXMLlkjFileReader; interface uses Classes,xmldom, XMLIntf, msxmldom,XMLDoc,SysUtils,Math, Variants,DateUtils, uLKJRuntimeFile, uVSConst,uConvertDefine,uRtFileReaderBase; type ////////////////////////////////////////////////////////////////////////////// ///LKJRuntimeFile的XML读写类 ////////////////////////////////////////////////////////////////////////////// TLKJRuntimeXMLReader = class(TRunTimeFileReaderBase) public constructor Create(); destructor Destroy;override; private m_FieldConvert : TFieldConvert; public procedure ReadHead(FileName : string;var HeadInfo: RLKJRTFileHeadInfo);override; procedure LoadFromFile(FileName : string;RuntimeFile : TLKJRuntimeFile);override; procedure LoadFromFiles(FileList : TStrings;RuntimeFile : TLKJRuntimeFile);override; procedure SaveToFile(FileName : string;RuntimeFile : TLKJRuntimeFile); end; implementation { TLKJRuntimeXMLReader } constructor TLKJRuntimeXMLReader.Create; begin inherited Create; m_FieldConvert := TFieldConvert.Create; end; destructor TLKJRuntimeXMLReader.Destroy; begin m_FieldConvert.Free; inherited; end; procedure TLKJRuntimeXMLReader.LoadFromFile(FileName: string; RuntimeFile: TLKJRuntimeFile); var i: Integer; LKJCommonRec: TLKJCommonRec; node,SubNode: IXMLNode; XmlDoc: IXMLDocument; begin XmlDoc := NewXMLDocument(); try XmlDoc.LoadFromFile(FileName); node := XmlDoc.DocumentElement; ReadHead(FileName,RuntimeFile.HeadInfo); for I := 0 to Node.ChildNodes.Count - 1 do begin LKJCommonRec:= TLKJCommonRec.Create; SubNode := Node.ChildNodes.Nodes[i]; with LKJCommonRec.CommonRec do begin nRow := SubNode.Attributes['Rec']; strDisp := SubNode.Attributes['Disp']; nEvent:= SubNode.Attributes['nEvent']; DTEvent:= StrToDateTime(SubNode.Attributes['Hms']); nCoord:= m_FieldConvert.GetnCoord(SubNode.Attributes['Glb']); nDistance:= SubNode.Attributes['Jl']; strXhj := SubNode.Attributes['Xhj']; strSignal := SubNode.Attributes['Signal']; LampSign:= SubNode.Attributes['Xh_code']; nLampNo:= SubNode.Attributes['Xhj_no']; SignType:= SubNode.Attributes['Xht_code']; nSpeed:= SubNode.Attributes['Speed']; nLimitSpeed:= SubNode.Attributes['S_lmt']; WorkZero:= m_FieldConvert.ConvertWorkZero(SubNode.Attributes['Shoub']); HandPos:= m_FieldConvert.ConvertHandPos(SubNode.Attributes['Shoub']); WorkDrag:= m_FieldConvert.ConvertWorkDrag(SubNode.Attributes['Shoub']); nShoub := SubNode.Attributes['Shoub']; strGK := SubNode.Attributes['Hand']; nLieGuanPressure:= SubNode.Attributes['Gya']; nGangPressure:= SubNode.Attributes['Gangy']; nRotate:= SubNode.Attributes['Rota']; nJG1Pressure:= SubNode.Attributes['Jg1']; nJG2Pressure:= SubNode.Attributes['Jg2']; strOther:= SubNode.Attributes['OTHER']; ShuoMing := SubNode.Attributes['Shuoming']; JKZT := SubNode.Attributes['JKZT']; nValidJG := SubNode.Attributes['ValidJG']; end; RuntimeFile.Records.Add(LKJCommonRec); end; finally XmlDoc := nil; end; end; procedure TLKJRuntimeXMLReader.LoadFromFiles(FileList: TStrings; RuntimeFile: TLKJRuntimeFile); begin ; end; procedure TLKJRuntimeXMLReader.ReadHead(FileName: string; var HeadInfo: RLKJRTFileHeadInfo); var XmlDoc: IXMLDocument; node,subNode: IXMLNode; i: Integer; begin FillChar(HeadInfo,SizeOf(HeadInfo),0); XmlDoc := NewXMLDocument(); try XmlDoc.LoadFromFile(FileName); node := XmlDoc.DocumentElement; for I := 0 to Node.ChildNodes.Count - 1 do begin subNode := Node.ChildNodes[i]; if i > 40 then Break; case subNode.Attributes['nEvent'] of File_Headinfo_dtBegin : begin HeadInfo.DTFileHeadDt := StrToDateTime(subNode.Attributes['Hms']); end; File_Headinfo_Factory : begin HeadInfo.Factory := m_FieldConvert.GetJkFactoryInfo(subNode.Attributes['OTHER']); end; File_Headinfo_KeHuo : begin m_FieldConvert.GetKeHuoBenBu(subNode.Attributes['OTHER'],HeadInfo.TrainType,HeadInfo.BenBu); end; File_Headinfo_CheCi : begin m_FieldConvert.GetCheCiInfo(subNode.Attributes['OTHER'],HeadInfo.nTrainNo,HeadInfo.strTrainHead); end; File_Headinfo_TotalWeight : begin HeadInfo.nTotalWeight := StrToInt(subNode.Attributes['OTHER']); end; File_Headinfo_DataJL : begin HeadInfo.nDataLineID := StrToInt(subNode.Attributes['OTHER']); end; File_Headinfo_JLH : begin HeadInfo.nJKLineID := StrToInt(subNode.Attributes['OTHER']); end; File_Headinfo_Driver : begin HeadInfo.nFirstDriverNO := m_FieldConvert.GetDriverNo(subNode.Attributes['OTHER']); end; File_Headinfo_SubDriver : begin HeadInfo.nSecondDriverNO := m_FieldConvert.GetDriverNo(subNode.Attributes['OTHER']); end; File_Headinfo_LiangShu : begin HeadInfo.nSum := StrToInt(subNode.Attributes['OTHER']); end; File_Headinfo_JiChang : begin end; File_Headinfo_ZZhong : begin HeadInfo.nLoadWeight := StrToInt(subNode.Attributes['OTHER']); end; File_Headinfo_TrainNo : begin HeadInfo.nLocoID := m_FieldConvert.GetLocalID((subNode.Attributes['OTHER'])); end; File_Headinfo_TrainType : begin HeadInfo.nLocoType := StrToInt(subNode.Attributes['OTHER']); end; File_Headinfo_LkjID : begin HeadInfo.nDeviceNo := StrToInt(subNode.Attributes['OTHER']); end; File_Headinfo_StartStation : begin HeadInfo.nStartStation := StrToInt(subNode.Attributes['OTHER']) end; end; end; finally end; end; procedure TLKJRuntimeXMLReader.SaveToFile(FileName: string; RuntimeFile: TLKJRuntimeFile); var i : Integer; xmlDoc : IXMLDocument; RootNode, Node: IXMLNode; CRec: RCommonRec; begin xmlDoc := NewXMLDocument(); try XmlDoc.DocumentElement := XmlDoc.CreateNode('运行记录'); RootNode := XmlDoc.DocumentElement;; for I := 0 to RuntimeFile.Records.Count - 1 do begin CRec := RuntimeFile.Records[i].CommonRec; Node := RootNode.AddChild('Row' + IntToStr(i)); Node.Attributes['Rec'] := CRec.nRow; Node.Attributes['Disp'] := CRec.strDisp; Node.Attributes['nEvent'] := CRec.nEvent; Node.Attributes['Hms'] := CRec.DTEvent; Node.Attributes['Glb'] := m_FieldConvert.ConvertCoordToStr(CRec.nCoord); Node.Attributes['Xhj'] := CRec.strXhj; Node.Attributes['Xht_code'] := CRec.SignType; Node.Attributes['Xhj_no'] := CRec.nLampNo; Node.Attributes['Xh_code'] := CRec.LampSign; Node.Attributes['Speed'] := CRec.nSpeed; Node.Attributes['Shoub'] := CRec.nShoub; Node.Attributes['Hand'] := CRec.strGK; Node.Attributes['Gya'] := CRec.nLieGuanPressure; Node.Attributes['Rota'] := CRec.nRotate; Node.Attributes['S_lmt'] := CRec.nLimitSpeed; Node.Attributes['Jl'] := CRec.nDistance; Node.Attributes['Gangy'] := CRec.nGangPressure; Node.Attributes['OTHER'] := CRec.strOther; Node.Attributes['Signal'] := CRec.strSignal; Node.Attributes['Jg1'] := CRec.nJG1Pressure; Node.Attributes['Jg2'] := CRec.nJG2Pressure; Node.Attributes['JKZT'] := CRec.JKZT; Node.Attributes['Shuoming'] := CRec.ShuoMing; Node.Attributes['ValidJG'] := CRec.nValidJG; Node.Attributes['JiaoLu'] := CRec.nDataLineID; Node.Attributes['Station'] := CRec.nStation; end; xmlDoc.SaveToFile(FileName); XmlDoc.DocumentElement.ChildNodes.Clear; finally xmlDoc := nil; end; end; end.
{ *************************************************************************** } { } { Kylix and Delphi Cross-Platform Visual Component Library } { Internet Application Runtime } { } { Copyright (C) 1997, 2001 Borland Software Corporation } { } { Licensees holding a valid Borland No-Nonsense License for this Software may } { use this file in accordance with such license, which appears in the file } { license.txt that came with this Software. } { } { Русификация: 1999-2002 Polaris Software } { http://polesoft.da.ru } { *************************************************************************** } unit WebConst; interface {$IFDEF VER130} {$DEFINE D5_} {$ENDIF} {$IFDEF VER140} {$DEFINE D5_} {$DEFINE D6_} {$ENDIF} {$IFDEF VER150} {$DEFINE D5_} {$DEFINE D6_} {$ENDIF} resourcestring {$IFDEF D6_} {$IFNDEF VER140} sErrorDecodingURLText = 'Ошибка расшифровки стиля URL (%%XX), закодированного строкой, в позиции %d'; {$ELSE} sErrorDecodingURLText = 'Ошибка расшифровки стиля URL (%XX), закодированного строкой, в позиции %d'; {$ENDIF} sInvalidURLEncodedChar = 'Неверный закодированный символ URL (%s) в позиции %d'; sInvalidHTMLEncodedChar = 'Неверный закодированный символ HTML (%s) в позиции %d'; {$ENDIF} sInvalidActionRegistration = 'Неверная регистрация Action'; {$IFNDEF D5_} sOnlyOneDataModuleAllowed = 'Допустим только один модуль данных на приложение'; sNoDataModulesRegistered = 'Не зарегистрировано ни одного модуля данных'; sNoDispatcherComponent = 'Не найдено ни одного компонента-диспетчера в модуле данных'; sOnlyOneDispatcher = 'Только один WebDispatcher на формы/модуля данных'; {$ENDIF} sDuplicateActionName = 'Дубликат имени action'; {$IFDEF D6_} sFactoryAlreadyRegistered = 'Web Module Factory уже зарегистрирована'; sAppFactoryAlreadyRegistered = 'Web App Module Factory уже зарегистрирована.'; {$ENDIF} {$IFDEF D5_} sOnlyOneDispatcher = 'Только один WebDispatcher на формы/модуля данных'; {$ELSE} sTooManyActiveConnections = 'Достигнут максимум конкурирующих соединений. ' + 'Повторите попытку позже'; {$ENDIF} sHTTPItemName = 'Name'; sHTTPItemURI = 'PathInfo'; sHTTPItemEnabled = 'Enabled'; sHTTPItemDefault = 'Default'; {$IFDEF D5_} sHTTPItemProducer = 'Producer'; {$ENDIF} {$IFNDEF D5_} sInternalServerError = '<html><title>Внутренняя Ошибка Сервера 500</title>'#13#10 + '<h1>Внутренняя Ошибка Сервера 500</h1><hr>'#13#10 + 'Исключительная ситуация: %s<br>'#13#10 + 'Сообщение: %s<br></html>'#13#10; {$ENDIF} {$IFDEF VER120} sDocumentMoved = '<html><title>Документ перемещен 302</title>'#13#10 + '<body><h1>Объект перемещен</h1><hr>'#13#10 + 'Этот объект может быть найден <a HREF="%s">здесь.</a><br>'#13#10 + '<br></body></html>'#13#10; {$ENDIF} {$IFDEF VER100} sWindowsSocketError = 'Ошибка Windows socket: %s (%d), в API ''%s'''; sNoAddress = 'Не указан адрес'; sCannotCreateSocket = 'Не могу создать новый socket'; sCannotListenOnOpen = 'Не могу слушать открытый socket'; sSocketAlreadyOpen = 'Socket уже открыт'; sCantChangeWhileActive = 'Не могу изменить значение, пока socket активный'; sMustCreateThread = 'Поток должен создаваться в режиме Thread blocking'; sSocketMustBeBlocking = 'Socket должен быть в blocking mode'; sSocketIOError = '%s ошибка %d, %s'; sSocketRead = 'Чтения'; sSocketWrite = 'Записи'; sAsyncSocketError = 'Ошибка асинхронного socket %d'; {$ENDIF} sResNotFound = 'Ресурс %s не найден'; sTooManyColumns = 'Слишком много столбцов в таблице'; sFieldNameColumn = 'Field Name'; sFieldTypeColumn = 'Field Type'; {$IFNDEF D5_} sInvalidMask = '''%s'' - неверная маска (%d)'; {$ENDIF} {$IFDEF D6_} sInvalidWebComponentsRegistration = 'Неверная регистрация Web компонента'; sInvalidWebComponentsEnumeration = 'Неверная нумерация Web компонента'; sInvalidWebParent = 'Операция не поддерживается. Компонент %s не поддерживает IGetWebComponentList'; sVariableIsNotAContainer = 'Переменная %s - не контейнер'; {$IFNDEF VER140} sInternalApplicationError = '<html><body><h1>Внутренняя ошибка приложения</h1>' + sLineBreak + '<p>%0:s' + sLineBreak + '<p><hr width="100%%"><i>%1:s</i></body></html>'; {$ELSE} sInternalApplicationError = '<h1>Внутренняя ошибка приложения</h1>'#13#10 + '<p>%0:s'#13#10 + '<p><hr width="100%%"><i>%1:s</i>'; {$ENDIF} sInvalidParent = 'Неверный родитель'; sActionDoesNotProvideResponse = 'Action не обеспечивает ответ'; sActionCantRespondToUnkownHTTPMethod = 'Action не может ответить неизвестному HTTP методу'; sActionCantRedirectToBlankURL = 'Action не может нереадресовать на пустой URL'; {$ENDIF} implementation end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [ECF_CONFIGURACAO] 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 EcfConfiguracaoVO; {$mode objfpc}{$H+} interface uses VO, Classes, SysUtils, FGL, EcfResolucaoVO, EcfImpressoraVO, EcfCaixaVO, EcfEmpresaVO, EcfConfiguracaoBalancaVO, EcfRelatorioGerencialVO, EcfConfiguracaoLeitorSerVO; type TEcfConfiguracaoVO = class(TVO) private FID: Integer; FID_ECF_IMPRESSORA: Integer; FID_ECF_RESOLUCAO: Integer; FID_ECF_CAIXA: Integer; FID_ECF_EMPRESA: Integer; FMENSAGEM_CUPOM: String; FPORTA_ECF: String; FIP_SERVIDOR: String; FIP_SITEF: String; FTIPO_TEF: String; FTITULO_TELA_CAIXA: String; FCAMINHO_IMAGENS_PRODUTOS: String; FCAMINHO_IMAGENS_MARKETING: String; FCAMINHO_IMAGENS_LAYOUT: String; FCOR_JANELAS_INTERNAS: String; FMARKETING_ATIVO: String; FCFOP_ECF: Integer; FCFOP_NF2: Integer; FTIMEOUT_ECF: Integer; FINTERVALO_ECF: Integer; FDESCRICAO_SUPRIMENTO: String; FDESCRICAO_SANGRIA: String; FTEF_TIPO_GP: Integer; FTEF_TEMPO_ESPERA: Integer; FTEF_ESPERA_STS: Integer; FTEF_NUMERO_VIAS: Integer; FDECIMAIS_QUANTIDADE: Integer; FDECIMAIS_VALOR: Integer; FBITS_POR_SEGUNDO: Integer; FQUANTIDADE_MAXIMA_CARTOES: Integer; FPESQUISA_PARTE: String; FULTIMA_EXCLUSAO: Integer; FLAUDO: String; FDATA_ATUALIZACAO_ESTOQUE: TDateTime; FPEDE_CPF_CUPOM: String; FTIPO_INTEGRACAO: Integer; FTIMER_INTEGRACAO: Integer; FGAVETA_SINAL_INVERTIDO: String; FGAVETA_UTILIZACAO: Integer; FQUANTIDADE_MAXIMA_PARCELA: Integer; FIMPRIME_PARCELA: String; FUSA_TECLADO_REDUZIDO: String; FPERMITE_LANCAR_NF_MANUAL: String; FEcfResolucaoVO: TEcfResolucaoVO; FEcfImpressoraVO: TEcfImpressoraVO; FEcfCaixaVO: TEcfCaixaVO; FEcfEmpresaVO: TEcfEmpresaVO; FEcfConfiguracaoBalancaVO: TEcfConfiguracaoBalancaVO; FEcfRelatorioGerencialVO: TEcfRelatorioGerencialVO; FEcfConfiguracaoLeitorSerVO: TEcfConfiguracaoLeitorSerVO; published constructor Create; override; destructor Destroy; override; property Id: Integer read FID write FID; property IdEcfImpressora: Integer read FID_ECF_IMPRESSORA write FID_ECF_IMPRESSORA; property IdEcfResolucao: Integer read FID_ECF_RESOLUCAO write FID_ECF_RESOLUCAO; property IdEcfCaixa: Integer read FID_ECF_CAIXA write FID_ECF_CAIXA; property IdEcfEmpresa: Integer read FID_ECF_EMPRESA write FID_ECF_EMPRESA; property MensagemCupom: String read FMENSAGEM_CUPOM write FMENSAGEM_CUPOM; property PortaEcf: String read FPORTA_ECF write FPORTA_ECF; property IpServidor: String read FIP_SERVIDOR write FIP_SERVIDOR; property IpSitef: String read FIP_SITEF write FIP_SITEF; property TipoTef: String read FTIPO_TEF write FTIPO_TEF; property TituloTelaCaixa: String read FTITULO_TELA_CAIXA write FTITULO_TELA_CAIXA; property CaminhoImagensProdutos: String read FCAMINHO_IMAGENS_PRODUTOS write FCAMINHO_IMAGENS_PRODUTOS; property CaminhoImagensMarketing: String read FCAMINHO_IMAGENS_MARKETING write FCAMINHO_IMAGENS_MARKETING; property CaminhoImagensLayout: String read FCAMINHO_IMAGENS_LAYOUT write FCAMINHO_IMAGENS_LAYOUT; property CorJanelasInternas: String read FCOR_JANELAS_INTERNAS write FCOR_JANELAS_INTERNAS; property MarketingAtivo: String read FMARKETING_ATIVO write FMARKETING_ATIVO; property CfopEcf: Integer read FCFOP_ECF write FCFOP_ECF; property CfopNf2: Integer read FCFOP_NF2 write FCFOP_NF2; property TimeoutEcf: Integer read FTIMEOUT_ECF write FTIMEOUT_ECF; property IntervaloEcf: Integer read FINTERVALO_ECF write FINTERVALO_ECF; property DescricaoSuprimento: String read FDESCRICAO_SUPRIMENTO write FDESCRICAO_SUPRIMENTO; property DescricaoSangria: String read FDESCRICAO_SANGRIA write FDESCRICAO_SANGRIA; property TefTipoGp: Integer read FTEF_TIPO_GP write FTEF_TIPO_GP; property TefTempoEspera: Integer read FTEF_TEMPO_ESPERA write FTEF_TEMPO_ESPERA; property TefEsperaSts: Integer read FTEF_ESPERA_STS write FTEF_ESPERA_STS; property TefNumeroVias: Integer read FTEF_NUMERO_VIAS write FTEF_NUMERO_VIAS; property DecimaisQuantidade: Integer read FDECIMAIS_QUANTIDADE write FDECIMAIS_QUANTIDADE; property DecimaisValor: Integer read FDECIMAIS_VALOR write FDECIMAIS_VALOR; property BitsPorSegundo: Integer read FBITS_POR_SEGUNDO write FBITS_POR_SEGUNDO; property QuantidadeMaximaCartoes: Integer read FQUANTIDADE_MAXIMA_CARTOES write FQUANTIDADE_MAXIMA_CARTOES; property PesquisaParte: String read FPESQUISA_PARTE write FPESQUISA_PARTE; property UltimaExclusao: Integer read FULTIMA_EXCLUSAO write FULTIMA_EXCLUSAO; property Laudo: String read FLAUDO write FLAUDO; property DataAtualizacaoEstoque: TDateTime read FDATA_ATUALIZACAO_ESTOQUE write FDATA_ATUALIZACAO_ESTOQUE; property PedeCpfCupom: String read FPEDE_CPF_CUPOM write FPEDE_CPF_CUPOM; property TipoIntegracao: Integer read FTIPO_INTEGRACAO write FTIPO_INTEGRACAO; property TimerIntegracao: Integer read FTIMER_INTEGRACAO write FTIMER_INTEGRACAO; property GavetaSinalInvertido: String read FGAVETA_SINAL_INVERTIDO write FGAVETA_SINAL_INVERTIDO; property GavetaUtilizacao: Integer read FGAVETA_UTILIZACAO write FGAVETA_UTILIZACAO; property QuantidadeMaximaParcela: Integer read FQUANTIDADE_MAXIMA_PARCELA write FQUANTIDADE_MAXIMA_PARCELA; property ImprimeParcela: String read FIMPRIME_PARCELA write FIMPRIME_PARCELA; property UsaTecladoReduzido: String read FUSA_TECLADO_REDUZIDO write FUSA_TECLADO_REDUZIDO; property PermiteLancarNfManual: String read FPERMITE_LANCAR_NF_MANUAL write FPERMITE_LANCAR_NF_MANUAL; property EcfResolucaoVO: TEcfResolucaoVO read FEcfResolucaoVO write FEcfResolucaoVO; property EcfImpressoraVO: TEcfImpressoraVO read FEcfImpressoraVO write FEcfImpressoraVO; property EcfCaixaVO: TEcfCaixaVO read FEcfCaixaVO write FEcfCaixaVO; property EcfEmpresaVO: TEcfEmpresaVO read FEcfEmpresaVO write FEcfEmpresaVO; property EcfConfiguracaoBalancaVO: TEcfConfiguracaoBalancaVO read FEcfConfiguracaoBalancaVO write FEcfConfiguracaoBalancaVO; property EcfRelatorioGerencialVO: TEcfRelatorioGerencialVO read FEcfRelatorioGerencialVO write FEcfRelatorioGerencialVO; property EcfConfiguracaoLeitorSerVO: TEcfConfiguracaoLeitorSerVO read FEcfConfiguracaoLeitorSerVO write FEcfConfiguracaoLeitorSerVO; end; TListaEcfConfiguracaoVO = specialize TFPGObjectList<TEcfConfiguracaoVO>; implementation constructor TEcfConfiguracaoVO.Create; begin inherited; FEcfResolucaoVO := TEcfResolucaoVO.Create; FEcfImpressoraVO := TEcfImpressoraVO.Create; FEcfCaixaVO := TEcfCaixaVO.Create; FEcfEmpresaVO := TEcfEmpresaVO.Create; FEcfConfiguracaoBalancaVO := TEcfConfiguracaoBalancaVO.Create; FEcfRelatorioGerencialVO := TEcfRelatorioGerencialVO.Create; FEcfConfiguracaoLeitorSerVO := TEcfConfiguracaoLeitorSerVO.Create; end; destructor TEcfConfiguracaoVO.Destroy; begin FreeAndNil(FEcfResolucaoVO); FreeAndNil(FEcfImpressoraVO); FreeAndNil(FEcfCaixaVO); FreeAndNil(FEcfEmpresaVO); FreeAndNil(FEcfConfiguracaoBalancaVO); FreeAndNil(FEcfRelatorioGerencialVO); FreeAndNil(FEcfConfiguracaoLeitorSerVO); inherited; end; initialization Classes.RegisterClass(TEcfConfiguracaoVO); finalization Classes.UnRegisterClass(TEcfConfiguracaoVO); end.
unit API_Files; interface uses API_Types, System.Classes; { class procedure CreateFile(aFileName: String); class procedure AppendToFile(aFileName, aText: String); class procedure CreateDirIfNotExists(aDir: string); class procedure TFilesEngine.CreateDirIfNotExists(aDir: string); begin if not DirectoryExists(aDir) then MkDir(aDir); end; class procedure TFilesEngine.CreateFile(aFileName: string); var SL: TStringList; begin SL := TStringList.Create; try SL.SaveToFile(aFileName); finally SL.Free; end; end; class procedure TFilesEngine.AppendToFile(aFileName, aText: String); var EditFile: TextFile; begin //try AssignFile(EditFile, aFileName, CP_UTF8); //AssignFile(EditFile, aFileName); Append(EditFile); WriteLn(EditFile, aText); CloseFile(EditFile); //except //raise; //end; end; } type TFileInfo = record public DirectoryArr: TArray<string>; Drive: string; Extension: string; FileName: string; FullPath: string; Name: string; procedure LoadFromPath(aPath: string); end; TFilesEngine = class public class function CreateFileStream(const aPath: string): TFileStream; class function GetFileInfoArr(const aPath: string): TArray<TFileInfo>; class function GetMIMEType(const aPath: string): TMIMEType; class function GetTextFromFile(const aPath: string): string; class function IsFileExists(const aPath: string): Boolean; class procedure Move(aSourceFullPath, aDestFullPath: string; aForceDir: Boolean = True); class procedure SaveTextToFile(const aPath, aText: string); end; implementation uses System.IOUtils, System.SysUtils, System.Types; class function TFilesEngine.IsFileExists(const aPath: string): Boolean; begin Result := TFile.Exists(aPath); end; class function TFilesEngine.GetMIMEType(const aPath: string): TMIMEType; var Ext: string; begin Result := mtUnknown; Ext := UpperCase(ExtractFileExt(aPath)); if (Ext = '.JPG') or (Ext = '.JPEG') then Result := mtJPEG else if (Ext = '.PNG') then Result := mtPNG else if (Ext = '.BMP') then Result := mtPNG else if (Ext = '.GIF') then Result := mtGIF; end; class function TFilesEngine.CreateFileStream(const aPath: string): TFileStream; begin Result := TFile.OpenRead(aPath); end; class procedure TFilesEngine.Move(aSourceFullPath, aDestFullPath: string; aForceDir: Boolean = True); var DestDirectory: string; begin if aForceDir then begin DestDirectory := TPath.GetDirectoryName(aDestFullPath); if not TDirectory.Exists(DestDirectory) then TDirectory.CreateDirectory(DestDirectory); end; TFile.Move(aSourceFullPath, aDestFullPath); end; class procedure TFilesEngine.SaveTextToFile(const aPath, aText: string); var DirName: string; FileStream: TFileStream; begin DirName := TPath.GetDirectoryName(aPath); if not TDirectory.Exists(DirName) and not DirName.IsEmpty then TDirectory.CreateDirectory(DirName); if not TFile.Exists(aPath) then begin FileStream := TFile.Create(aPath); FileStream.Free; end; TFile.WriteAllText(aPath, aText); end; class function TFilesEngine.GetTextFromFile(const aPath: String): String; var SL: TStringList; begin //Result := TFile.ReadAllText(aPath); SL := TStringList.Create; try SL.LoadFromFile(aPath); Result := SL.Text; finally SL.Free; end; end; procedure TFileInfo.LoadFromPath(aPath: string); var i: Integer; PathWords: TArray<string>; PointIndex: Integer; begin PathWords := aPath.Split(['\']); FullPath := aPath; Drive := PathWords[0]; DirectoryArr := []; for i := 1 to Length(PathWords) - 2 do DirectoryArr := DirectoryArr + [PathWords[i]]; FileName := PathWords[High(PathWords)]; PointIndex := FileName.LastIndexOf('.'); Name := FileName.Substring(0, PointIndex); Extension := FileName.Substring(PointIndex + 1, FileName.Length); end; class function TFilesEngine.GetFileInfoArr(const aPath: string): TArray<TFileInfo>; var FileInfo: TFileInfo; Files: TStringDynArray; i: Integer; begin Result := []; if TDirectory.Exists(aPath) then begin Files := TDirectory.GetFiles(aPath); end else if TFile.Exists(aPath) then Files := [aPath]; for i := 0 to Length(Files) - 1 do begin FileInfo.LoadFromPath(Files[i]); Result := Result + [FileInfo]; end; end; end.
unit Quadratic; interface type ///Quadratic formula; Solves quadratic equations of the form /// alpha*x^2+beta*x+gamma=0 TQuadratic = class private // Temporary variables, initialised by Discriminant t_Discriminant, t_alpha, t_beta : double; protected // Parameters function alpha : double; virtual; abstract; function beta : double; virtual; abstract; function gamma : double; virtual; abstract; function Discriminant : Double; public /// Solve raises EInvalidArgument exception when no real solution possible function Solve(const Positive : Boolean) : Double; end; implementation uses Math; { *** TQuadratic ************************************************************* } function TQuadratic.Discriminant: Double; begin t_alpha := alpha; t_beta := beta; t_Discriminant := sqr(t_beta) - 4 * t_alpha * gamma; Result := t_Discriminant; end; function TQuadratic.Solve(const Positive : Boolean) : Double; var result1, result2 : Double; begin result := 0; if Discriminant>=0 then begin result1 := ( -t_beta + sqrt(t_Discriminant)) / (2 * t_alpha); result2 := ( -t_beta - sqrt(t_Discriminant)) / (2 * t_alpha); if Positive then begin if result1>result2 then result := result1 else result := result2; // Round result to 16 digits, as rounding errors in the calculations can // result in a very small number (about 1e-19) here, instead of zero. result:=RoundTo(result, -16); ASSERT(result>=0); end; end else raise EInvalidArgument.Create('No real solutions to quadratic equation'); end; end.
unit UnitLinksSupport; interface uses Winapi.Windows, System.SysUtils, System.Classes, System.StrUtils, Dmitry.Utils.System, uTranslate, uConstants; const LINK_TYPE_ID = 0; LINK_TYPE_ID_EXT = 1; LINK_TYPE_IMAGE = 2; LINK_TYPE_FILE = 3; LINK_TYPE_FOLDER = 4; LINK_TYPE_TXT = 5; LINK_TYPE_HREF = 6; LINK_TEXT_TYPE_ID = 'ID'; LINK_TEXT_TYPE_ID_EXT = 'IDExt'; LINK_TEXT_TYPE_IMAGE = 'Image'; LINK_TEXT_TYPE_FILE = 'File'; LINK_TEXT_TYPE_FOLDER = 'Folder'; LINK_TEXT_TYPE_TXT = 'Text'; LINK_TEXT_TYPE_HTML = 'Web link'; type TLinkInfo = record LinkType: Byte; LinkName: string; LinkValue: string; Tag: Byte; //unused by default end; const LINK_TAG_NONE = $0001; LINK_TAG_SELECTED = $0002; LINK_TAG_VALUE_VAR_NOT_SELECT = $0004; type TLinksInfo = array of TLinkInfo; TArLinksInfo = array of TLinksInfo; TSetLinkProcedure = procedure(Sender: TObject; ID: string; Info: TLinkInfo; N: Integer; Action: Integer) of object; const LINK_PROC_ACTION_ADD = 0; LINK_PROC_ACTION_MODIFY = 1; function CodeLinkInfo(Info: TLinkInfo): string; function CodeLinksInfo(Info: TLinksInfo): string; function ParseLinksInfo(Info: string): TLinksInfo; function CopyLinksInfo(Info: TLinksInfo): TLinksInfo; function VariousLinks(Info1, Info2: TLinksInfo): Boolean; overload; function VariousLinks(Info1, Info2: string): Boolean; overload; function DeleteLinkAtPos(var Info: string; Pos: Integer): Boolean; overload; function DeleteLinkAtPos(var Info: TLinksInfo; Pos: Integer): Boolean; overload; function GetCommonLinks(LinksList: TStringList): TLinksInfo; overload; function GetCommonLinks(Info: TArLinksInfo): TLinksInfo; overload; procedure ReplaceLinks(LinksToDelete, LinksToAdd: TLinksInfo; var Links: TLinksInfo); overload; procedure ReplaceLinks(LinksToDelete, LinksToAdd: string; var Links: string); overload; function CompareLinks(LinksA, LinksB: TLinksInfo; Simple: Boolean = False): Boolean; overload; function CompareLinks(LinksA, LinksB: string; Simple: Boolean = False): Boolean; overload; function LinkInLinksExists(Link: TLinkInfo; Links: TLinksInfo; UseValue: Boolean = True): Boolean; function CodeExtID(ExtID: string): string; function DeCodeExtID(S: string): string; function CompareTwoLinks(Link1, Link2: TLinkInfo; UseValue: Boolean = False): Boolean; function LinkType(LinkTypeN : integer) : String; implementation function CompareTwoLinks(Link1, Link2: TLinkInfo; UseValue: Boolean = False): Boolean; begin Result := False; if Link1.LinkType = Link2.LinkType then if AnsiLowerCase(Link1.LinkName) = AnsiLowerCase(Link2.LinkName) then if (AnsiLowerCase(Link1.LinkValue) = AnsiLowerCase(Link2.LinkValue)) or not UseValue then Result := True; end; function CopyLinksInfo(Info: TLinksInfo): TLinksInfo; var I: Integer; begin SetLength(Result, Length(Info)); for I := 0 to Length(Info) - 1 do Result[I] := Info[I]; end; function CodeLinkInfo(Info: TLinkInfo): string; begin Result := '[' + IntToStr(Info.LinkType) + ']{' + Info.LinkName + '}' + Info.LinkValue + ';'; end; function CodeLinksInfo(Info: TLinksInfo): string; var I: Integer; begin Result := ''; for I := 0 to Length(Info) - 1 do Result := Result + '[' + IntToStr(Info[I].LinkType) + ']{' + Info[I].LinkName + '}' + Info[I].LinkValue + ';'; end; function ParseLinksInfo(Info: string): TLinksInfo; var I, C, L: Integer; S: string; procedure AddOneLink(AInfo: string); var S1, S2, S3, S4, S5: Integer; begin S1 := Pos('[', AInfo); S2 := PosEx(']', AInfo, S1); S3 := PosEx('{', AInfo, S2); S4 := PosEx('}', AInfo, S3); S5 := PosEx(';', AInfo, S4); if (S1 <> 0) and (S2 <> 0) and (S3 <> 0) and (S4 <> 0) and (S5 <> 0) then begin L := Length(Result); SetLength(Result, L + 1); Result[L].LinkType := StrToIntDef(Copy(AInfo, S1 + 1, S2 - S1 - 1), 0); Result[L].LinkName := Copy(AInfo, S3 + 1, S4 - S3 - 1); Result[L].LinkValue := Copy(AInfo, S4 + 1, S5 - S4 - 1); Result[L].Tag := LINK_TAG_NONE; end; end; begin C := 0; SetLength(Result, 0); for I := 1 to Length(Info) do if Info[I] = ';' then begin S := Copy(Info, C, I - C + 1); AddOneLink(S); C := I + 1; end; end; function LinkInLinksExists(Link: TLinkInfo; Links: TLinksInfo; UseValue: Boolean = True): Boolean; var I: Integer; begin Result := False; for I := 0 to Length(Links) - 1 do begin if Link.LinkType = Links[I].LinkType then if AnsiLowerCase(Link.LinkName) = AnsiLowerCase(Links[I].LinkName) then if (AnsiLowerCase(Link.LinkValue) = AnsiLowerCase(Links[I].LinkValue)) or not UseValue then begin Result := True; Exit; end; end; end; function VariousLinks(Info1, Info2: string): Boolean; begin Result := VariousLinks(ParseLinksInfo(Info1), ParseLinksInfo(Info2)); end; function VariousLinks(Info1, Info2: TLinksInfo): Boolean; var I: Integer; begin Result := False; for I := 0 to Length(Info1) - 1 do if not LinkInLinksExists(Info1[I], Info2) then begin Result := True; Exit; end; for I := 0 to Length(Info2) - 1 do if not LinkInLinksExists(Info2[I], Info1) then begin Result := True; Exit; end; end; function DeleteLinkAtPos(var Info: string; Pos: Integer): Boolean; var Tinfo: TLinksInfo; begin Tinfo := ParseLinksInfo(Info); Result := DeleteLinkAtPos(Tinfo, Pos); Info := CodeLinksInfo(Tinfo); end; function DeleteLinkAtPos(var Info: TLinksInfo; Pos: Integer): Boolean; var I: Integer; begin Result := False; if Length(Info) - 1 < Pos then Exit; for I := Pos to Length(Info) - 2 do Info[I] := Info[I + 1]; SetLength(Info, Length(Info) - 1); end; procedure DeleteLinkInLinks(var Info: TLinksInfo; Link: TLinkInfo; DeleteNoVal: Boolean = True); var I, J: Integer; begin for I := 0 to Length(Info) - 1 do if Link.LinkType = Info[I].LinkType then if AnsiLowerCase(Link.LinkName) = AnsiLowerCase(Info[I].LinkName) then if (AnsiLowerCase(Link.LinkValue) = AnsiLowerCase(Info[I].LinkValue)) or DeleteNoVal then begin for J := I to Length(Info) - 2 do Info[J] := Info[J + 1]; SetLength(Info, Length(Info) - 1); Exit; end; end; function GetCommonLinks(LinksList: TStringList): TLinksInfo; var I: Integer; Tinfo: TArLinksInfo; begin SetLength(Tinfo, LinksList.Count); for I := 0 to LinksList.Count - 1 do Tinfo[I] := ParseLinksInfo(LinksList[I]); Result := GetCommonLinks(Tinfo); end; function GetCommonLinks(Info: TArLinksInfo): TLinksInfo; var I, J: Integer; begin if Length(Info) = 0 then Exit; Result := CopyLinksInfo(Info[0]); for I := 1 to Length(Info) - 1 do begin if Length(Info[I]) = 0 then begin SetLength(Result, 0); Break; end; for J := Length(Result) - 1 downto 0 do if not LinkInLinksExists(Result[J], Info[I], False) then DeleteLinkInLinks(Result, Result[J]); if Length(Result) = 0 then Exit; end; for I := 0 to Length(Result) - 1 do Result[I].Tag := LINK_TAG_NONE; for I := 0 to Length(Result) - 1 do begin for J := 0 to Length(Info) - 1 do begin if not LinkInLinksExists(Result[I], Info[J], True) then begin Result[I].Tag := LINK_TAG_VALUE_VAR_NOT_SELECT; Break; end; end; end; end; procedure DeleteLinksFromLinks(var Links: TLinksInfo; LinksToDelete: TLinksInfo; DeleteNoVal: Boolean = True); var I: Integer; begin for I := 0 to Length(LinksToDelete) - 1 do if LinksToDelete[I].Tag = LINK_TAG_NONE then DeleteLinkInLinks(Links, LinksToDelete[I], DeleteNoVal); end; procedure AddLinkToLinks(var Links: TLinksInfo; LinksToAdd: TLinkInfo); begin SetLength(Links, Length(Links) + 1); Links[Length(Links) - 1] := LinksToAdd; end; procedure AddLinksToLinks(var Links: TLinksInfo; LinksToAdd: TLinksInfo); var I: Integer; begin for I := 0 to Length(LinksToAdd) - 1 do if LinksToAdd[I].Tag and LINK_TAG_VALUE_VAR_NOT_SELECT = 0 then AddLinkToLinks(Links, LinksToAdd[I]); end; procedure ReplaceLinks(LinksToDelete, LinksToAdd: string; var Links: string); var LA, LB, LR: TLinksInfo; begin LA := ParseLinksInfo(LinksToDelete); LB := ParseLinksInfo(LinksToAdd); LR := ParseLinksInfo(Links); ReplaceLinks(LA, LB, LR); Links := CodeLinksInfo(LR); end; procedure ReplaceLinks(LinksToDelete, LinksToAdd: TLinksInfo; var Links: TLinksInfo); var I, J: Integer; B: Boolean; begin for I := 0 to Length(LinksToDelete) - 1 do if LinksToDelete[I].Tag and LINK_TAG_VALUE_VAR_NOT_SELECT <> 0 then begin B := False; for J := 0 to Length(LinksToAdd) - 1 do begin if (LinksToAdd[J].LinkType = LinksToDelete[I].LinkType) and (AnsiLowerCase(LinksToAdd[J].LinkName) = AnsiLowerCase(LinksToDelete[I].LinkName)) then begin B := True; Break; end; end; if not B then LinksToDelete[I].Tag := LINK_TAG_NONE; end; for I := 0 to Length(LinksToAdd) - 1 do if LinksToAdd[I].Tag and LINK_TAG_VALUE_VAR_NOT_SELECT = 0 then begin for J := 0 to Length(LinksToDelete) - 1 do begin if (LinksToAdd[I].LinkType = LinksToDelete[J].LinkType) and (AnsiLowerCase(LinksToAdd[I].LinkName) = AnsiLowerCase(LinksToDelete[J].LinkName)) then begin LinksToDelete[I].Tag := LINK_TAG_NONE; end; end; end; DeleteLinksFromLinks(Links, LinksToDelete, True); AddLinksToLinks(Links, LinksToAdd); end; function CompareLinks(LinksA, LinksB: string; Simple: Boolean = False): Boolean; var LA, LB: TLinksInfo; begin LA := ParseLinksInfo(LinksA); LB := ParseLinksInfo(LinksB); Result := CompareLinks(LA, LB, Simple); end; function CompareLinks(LinksA, LinksB: TLinksInfo; Simple: Boolean = False): Boolean; var I: Integer; begin Result := True; if not Simple then begin for I := 0 to Length(LinksA) - 1 do begin if not LinkInLinksExists(LinksA[I], LinksB) then begin Result := False; Break; end; end; for I := 0 to Length(LinksB) - 1 do begin if not LinkInLinksExists(LinksB[I], LinksA) then begin Result := False; Break; end; end; end else begin if Length(LinksA) <> Length(LinksB) then begin Result := False; Exit; end; for I := 0 to Length(LinksA) - 1 do begin if not CompareTwoLinks(LinksA[I], LinksB[I], True) then begin Result := False; Break; end; end; end; end; function CodeExtID(ExtID: string): string; var I: Integer; W: Word; begin Result := ''; for I := 1 to Length(ExtID) do begin W := Word(ExtID[I]); Result := Result + IntToHex((W shr 8) and $FF, 2); Result := Result + IntToHex(W and $FF, 2); end; end; function DeCodeExtID(S: string): string; var I: Integer; Str, Str2: string; begin Result := ''; for I := 1 to (Length(S) div 4) do begin Str := Copy(S, 1 + 4 * (I - 1), 2); Str2 := Copy(S, 1 + 4 * (I - 1) + 2, 2); Result := Result + Char(HexToIntDef(Str, 0) shl 8 + HexToIntDef(Str2, 0)); end; end; function LinkType(LinkTypeN: Integer) : String; begin Result := TA('Unknown'); if LinkTypeN = LINK_TYPE_ID then Result := LINK_TEXT_TYPE_ID; if LinkTypeN = LINK_TYPE_ID_EXT then Result := LINK_TEXT_TYPE_ID_EXT; if LinkTypeN = LINK_TYPE_IMAGE then Result := LINK_TEXT_TYPE_IMAGE; if LinkTypeN = LINK_TYPE_FILE then Result := LINK_TEXT_TYPE_FILE; if LinkTypeN = LINK_TYPE_FOLDER then Result := LINK_TEXT_TYPE_FOLDER; if LinkTypeN = LINK_TYPE_TXT then Result := LINK_TEXT_TYPE_TXT; if LinkTypeN = LINK_TYPE_HREF then Result := LINK_TEXT_TYPE_HTML; end; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Core.Spec.BPLEntry; interface uses JsonDataObjects, Spring.Collections, DPM.Core.Logging, DPM.Core.Spec.Interfaces, DPM.Core.Spec.Node; type TSpecBPLEntry = class(TSpecNode, ISpecBPLEntry) private FSource : string; FCopyLocal : boolean; FInstall : boolean; FBuildId : string; protected function LoadFromJson(const jsonObject : TJsonObject) : Boolean; override; function GetSource : string; procedure SetSource(const value : string); function GetCopyLocal : Boolean; function GetInstall : Boolean; function GetBuildId : string; procedure SetBuildId(const value : string); function Clone : ISpecBPLEntry; constructor CreateClone(const logger : ILogger; const src : string; const buildId : string; const copyLocal, install : boolean); reintroduce; public constructor Create(const logger : ILogger); override; end; implementation uses System.SysUtils; { TSpecBPLEntry } function TSpecBPLEntry.Clone : ISpecBPLEntry; begin result := TSpecBPLEntry.CreateClone(logger, Self.GetSource, Self.GetBuildId, FCopyLocal, FInstall); end; constructor TSpecBPLEntry.Create(const logger : ILogger); begin inherited Create(logger); end; constructor TSpecBPLEntry.CreateClone(const logger : ILogger; const src : string; const buildId : string; const copyLocal, install : boolean); begin inherited Create(logger); FSource := src; FCopyLocal := copyLocal; FInstall := install; FBuildId := buildId; end; function TSpecBPLEntry.GetBuildId : string; begin result := FBuildId; end; function TSpecBPLEntry.GetCopyLocal : Boolean; begin result := FCopyLocal; end; function TSpecBPLEntry.GetInstall : Boolean; begin result := FInstall; end; function TSpecBPLEntry.GetSource: string; begin result := FSource; end; function TSpecBPLEntry.LoadFromJson(const jsonObject : TJsonObject) : Boolean; begin result := true; FSource := jsonObject.S['src']; if FSource = '' then begin Logger.Error('Required attribute [src] is missing'); result := false; end; FCopyLocal := jsonObject.B['copyLocal']; FInstall := jsonObject.B['install']; FBuildId := jsonObject.S['buildId']; end; procedure TSpecBPLEntry.SetBuildId(const value: string); begin FBuildId := value; end; procedure TSpecBPLEntry.SetSource(const value: string); begin FSource := value; end; end.
unit globals; {$mode objfpc}{$H+} interface uses Classes, SysUtils, ps_inifile, forms, DataModule; const ///-i- Applicatie Eigen cns_Apl_Version = '1.1.0'; cns_Apl_MainFrmCaption = 'Standaard applicatie Mainform '; cns_Apl_Nm = 'Standard App'; cns_Apl_SoftwareNm = 'StandardApp'; /// File constants cns_DataBaseNm = 'dbStandaard.db'; cns_LinDefDataLocation = '/home/corbij/Portable/Documenten/DataBases/Sqlite/StandaardDb/'; /// Table names cns_tbl_Documents_nm = 'Documents'; cns_tbl_LookUps_nm = 'LookUps'; cns_tbl_LookUpItems_nm = 'LookUpItems'; cns_tbl_Subjects_nm = 'Subjects'; cns_tbl_Items_nm = 'Items'; cns_tbl_Versions_nm = 'Versions'; ///-o- Applicatie Eigen {$IFDEF WINDOWS } {$IFDEF WIN32 } cns_OS = 'Win32'; {$ENDIF} {$IFDEF WIN64 } cns_OS = 'Win64'; {$ENDIF} {$ENDIF} {$IFDEF WINDOWS } {$IFDEF WIN32 } cns_PathToSqliteDll = 'SqliteDll-32\sqlite3.dll'; {$ENDIF} {$IFDEF WIN64 } cns_PathToSqliteDll = 'SqliteDll-64\sqlite3.dll'; {$ENDIF} {$ENDIF} {$IFDEF LINUX} {$IFDEF cpui386} cns_OS = 'Lin32'; {$else} cns_OS = 'Lin64'; {$ENDIF} {$ENDIF} /// Report names /// File constants cns_DataDirIni = 'IniFiles'; cns_DataDirDatabase = 'DataBases'; cns_DataDirRepo = 'RepoDir_UserFiles'; cns_LinDataLocation = 'Data'; cns_WinDataLocation = 'ProfessionalSoftware'; /// Messages cns_Msg_PendingUpdates = 'Er zijn wijzigingen die nog niet zijn doorgevoerd'; cns_Msg_WiltUOpslaan = 'Wilt u de wijzigingen opslaan voor het sluiten vd pagina?'; cns_Msg_AlleenArtForm = 'U kunt de prijs alleen wijzigen in het artikel formulier'; cns_Msg_RefresIsHerbereken = 'Save + Refresh = Herbereken'; cns_Msg_DbOpnLaden = 'Herstart het programma om de database opnieuw in te laden'; cns_Msg_LtstBckUpDb = 'Laatste Backup database: '; cns_Msg_EnterFilterStr = 'Please enter a filter string'; cns_Msg_PartualKeySearch = '(Partual key search)'; cns_Msg_ProblClosingProgram = 'Something went wrong closing the program'; cns_Msg_UpdateFailed = 'Failde to update the table'; /// Captions cns_Txt_LijstTotaal = 'Lijst totaal: '; cns_Txt_ToonAllen = 'Toon allen'; cns_Txt_Categorien = 'Categorien'; cns_Txt_SelectionForm = ' #selection form#'; /// Ini keys cns_Ini_PathToRepoDir = 'PathToRepoDir'; cns_Ini_DataBasePath = 'DataBasePath'; cns_Ini_UserDataBasePath = 'UserDataBasePath'; cns_Ini_DBBackupDir = 'DBBackupDir'; cns_Ini_LastDBBackup = 'LastDBBackup'; cns_Ini_PathToAppData = 'PathToAppData'; cns_Ini_CurrAppMigration = 'CurrAppMigration'; /// Other constants cn_FldStatus_InRepo = 'InRepo'; cn_FldStatus_OutsideRepo = 'OutsideRepo'; /// Program parameters cns_PrgmPar_UserDb = false; /// File extentions cns_VersionExt = '-Ver-'; cns_Old = '-Old-'; type TFormArray = Array of TForm; var TheInputString: String = ''; MainDataMod: TDatModMain; FmtSettings: TFormatSettings; qIniPropStorage: TPsIniClass; qUseStndDataBase: Boolean = true; qCurrAppMigration: Integer; // Pad naar inifile, onveranderlijk qPathToRepoDir: String; qPathToIniDir: String; qPathToIniFile: String; qPathToAppDataDir: String; // Pad naar database veranderlijk (kan door gebr aangepast worden) qPathToDataBaseDir: String; qPathToDataBaseFile: String; qPathToUserDataBaseFile: String; qDirDbBackup: String; qPathToExeDir: String; // Indicators qInd_ProblDataBase: Boolean = false; implementation end.
(***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower Async Professional * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1991-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* EXPAGIN0.PAS 4.06 *} {*********************************************************} {**********************Description************************} {* A paging demonstration program *} {*********************************************************} unit ExPagin0; interface uses {$ifndef WIN32 } WinTypes, WinProcs, {$else } Windows, {$endif } Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, IniFiles, FileCtrl, OoMisc, AdPort, AdWnPort, AdPager; type TForm1 = class(TForm) btnSend: TButton; mmoMsg: TMemo; Label1: TLabel; Label4: TLabel; pnlStatus: TPanel; btnExit: TButton; bvlStatus1: TBevel; Label7: TLabel; btnDisconnect: TButton; ComPort: TApdComPort; TAPPager: TApdTAPPager; Label3: TLabel; edPagerAddr: TEdit; edPagerID: TEdit; WinsockPort: TApdWinsockPort; TAPLog: TApdPagerLog; SNPPPager: TApdSNPPPager; SNPPLog: TApdPagerLog; mmoPageStatus: TMemo; Label6: TLabel; GroupBox1: TGroupBox; cbLogging: TCheckBox; btnViewLog: TButton; btnClearLog: TButton; GroupBox2: TGroupBox; lbUsers: TListBox; btnAdd: TButton; btnEdit: TButton; btnRemove: TButton; procedure FormCreate(Sender: TObject); procedure btnSendClick(Sender: TObject); procedure btnExitClick(Sender: TObject); procedure btnDisconnectClick(Sender: TObject); procedure PageEvent(Sender: TObject; Event: TTAPStatus); procedure mmoMsgChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure cbLoggingClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure lbUsersClick(Sender: TObject); procedure btnEditClick(Sender: TObject); procedure btnAddClick(Sender: TObject); procedure btnRemoveClick(Sender: TObject); procedure ComPortTriggerAvail(CP: TObject; Count: Word); procedure btnViewLogClick(Sender: TObject); procedure btnClearLogClick(Sender: TObject); procedure SNPPPagerSNPPEvent(Sender: TObject; Code: Integer; Msg: String); private { Private declarations } procedure GetUsers; procedure AddEntry(const Name, Protocol, Addr, PagerID: string); function GetEntry(User: string): string; function GetCurUser: string; procedure SendBySNPP; procedure SendByTAP; procedure SNPPQuit; procedure ClearEds; procedure GetUserInfo(User: string); procedure UpdateMessage; procedure TAPQuit; procedure ClearCurVars; procedure SetLogFiles; procedure ClearLog; procedure ViewLog; procedure SetStatus(StatusMsg: string); procedure InitLogFile; procedure SetLogging(AreLogging: Boolean); function GetLogging: Boolean; public { Public declarations } PacketCt, AckCt: Integer; Cancelled : Boolean; PagerList, PagerINI: TIniFile; LineBuff: string; { status monitor buffering } PageType, CurUser, CurPagerAddress, CurWSPort, CurPagerID: string; LogName: string; property Logging: boolean read GetLogging write SetLogging; end; var Form1: TForm1; implementation uses ExPagin1, ExPagin2; {$R *.DFM} const PAGER_FILE = 'PAGERS.LST'; PAGER_INIT = 'PAGING.INI'; EntryType: array [0..1] of string = ('TAP', 'SNPP'); { Form Methods } procedure TForm1.FormCreate(Sender: TObject); begin ClearCurVars; PageType := 'TAP'; PagerList := TIniFile.Create(ExtractFilePath(Application.ExeName) + PAGER_FILE); GetUsers; ClearEds; PagerINI := TIniFile.Create(ExtractFilePath(Application.ExeName) + PAGER_INIT); Logging := PagerINI.ReadBool('INIT', 'LOGGING', FALSE); end; procedure TForm1.FormShow(Sender: TObject); begin UpdateMessage; end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin Cancelled := TRUE; TAPQuit; SNPPQuit; end; procedure TForm1.FormDestroy(Sender: TObject); begin PagerList.Free; PagerINI.Free; end; { Communications Event Handlers } procedure TForm1.ComPortTriggerAvail(CP: TObject; Count: Word); var Ch: Char; i: Word; begin for i := 1 to Count do begin Ch := ComPort.GetChar; case Ch of #13: begin mmoPageStatus.Lines.Add(LineBuff); LineBuff := ''; end; #10: {ignore }; else LineBuff := LineBuff + Ch; end; end; end; procedure TForm1.PageEvent(Sender: TObject; Event: TTAPStatus); begin case Event of psLoginPrompt: SetStatus('Got Login Prompt'); psLoggedIn: SetStatus('Logged In'); psLoginErr: SetStatus('Login Error'); psLoginFail: SetStatus('Login Failed'); psMsgOkToSend: SetStatus('Got OK to Send'); psSendingMsg: begin Inc(PacketCt); SetStatus('Sending packet ' + IntToStr(PacketCt) + '...'); end; psMsgAck:begin Inc(AckCt); SetStatus('Packet ' + IntToStr(AckCt) + ' Acknowledged'); end; psMsgCompleted: SetStatus('Message Completed'); psMsgNak: SetStatus('Message Error'); psMsgRs: SetStatus('Message Abort'); psDone: begin SetStatus('Page Done'); end; end; end ; { Control Event Handlers } procedure TForm1.btnExitClick(Sender: TObject); begin Close; end; procedure TForm1.mmoMsgChange(Sender: TObject); begin UpdateMessage; end; procedure TForm1.lbUsersClick(Sender: TObject); begin GetUserInfo(GetCurUser); edPagerID.Text := CurPagerID; edPagerAddr.Text := CurPagerAddress end; procedure TForm1.btnSendClick(Sender: TObject); var i: Integer; begin btnSend.Caption := 'Please Wait'; btnSend.Enabled := FALSE; PacketCt := 0; AckCt := 0; i := 0; Cancelled := FALSE; while (not Cancelled) and (i <= Pred(lbUsers.Items.Count)) do begin if lbUsers.Selected[i] then begin CurUser := lbUsers.Items[i]; GetUserInfo(CurUser); if PageType = 'TAP' then begin SendByTAP; end else if PageType = 'SNPP' then begin SendBySNPP; end else Application.MessageBox('Unknown transmission type requested', 'Error', MB_OK or MB_ICONEXCLAMATION); end; Inc(i); end; btnSend.Caption := 'Send'; btnSend.Enabled := TRUE; end; procedure TForm1.btnDisconnectClick(Sender: TObject); begin if PageType = 'TAP' then begin TAPQuit; end else if PageType = 'SNPP' then begin SNPPQuit; end else begin Application.MessageBox('Unknown protocol', 'Error', MB_OK or MB_ICONEXCLAMATION); end; Cancelled := TRUE; end; procedure TForm1.cbLoggingClick(Sender: TObject); begin Logging := cbLogging.Checked; end; procedure TForm1.btnViewLogClick(Sender: TObject); begin InitLogFile; ViewLog; end; procedure TForm1.btnClearLogClick(Sender: TObject); begin ClearLog; end; procedure TForm1.ClearEds; begin edPagerAddr.Text := ''; edPagerID.Text := ''; end; procedure TForm1.UpdateMessage; begin TAPPager.Message.Assign(mmoMsg.Lines); SNPPPager.Message.Assign(mmoMsg.Lines); end; procedure TForm1.ClearCurVars; begin CurUser := ''; CurPagerID := ''; CurPagerAddress := ''; CurWSPort := ''; end; procedure TForm1.SetStatus(StatusMsg: string); var S: string; begin S := Format('Status: %s', [StatusMsg]); Label7.Caption := S; end ; procedure TForm1.GetUsers; begin lbUsers.Items.Clear; PagerList.ReadSection('PAGERS', lbUsers.Items); end; function TForm1.GetCurUser: string; begin Result := lbUsers.Items[lbUsers.ItemIndex]; end; function TForm1.GetEntry(User: string): string; begin Result := PagerList.ReadString('PAGERS', User, ''); end; procedure TForm1.GetUserInfo(User: string); var PBar, PComma, PColon: Integer; UserDat: string; begin UserDat := GetEntry(User); PBar := Pos('|', UserDat); PComma := Pos(',', UserDat); PColon := Pos(':', UserDat); PageType := Copy(UserDat, 1, PBar - 1); if (PageType = 'TAP') then begin CurPagerAddress := Copy(UserDat, PBar + 1, (PComma - 1) - PBar); CurWSPort := ''; CurPagerID := Copy(UserDat, PComma + 1, Length(UserDat)-PComma); end else if (PageType = 'SNPP') then begin CurPagerAddress := Copy(UserDat, PBar + 1, (PColon - 1) - PBar); CurWSPort := Copy(UserDat, PColon + 1, (PComma - 1) - PColon); CurPagerID := Copy(UserDat, PComma + 1, Length(UserDat)-PComma); end else {bad entry} begin CurPagerAddress := ''; CurWSPort := ''; CurPagerID := ''; end; end; procedure TForm1.SendByTAP; begin TAPPager.PhoneNumber := CurPagerAddress; TAPPager.PagerID := CurPagerID; TAPPager.Message := mmoMsg.Lines; TAPPager.Send; end; procedure TForm1.TAPQuit; begin TAPPager.CancelCall; TAPPager.Disconnect; end; procedure TForm1.SendBySNPP; begin WinsockPort.WsAddress := CurPagerAddress; WinsockPort.WsPort := CurWSPort; SNPPPager.PagerID := CurPagerID; SNPPPager.Message := mmoMsg.Lines; SNPPPager.Send; end; procedure TForm1.SNPPQuit; begin SNPPPager.Quit; end; { Pager List Managaement } procedure TForm1.AddEntry(const Name, Protocol, Addr, PagerID: string); begin PagerList.WriteString('PAGERS', Name, Protocol + '|' + Addr + ',' + PagerID); GetUsers; end; procedure TForm1.btnEditClick(Sender: TObject); var Rslt: Integer; begin if lbUsers.ItemIndex = -1 then begin Application.MessageBox('No user selected', 'Error', MB_OK or MB_ICONINFORMATION); Exit; end; Form2.edName.Text := GetCurUser; Form2.edName.ReadOnly := TRUE; Form2.edPagerAddr.Text := edPagerAddr.Text; Form2.edPagerID.Text := edPagerID.Text; Form2.Caption := 'Update User'; Rslt := Form2.ShowModal; if Rslt = mrOK then begin AddEntry(Form2.edName.Text, EntryType[Form2.RadioGroup1.ItemIndex], Form2.edPagerAddr.Text, Form2.edPagerID.Text); GetUsers; end; Form2.ClearEds; end; procedure TForm1.btnAddClick(Sender: TObject); var Rslt: Integer; begin Form2.edName.ReadOnly := FALSE; Form2.Caption := 'Add New User'; Rslt := Form2.ShowModal; if Rslt = mrOK then begin AddEntry(Form2.edName.Text, EntryType[Form2.RadioGroup1.ItemIndex], Form2.edPagerAddr.Text, Form2.edPagerID.Text); GetUsers; end; Form2.ClearEds; end; procedure TForm1.btnRemoveClick(Sender: TObject); var Rslt: Integer; begin Rslt := Application.MessageBox('You are about to remove the selected user from the list, proceed?', 'Inquiry', MB_YESNO or MB_ICONQUESTION); if (Rslt = ID_YES) then begin PagerList.DeleteKey('PAGERS', GetCurUser); GetUsers; end; end; { Logging Management } procedure TForm1.InitLogFile; var LName, LPath: string; F: TextFile; begin LName := PagerINI.ReadString('INIT', 'LOGFILE', ''); LPath := ExtractFilePath(LName); LName := ExtractFileName(LName); if (not DirectoryExists(LPath)) then begin { no such directory, use default } LPath := ExtractFilePath(Application.ExeName); end; if (LName = '') or (not FileExists(LPath + LName)) then begin { create file } AssignFile(F, LPath + LName); ReWrite(F); CloseFile(F); { store new log path } PagerINI.WriteString('INIT', 'LOGFILE', LPath + LName); end; LogName := LPath + LName; end; procedure TForm1.ViewLog; begin Form3.Memo1.Lines.LoadFromFile(LogName); Form3.Edit1.Text := LogName; Form3.ShowModal; if Form3.Changed then begin LogName := Form3.Edit1.Text; PagerINI.WriteString('INIT', 'LOGFILE', LogName); SetLogFiles; InitLogFile; end; end; procedure TForm1.ClearLog; var Rslt: Integer; begin Rslt := Application.MessageBox('You are about to delete the pager log, proceed?', 'Inquiry', MB_YESNO or MB_ICONQUESTION); if (Rslt = ID_YES) then if FileExists(LogName) then begin DeleteFile(LogName); InitLogFile; end; end; procedure TForm1.SetLogging(AreLogging: Boolean); begin cbLogging.Checked := AreLogging; PagerINI.WriteBool('INIT', 'LOGGING', AreLogging); SetLogFiles; end; function TForm1.GetLogging: Boolean; begin Result := cbLogging.Checked; end; procedure TForm1.SetLogFiles; begin LogName := PagerINI.ReadString('INIT', 'LOGFILE', ''); InitLogFile; if Logging then begin TAPLog.HistoryName := LogName; SNPPLog.HistoryName := LogName; end else begin TAPLog.HistoryName := ''; SNPPLog.HistoryName := ''; end; end; procedure TForm1.SNPPPagerSNPPEvent(Sender: TObject; Code: Integer; Msg: String); begin mmoPageStatus.Lines.Add(Msg); end; end.
unit htStylePainter; interface uses Windows, Types, Graphics, htStyle; type ThtStylePainter = class private FPaintRect: TRect; FCanvas: TCanvas; FStyle: ThtStyle; FColor: TColor; protected procedure Borders4(inSide: ThtBorderSide; inL, inT, inR, inB: TColor); procedure PaintBorder(inSide: ThtBorderSide); procedure PaintDashEdge(inWidth: Integer; inSide: ThtBorderSide); procedure PaintDotEdge(inWidth: Integer; inSide: ThtBorderSide); procedure PaintDoubleEdge(inWidth: Integer; inSide: ThtBorderSide); procedure PaintInsetEdge(inWidth: Integer; inSide: ThtBorderSide); procedure PaintOutsetEdge(inWidth: Integer; inSide: ThtBorderSide); procedure PaintRectEdge(inStyle: TPenStyle; inWidth: Integer; inSide: ThtBorderSide); public constructor Create; procedure PaintBackground; procedure PaintBorders; procedure PaintColorBackground; procedure PaintInsetBorders; procedure PaintOutsetBorders; procedure PaintPictureBackground; procedure Prepare(inCanvas: TCanvas; inColor: TColor; inStyle: ThtStyle; const inRect: TRect); public property Color: TColor read FColor write FColor; property Canvas: TCanvas read FCanvas write FCanvas; property PaintRect: TRect read FPaintRect write FPaintRect; property Style: ThtStyle read FStyle write FStyle; end; var StylePainter: ThtStylePainter; implementation uses LrVclUtils, LrGraphics, htUtils, htInterfaces; function htGetRectEdge(const inRect: TRect; inSide: ThtBorderSide; inWidth: Integer = 0): TRect; begin with inRect do case inSide of bsLeft: Result := Rect(Left, Top, Left, Bottom-1); bsTop: Result := Rect(Left, Top, Right-1, Top); bsRight: Result := Rect(Right-inWidth-1, Top, Right-inWidth-1, Bottom-1); bsBottom: Result := Rect(Left, Bottom-inWidth-1, Right, Bottom-inWidth-1); end; end; procedure htInflateBySide(var ioRect: TRect; inD: Integer; inSide: ThtBorderSide); begin case inSide of bsLeft, bsRight: InflateRect(ioRect, inD, 0); bsTop, bsBottom: InflateRect(ioRect, 0, inD); end; end; constructor ThtStylePainter.Create; begin Color := clDefault; end; procedure ThtStylePainter.PaintDotEdge(inWidth: Integer; inSide: ThtBorderSide); var r: TRect; x, y, dx, dy: Single; l, c, i: Integer; begin r := PaintRect; InflateRect(r, -inWidth div 2, -inWidth div 2); r := htGetRectEdge(r, inSide); x := r.Left; dx := r.Right - x; y := r.Top; dy := r.Bottom - y; l := LrMax(Round(dx), Round(dy)); c := l div (inWidth * 2); dx := dx / c; dy := dy / c; with Canvas do begin Pen.Style := psSolid; Pen.Width := inWidth; for i := 0 to c do begin MoveTo(Round(x), Round(y)); LineTo(Round(x)+1, Round(y)); x := x + dx; y := y + dy; end; end; end; procedure ThtStylePainter.PaintDashEdge(inWidth: Integer; inSide: ThtBorderSide); const cDash = 6; cSpace = 3; cBolt = cDash + cSpace; var r: TRect; x, y, dx, dy: Single; d, s, b: Integer; l, c, i, wx, wy: Integer; begin r := PaintRect; Inc(r.Bottom); Inc(r.Right); r := htGetRectEdge(r, inSide, inWidth); // x := r.Left; y := r.Top; dx := r.Right - x; dy := r.Bottom - y; // d := inWidth * 2; if (d < 4) then d := 4; s := d div 2; b := d + s; // l := LrMax(Round(dx), Round(dy)) + s; c := (l + b div 2) div b; // if (dx < dy) then begin wx := inWidth; wy := d; dx := 0; dy := l / c; end else begin wx := d; wy := inWidth; dx := l / c; dy := 0; end; // with Canvas do begin for i := 0 to c do begin FillRect(Rect(Round(x), Round(y), Round(x) + wx, Round(y) + wy)); x := x + dx; y := y + dy; end; end; end; procedure ThtStylePainter.PaintRectEdge(inStyle: TPenStyle; inWidth: Integer; inSide: ThtBorderSide); var i: Integer; e, r: TRect; begin r := PaintRect; Canvas.Pen.Style := inStyle; for i := 1 to inWidth do begin e := htGetRectEdge(r, inSide); Canvas.MoveTo(e.Left, e.Top); Canvas.LineTo(e.Right, e.Bottom); htInflateBySide(r, -1, inSide); end; end; procedure ThtStylePainter.PaintOutsetEdge(inWidth: Integer; inSide: ThtBorderSide); begin case inSide of bsLeft, bsTop: Canvas.Pen.Color := $EEEEEE; bsRight, bsBottom: Canvas.Pen.Color := clBtnShadow; end; PaintRectEdge(psSolid, inWidth, inSide); end; procedure ThtStylePainter.PaintInsetEdge(inWidth: Integer; inSide: ThtBorderSide); begin case inSide of bsLeft, bsTop: Canvas.Pen.Color := clBtnShadow; bsRight, bsBottom: Canvas.Pen.Color := $EEEEEE; end; PaintRectEdge(psSolid, inWidth, inSide); end; procedure ThtStylePainter.PaintDoubleEdge(inWidth: Integer; inSide: ThtBorderSide); var wp, wx: Integer; begin wp := inWidth div 3; wx := inWidth - wp * 3; if (wp < 0) then PaintRectEdge(psSolid, inWidth, inSide) else begin PaintRectEdge(psSolid, wp, inSide); htInflateBySide(FPaintRect, -wp - wp - wx, inSide); PaintRectEdge(psSolid, wp, inSide); end; end; procedure ThtStylePainter.PaintBorder(inSide: ThtBorderSide); var w: Integer; c: TColor; begin w := Style.Border.GetBorderPixels(inSide); c := Style.Border.GetBorderColor(inSide); Canvas.Pen.Color := c; Canvas.Brush.Color := c; case Style.Border.GetBorderStyle(inSide) of bsSolidBorder: PaintRectEdge(psSolid, w, inSide); bsDotted: PaintDotEdge(w, inSide); bsDashed: PaintDashEdge(w, inSide); bsDouble: PaintDoubleEdge(w, inSide); bsOutset: PaintOutsetEdge(w, inSide); bsInset: PaintInsetEdge(w, inSide); end; Canvas.Pen.Width := 1; end; procedure ThtStylePainter.Borders4(inSide: ThtBorderSide; inL, inT, inR, inB: TColor); var r: TRect; begin with Canvas.Pen do case inSide of bsLeft, bsTop: Color := inL; else Color := inT; end; r := PaintRect; PaintRectEdge(psSolid, 1, inSide); InflateRect(FPaintRect, -1, -1); with Canvas.Pen do case inSide of bsLeft, bsTop: Color := inR; else Color := inB; end; PaintRectEdge(psSolid, 1, inSide); PaintRect := r; end; procedure ThtStylePainter.PaintInsetBorders; var i: ThtBorderSide; begin for i := bsLeft to bsBottom do case Style.Border.GetBorderStyle(i) of bsDefault: Borders4(i, clBlack, $EEEEEE, clBtnShadow, Color) else PaintBorder(i); end; end; procedure ThtStylePainter.PaintOutsetBorders; var i: ThtBorderSide; begin for i := bsLeft to bsBottom do case Style.Border.GetBorderStyle(i) of bsDefault: Borders4(i, clWhite, clBtnShadow, $EEEEEE, clBlack) else PaintBorder(i); end; end; procedure ThtStylePainter.PaintBorders; var i: ThtBorderSide; begin for i := bsLeft to bsBottom do PaintBorder(i); end; procedure ThtStylePainter.PaintPictureBackground; begin if Style.Background.Picture.HasGraphic then LrTileGraphic(Canvas, PaintRect, Style.Background.Picture.Graphic) end; procedure ThtStylePainter.PaintColorBackground; begin if htVisibleColor(Color) then with Canvas do begin Brush.Color := Color; FillRect(PaintRect); end; end; procedure ThtStylePainter.PaintBackground; begin if Style.Background.Picture.HasGraphic then PaintPictureBackground else PaintColorBackground; end; procedure ThtStylePainter.Prepare(inCanvas: TCanvas; inColor: TColor; inStyle: ThtStyle; const inRect: TRect); begin Canvas := inCanvas; Color := inColor; Style := inStyle; PaintRect := inRect; end; initialization StylePainter := ThtStylePainter.Create; finalization StylePainter.Free; end.
unit XED.OperandEnum; {$Z4} interface type TXED_Operand_Enum = ( XED_OPERAND_INVALID, XED_OPERAND_AGEN, XED_OPERAND_AMD3DNOW, XED_OPERAND_ASZ, XED_OPERAND_BASE0, XED_OPERAND_BASE1, XED_OPERAND_BCAST, XED_OPERAND_BCRC, XED_OPERAND_BRDISP_WIDTH, XED_OPERAND_CET, XED_OPERAND_CHIP, XED_OPERAND_CLDEMOTE, XED_OPERAND_DEFAULT_SEG, XED_OPERAND_DF32, XED_OPERAND_DF64, XED_OPERAND_DISP, XED_OPERAND_DISP_WIDTH, XED_OPERAND_DUMMY, XED_OPERAND_EASZ, XED_OPERAND_ELEMENT_SIZE, XED_OPERAND_ENCODER_PREFERRED, XED_OPERAND_ENCODE_FORCE, XED_OPERAND_EOSZ, XED_OPERAND_ERROR, XED_OPERAND_ESRC, XED_OPERAND_FIRST_F2F3, XED_OPERAND_HAS_MODRM, XED_OPERAND_HAS_SIB, XED_OPERAND_HINT, XED_OPERAND_ICLASS, XED_OPERAND_ILD_F2, XED_OPERAND_ILD_F3, XED_OPERAND_ILD_SEG, XED_OPERAND_IMM0, XED_OPERAND_IMM0SIGNED, XED_OPERAND_IMM1, XED_OPERAND_IMM1_BYTES, XED_OPERAND_IMM_WIDTH, XED_OPERAND_INDEX, XED_OPERAND_LAST_F2F3, XED_OPERAND_LLRC, XED_OPERAND_LOCK, XED_OPERAND_LZCNT, XED_OPERAND_MAP, XED_OPERAND_MASK, XED_OPERAND_MAX_BYTES, XED_OPERAND_MEM0, XED_OPERAND_MEM1, XED_OPERAND_MEM_WIDTH, XED_OPERAND_MOD, XED_OPERAND_MODE, XED_OPERAND_MODEP5, XED_OPERAND_MODEP55C, XED_OPERAND_MODE_FIRST_PREFIX, XED_OPERAND_MODE_SHORT_UD0, XED_OPERAND_MODRM_BYTE, XED_OPERAND_MPXMODE, XED_OPERAND_MUST_USE_EVEX, XED_OPERAND_NEEDREX, XED_OPERAND_NEED_MEMDISP, XED_OPERAND_NEED_SIB, XED_OPERAND_NELEM, XED_OPERAND_NOMINAL_OPCODE, XED_OPERAND_NOREX, XED_OPERAND_NO_SCALE_DISP8, XED_OPERAND_NPREFIXES, XED_OPERAND_NREXES, XED_OPERAND_NSEG_PREFIXES, XED_OPERAND_OSZ, XED_OPERAND_OUTREG, XED_OPERAND_OUT_OF_BYTES, XED_OPERAND_P4, XED_OPERAND_POS_DISP, XED_OPERAND_POS_IMM, XED_OPERAND_POS_IMM1, XED_OPERAND_POS_MODRM, XED_OPERAND_POS_NOMINAL_OPCODE, XED_OPERAND_POS_SIB, XED_OPERAND_PREFIX66, XED_OPERAND_PTR, XED_OPERAND_REALMODE, XED_OPERAND_REG_, // Modified by Max 19/07/2021 12:49:52 conflitto con funzione 'xed_operand_reg' XED_OPERAND_REG0, XED_OPERAND_REG1, XED_OPERAND_REG2, XED_OPERAND_REG3, XED_OPERAND_REG4, XED_OPERAND_REG5, XED_OPERAND_REG6, XED_OPERAND_REG7, XED_OPERAND_REG8, XED_OPERAND_REG9, XED_OPERAND_RELBR, XED_OPERAND_REP, XED_OPERAND_REX, XED_OPERAND_REXB, XED_OPERAND_REXR, XED_OPERAND_REXRR, XED_OPERAND_REXW, XED_OPERAND_REXX, XED_OPERAND_RM, XED_OPERAND_ROUNDC, XED_OPERAND_SAE, XED_OPERAND_SCALE, XED_OPERAND_SEG0, XED_OPERAND_SEG1, XED_OPERAND_SEG_OVD, XED_OPERAND_SIBBASE, XED_OPERAND_SIBINDEX, XED_OPERAND_SIBSCALE, XED_OPERAND_SMODE, XED_OPERAND_SRM, XED_OPERAND_TZCNT, XED_OPERAND_UBIT, XED_OPERAND_UIMM0, XED_OPERAND_UIMM1, XED_OPERAND_USING_DEFAULT_SEGMENT0, XED_OPERAND_USING_DEFAULT_SEGMENT1, XED_OPERAND_VEXDEST210, XED_OPERAND_VEXDEST3, XED_OPERAND_VEXDEST4, XED_OPERAND_VEXVALID, XED_OPERAND_VEX_C4, XED_OPERAND_VEX_PREFIX, XED_OPERAND_VL, XED_OPERAND_WBNOINVD, XED_OPERAND_ZEROING, XED_OPERAND_LAST); /// This converts strings to #xed_operand_enum_t types. /// @param s A C-string. /// @return #xed_operand_enum_t /// @ingroup ENUM function str2xed_operand_enum_t(s: PAnsiChar): TXED_Operand_Enum; cdecl; external 'xed.dll'; /// This converts strings to #xed_operand_enum_t types. /// @param p An enumeration element of type xed_operand_enum_t. /// @return string /// @ingroup ENUM function xed_operand_enum_t2str(const p: TXED_Operand_Enum): PAnsiChar; cdecl; external 'xed.dll'; /// Returns the last element of the enumeration /// @return xed_operand_enum_t The last element of the enumeration. /// @ingroup ENUM function xed_operand_enum_t_last:TXED_Operand_Enum;cdecl; external 'xed.dll'; implementation end.
unit ProductsViewFrame; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Interfaces, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, cxDataControllerConditionalFormattingRulesManagerDialog, Data.DB, cxDBData, cxGridLevel, cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, Vcl.ExtCtrls, Vcl.Buttons, Vcl.Menus, Vcl.StdCtrls, cxButtons, Aurelius.Bind.Dataset, System.Generics.Collections, DataModels; type TProductsView = class(TFrame, IProductsView) Panel1: TPanel; View: TcxGridDBTableView; Level: TcxGridLevel; Grid: TcxGrid; Button1: TButton; ProductsDataSet: TAureliusDataset; ProductsDataSource: TDataSource; Button2: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private FPresenter: IProductsPresenter; FMain: IMainView; { Private declarations } public procedure SetPresenter(APresenter: IProductsPresenter); procedure SetMainAndPanel(AMain: IMainView; APanel: IPanelFrame); procedure ShowData(AProducts: TList<TProducts>); end; implementation {$R *.dfm} { TFrame1 } procedure TProductsView.Button1Click(Sender: TObject); begin FMain.CloseTab(Self.Parent as IPanelFrame); end; procedure TProductsView.Button2Click(Sender: TObject); begin FPresenter.LoadData; end; procedure TProductsView.SetMainAndPanel(AMain: IMainView; APanel: IPanelFrame); begin FMain := AMain; Self.Parent := TWinControl(APanel); Self.Name := 'ProductsView' + IntToStr(Self.Parent.Tag); end; procedure TProductsView.SetPresenter(APresenter: IProductsPresenter); begin FPresenter := APresenter; end; procedure TProductsView.ShowData(AProducts: TList<TProducts>); begin ProductsDataSet.SetSourceList(AProducts); ProductsDataSet.Open; View.DataController.CreateAllItems(); end; end.
program au; uses Classes, SysUtils; procedure Info; begin writeln('program convert project between Ansi and UTF8'); writeln('convert *.dpr, *.pas and *.dfm in current directory'); writeln('usage: au paramneter'); writeln('ansi convert to Ansi'); writeln('utf8 convert to UTF8'); end; //from SynEdit type TSaveFormat = (sfUTF16LSB, sfUTF16MSB, sfUTF8, sfUTF8NoBOM, sfAnsi); const UTF8BOM: array[0..2] of Byte = ($EF, $BB, $BF); UTF16BOMLE: array[0..1] of Byte = ($FF, $FE); UTF16BOMBE: array[0..1] of Byte = ($FE, $FF); UTF32BOMLE: array[0..3] of Byte = ($FF, $FE, $00, $00); UTF32BOMBE: array[0..3] of Byte = ($00, $00, $FE, $FF); function DetectBOM(Stream: TStream): TSaveFormat; var ByteOrderMask: array[0..3] of Byte; BytesRead: Integer; begin Stream.Position:=0; BytesRead := Stream.Read(ByteOrderMask[0], SizeOf(ByteOrderMask)); if (BytesRead >= 2) and (ByteOrderMask[0] = UTF16BOMLE[0]) and (ByteOrderMask[1] = UTF16BOMLE[1]) then result:=sfUTF16LSB else if (BytesRead >= 2) and (ByteOrderMask[0] = UTF16BOMBE[0]) and (ByteOrderMask[1] = UTF16BOMBE[1]) then result:=sfUTF16MSB else if (BytesRead >= 3) and (ByteOrderMask[0] = UTF8BOM[0]) and (ByteOrderMask[1] = UTF8BOM[1]) and (ByteOrderMask[2] = UTF8BOM[2]) then result:=sfUTF8 else result:=sfAnsi; end; procedure ConvertAnsiToUTF8(Filename:string); var SA: AnsiString; SW: UnicodeString; Stream: TFileStream; Size: integer; begin Stream := TFileStream.Create(Filename, fmOpenRead); Size := Stream.Size - Stream.Position; SetLength(SA, Size div SizeOf(AnsiChar)); Stream.Read(SA[1], Size); Stream.Free; SW := SA; SA := UTF8Encode(SW); Stream:=TFileStream.Create(Filename, fmCreate); Stream.WriteBuffer(UTF8BOM[0], SizeOf(UTF8BOM)); Stream.WriteBuffer(SA[1], Length(SA) * SizeOf(AnsiChar)); Stream.Free; writeln(Filename,' - converted Ansi -> UTF8 with BOM'); end; procedure ConvertUTF8ToAnsi(Filename:string); var SA: AnsiString; SW: UnicodeString; Stream: TFileStream; Size: integer; Len: integer; begin Stream := TFileStream.Create(Filename, fmOpenRead); Stream.Position := SizeOf(UTF8BOM); Size := Stream.Size - Stream.Position; SetLength(SA, Size div SizeOf(AnsiChar)); Stream.Read(SA[1], Size); Stream.Free; SW := UTF8Decode(SA); SA := SW; Stream:=TFileStream.Create(Filename, fmCreate); Len := Length(SA); Stream.WriteBuffer(SA[1], Len * SizeOf(AnsiChar)); Stream.Free; writeln(Filename,' - converted UTF8 with BOM -> Ansi'); end; procedure ProcessFile(Filename:string; toUTF8:boolean); var Stream: TFileStream; Bom: TSaveFormat; begin Stream:=TFileStream.Create(Filename, fmOpenRead); Bom:=DetectBOM(Stream); Stream.Free; if (Bom<>sfUTF8)and(Bom<>sfAnsi) then writeln(Filename,' detect 16 bit Unicode BOM, no changes') else begin if (Bom=sfUTF8)and toUTF8 then writeln(Filename,' already has UTF8 BOM') else if (Bom=sfAnsi)and not toUTF8 then writeln(Filename,' has no UTF8 BOM') else if toUTF8 then ConvertAnsiToUTF8(Filename) else ConvertUTF8ToAnsi(Filename); end; end; procedure ScanDir(toUTF8: boolean); var SearchResult : TSearchRec; extstr: string; strings: TStringList; i: integer; begin strings:=TStringList.Create; if FindFirst('*', faAnyFile, SearchResult) = 0 then begin repeat extstr := LowerCase(ExtractFileExt(SearchResult.Name)); if (extstr='.dpr')or(extstr='.pas')or(extstr='.dfm') then strings.Add(SearchResult.Name); until FindNext(SearchResult) <> 0; FindClose(searchResult); end; for i:=0 to strings.Count-1 do ProcessFile(strings[i], toUTF8); strings.Free; end; begin if (ParamCount=1)and((ParamStr(1)='ansi') or (ParamStr(1)='utf8')) then ScanDir(ParamStr(1)='utf8') else Info; end.
unit Myclass; {$mode objfpc}{$H+} interface uses Classes, SysUtils, forms; type { 订单数据! 订单数据! 订单数据! 订单数据! 订单数据! 订单数据! 订单数据! 订单数据! 订单数据! } {TOrderItem 订单结构} TOrderItem = packed record Number:string[10]; //订单号 Date:integer; //成交日 Code:string[6]; //股代码 StockName:string[20]; Market:string[2]; quantity:integer; //数量 Orig_price:double; //下单时单价 Deal_Price:double; //成交价 Amount:double; //总金额 direct:boolean; //交易方向 true为买 status:boolean; //成交状态 true为已成交 end; POrderItem = ^TOrderItem; {THistoryOrder 历史订单列表} THistoryOrder = class(Tcomponent) private Flist:Tlist; function GetCount: integer; public constructor Create(AOwner:TComponent); override; destructor Destroy; override; procedure Clear; function Add(Avalue:TOrderItem):integer; //过了今天的成交订单移入 procedure LoadFromFile(AFilename:String); //分时读取更新 procedure SaveToFile(AFilename:String); //将更新后的订单存到文件 function Item(AIndex:integer):TOrderItem; property Count:integer read GetCount; end; {TCurrentOrder 当日订单列表} TCurrentOrder = class(Tcomponent) private Flist:Tlist; function GetCount: integer; public constructor Create(AOwner:TComponent); override; destructor Destroy; override; procedure Clear; function Add(AValue:TorderItem):integer; //下订单 function Delete(AIndex:integer):boolean; //过了今天的成交订单移入 function Item(AIndex:integer):TOrderItem; procedure LoadFromFile(AFilename:String); //分时读取更新 procedure SaveToFile(AFilename:String); //将更新后的订单存到文件 property Count:integer read GetCount; end; implementation //订单 { THistoryOrder } function THistoryOrder.GetCount: integer; begin Result:=FList.Count; end; constructor THistoryOrder.Create(AOwner: TComponent); begin inherited Create(AOwner); Flist:=Tlist.Create; end; destructor THistoryOrder.Destroy; begin Clear; Flist.Free; inherited Destroy; end; procedure THistoryOrder.Clear; var i:integer; begin for i:=0 to FList.Count-1 do begin Dispose(POrderItem(FList.Items[i])); end; FList.Clear; end; function THistoryOrder.Add(Avalue: TOrderItem): integer; var m:POrderItem; begin new(m); m^.Number:=AValue.Number; m^.Date:=AValue.Date; m^.Code:=AValue.Code; m^.StockName:=AValue.StockName; m^.Market:=AValue.Market; m^.quantity:=AValue.quantity; m^.Orig_price:=AValue.Orig_price; m^.Deal_price:=AValue.Deal_price; m^.Amount:=AValue.AMount; m^.direct:=AValue.direct; m^.Status:=AValue.Status; Result:=Flist.Add(m); end; procedure THistoryOrder.LoadFromFile(AFilename:String); var mcount:integer; mFile:TFileStream; i:integer; mItem:TOrderItem; begin mFile:=TFileStream.Create(AFilename,fmOpenRead); Clear; mFile.Seek(0,soBeginning); mFile.Read(mcount,sizeof(mcount)); Clear; for i:=0 to mCount-1 do begin mFile.Read(mItem,sizeof(mitem)); Add(mItem); end; mFile.Free; end; procedure THistoryOrder.SaveToFile(AFilename:String); var mcount:integer; mFile:TFileStream; i:integer; mItem:TOrderItem; begin mFile:=TFileStream.Create(AFilename,fmCreate); mcount:=FList.Count; mFile.Seek(0,soBeginning); mFile.Write(mcount,sizeof(mcount)); for i:=0 to FList.Count-1 do begin mItem:=Self.Item(i); mFile.Write(mItem,sizeof(mitem)); end; mFile.Free; end; function THistoryOrder.Item(AIndex: integer): TOrderItem; var m:POrderItem; begin m:=POrderItem(Flist.Items[AIndex]); Result.Number:=m^.Number; Result.Date:=m^.Date; Result.Code:=m^.Code; Result.StockName:=m^.StockName; Result.Market:=m^.Market; Result.quantity:=m^.quantity; Result.Orig_price:=m^.Orig_price; Result.Deal_price:=m^.Deal_price; Result.Amount:=m^.Amount; Result.direct:=m^.direct; Result.status:=m^.status; end; { TCurrentOrder } function TCurrentOrder.GetCount: integer; begin Result:=FList.Count; end; constructor TCurrentOrder.Create(AOwner: TComponent); begin inherited Create(AOwner); FList:=TList.Create; end; destructor TCurrentOrder.Destroy; begin Clear; Flist.Free; inherited Destroy; end; procedure TCurrentOrder.Clear; var i:integer; begin for i:=0 to FList.Count-1 do begin Dispose(POrderItem(FList.Items[i])); end; FList.Clear; end; function TCurrentOrder.Add(AValue: TorderItem): integer; var m:POrderItem; begin new(m); m^.Number:=AValue.Number; m^.Date:=AValue.Date; m^.Code:=AValue.Code; m^.StockName:=AValue.StockName; m^.Market:=AValue.Market; m^.quantity:=AValue.quantity; m^.Orig_price:=AValue.Orig_price; m^.Deal_price:=AValue.Deal_price; m^.Amount:=AValue.AMount; m^.direct:=AValue.direct; m^.Status:=AValue.Status; Result:=Flist.Add(m); end; function TCurrentOrder.Delete(AIndex: integer): boolean; begin try Flist.Delete(AIndex); result:=true; except result:=False; end; end; function TCurrentOrder.Item(AIndex: integer): TOrderItem; var m:POrderItem; begin m:=POrderItem(Flist.Items[AIndex]); Result.Number:=m^.Number; Result.Date:=m^.Date; Result.Code:=m^.Code; Result.StockName:=m^.StockName; Result.Market:=m^.Market; Result.quantity:=m^.quantity; Result.Orig_price:=m^.Orig_price; Result.Deal_price:=m^.Deal_price; Result.Amount:=m^.Amount; Result.direct:=m^.direct; Result.status:=m^.status; end; procedure TCurrentOrder.LoadFromFile(AFilename:String); var mcount:integer; mFile:TFileStream; i:integer; mItem:TOrderItem; begin mFile:=TFileStream.Create(AFilename,fmOpenRead); Clear; mFile.Seek(0,soBeginning); mFile.Read(mcount,sizeof(mcount)); for i:=0 to mCount-1 do begin mFile.Read(mItem,sizeof(mItem)); Add(mItem); end; mFile.Free; end; procedure TCurrentOrder.SaveToFile(AFilename:String); var mcount:integer; mFile:TFileStream; i:integer; mItem:TOrderItem; begin mFile:=TFileStream.Create(AFilename,fmCreate); mcount:=FList.Count; mFile.Seek(0,soBeginning); mFile.Write(mcount,sizeof(mcount)); for i:=0 to FList.Count-1 do begin mItem:=Self.Item(i); mFile.Write(mItem,sizeof(mItem)); end; mFile.Free; end; end.
{------------------------------------------------------------------------------- This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. -------------------------------------------------------------------------------} {=============================================================================== zlib bindings (expected zlib version: 1.2.11) Common types, constants and functions These units provides plain (no wrappers or helpers) bindings for zlib library. Most comments were copied directly from zlib.h header without any change. This binding is distributed with all necessary binaries (object files, DLLs) precompiled. For details please refer to file bin_readme.txt. ©František Milt 2019-03-26 Version 1.1 Contacts: František Milt: frantisek.milt@gmail.com Support: If you find this code useful, please consider supporting the author by making a small donation using following link(s): https://www.paypal.me/FMilt Dependencies: AuxTypes - github.com/ncs-sniper/Lib.AuxTypes * StrRect - github.com/ncs-sniper/Lib.StrRect StrRect is required only for dynamically linked part of the binding (unit ZLibDynamic) and only when compiler for Windows OS. ===============================================================================} unit ZLibCommon; {$INCLUDE '.\ZLib_defs.inc'} interface uses SysUtils, AuxTypes; {=============================================================================== Basic constants and types ===============================================================================} const {$IFDEF Windows} LibName = 'zlib1.dll'; {$ELSE} LibName = 'libz.so.1.2.11'; {$ENDIF} type int = Int32; pint = ^int; off64_t = Int64; size_t = PtrUInt; uInt = UInt32; puInt = ^uInt; {$IF Defined(Linux) and Defined(x64)} off_t = Int64; long = Int64; uLong = UInt64; puLong = ^uLong; {$ELSE} off_t = Int32; long = Int32; uLong = UInt32; puLong = ^uLong; {$IFEND} unsigned = UInt32; punsigned = ^unsigned; PPByte = ^PByte; {=============================================================================== Zlib constants and types ===============================================================================} const z_errmsg: array[0..9] of PAnsiChar = ( 'need dictionary', // Z_NEED_DICT 2 'stream end', // Z_STREAM_END 1 '', // Z_OK 0 'file error', // Z_ERRNO (-1) 'stream error', // Z_STREAM_ERROR (-2) 'data error', // Z_DATA_ERROR (-3) 'insufficient memory', // Z_MEM_ERROR (-4) 'buffer error', // Z_BUF_ERROR (-5) 'incompatible version', // Z_VERSION_ERROR (-6) ''); type z_size_t = size_t; z_off_t = off_t; z_off64_t = off64_t; z_crc_t = UInt32; pz_crc_t = ^z_crc_t; const MAX_MEM_LEVEL = 9; MAX_WBITS = 15; DEF_MEM_LEVEL = 8; DEF_WBITS = MAX_WBITS; SEEK_SET = 0; (* Seek from beginning of file. *) SEEK_CUR = 1; (* Seek from current position. *) SEEK_END = 2; (* Set file pointer to EOF plus "offset" *) WBITS_RAW = -15; WBITS_ZLIB = 15; WBITS_GZIP = 31; const ZLIB_VERSION = AnsiString('1.2.11'); ZLIB_VERNUM = $12b0; ZLIB_VER_MAJOR = 1; ZLIB_VER_MINOR = 2; ZLIB_VER_REVISION = 11; ZLIB_VER_SUBREVISION = 0; (* The 'zlib' compression library provides in-memory compression and decompression functions, including integrity checks of the uncompressed data. This version of the library supports only one compression method (deflation) but other algorithms will be added later and will have the same stream interface. Compression can be done in a single step if the buffers are large enough, or can be done by repeated calls of the compression function. In the latter case, the application must provide more input and/or consume the output (providing more output space) before each call. The compressed data format used by default by the in-memory functions is the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped around a deflate stream, which is itself documented in RFC 1951. The library also supports reading and writing files in gzip (.gz) format with an interface similar to that of stdio using the functions that start with "gz". The gzip format is different from the zlib format. gzip is a gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. This library can optionally read and write gzip and raw deflate streams in memory as well. The zlib format was designed to be compact and fast for use in memory and on communications channels. The gzip format was designed for single- file compression on file systems, has a larger header than zlib to maintain directory information, and uses a different, slower check method than zlib. The library does not install any signal handler. The decoder checks the consistency of the compressed data, so the library should never crash even in the case of corrupted input. *) type alloc_func = Function(opaque: Pointer; items, size: uInt): Pointer; cdecl; free_func = procedure(opaque, address: Pointer); cdecl; internal_state = record end; z_stream_s = record next_in: PByte; (* next input byte *) avail_in: uInt; (* number of bytes available at next_in *) total_in: uLong; (* total number of input bytes read so far *) next_out: PByte; (* next output byte will go here *) avail_out: uInt; (* remaining free space at next_out *) total_out: uLong; (* total number of bytes output so far *) msg: PAnsiChar; (* last error message, NULL if no error *) state: ^internal_state; (* not visible by applications *) zalloc: alloc_func; (* used to allocate the internal state *) zfree: free_func; (* used to free the internal state *) opaque: Pointer; (* private data object passed to zalloc and zfree *) data_type: int; (* best guess about the data type: binary or text for deflate, or the decoding state for inflate *) adler: uLong; (* Adler-32 or CRC-32 value of the uncompressed data *) reserved: uLong; (* reserved for future use *) end; z_stream = z_stream_s; z_streamp = ^z_stream_s; (* gzip header information passed to and from zlib routines. See RFC 1952 for more details on the meanings of these fields. *) gz_header_s = record text: int; (* true if compressed data believed to be text *) time: uLong; (* modification time *) xflags: int; (* extra flags (not used when writing a gzip file) *) os: int; (* operating system *) extra: PByte; (* pointer to extra field or Z_NULL if none *) extra_len: uInt; (* extra field length (valid if extra != Z_NULL) *) extra_max: uInt; (* space at extra (only when reading header) *) name: PByte; (* pointer to zero-terminated file name or Z_NULL *) name_max: uInt; (* space at name (only when reading header) *) comment: PByte; (* pointer to zero-terminated comment or Z_NULL *) comm_max: uInt; (* space at comment (only when reading header) *) hcrc: int; (* true if there was or will be a header crc *) done: int; (* true when done reading gzip header (not used when writing a gzip file) *) end; gz_header = gz_header_s; gz_headerp = ^gz_header; (* The application must update next_in and avail_in when avail_in has dropped to zero. It must update next_out and avail_out when avail_out has dropped to zero. The application must initialize zalloc, zfree and opaque before calling the init function. All other fields are set by the compression library and must not be updated by the application. The opaque value provided by the application will be passed as the first parameter for calls of zalloc and zfree. This can be useful for custom memory management. The compression library attaches no meaning to the opaque value. zalloc must return Z_NULL if there is not enough memory for the object. If zlib is used in a multi-threaded application, zalloc and zfree must be thread safe. In that case, zlib is thread-safe. When zalloc and zfree are Z_NULL on entry to the initialization function, they are set to internal routines that use the standard library functions malloc() and free(). On 16-bit systems, the functions zalloc and zfree must be able to allocate exactly 65536 bytes, but will not be required to allocate more than this if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers returned by zalloc for objects of exactly 65536 bytes *must* have their offset normalized to zero. The default allocation function provided by this library ensures this (see zutil.c). To reduce memory requirements and avoid any allocation of 64K objects, at the expense of compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h). The fields total_in and total_out can be used for statistics or progress reports. After compression, total_in holds the total size of the uncompressed data and may be saved for use by the decompressor (particularly if the decompressor wants to decompress everything in a single step). *) (* constants *) const Z_NO_FLUSH = 0; Z_PARTIAL_FLUSH = 1; Z_SYNC_FLUSH = 2; Z_FULL_FLUSH = 3; Z_FINISH = 4; Z_BLOCK = 5; Z_TREES = 6; (* Allowed flush values; see deflate() and inflate() below for details *) Z_OK = 0; Z_STREAM_END = 1; Z_NEED_DICT = 2; Z_ERRNO = -1; Z_STREAM_ERROR = -2; Z_DATA_ERROR = -3; Z_MEM_ERROR = -4; Z_BUF_ERROR = -5; Z_VERSION_ERROR = -6; (* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. *) Z_NO_COMPRESSION = 0; Z_BEST_SPEED = 1; Z_BEST_COMPRESSION = 9; Z_DEFAULT_COMPRESSION = -1; (* compression levels *) Z_FILTERED = 1; Z_HUFFMAN_ONLY = 2; Z_RLE = 3; Z_FIXED = 4; Z_DEFAULT_STRATEGY = 0; (* compression strategy; see deflateInit2() below for details *) Z_BINARY = 0; Z_TEXT = 1; Z_ASCII = Z_TEXT; (* for compatibility with 1.2.2 and earlier *) Z_UNKNOWN = 2; (* Possible values of the data_type field for deflate() *) Z_DEFLATED = 8; (* The deflate compression method (the only one supported in this version) *) Z_NULL = nil; (* for initializing zalloc, zfree, opaque *) type in_func = Function(Ptr: Pointer; Buff: PPByte): unsigned; cdecl; out_func = Function(Ptr: Pointer; Buff: PByte; Len: unsigned): int; cdecl; gzFile_s = record have: unsigned; next: PByte; pos: z_off64_t; end; gzFile = ^gzFile_s; (* semi-opaque gzip file descriptor *) {=============================================================================== Auxiliary types and functions ===============================================================================} type EZLibException = class(Exception); TModuleHandle = {$IFDEF Windows}THandle{$ELSE}Pointer{$ENDIF}; procedure CheckCompatibility(Flags: uLong); Function GetCheckProcAddress(Module: TModuleHandle; ProcName: String): Pointer; implementation uses {$IFDEF Windows}Windows{$ELSE}dl{$ENDIF}; procedure CheckCompatibility(Flags: uLong); begin // check sizes of integer types Assert((Flags and 3) = 1,'uInt is not 32bit in size'); {$IF Defined(Linux) and Defined(x64)} Assert(((Flags shr 2) and 3) = 2,'uLong is not 64bit in size'); Assert(((Flags shr 6) and 3) = 2,'z_off_t is not 64bit in size'); {$ELSE} Assert(((Flags shr 2) and 3) = 1,'uLong is not 32bit in size'); Assert(((Flags shr 6) and 3) = 1,'z_off_t is not 32bit in size'); {$IFEND} {$IFDEF x64} Assert(((Flags shr 4) and 3) = 2,'voidpf is not 64bit in size'); {$ELSE} Assert(((Flags shr 4) and 3) = 1,'voidpf is not 32bit in size'); {$ENDIF} // check whether calling convention is *not* STDCALL (ie. it is CDECL)) Assert(((Flags shr 10) and 1) = 0,'incomatible calling convention'); // check if all funcionality is available Assert(((Flags shr 16) and 1) = 0,'gz* functions cannot compress'); Assert(((Flags shr 17) and 1) = 0,'unable to write gzip stream'); end; //------------------------------------------------------------------------------ Function GetCheckProcAddress(Module: TModuleHandle; ProcName: String): Pointer; begin {$IFDEF Windows} Result := GetProcAddress(Module,PChar(ProcName)); {$ELSE} Result := dlsym(Module,PChar(ProcName)); {$ENDIF} If not Assigned(Result) then raise EZLibException.CreateFmt('GetCheckProcAddress: Address of function "%s" could not be obtained',[ProcName]); end; end.
unit uTPLb_StrUtils; interface uses SysUtils; function AnsiBytesOf(const S: string): TBytes; implementation function AnsiBytesOf(const S: string): TBytes; begin Result := TEncoding.ANSI.GetBytes(S); end; end.
// // VXScene Component Library, based on GLScene http://glscene.sourceforge.net // { A shader that applies cel shading through a vertex program and shade definition texture. } unit VXS.CelShader; interface {$I VXScene.inc} uses System.Classes, System.SysUtils, VXS.OpenGL, VXS.Texture, VXS.Context, VXS.Graphics, VXS.Utils, VXS.VectorGeometry, VXS.Color, VXS.RenderContextInfo, VXS.Material, VXS.State, VXS.TextureFormat; type { Cel shading options. csoOutlines: Render a second outline pass. csoTextured: Allows for a primary texture that the cel shading is modulated with and forces the shade definition to render as a second texture. } TVXCelShaderOption = (csoOutlines, csoTextured, csoNoBuildShadeTexture); TVXCelShaderOptions = set of TVXCelShaderOption; // An event for user defined cel intensity. TVXCelShaderGetIntensity = procedure(Sender: TObject; var intensity: Byte) of object; { A generic cel shader. } TVXCelShader = class(TVXShader) private FOutlineWidth: Single; FCelShaderOptions: TVXCelShaderOptions; FVPHandle: TVXVertexProgramHandle; FShadeTexture: TVXTexture; FOnGetIntensity: TVXCelShaderGetIntensity; FOutlinePass, FUnApplyShadeTexture: Boolean; FOutlineColor: TVXColor; protected procedure SetCelShaderOptions(const val: TVXCelShaderOptions); procedure SetOutlineWidth(const val: Single); procedure SetOutlineColor(const val: TVXColor); procedure BuildShadeTexture; procedure Loaded; override; function GenerateVertexProgram: string; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure DoApply(var rci: TVXRenderContextInfo; Sender: TObject); override; function DoUnApply(var rci: TVXRenderContextInfo): Boolean; override; property ShadeTexture: TVXTexture read FShadeTexture; published property CelShaderOptions: TVXCelShaderOptions read FCelShaderOptions write SetCelShaderOptions; property OutlineColor: TVXColor read FOutlineColor write SetOutlineColor; property OutlineWidth: Single read FOutlineWidth write SetOutlineWidth; property OnGetIntensity: TVXCelShaderGetIntensity read FOnGetIntensity write FOnGetIntensity; end; // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------ // ------------------ TVXCelShader ------------------ // ------------------ constructor TVXCelShader.Create(AOwner: TComponent); begin inherited; FOutlineWidth := 3; FCelShaderOptions := [csoOutlines]; FShadeTexture := TVXTexture.Create(Self); with FShadeTexture do begin Enabled := True; MinFilter := miNearest; MagFilter := maNearest; TextureWrap := twNone; TextureMode := tmModulate; end; FOutlineColor := TVXColor.Create(Self); FOutlineColor.OnNotifyChange := NotifyChange; FOutlineColor.Initialize(clrBlack); ShaderStyle := ssLowLevel; FVPHandle := TVXVertexProgramHandle.Create; end; destructor TVXCelShader.Destroy; begin FVPHandle.Free; FShadeTexture.Free; FOutlineColor.Free; inherited; end; procedure TVXCelShader.Loaded; begin inherited; BuildShadeTexture; end; procedure TVXCelShader.BuildShadeTexture; var bmp32: TVXBitmap32; i: Integer; intensity: Byte; begin if csoNoBuildShadeTexture in FCelShaderOptions then exit; with FShadeTexture do begin ImageClassName := 'TVXBlankImage'; TVXBlankImage(Image).Width := 128; TVXBlankImage(Image).Height := 2; end; bmp32 := FShadeTexture.Image.GetBitmap32; bmp32.Blank := false; for i := 0 to bmp32.Width - 1 do begin intensity := i * (256 div bmp32.Width); if Assigned(FOnGetIntensity) then FOnGetIntensity(Self, intensity) else begin if intensity > 230 then intensity := 255 else if intensity > 150 then intensity := 230 else if intensity > 100 then intensity := intensity + 50 else intensity := 150; end; bmp32.Data^[i].r := intensity; bmp32.Data^[i].g := intensity; bmp32.Data^[i].b := intensity; bmp32.Data^[i].a := 1; bmp32.Data^[i + bmp32.Width] := bmp32.Data^[i]; end; end; function TVXCelShader.GenerateVertexProgram: string; var VP: TStringList; begin VP := TStringList.Create; VP.Add('!!ARBvp1.0'); VP.Add('OPTION ARB_position_invariant;'); VP.Add('PARAM mvinv[4] = { state.matrix.modelview.inverse };'); VP.Add('PARAM lightPos = program.local[0];'); VP.Add('TEMP temp, light, normal;'); VP.Add(' DP4 light.x, mvinv[0], lightPos;'); VP.Add(' DP4 light.y, mvinv[1], lightPos;'); VP.Add(' DP4 light.z, mvinv[2], lightPos;'); VP.Add(' ADD light, light, -vertex.position;'); VP.Add(' DP3 temp.x, light, light;'); VP.Add(' RSQ temp.x, temp.x;'); VP.Add(' MUL light, temp.x, light;'); VP.Add(' DP3 temp, vertex.normal, vertex.normal;'); VP.Add(' RSQ temp.x, temp.x;'); VP.Add(' MUL normal, temp.x, vertex.normal;'); VP.Add(' MOV result.color, state.material.diffuse;'); if csoTextured in FCelShaderOptions then begin VP.Add(' MOV result.texcoord[0], vertex.texcoord[0];'); VP.Add(' DP3 result.texcoord[1].x, normal, light;'); end else begin VP.Add(' DP3 result.texcoord[0].x, normal, light;'); end; VP.Add('END'); Result := VP.Text; VP.Free; end; procedure TVXCelShader.DoApply(var rci: TVXRenderContextInfo; Sender: TObject); var light: TVector; begin if (csDesigning in ComponentState) then exit; FVPHandle.AllocateHandle; if FVPHandle.IsDataNeedUpdate then begin FVPHandle.LoadARBProgram(GenerateVertexProgram); Enabled := FVPHandle.Ready; FVPHandle.NotifyDataUpdated; if not Enabled then Abort; end; rci.VXStates.Disable(stLighting); glGetLightfv(GL_LIGHT0, GL_POSITION, @light.X); FVPHandle.Enable; FVPHandle.Bind; glProgramLocalParameter4fvARB(GL_VERTEX_PROGRAM_ARB, 0, @light.X); if (csoTextured in FCelShaderOptions) then FShadeTexture.ApplyAsTexture2(rci, nil) else FShadeTexture.Apply(rci); FOutlinePass := csoOutlines in FCelShaderOptions; FUnApplyShadeTexture := True; end; function TVXCelShader.DoUnApply(var rci: TVXRenderContextInfo): Boolean; begin Result := False; if (csDesigning in ComponentState) then exit; FVPHandle.Disable; if FUnApplyShadeTexture then begin if (csoTextured in FCelShaderOptions) then FShadeTexture.UnApplyAsTexture2(rci, false) else FShadeTexture.UnApply(rci); FUnApplyShadeTexture := False; end; if FOutlinePass then with rci.VxStates do begin ActiveTexture := 0; ActiveTextureEnabled[ttTexture2D] := False; Enable(stBlend); Enable(stLineSmooth); Disable(stLineStipple); Enable(stCullFace); PolygonMode := pmLines; LineWidth := FOutlineWidth; CullFaceMode := cmFront; LineSmoothHint := hintNicest; SetBlendFunc(bfSrcAlpha, bfOneMinusSrcAlpha); DepthFunc := cfLEqual; glColor4fv(FOutlineColor.AsAddress); Result := True; FOutlinePass := False; Exit; end else with rci.VxStates do begin rci.VXStates.PolygonMode := pmFill; rci.VXStates.CullFaceMode := cmBack; rci.VXStates.DepthFunc := cfLEqual; end; end; procedure TVXCelShader.SetCelShaderOptions(const val: TVXCelShaderOptions); begin if val <> FCelShaderOptions then begin FCelShaderOptions := val; BuildShadeTexture; FVPHandle.NotifyChangesOfData; NotifyChange(Self); end; end; procedure TVXCelShader.SetOutlineWidth(const val: Single); begin if val <> FOutlineWidth then begin FOutlineWidth := val; NotifyChange(Self); end; end; procedure TVXCelShader.SetOutlineColor(const val: TVXColor); begin if val <> FOutlineColor then begin FOutlineColor.Assign(val); NotifyChange(Self); end; end; end.
unit uFrmNewPOTransfer; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, PAIDETODOS, Buttons, DBCtrls, StdCtrls, Mask, SuperComboADO, DB, siComp, siLangRT, LblEffct, ExtCtrls, DBClient; type TFrmNewPOTransfer = class(TFrmParent) dtsTransfer: TDataSource; lblModel: TLabel; lblSince: TLabel; lblTo: TLabel; lblQty: TLabel; lblDate: TLabel; lblUser: TLabel; cmbModel: TDBSuperComboADO; edtUser: TEdit; cmbTo: TDBSuperComboADO; cmbSince: TDBSuperComboADO; edtQty: TDBEdit; spHelp: TSpeedButton; btSave: TButton; edtDate: TDBEdit; procedure btSaveClick(Sender: TObject); procedure btCloseClick(Sender: TObject); private { Private declarations } bResult: Boolean; function ValidateTransfer: Boolean; public { Public declarations } function Start(cds : TClientDataSet; IDModel : Integer): Boolean; end; implementation uses uFrmNewPO, uDM, uMsgBox, uMsgConstant; {$R *.dfm} { TFrmNewPOTransfer } function TFrmNewPOTransfer.Start(cds : TClientDataSet; IDModel : Integer): Boolean; begin bResult := False; dtsTransfer.DataSet := cds; cmbModel.LookUpValue := IntToStr(IDModel); ShowModal; if bResult then dtsTransfer.DataSet.Post else dtsTransfer.DataSet.Cancel; Result := bResult; end; procedure TFrmNewPOTransfer.btSaveClick(Sender: TObject); begin if ValidateTransfer then begin dtsTransfer.DataSet.FieldByName('LojaOrigem').AsString := cmbSince.Text; dtsTransfer.DataSet.FieldByName('LojaDestino').AsString := cmbTo.Text; dtsTransfer.DataSet.FieldByName('Model').AsString := cmbModel.Text; dtsTransfer.DataSet.FieldByName('SystemUser').AsString := edtUser.Text; bResult := True; Close; inherited; end; end; procedure TFrmNewPOTransfer.btCloseClick(Sender: TObject); begin bResult := False; Close; inherited; end; function TFrmNewPOTransfer.ValidateTransfer: Boolean; begin Result := False; if cmbSince.LookUpValue = '' then begin MsgBox(MSG_CRT_NO_ORG_STORE, vbOkOnly + vbCritical); Exit; end; if cmbTo.LookUpValue = '' then begin MsgBox(MSG_CRT_NO_DES_STORE, vbOkOnly + vbCritical); Exit; end; if cmbSince.LookUpValue = cmbTo.LookUpValue then begin MsgBox(MSG_INF_DIFER_STORE, vbOkOnly + vbCritical); Exit; end; if cmbModel.LookUpValue = '' then begin MsgBox(MSG_CRT_NO_MODEL, vbOkOnly + vbCritical); Exit; end; if dtsTransfer.DataSet.FieldByName('qty').AsInteger <= 0 then begin MsgBox(MSG_CRT_QTY_BIGGER_0, vbOkOnly + vbCritical); Exit; end; Result := True; end; end.
{ ZFM-20 series fingerprint sensor support library. Copyright (c) 2015 Dilshan R Jayakody [jayakody2000lk@gmail.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. } unit uzfm; {$mode objfpc}{$H+} interface uses SysUtils; const ZFM_BASE_PACKAGE_SIZE = 11; // Size of the request package excluding payload buffer. ZFM_STATIC_HEADER_SIZE = 6; // Size of the static part of the request. ZFM_CMD_HANDSHAKE = $17; // Communicate link. ZFM_CMD_GEN_IMG = $01; // Collect finger image. ZFM_CMD_UPLOAD_IMG = $0A; // Upload the image in ImgBuffer to upper computer. ZFM_PACKAGE_ID_ACK = $07; // Acknowledge packet. ZFM_PACKAGE_ID_CMD = $01; // Command packet. ZFM_PACKAGE_ID_DATA = $02; // Data packet. ZFM_PACKAGE_ID_END = $08; // End of Data packet. type TZfmBuffer = array of byte; TZfmCommandType = (tzCmd, tzData, tzAck, tzEnd); TZfmSensor = class(TObject) public constructor Create; function CreateZfmPackage(CmdType: TZfmCommandType; Data: TZfmBuffer): TZfmBuffer; function CreateZfmCommand(Data: TZfmBuffer): TZfmBuffer; procedure SetSensorAddress(SensorAddr: TZfmBuffer); function DecodeZfmAcknowledge(AckData: TZfmBuffer; out Data: TZfmBuffer): Boolean; function IsValidSensorHeader(inBuffer: TZfmBuffer): Boolean; private headerArray : array [1..ZFM_STATIC_HEADER_SIZE] of byte; function GetPackageIDByte(CmdType: TZfmCommandType): Byte; end; implementation constructor TZfmSensor.Create; const defaultHeader : array [1..ZFM_STATIC_HEADER_SIZE] of byte = ($EF, $01, $FF, $FF, $FF, $FF); begin Move(defaultHeader[1], headerArray[1], ZFM_STATIC_HEADER_SIZE); end; // Assign new sensor address to ZFM sensor module. procedure TZfmSensor.SetSensorAddress(SensorAddr: TZfmBuffer); begin Move(SensorAddr[0], headerArray[3], 4); end; // Function to convert TZfmCommandType to byte. function TZfmSensor.GetPackageIDByte(CmdType: TZfmCommandType): Byte; begin Result := ZFM_PACKAGE_ID_CMD; case CmdType of tzData : Result := ZFM_PACKAGE_ID_DATA; tzAck : Result := ZFM_PACKAGE_ID_ACK; tzEnd : Result := ZFM_PACKAGE_ID_END; end; end; // Create ZFM-20 series compatiable package based on specified command type and data buffer. function TZfmSensor.CreateZfmPackage(CmdType: TZfmCommandType; Data: TZfmBuffer): TZfmBuffer; var outputDataBuffer: TZfmBuffer; dataLength, tmpPos: Word; checkSum: LongWord; begin SetLength(outputDataBuffer, ZFM_BASE_PACKAGE_SIZE + Length(Data)); // Move static header part to output buffer. Move(headerArray[1], outputDataBuffer[0], ZFM_STATIC_HEADER_SIZE); outputDataBuffer[6] := GetPackageIDByte(CmdType); // Size of the payload buffer. dataLength := 2 + Length(Data); outputDataBuffer[7] := Hi(dataLength); outputDataBuffer[8] := Lo(dataLength); // Copy payload to output buffer. if(Length(Data) > 0) then begin Move(Data[0], outputDataBuffer[9], Length(Data)); end; // Calculate checksum for output buffer. checkSum := outputDataBuffer[6] + dataLength; for tmpPos := 0 to (Length(Data) - 1) do begin checkSum := checkSum + Data[tmpPos]; end; outputDataBuffer[Length(outputDataBuffer) - 2] := Lo(checkSum shr 8); outputDataBuffer[Length(outputDataBuffer) - 1] := Lo(checkSum); Result := outputDataBuffer; end; // Send command to ZFM-20 series sensor. function TZfmSensor.CreateZfmCommand(Data: TZfmBuffer): TZfmBuffer; begin Result := CreateZfmPackage(tzCmd, Data); end; // Decode acknowledge package and extract data. function TZfmSensor.DecodeZfmAcknowledge(AckData: TZfmBuffer; out Data: TZfmBuffer): Boolean; var dataLen: Integer; begin SetLength(Data, 0); Result := false; if(Length(AckData) > 0) then begin // Validate header and chip address values. if(CompareMem(@AckData[0], @headerArray[1], ZFM_STATIC_HEADER_SIZE)) then begin // Check package ID for acknowledge byte. if(AckData[6] = ZFM_PACKAGE_ID_ACK)then begin // Extract data size and copy content to output data buffer. dataLen := Integer((AckData[8] + (AckData[7] shl 8))) - 2; if(dataLen > 0) then begin SetLength(Data, dataLen); Move(AckData[9], Data[0], dataLen); Result := true; end; end; end; end; end; // Check specified buffer contain valid sensor response header. function TZfmSensor.IsValidSensorHeader(inBuffer: TZfmBuffer): Boolean; begin Result := false; if(Length(inBuffer) >= ZFM_STATIC_HEADER_SIZE) then begin Result := CompareMem(@inBuffer[0], @headerArray[1], ZFM_STATIC_HEADER_SIZE); end; end; end.
unit tal_SimpleListForm; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, tal_iedit, tvl_ibindings, trl_ipersist, trl_irttibroker; type { TSimpleListForm } TSimpleListForm = class(TForm, IListData) btnAdd: TButton; btnDelete: TButton; btnEdit: TButton; lbList: TListBox; procedure btnAddClick(Sender: TObject); procedure btnDeleteClick(Sender: TObject); procedure btnEditClick(Sender: TObject); private fFactory: IPersistFactory; fStore: IPersistStore; fBinder: IRBTallyBinder; fEdit: IEditData; fDataClass: string; protected procedure List; published property Factory: IPersistFactory read fFactory write fFactory; property Store: IPersistStore read fStore write fStore; property Binder: IRBTallyBinder read fBinder write fBinder; property Edit: IEditData read fEdit write fEdit; property DataClass: string read fDataClass write fDataClass; end; var SimpleListForm: TSimpleListForm; implementation {$R *.lfm} { TSimpleListForm } procedure TSimpleListForm.btnAddClick(Sender: TObject); var mData: IRBData; begin mData := Factory.CreateObject(DataClass); if Edit.Edit(mData) then begin Store.Save(mData); Store.Flush; Binder.Reload; end; end; procedure TSimpleListForm.btnDeleteClick(Sender: TObject); begin Store.Delete(Binder.CurrentData); Store.Flush; Binder.Reload; end; procedure TSimpleListForm.btnEditClick(Sender: TObject); var mData, mNewData: IRBData; begin mData := Binder.CurrentData; if mData = nil then Exit; mNewData := Factory.CreateObject(mData.ClassName); mNewData.Assign(mData); if Edit.Edit(mNewData) then begin mData.Assign(mNewData); Store.Save(mData); Store.Flush; Binder.Reload; end; end; procedure TSimpleListForm.List; begin Binder.Bind(lbList, DataClass); ShowModal; end; end.
(*==========================================================================; * * Copyright (C) 1995-1997 Microsoft Corporation. All Rights Reserved. * * File: dsound.h * Content: DirectSound include file * * DirectX 5 Delphi adaptation by Erik Unger * Generic source created with PERL Header Converter 0.74 from David Sisson * * Modyfied: 21.3.98 * * Download: http://www.sbox.tu-graz.ac.at/home/ungerik/DelphiGraphics/ * E-Mail: h_unger@magnet.at * ***************************************************************************) unit DSound; {$INCLUDE COMSWITCH.INC} {$INCLUDE STRINGSWITCH.INC} interface uses {$IFDEF D2COM} OLE2, {$ENDIF} Windows, SysUtils, MMSystem, D3Dtypes; const _FACDS = $878; function MAKE_DSHResult(code: variant) : HResult; const // Direct Sound Component GUID {47D4D946-62E8-11cf-93BC-444553540000} CLSID_DirectSound: TGUID = (D1:$47d4d946;D2:$62e8;D3:$11cf;D4:($93,$bc,$44,$45,$53,$54,$00,$0)); // DirectSound Capture Component GUID {B0210780-89CD-11d0-AF08-00A0C925CD16} CLSID_DirectSoundCapture: TGUID = (D1:$b0210780;D2:$89cd;D3:$11d0;D4:($af,$8,$00,$a0,$c9,$25,$cd,$16)); // // GUID's for all the objects // const IID_IDirectSound: TGUID = (D1:$279AFA83;D2:$4981;D3:$11CE;D4:($A5,$21,$00,$20,$AF,$0B,$E5,$60)); IID_IDirectSoundBuffer: TGUID = (D1:$279AFA85;D2:$4981;D3:$11CE;D4:($A5,$21,$00,$20,$AF,$0B,$E5,$60)); IID_IDirectSound3DListener: TGUID = (D1:$279AFA84;D2:$4981;D3:$11CE;D4:($A5,$21,$00,$20,$AF,$0B,$E5,$60)); IID_IDirectSound3DBuffer: TGUID = (D1:$279AFA86;D2:$4981;D3:$11CE;D4:($A5,$21,$00,$20,$AF,$0B,$E5,$60)); IID_IDirectSoundCapture: TGUID = (D1:$b0210781;D2:$89cd;D3:$11d0;D4:($af,$08,$00,$a0,$c9,$25,$cd,$16)); IID_IDirectSoundCaptureBuffer: TGUID = (D1:$b0210782;D2:$89cd;D3:$11d0;D4:($af,$08,$00,$a0,$c9,$25,$cd,$16)); IID_IDirectSoundNotify: TGUID = (D1:$b0210783;D2:$89cd;D3:$11d0;D4:($af,$08,$00,$a0,$c9,$25,$cd,$16)); IID_IKsPropertySet: TGUID = (D1:$31efac30;D2:$515c;D3:$11d0;D4:($a9,$aa,$00,$aa,$00,$61,$be,$93)); // // Structures // type {$IFDEF D2COM} IDirectSound = class; IDirectSoundBuffer = class; IDirectSound3DListener = class; IDirectSound3DBuffer = class; IDirectSoundCapture = class; IDirectSoundCaptureBuffer = class; IDirectSoundNotify = class; IKsPropertySet = class; {$ELSE} IDirectSound = interface; IDirectSoundBuffer = interface; IDirectSound3DListener = interface; IDirectSound3DBuffer = interface; IDirectSoundCapture = interface; IDirectSoundCaptureBuffer = interface; IDirectSoundNotify = interface; IKsPropertySet = interface; {$ENDIF} PDSCaps = ^TDSCaps; TDSCaps = packed record dwSize: DWORD; dwFlags: DWORD; dwMinSecondarySampleRate: DWORD; dwMaxSecondarySampleRate: DWORD; dwPrimaryBuffers: DWORD; dwMaxHwMixingAllBuffers: DWORD; dwMaxHwMixingStaticBuffers: DWORD; dwMaxHwMixingStreamingBuffers: DWORD; dwFreeHwMixingAllBuffers: DWORD; dwFreeHwMixingStaticBuffers: DWORD; dwFreeHwMixingStreamingBuffers: DWORD; dwMaxHw3DAllBuffers: DWORD; dwMaxHw3DStaticBuffers: DWORD; dwMaxHw3DStreamingBuffers: DWORD; dwFreeHw3DAllBuffers: DWORD; dwFreeHw3DStaticBuffers: DWORD; dwFreeHw3DStreamingBuffers: DWORD; dwTotalHwMemBytes: DWORD; dwFreeHwMemBytes: DWORD; dwMaxContigFreeHwMemBytes: DWORD; dwUnlockTransferRateHwBuffers: DWORD; dwPlayCpuOverheadSwBuffers: DWORD; dwReserved1: DWORD; dwReserved2: DWORD; end; PCDSCaps = ^TDSCaps; PDSBCaps = ^TDSBCaps; TDSBCaps = packed record dwSize: DWORD; dwFlags: DWORD; dwBufferBytes: DWORD; dwUnlockTransferRate: DWORD; dwPlayCpuOverhead: DWORD; end; PCDSBCaps = ^TDSBCaps; PDSBufferDesc = ^TDSBufferDesc; TDSBufferDesc = packed record dwSize: DWORD; dwFlags: DWORD; dwBufferBytes: DWORD; dwReserved: DWORD; lpwfxFormat: PWaveFormatEx; end; PCDSBufferDesc = ^TDSBufferDesc; PDS3DBuffer = ^TDS3DBuffer; TDS3DBuffer = packed record dwSize: DWORD; vPosition: TD3DVector; vVelocity: TD3DVector; dwInsideConeAngle: DWORD; dwOutsideConeAngle: DWORD; vConeOrientation: TD3DVector; lConeOutsideVolume: Longint; flMinDistance: TD3DValue; flMaxDistance: TD3DValue; dwMode: DWORD; end; TCDS3DBuffer = ^TDS3DBuffer; PDS3DListener = ^TDS3DListener; TDS3DListener = packed record dwSize: DWORD; vPosition: TD3DVector; vVelocity: TD3DVector; vOrientFront: TD3DVector; vOrientTop: TD3DVector; flDistanceFactor: TD3DValue; flRolloffFactor: TD3DValue; flDopplerFactor: TD3DValue; end; PCDS3DListener = ^TDS3DListener; PDSCCaps = ^TDSCCaps; TDSCCaps = packed record dwSize: DWORD; dwFlags: DWORD; dwFormats: DWORD; dwChannels: DWORD; end; PCDSCCaps = ^TDSCCaps; PDSCBufferDesc = ^TDSCBufferDesc; TDSCBufferDesc = packed record dwSize: DWORD; dwFlags: DWORD; dwBufferBytes: DWORD; dwReserved: DWORD; lpwfxFormat: PWaveFormatEx; end; PCDSCBufferDesc = ^TDSCBufferDesc; PDSCBCaps = ^TDSCBCaps; TDSCBCaps = packed record dwSize: DWORD; dwFlags: DWORD; dwBufferBytes: DWORD; dwReserved: DWORD; end; PCDSCBCaps = ^TDSCBCaps; PDSBPositionNotify = ^TDSBPositionNotify; TDSBPositionNotify = packed record dwOffset: DWORD; hEventNotify: THandle; end; PCDSBPositionNotify = ^TDSBPositionNotify; // // DirectSound API // TDSEnumCallbackW = function (lpGuid: PGUID; lpstrDescription: PWideChar; lpstrModule: PWideChar; lpContext: Pointer) : BOOL; stdcall; TDSEnumCallbackA = function (lpGuid: PGUID; lpstrDescription: PAnsiChar; lpstrModule: PAnsiChar; lpContext: Pointer) : BOOL; stdcall; {$IFDEF UNICODE} TDSEnumCallback = TDSEnumCallbackW; {$ELSE} TDSEnumCallback = TDSEnumCallbackA; {$ENDIF} // // IDirectSound // {$IFDEF D2COM} IDirectSound = class (IUnknown) {$ELSE} IDirectSound = interface (IUnknown) ['{279AFA83-4981-11CE-A521-0020AF0BE560}'] {$ENDIF} // IDirectSound methods function CreateSoundBuffer(const lpDSBufferDesc: TDSBufferDesc; var lpIDirectSoundBuffer: IDirectSoundBuffer; pUnkOuter: IUnknown) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetCaps(var Arg1: TDSCaps) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function DuplicateSoundBuffer(lpDsbOriginal: IDirectSoundBuffer; var lpDsbDuplicate: IDirectSoundBuffer) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetCooperativeLevel(Arg1: HWND; Arg2: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function Compact: HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetSpeakerConfig(var Arg1: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetSpeakerConfig(Arg1: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function Initialize(Arg1: PGUID) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} end; // // IDirectSoundBuffer // {$IFDEF D2COM} IDirectSoundBuffer = class (IUnknown) {$ELSE} IDirectSoundBuffer = interface (IUnknown) ['{279AFA85-4981-11CE-A521-0020AF0BE560}'] {$ENDIF} // IDirectSoundBuffer methods function GetCaps(var Arg1: TDSBCaps) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetCurrentPosition(var Arg1: DWORD; var Arg2: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetFormat(Arg1: PWaveFormatEx; Arg2: DWORD; var Arg3: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetVolume(var Arg1: Longint) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetPan(var Arg1: Longint) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetFrequency(var Arg1: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetStatus(var Arg1: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function Initialize(Arg1: IDirectSound; const Arg2: TDSBufferDesc) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function Lock(Arg1: DWORD; Arg2: DWORD; var Arg3: Pointer; var Arg4: DWORD; var Arg5: Pointer; var Arg6: DWORD; Arg7: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function Play(Arg1: DWORD; Arg2: DWORD; Arg3: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetCurrentPosition(Arg1: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetFormat(const Arg1: TWaveFormatEx) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetVolume(Arg1: Longint) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetPan(Arg1: Longint) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetFrequency(Arg1: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function Stop: HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function Unlock(Arg1: Pointer; Arg2: DWORD; Arg3: Pointer; Arg4: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function Restore: HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} end; // // IDirectSound3DListener // {$IFDEF D2COM} IDirectSound3DListener = class (IUnknown) {$ELSE} IDirectSound3DListener = interface (IUnknown) ['{279AFA84-4981-11CE-A521-0020AF0BE560}'] {$ENDIF} // IDirectSound3D methods function GetAllParameters(var Arg1: TDS3DListener) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetDistanceFactor(var Arg1: TD3DValue) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetDopplerFactor(var Arg1: TD3DValue) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetOrientation(var Arg1: TD3DVector; var Arg2: TD3DVector) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetPosition(var Arg1: TD3DVector) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetRolloffFactor(var Arg1: TD3DValue) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetVelocity(var Arg1: TD3DVector) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetAllParameters(const Arg1: TDS3DListener; Arg2: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetDistanceFactor(Arg1: TD3DValue; Arg2: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetDopplerFactor(Arg1: TD3DValue; Arg2: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetOrientation(Arg1: TD3DValue; Arg2: TD3DValue; Arg3: TD3DValue; Arg4: TD3DValue; Arg5: TD3DValue; Arg6: TD3DValue; Arg7: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetPosition(Arg1: TD3DValue; Arg2: TD3DValue; Arg3: TD3DValue; Arg4: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetRolloffFactor(Arg1: TD3DValue; Arg2: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetVelocity(Arg1: TD3DValue; Arg2: TD3DValue; Arg3: TD3DValue; Arg4: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function CommitDeferredSettings: HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} end; // // IDirectSound3DBuffer // {$IFDEF D2COM} IDirectSound3DBuffer = class (IUnknown) {$ELSE} IDirectSound3DBuffer = interface (IUnknown) ['{279AFA86-4981-11CE-A521-0020AF0BE560}'] {$ENDIF} // IDirectSoundBuffer3D methods function GetAllParameters(var Arg1: TDS3DBuffer) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetConeAngles(var Arg1: DWORD; var Arg2: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetConeOrientation(var Arg1: TD3DVector) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetConeOutsideVolume(var Arg1: Longint) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetMaxDistance(var Arg1: TD3DValue) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetMinDistance(var Arg1: TD3DValue) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetMode(var Arg1: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetPosition(var Arg1: TD3DVector) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetVelocity(var Arg1: TD3DVector) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetAllParameters(const Arg1: TDS3DBuffer; Arg2: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetConeAngles(Arg1: DWORD; Arg2: DWORD; Arg3: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetConeOrientation(Arg1: TD3DValue; Arg2: TD3DValue; Arg3: TD3DValue; Arg4: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetConeOutsideVolume(Arg1: Longint; Arg2: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetMaxDistance(Arg1: TD3DValue; Arg2: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetMinDistance(Arg1: TD3DValue; Arg2: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetMode(Arg1: DWORD; Arg2: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetPosition(Arg1: TD3DValue; Arg2: TD3DValue; Arg3: TD3DValue; Arg4: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function SetVelocity(Arg1: TD3DValue; Arg2: TD3DValue; Arg3: TD3DValue; Arg4: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} end; // // IDirectSoundCapture // {$IFDEF D2COM} IDirectSoundCapture = class (IUnknown) {$ELSE} IDirectSoundCapture = interface (IUnknown) ['{b0210781-89cd-11d0-af08-00a0c925cd16}'] {$ENDIF} // IDirectSoundCapture methods function CreateCaptureBuffer(const Arg1: TDSCBufferDesc; var Arg2: IDirectSoundCAPTUREBUFFER; Arg3: IUnknown) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetCaps(var Arg1: TDSCCaps) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function Initialize(Arg1: PGUID) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} end; // // IDirectSoundCaptureBuffer // {$IFDEF D2COM} IDirectSoundCaptureBuffer = class (IUnknown) {$ELSE} IDirectSoundCaptureBuffer = interface (IUnknown) ['{b0210782-89cd-11d0-af08-00a0c925cd16}'] {$ENDIF} // IDirectSoundCaptureBuffer methods function GetCaps(var Arg1: TDSCBCaps) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetCurrentPosition(var Arg1: DWORD; var Arg2: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetFormat(Arg1: PWaveFormatEx; Arg2: DWORD; var Arg3: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function GetStatus(var Arg1: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function Initialize(Arg1: IDirectSoundCapture; const Arg2: TDSCBufferDesc) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function Lock(Arg1: DWORD; Arg2: DWORD; var Arg3: Pointer; var Arg4: DWORD; var Arg5: Pointer; var Arg6: DWORD; Arg7: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function Start(Arg1: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function Stop: HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function Unlock(Arg1: Pointer; Arg2: DWORD; Arg3: Pointer; Arg4: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} end; // // IDirectSoundNotify // {$IFDEF D2COM} IDirectSoundNotify = class (IUnknown) {$ELSE} IDirectSoundNotify = interface (IUnknown) ['{b0210783-89cd-11d0-af08-00a0c925cd16}'] {$ENDIF} // IDirectSoundNotify methods function SetNotificationPositions(Arg1: DWORD; const Arg2: TDSBPositionNotify) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} end; // // IKsPropertySet // {$IFDEF D2COM} IKsPropertySet = class (IUnknown) {$ELSE} IKsPropertySet = interface (IUnknown) ['{31efac30-515c-11d0-a9aa-00aa0061be93}'] {$ENDIF} // IKsPropertySet methods function Get(Arg1: PGUID; Arg2: DWORD; Arg3: Pointer; Arg4: DWORD; Arg5: Pointer; Arg6: DWORD; Arg7: PULONG) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} // Warning: The following function is defined as Set() in DirectX // which is a reserved word in Delphi! function SetProperty(Arg1: PGUID; Arg2: DWORD; Arg3: Pointer; Arg4: DWORD; Arg5: Pointer; Arg6: DWORD) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} function QuerySupport(Arg1: PGUID; Arg2: DWORD; Arg3: PULONG) : HResult; {$IFDEF D2COM} virtual; stdcall; abstract; {$ELSE} stdcall; {$ENDIF} end; const KSPROPERTY_SUPPORT_GET = $00000001; KSPROPERTY_SUPPORT_SET = $00000002; // // Creation Routines // function DirectSoundCreate(Arg1: PGUID; var Arg2: IDirectSound; Arg3: IUnknown) : HResult; stdcall; function DirectSoundEnumerateW(Arg1: TDSEnumCallbackW; Arg2: Pointer) : HResult; stdcall; function DirectSoundEnumerateA(Arg1: TDSEnumCallbackA; Arg2: Pointer) : HResult; stdcall; function DirectSoundEnumerate(Arg1: TDSEnumCallbackA; Arg2: Pointer) : HResult; stdcall; function DirectSoundCaptureCreate(Arg1: PGUID; var Arg2: IDirectSoundCapture; Arg3: IUnknown) : HResult; stdcall; function DirectSoundCaptureEnumerateW(Arg1: TDSEnumCallbackW; Arg2: Pointer) : HResult; stdcall; function DirectSoundCaptureEnumerateA(Arg1: TDSEnumCallbackA; Arg2: Pointer) : HResult; stdcall; function DirectSoundCaptureEnumerate(Arg1: TDSEnumCallbackA; Arg2: Pointer) : HResult; stdcall; // // Return Codes // const DS_OK = 0; // The call failed because resources (such as a priority level) // were already being used by another caller. DSERR_ALLOCATED = $88780000 + 10; // The control (vol,pan,etc.) requested by the caller is not available. DSERR_CONTROLUNAVAIL = $88780000 + 30; // An invalid parameter was passed to the returning function DSERR_INVALIDPARAM = E_INVALIDARG; // This call is not valid for the current state of this object DSERR_INVALIDCALL = $88780000 + 50; // An undetermined error occured inside the DirectSound subsystem DSERR_GENERIC = E_FAIL; // The caller does not have the priority level required for the function to // succeed. DSERR_PRIOLEVELNEEDED = $88780000 + 70; // Not enough free memory is available to complete the operation DSERR_OUTOFMEMORY = E_OUTOFMEMORY; // The specified WAVE format is not supported DSERR_BADFORMAT = $88780000 + 100; // The function called is not supported at this time DSERR_UNSUPPORTED = E_NOTIMPL; // No sound driver is available for use DSERR_NODRIVER = $88780000 + 120; // This object is already initialized DSERR_ALREADYINITIALIZED = $88780000 + 130; // This object does not support aggregation DSERR_NOAGGREGATION = CLASS_E_NOAGGREGATION; // The buffer memory has been lost, and must be restored. DSERR_BUFFERLOST = $88780000 + 150; // Another app has a higher priority level, preventing this call from // succeeding. DSERR_OTHERAPPHASPRIO = $88780000 + 160; // This object has not been initialized DSERR_UNINITIALIZED = $88780000 + 170; // The requested COM interface is not available DSERR_NOINTERFACE = E_NOINTERFACE; // // Flags // DSCAPS_PRIMARYMONO = $00000001; DSCAPS_PRIMARYSTEREO = $00000002; DSCAPS_PRIMARY8BIT = $00000004; DSCAPS_PRIMARY16BIT = $00000008; DSCAPS_CONTINUOUSRATE = $00000010; DSCAPS_EMULDRIVER = $00000020; DSCAPS_CERTIFIED = $00000040; DSCAPS_SECONDARYMONO = $00000100; DSCAPS_SECONDARYSTEREO = $00000200; DSCAPS_SECONDARY8BIT = $00000400; DSCAPS_SECONDARY16BIT = $00000800; DSBPLAY_LOOPING = $00000001; DSBSTATUS_PLAYING = $00000001; DSBSTATUS_BUFFERLOST = $00000002; DSBSTATUS_LOOPING = $00000004; DSBLOCK_FROMWRITECURSOR = $00000001; DSBLOCK_ENTIREBUFFER = $00000002; DSSCL_NORMAL = $00000001; DSSCL_PRIORITY = $00000002; DSSCL_EXCLUSIVE = $00000003; DSSCL_WRITEPRIMARY = $00000004; DS3DMODE_NORMAL = $00000000; DS3DMODE_HEADRELATIVE = $00000001; DS3DMODE_DISABLE = $00000002; DS3D_IMMEDIATE = $00000000; DS3D_DEFERRED = $00000001; DS3D_MINDISTANCEFACTOR = 0.0; DS3D_MAXDISTANCEFACTOR = 10.0; DS3D_DEFAULTDISTANCEFACTOR = 1.0; DS3D_MINROLLOFFFACTOR = 0.0; DS3D_MAXROLLOFFFACTOR = 10.0; DS3D_DEFAULTROLLOFFFACTOR = 1.0; DS3D_MINDOPPLERFACTOR = 0.0; DS3D_MAXDOPPLERFACTOR = 10.0; DS3D_DEFAULTDOPPLERFACTOR = 1.0; DS3D_DEFAULTMINDISTANCE = 1.0; DS3D_DEFAULTMAXDISTANCE = 1000000000.0; DS3D_MINCONEANGLE = 0; DS3D_MAXCONEANGLE = 360; DS3D_DEFAULTCONEANGLE = 360; DS3D_DEFAULTCONEOUTSIDEVOLUME = 0; DSBCAPS_PRIMARYBUFFER = $00000001; DSBCAPS_STATIC = $00000002; DSBCAPS_LOCHARDWARE = $00000004; DSBCAPS_LOCSOFTWARE = $00000008; DSBCAPS_CTRL3D = $00000010; DSBCAPS_CTRLFREQUENCY = $00000020; DSBCAPS_CTRLPAN = $00000040; DSBCAPS_CTRLVOLUME = $00000080; DSBCAPS_CTRLPOSITIONNOTIFY = $00000100; DSBCAPS_CTRLDEFAULT = $000000E0; DSBCAPS_CTRLALL = $000001F0; DSBCAPS_STICKYFOCUS = $00004000; DSBCAPS_GLOBALFOCUS = $00008000; DSBCAPS_GETCURRENTPOSITION2 = $00010000; DSBCAPS_MUTE3DATMAXDISTANCE = $00020000; DSCBCAPS_WAVEMAPPED = $80000000; DSSPEAKER_HEADPHONE = $00000001; DSSPEAKER_MONO = $00000002; DSSPEAKER_QUAD = $00000003; DSSPEAKER_STEREO = $00000004; DSSPEAKER_SURROUND = $00000005; // #define DSSPEAKER_COMBINED(c, g) // ((DWORD)(((BYTE)(c)) | ((DWORD)((BYTE)(g))) << 16)) function DSSPEAKER_COMBINED(c, g: DWORD) : DWORD; // #define DSSPEAKER_CONFIG(a) ((BYTE)(a)) function DSSPEAKER_CONFIG(a: DWORD) : byte; // #define DSSPEAKER_GEOMETRY(a) ((BYTE)(((DWORD)(a) >> 16) & 0x00FF)) function DSSPEAKER_GEOMETRY(a: DWORD) : byte; const DSCCAPS_EMULDRIVER = $00000020; DSCBLOCK_ENTIREBUFFER = $00000001; DSCBSTATUS_CAPTURING = $00000001; DSCBSTATUS_LOOPING = $00000002; DSCBSTART_LOOPING = $00000001; DSBFREQUENCY_MIN = 100; DSBFREQUENCY_MAX = 100000; DSBFREQUENCY_ORIGINAL = 0; DSBPAN_LEFT = -10000; DSBPAN_CENTER = 0; DSBPAN_RIGHT = 10000; DSBVOLUME_MIN = -10000; DSBVOLUME_MAX = 0; DSBSIZE_MIN = 4; DSBSIZE_MAX = $0FFFFFFF; DSBPN_OFFSETSTOP = $FFFFFFFF; implementation function DirectSoundCreate; external 'DSound.dll'; function DirectSoundEnumerateW; external 'DSound.dll'; function DirectSoundEnumerateA; external 'DSound.dll'; {$IFDEF UNICODE} function DirectSoundEnumerate; external 'DSound.dll' name 'DirectSoundEnumerateW'; {$ELSE} function DirectSoundEnumerate; external 'DSound.dll' name 'DirectSoundEnumerateA'; {$ENDIF} function DirectSoundCaptureCreate; external 'DSound.dll'; function DirectSoundCaptureEnumerateW; external 'DSound.dll'; function DirectSoundCaptureEnumerateA; external 'DSound.dll'; {$IFDEF UNICODE} function DirectSoundCaptureEnumerate; external 'DSound.dll' name 'DirectSoundCaptureEnumerateW'; {$ELSE} function DirectSoundCaptureEnumerate; external 'DSound.dll' name 'DirectSoundCaptureEnumerateA'; {$ENDIF} // #define MAKE_DSHResult(code) MAKE_HResult(1, _FACDS, code) function MAKE_DSHResult(code: variant) : HResult; begin Result := (1 shl 31) or (_FACDS shl 16) or code; end; // #define DSSPEAKER_COMBINED(c, g) // ((DWORD)(((BYTE)(c)) | ((DWORD)((BYTE)(g))) << 16)) function DSSPEAKER_COMBINED(c, g: DWORD) : DWORD; begin Result := (byte(c) or byte(g)) shl 16; end; // #define DSSPEAKER_CONFIG(a) ((BYTE)(a)) function DSSPEAKER_CONFIG(a: DWORD) : byte; begin Result := byte(a); end; // #define DSSPEAKER_GEOMETRY(a) ((BYTE)(((DWORD)(a) >> 16) & 0x00FF)) function DSSPEAKER_GEOMETRY(a: DWORD) : byte; begin Result := byte(a shr 16 and $FF); end; end.
unit MainCrypt; interface function GetCrypted(password : string): string; function GetUnCrypted(cryptstring : string): string; implementation uses SysUtils, Dialogs; function GetCrypted(password : string): string; var i : integer; number : integer; crypted : string; s : char; add : string; begin crypted := ''; for i:=1 to length(password) do begin s := password[i]; number := ord(s) + i; if number > 255 then number := number - 256; add := IntToStr(number); if length(Add)=1 then add:= '00'+add; if length(Add)=2 then add:= '0'+add; crypted := crypted + add; end; GetCrypted := crypted; end; function GetUnCrypted(cryptstring : string): string; var i :integer; part : string; number : integer; add : char; password : string; begin Password := ''; for i:= 1 to Round(length(CryptString)/3) do Begin part := copy(CryptString,(3*i-2),3); number := StrToInt(part); number := number - i; If number < 0 then number := number + 256; add := chr(number); password := password + Add; End; GetUnCrypted := password; end; end.
{***************************************************************************} { } { Delphi Package Manager - DPM } { } { Copyright © 2019 Vincent Parrett and contributors } { } { vincent@finalbuilder.com } { https://www.finalbuilder.com } { } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit DPM.Core.Utils.Directory; interface uses System.IOUtils, Spring.Collections; type TDirectoryUtils = record class function IsDirectoryWriteable(const directory : string) : boolean; static; //this is about 30% faster than System.IUtils version class function GetFiles(const Path : string) : IList<string>; overload; inline; static; class function GetFiles(const Path, SearchPattern : string) : IList<string>; overload; inline; static; class function GetFiles(const Path, SearchPattern : string; const SearchOption : TSearchOption) : IList<string>; overload; static; end; implementation uses WinApi.Windows, System.SysUtils; { TDirectoryUtils } function RandomString(const ALength : Integer) : string; var i : Integer; LCharType : Integer; begin Result := ''; for i := 1 to ALength do begin LCharType := Random(3); case LCharType of 0 : Result := Result + Chr(ord('a') + Random(26)); 1 : Result := Result + Chr(ord('A') + Random(26)); 2 : Result := Result + Chr(ord('0') + Random(10)); end; end; end; class function TDirectoryUtils.IsDirectoryWriteable(const directory : string) : boolean; var fileName : string; H : THandle; begin fileName := IncludeTrailingPathDelimiter(directory) + RandomString(5) + '.tmp'; H := CreateFile(PChar(FileName), GENERIC_READ or GENERIC_WRITE, 0, nil, CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY or FILE_FLAG_DELETE_ON_CLOSE, 0); Result := H <> INVALID_HANDLE_VALUE; if Result then CloseHandle(H); end; class function TDirectoryUtils.GetFiles(const Path : string) : IList<string>; begin result := GetFiles(ExtractFilePath(Path), ExtractFileName(Path), TSearchOption.soTopDirectoryOnly); end; class function TDirectoryUtils.GetFiles(const Path, SearchPattern : string) : IList<string>; begin result := GetFiles(Path, SearchPattern, TSearchOption.soTopDirectoryOnly); end; class function TDirectoryUtils.GetFiles(const Path, SearchPattern : string; const SearchOption : TSearchOption) : IList<string>; var foundFiles : IList<string>; procedure DoSearch(const dir : string); var searchRec : TSearchRec; theDir : string; begin theDir := IncludeTrailingPathDelimiter(dir); if FindFirst(theDir + SearchPattern, faAnyFile, searchRec) = 0 then begin try repeat if (searchRec.Attr and faDirectory) = 0 then foundFiles.Add(theDir + searchRec.Name) else if SearchOption = TSearchOption.soAllDirectories then begin if (searchRec.Name <> '.') and (searchRec.Name <> '..') then DoSearch(theDir + searchRec.Name); end; until (FindNext(searchRec) <> 0); finally FindClose(searchRec); end; end; end; begin foundFiles := TCollections.CreateList < string > ; result := foundFiles; DoSearch(Path); end; end.
unit ThTextArea; interface uses SysUtils, Windows, Types, Classes, Controls, Graphics, StdCtrls, Forms, ThInterfaces, ThTextPaint, ThWebControl, ThTag; type TThCustomTextArea = class(TThWebControl, IThFormInput) private FMemo: TMemo; FMargin: Integer; procedure SetMargin(const Value: Integer); protected function GetLines: TStrings; function GetWordWrap: Boolean; procedure SetLines(const Value: TStrings); procedure SetWordWrap(const Value: Boolean); protected procedure AdjustClientRect(var inRect: TRect); override; procedure CreateMemo; virtual; procedure CssStyleChanged; override; procedure LinesChange(inSender: TObject); procedure Tag(inTag: TThTag); override; protected property Lines: TStrings read GetLines write SetLines; property Memo: TMemo read FMemo write FMemo; property Margin: Integer read FMargin write SetMargin; property WordWrap: Boolean read GetWordWrap write SetWordWrap; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; // TThTextArea = class(TThCustomTextArea) published property Align; property Lines; property Margin; property Style; property StyleClass; property Visible; property WordWrap; end; implementation { TThCustomTextArea } constructor TThCustomTextArea.Create(AOwner: TComponent); begin inherited; CreateMemo; CtrlStyle.Font.DefaultFontFamily := 'Courier New'; CtrlStyle.Font.DefaultFontPx := 13; Style.Color := clWhite; FMargin := 3; end; destructor TThCustomTextArea.Destroy; begin FMemo.Free; inherited; end; procedure TThCustomTextArea.CreateMemo; begin Memo := TMemo.Create(Self); with Memo do begin Parent := Self; Align := alClient; ReadOnly := true; Scrollbars := ssBoth; ParentColor := true; end; end; procedure TThCustomTextArea.AdjustClientRect(var inRect: TRect); begin inherited; with inRect do inRect := Rect(Left + 2, Top + 1, Right - 6, Bottom); if CtrlStyle.Padding.PadBottom >= FMargin then Inc(inRect.Bottom, FMargin); end; procedure TThCustomTextArea.CssStyleChanged; begin inherited; if CtrlStyle.Border.BorderVisible then Memo.BorderStyle := bsNone else Memo.BorderStyle := bsSingle; end; procedure TThCustomTextArea.LinesChange(inSender: TObject); begin Invalidate; end; function TThCustomTextArea.GetLines: TStrings; begin Result := Memo.Lines; end; procedure TThCustomTextArea.SetLines(const Value: TStrings); begin Memo.Lines.Assign(Value); end; function TThCustomTextArea.GetWordWrap: Boolean; begin Result := Memo.WordWrap; end; procedure TThCustomTextArea.SetWordWrap(const Value: Boolean); begin Memo.WordWrap := Value; if Value then Memo.ScrollBars := ssVertical else Memo.ScrollBars := ssBoth; Invalidate; end; procedure TThCustomTextArea.Tag(inTag: TThTag); begin inherited; with inTag do begin Element := 'textarea'; Content := Lines.Text; if WordWrap then Add('wrap', 'soft') else Add('wrap', 'off'); AddStyle('width', '100%'); //AddStyle('width', Width, 'px'); AddStyle('height', Height, 'px'); end; end; procedure TThCustomTextArea.SetMargin(const Value: Integer); begin FMargin := Value; end; end.
(* Category: SWAG Title: TEXT FILE MANAGEMENT ROUTINES Original name: 0003.PAS Description: Line counter Author: SWAG SUPPORT TEAM Date: 05-28-93 13:58 *) { >I'm wondering if anyone can post me a source For another way to >find out the max lines in a Text File. } {.$DEFinE DebugMode} Program LineCounter; Const co_LineFeed = 10; Type byar_60K = Array[1..61440] of Byte; Var wo_Index, wo_BytesRead : Word; lo_FileSize, lo_BytesProc, lo_LineCount : LongInt; fi_Temp : File; byar_Buffer : byar_60K; begin (* Attempt to open TEST.doC File. *) assign(fi_Temp, 'linecnt.pas'); {$I-} reset(fi_Temp, 1); {$I+} (* Check if attempt was sucessful. *) if (ioresult <> 0) then begin Writeln('ERRor opening linecnt.pas File'); halt end; (* Record the size in Bytes of TEST.doC . *) lo_FileSize := Filesize(fi_Temp); (* Initialize Variables. *) lo_LineCount := 0; lo_BytesProc := 0; (* Repeat Until entire File has been processed. *) Repeat (* Read in all or a 60K chunk of TEST.doC into the *) (* "buffer" For processing. *) blockread(fi_Temp, byar_Buffer, sizeof(byar_60K), wo_BytesRead); (* Count the number of line-feed Characters in the *) (* "buffer". *) For wo_Index := 1 to wo_BytesRead do if (byar_Buffer[wo_Index] = co_LineFeed) then inc(lo_LineCount); (* Record the number of line-feeds found in the buffer. *) inc(lo_BytesProc, wo_BytesRead) Until (lo_BytesProc = lo_FileSize); (* Close the TEST.doC File. *) close(fi_Temp); (* Display the results. *) Writeln(' total number of lines in linecnt.pas = ', lo_LineCount) end. { ...to find a specific line, you'll have to process the Text File up to the line you are after, then use a "seek" so that you can read in just this line into a String Variable. (You'll have to determine the length of the String, and then set the String's length-Byte.) }
unit SSLDemo.KeyPairFrame; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, OpenSSL.RSAUtils, Vcl.StdCtrls; type TKeyPairFrame = class(TFrame) btnKeyPairGen: TButton; procedure btnKeyPairGenClick(Sender: TObject); private { Private declarations } public { Public declarations } end; implementation {$R *.dfm} procedure TKeyPairFrame.btnKeyPairGenClick(Sender: TObject); var KeyPair: TRSAKeyPair; RSAUtil: TRSAUtil; begin KeyPair := TRSAKeyPair.Create; try KeyPair.GenerateKey; RSAUtil := TRSAUtil.Create; try RSAUtil.PrivateKey := KeyPair.PrivateKey; finally RSAUtil.Free; end; finally KeyPair.Free; end; end; end.
unit API_Crypt; interface uses LbCipher, LbClass; type TCryptParams = record SynchKey: TKey128; end; TCryptEngine = class abstract protected FCrypter: TObject; public function Decrypt(aValue: string): string; virtual; abstract; function Encrypt(aValue: string): string; virtual; abstract; constructor Create(aCryptParams: TCryptParams); virtual; abstract; destructor Destroy; override; end; TCryptEngineClass = class of TCryptEngine; TCryptBlowfish = class(TCryptEngine) private function GetCrypter: TLbBlowfish; public function Decrypt(aValue: string): string; override; function Encrypt(aValue: string): string; override; constructor Create(aCryptParams: TCryptParams); override; property Crypter: TLbBlowfish read GetCrypter; end; implementation constructor TCryptBlowfish.Create(aCryptParams: TCryptParams); begin inherited; FCrypter := TLbBlowfish.Create(nil); Crypter.SetKey(aCryptParams.SynchKey); end; function TCryptBlowfish.GetCrypter: TLbBlowfish; begin Result := FCrypter as TLbBlowfish; end; function TCryptBlowfish.Decrypt(aValue: string): string; begin Result := Crypter.DecryptString(aValue); end; function TCryptBlowfish.Encrypt(aValue: string): string; begin Result := Crypter.EncryptString(aValue); end; destructor TCryptEngine.Destroy; begin FCrypter.Free; inherited; end; end.
unit uMediaHarmonica; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Imaging.jpeg, Vcl.ExtCtrls; type TforMediaHar = class(TForm) labExemplo: TLabel; ImgFundo: TImage; imgExemplo: TImage; EdiValores: TEdit; memoValores: TMemo; ButAdicionarValores: TButton; labResultado: TLabel; butLimpar: TButton; procedure FormActivate(Sender: TObject); procedure EdiValoresDblClick(Sender: TObject); procedure ButAdicionarValoresClick(Sender: TObject); procedure butLimparClick(Sender: TObject); private { Private declarations } Procedure Exemplo; public { Public declarations } end; var forMediaHar: TforMediaHar; implementation {$R *.dfm} { TforMediaHar } procedure TforMediaHar.ButAdicionarValoresClick(Sender: TObject); var contador : integer; valores,calculo: real; resultado : real; begin for contador := 0 to memoValores.Lines.Count -1 do begin valores := valores + (1/strToFloat(memoValores.Lines[contador])); end; calculo := (contador / valores); labResultado.caption := formatFloat('Resultado: ' +'0.00', calculo); end; procedure TforMediaHar.butLimparClick(Sender: TObject); begin ediValores.text:=''; memoValores.lines.Text := ''; labResultado.Caption := 'Resultado'; end; procedure TforMediaHar.EdiValoresDblClick(Sender: TObject); begin memoValores.Lines.Add(ediValores.text); ediValores.Text := ''; end; procedure TforMediaHar.Exemplo; begin labExemplo.Caption := ' O media hamôrnica está relacionada' + #13 + 'ao calculo de grandezas inversamente' + #13 + 'Proporcionais exemplo : tempo e velocidade' + #13+ 'Um carro que percorreu um determinada' + #13 + 'distância na primeira metada estava a 50km/h na' + #13+ 'segunda metade com 60km/h qual é a velocidade média'; end; procedure TforMediaHar.FormActivate(Sender: TObject); begin exemplo; end; end.
unit ConstructorTest; {$mode objfpc}{$H+} interface uses SysUtils, fpcunit, testregistry, uIntXLibTypes, uIntX, uConstants; type { TTestConstructor } TTestConstructor = class(TTestCase) published procedure DefaultCtor(); procedure IntCtor(); procedure UInt32Ctor(); procedure IntArrayCtor(); procedure CallIntArrayNullCtor(); private procedure IntArrayNullCtor(); end; implementation procedure TTestConstructor.DefaultCtor(); begin TIntX.Create(0); end; procedure TTestConstructor.IntCtor(); begin TIntX.Create(7); end; procedure TTestConstructor.UInt32Ctor(); begin TIntX.Create(TConstants.MaxUInt32Value); end; procedure TTestConstructor.IntArrayCtor(); var temp: TIntXLibUInt32Array; begin SetLength(temp, 3); temp[0] := 1; temp[1] := 2; temp[2] := 3; TIntX.Create(temp, True); end; procedure TTestConstructor.IntArrayNullCtor(); var temp: TIntXLibUInt32Array; begin temp := nil; TIntX.Create(temp, False); end; procedure TTestConstructor.CallIntArrayNullCtor(); var TempMethod: TRunMethod; begin TempMethod := @IntArrayNullCtor; AssertException(EArgumentNilException, TempMethod); end; initialization RegisterTest(TTestConstructor); end.
unit UStrings; { Defines common string types and routines on all supported compilers. The code everywhere mostly expects us running on Unicode Delphi, with String type being in UTF16. However, on some compilers we may need to use custom Unicode types, so for maximal compability use UnicodeString and UnicodeChar explicitly. } interface type {$IFNDEF UNICODE} UnicodeString = WideString; {$ENDIF} UnicodeChar = WideChar; PUnicodeChar = PWideChar; TStringArray = array of string; function SplitStr(s: string; cnt: integer; ch: char=','): TStringArray; overload; function SplitStr(s: string; ch: char=','): TStringArray; overload; function UTrim(const S: UnicodeString; const Chars: UnicodeString): UnicodeString; overload; function StartsStr(const substr, str: string): boolean; overload; inline; function StartsStr(substr, str: PChar): boolean; overload; function repl(const s: string; const sub, repl: string): string; overload; { Character processing } type //Character types for EvalChar TEvalCharType = ( EC_UNKNOWN = 0, // unrecognized EC_IDG_CHAR = 1, // ideographic char EC_HIRAGANA = 2, // hiragana EC_KATAKANA = 3, // katakana EC_IDG_PUNCTUATION = 4, // ideographic punctuation EC_IDG_OTHER = 5, // ideographic other EC_LATIN_FW = 6, // full-width latin EC_LATIN_HW = 7, // half-width latin EC_KATAKANA_HW = 8, // half-width katakana EC_BOPOMOFO = 9 // bopomofo ); TEvalCharTypes = set of TEvalCharType; function EvalChar(char: WideChar): TEvalCharType; overload; inline; function EvalChar(const char: UnicodeString): TEvalCharType; overload; inline; //Returns a set of (1 shl EC_*) flags indicating some chars are present in string function EvalChars(const chars: UnicodeString): TEvalCharTypes; implementation uses SysUtils; //Same but doesn't add it anywhere function SplitStr(s: string; cnt: integer; ch:char): TStringArray; var i:integer; begin SetLength(Result, cnt); i:=0; while i<cnt do begin if pos(ch,s)>0 then begin Result[i] := copy(s,1,pos(ch,s)-1); delete(s,1,pos(ch,s)); end else begin Result[i] := s; s:=''; end; inc(i); end; end; //Same but does not use fixed number of parts function SplitStr(s: string; ch: char=','): TStringArray; var i: integer; begin SetLength(Result, 0); i := pos(ch,s); while i>0 do begin SetLength(Result, Length(Result)+1); Result[Length(Result)-1] := copy(s, 1, i-1); delete(s, 1, i); i := pos(ch,s); end; if s<>'' then begin SetLength(Result, Length(Result)+1); Result[Length(Result)-1] := s; end; end; //<= 0 if not found function UCharPos(const Ch: WideChar; const Str: UnicodeString): integer; begin Result := 1; while Result<=Length(Str) do begin if Ch=Str[Result] then exit; Inc(Result); end; Result := -1; end; function UTrim(const S: UnicodeString; const Chars: UnicodeString): UnicodeString; var i_l, i_r: integer; begin //Left side i_l:=1; while i_l<=Length(s) do begin if UCharPos(s[i_l], Chars)<=0 then break; Inc(i_l); end; //Right side i_r:=Length(s); while i_r>=1 do begin if UCharPos(s[i_r], Chars)<=0 then break; Dec(i_r); end; if (i_l=1) and (i_r=Length(s)) then Result := S else if i_r<i_l then Result := '' else Result := Copy(S,i_l,i_r-i_l+1); end; //True if str starts with substr. Delphi version is slow. function StartsStr(const substr, str: string): boolean; begin Result := StartsStr(PChar(substr), PChar(str)); end; function StartsStr(substr, str: PChar): boolean; begin if substr=nil then Result := true else if str=nil then Result := false else begin while (substr^<>#00) and (substr^=str^) do begin Inc(substr); Inc(str); end; Result := (substr^=#00); end; end; function repl(const s:string;const sub,repl:string):string; var i_pos: integer; begin Result := s; i_pos := pos(sub, Result); while i_pos>0 do begin Result:=copy(Result,1,i_pos-1) + repl +copy(Result,i_pos+length(sub),length(Result)-i_pos+1-length(sub)); i_pos := pos(sub,Result); end; end; { Character processing } function EvalChar(char: WideChar): TEvalCharType; var ch: Word absolute char; begin if ch=$3005 then result:=EC_IDG_CHAR else // kurikaeshi if (ch>=$3000) and (ch<=$303F) then result:=EC_IDG_PUNCTUATION else if (ch>=$3040) and (ch<=$309F) then result:=EC_HIRAGANA else if (ch>=$30A0) and (ch<=$30FF) then result:=EC_KATAKANA else if (ch>=$3100) and (ch<=$312F) then result:=EC_BOPOMOFO else if (ch>=$3200) and (ch<=$33FF) then result:=EC_IDG_OTHER else if (ch>=$3400) and (ch<=$9FFF) then result:=EC_IDG_CHAR else if (ch>=$F900) and (ch<=$FAFF) then result:=EC_IDG_CHAR else if (ch>=$FE30) and (ch<=$FE4F) then result:=EC_IDG_PUNCTUATION else if (ch>=$FF00) and (ch<=$FF5F) then result:=EC_LATIN_FW else if (ch>=$FF60) and (ch<=$FF9F) then result:=EC_KATAKANA_HW else if {(ch>=$0000) and} (ch<=$007F) then result:=EC_LATIN_HW else //first part always true result:=EC_UNKNOWN; end; function EvalChar(const char: UnicodeString): TEvalCharType; begin Result := EvalChar(WideChar(PWideChar(char)^)); end; function EvalChars(const chars: UnicodeString): TEvalCharTypes; var i: integer; begin Result := []; for i := 1 to Length(chars) do Result := Result + [EvalChar(chars[i])]; end; end.
unit ExtFontDialog; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, SettingFonts; type TFormSetFonts = class; TExtFontDialog = class(TCommonDialog) private { Private declarations } FormSetFonts: TFormSetFonts; FFileFonts : string; protected { Protected declarations } public { Public declarations } Items : TFontSet; constructor Create( AOwner : TComponent ); override; destructor Destroy; override; function Execute : boolean; procedure LoadFonts; procedure SaveFonts; published { Published declarations } property FileFonts : string read FFileFonts write FFileFonts; end; TFormSetFonts = class(TForm) ListBox1: TListBox; Button1: TButton; Button2: TButton; Label1: TLabel; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } Creator : TExtFontDialog; public { Public declarations } end; procedure Register; implementation {$R *.DFM} procedure Register; begin RegisterComponents('Losev Controls', [TExtFontDialog]); end; constructor TExtFontDialog.Create( AOwner : TComponent ); begin inherited Create( AOwner ); Items:=TFontSet.Create; end; destructor TExtFontDialog.Destroy; begin inherited Destroy; end; function TExtFontDialog.Execute : boolean; begin FormSetFonts:=TFormSetFonts.Create( nil ); FormSetFonts.Creator:=self; Items.AssignGroupsNames( FormSetFonts.ListBox1.Items ); FormSetFonts.ListBox1.ItemIndex:=0; FormSetFonts.ShowModal; Result:=true; end; procedure TExtFontDialog.LoadFonts; begin Items.LoadFonts( FFileFonts ); end; procedure TExtFontDialog.SaveFonts; begin Items.SaveFonts( FFileFonts ); end; procedure TFormSetFonts.Button1Click(Sender: TObject); begin Creator.Items.DialogSetFontGroup( ListBox1.ItemIndex ); end; procedure TFormSetFonts.Button2Click(Sender: TObject); begin Close; end; end.
{$I-,Q-,R-,S-} {Problema 14: Fiesta Vacuna Bronce [Richard Ho, 2006] Una vaca de cada una de N granjas (1 <= N <= 1000) convenientemente numeradas 1..N van a ir a una gran fiesta vacuna que tendrá lugar en la granja #X (1 <= X <= N). Un total de M (1 <= M <= 100,000) carreteras bidireccionales conectan pares de granjas; la carretera i requiere Ti (1 <= Ti <= 100) unidades de tiempo para recorrerse. Algunas granjas están conectadas por dos caminos; todas las granjas están conectadas por al menos una carretera. Después que las vacas se reunen en la granja #X, ellas se dan cuenta que cada vaca se olvidó algo en su granja. Ellas deciden suspender la fiesta y enviar todas las vacas de regreso a sus granjas para traer lo que se les olvidó. Todas las vacas usan rutas optimas para ir a sus granjas y devolverse a la fiesta. ¿Cuál es el mínimo número de unidades de tiempo que la fiesta debe ser suspendida? NOMBRE DEL PROBLEMA: bparty FORMATO DE ENTRADA: * Línea 1: Tres enteros separados por espacios, respectivamente: N, M y X. * Líneas 2..M+1: La línea i+1 describe la carretera i con tres enteros separados por espacios, respectivamente: Ai, Bi, y Ti. La carretera descrita conecta Ai y Bi y requiere Ti unidades de tiempo para recorrerse. Entrada Ejemplo (archivo bparty.in): 4 8 2 1 2 7 1 3 8 1 4 4 2 1 3 2 3 1 3 1 2 3 4 6 4 2 2 DETALLES DE LA ENTRADA: Cuatro vacas; ocho caminos; la fiesta en la granja 2. FORMATO DE SALIDA: * Línea 1: Un entero: la mínima cantidad de tiempo en que la fiesta debe ser suspendida. ARCHIVO EJEMPLO (archivo bparty.out): 6 DETALLES DE LA SALIDA: Existen carreteras directas que conectan a la granja 2 con las otras granjas( a la granja 1: 7 y 3; a la granja 3: 1; a la granja 4: 2). El camino más largo tiene longitud 3, por lo tanto el viaje de ida y vuelta es de 6. ********************************************************************** Translation by Mario Cruz } const mx = 1001; var fe,fs : text; n,m,p,sol : longint; tab : array[1..mx,1..mx] of longint; d : array[0..mx] of longint; s : array[1..mx] of boolean; procedure open; var i,j,a,b : longint; begin assign(fe,'bparty.in'); reset(fe); assign(fs,'bparty.out'); rewrite(fs); readln(fe,n,m,p); fillchar(tab,sizeof(tab),127); for i:=1 to m do begin readln(fe,a,b,j); if tab[a,b] > j then begin tab[a,b]:=j; tab[b,a]:=j; end; end; close(fe); end; procedure work; var i,j,x : longint; begin fillchar(d,sizeof(d),127); d[p]:=0; x:=p; for i:=1 to n-1 do begin s[x]:=true; for j:=1 to n do if (tab[x,j] + d[x] < d[j]) then d[j]:=(tab[x,j] + d[x]); x:=0; for j:=1 to n do if (not s[j]) and (d[j] < d[x]) then x:=j; end; sol:=0; for i:=1 to n do if d[i] > sol then sol:=d[i]; end; procedure closer; begin writeln(fs,sol*2); close(fs); end; begin open; work; closer; end.
{ Copyright (c) 2016, Vencejo Software Distributed under the terms of the Modified BSD License The full license is distributed with this software } unit MainForm; interface uses Windows, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Spin, ooConfig.Intf, ooINIConfig, ooConfigSectionTest; type TMainForm = class(TForm) Edit1: TEdit; CheckBox1: TCheckBox; SpinEdit1: TSpinEdit; SaveButton: TButton; LoadButton: TButton; procedure FormCreate(Sender: TObject); procedure SaveButtonClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure LoadButtonClick(Sender: TObject); private ConfigSectionTest: TConfigSectionTest; function IniFileName: String; procedure ConfigToControls; procedure ControlsToConfig; end; var NewMainForm: TMainForm; implementation {$R *.dfm} function TMainForm.IniFileName: String; begin Result := IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName)) + 'Config.ini'; end; procedure TMainForm.ConfigToControls; begin Edit1.Text := ConfigSectionTest.ValueString; CheckBox1.Checked := ConfigSectionTest.ValueBoolean; SpinEdit1.Value := ConfigSectionTest.ValueInteger; end; procedure TMainForm.ControlsToConfig; begin ConfigSectionTest.ValueString := Edit1.Text; ConfigSectionTest.ValueBoolean := CheckBox1.Checked; ConfigSectionTest.ValueInteger := SpinEdit1.Value; end; procedure TMainForm.SaveButtonClick(Sender: TObject); begin ControlsToConfig; TINIConfig.New(IniFileName).SaveSection(ConfigSectionTest); end; procedure TMainForm.LoadButtonClick(Sender: TObject); begin TINIConfig.New(IniFileName).LoadSection(ConfigSectionTest); ConfigToControls; end; procedure TMainForm.FormCreate(Sender: TObject); begin ConfigSectionTest := TConfigSectionTest.Create; LoadButtonClick(Self); end; procedure TMainForm.FormDestroy(Sender: TObject); begin ConfigSectionTest.Free; end; end.
unit uModelBaseIntf; interface uses DBClient, uParamObject, uBaseInfoDef, uDefCom, uBillData; type IModelBase = interface(IInterface) ['{D4A81B24-B133-4DC4-9BEE-DF637C894A81}'] procedure SetParamList(const Value: TParamObject); end; //基本信息的输入 IModelBaseType = interface(IModelBase) ['{40DF4178-D8D6-4816-80D1-D48D8DC7ED2E}'] procedure OnSetDataEvent(AOnSetDataEvent: TParamDataEvent);//把数据库中的显示到界面 procedure OnGetDataEvent(AOnGetDataEvent: TParamDataEvent);//把界面的数据写到参数表中 function IniData(ATypeId: string): Integer; function DataChangeType: TDataChangeType; // 当前业务操作数据变化类型 function SaveData: Boolean; //保存数据 function CurTypeId: string; //当前ID procedure SetBasicType(const Value: TBasicType); end; //基本信息列表 IModelBaseList = interface(IModelBase) ['{DBBF9289-8356-45B8-B433-065088B600B7}'] function GetBasicType: TBasicType; procedure SetBasicType(const Value: TBasicType); procedure LoadGridData(ATypeid, ACustom: string; ACdsBaseList: TClientDataSet); function DeleteRec(ATypeId: string): Boolean; //删除一条记录 end; //单据操作 IModelBill = interface(IModelBase) ['{192C9A3B-07F4-43E9-952D-8C486AF158C3}'] function SaveBill(const ABillData: TBillData; AOutPutData: TParamObject): Integer; //保存单据 function BillCreate(AModi, AVchType, AVchcode, AOldVchCode: Integer; ADraft: TBillSaveState; AOutPutData: TParamObject): Integer; //单据过账 procedure LoadBillDataMaster(AInParam, AOutParam: TParamObject); //得到单据主表信息 procedure LoadBillDataDetail(AInParam: TParamObject; ACdsD: TClientDataSet); //得到单据从表信息 function GetVchNumber(AParam: TParamObject): Integer;//获取单据编号 end; //报表操作 IModelReport = interface(IModelBase) ['{8AB57955-F14E-4B27-8790-92339017C1B6}'] procedure LoadGridData(AParam: TParamObject; ACdsReport: TClientDataSet); //查询数据 end; implementation end.
{* FtermSSH : An SSH implementation in Delphi for FTerm2 by kxn@cic.tsinghua.edu.cn Cryptograpical code from OpenSSL Project *} unit sshrsa; interface uses SSHBN, sshutil; type RSA_STRUCT = record pad, version: integer; meth: pointer; n, e, d, p, q, dmp1, dmpq1, iqmp: BIGNUM; // there are other members here end; RSA = ^RSA_STRUCT; TSSHRSA = class public rsa: RSA; // no friend class in delphi, sigh constructor Create; destructor Destroy; override; procedure PublicEncrypt(A, B: BIGNUM); end; function RSA_new: RSA; cdecl; external 'libeay32.dll'; procedure RSA_free(r: RSA); cdecl; external 'libeay32.dll'; function RSA_public_encrypt(Len: integer; Source, Dest: Pointer; rsa: RSA; padding: integer): integer; cdecl; external 'libeay32.dll'; procedure MakeKey(Buffer: TSSHBuffer; rsa: TSSHRSA); // this is ssh1 specific implementation procedure MakeKey(Buffer: TSSHBuffer; rsa: TSSHRSA); var i: integer; begin Buffer.GetInteger(i); rsa.rsa.e := BN_new; Buffer.GetSSH1BN(rsa.rsa.e); rsa.rsa.n := BN_new; Buffer.GetSSH1BN(rsa.rsa.n); end; { TSSHRSA } constructor TSSHRSA.Create; begin rsa := RSA_new; end; destructor TSSHRSA.Destroy; begin if rsa <> nil then RSA_Free(rsa); inherited; end; procedure TSSHRSA.PublicEncrypt(A, B: BIGNUM); var inp, outp: Pointer; ilen, len: integer; begin if (BN_num_bits(rsa.e) < 2) or not BN_is_odd(rsa.e) then raise ESSHError.Create('exponent too small or not odd'); GetMem(outp, BN_Num_bytes(rsa.n)); ilen := BN_Num_bytes(B); GetMem(inp, ilen); BN_bn2bin(B, inp); len := RSA_public_encrypt(ilen, inp, outp, rsa, 1); // 1 is RSA_PKCS1_PADDING if len <= 0 then begin FreeMem(inp); FreeMem(outp); // free memory before throwing an exception raise ESSHError.Create('rsa encrypt failed'); end; BN_bin2bn(outp, len, A); FreeMem(outp); FreeMem(inp); end; end.
unit uPrintComissReceipt; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Db, DBTables, ComCtrls, ADODB, siComp, siLangRT, PaiDeForms; const COMIS_AGENCY = 1; COMIS_SALESPRSON = 2; COMIS_OTHER = 3; type TPrintComissReceipt = class(TFrmParentForms) lblPrint: TLabel; pnlPrinter: TPanel; AniPrint: TAnimate; btOk: TButton; quLancamento: TADOQuery; quLancamentoDataLancamento: TDateTimeField; quLancamentoTotalQuitado: TFloatField; quLancamentoIDLancamento: TIntegerField; quLancamentoPessoa: TStringField; quLancamentoValorNominal: TFloatField; quLancamentoPessoaLastName: TStringField; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure btOkClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } //Translation sCommReceipt, sReprint, sNoPayable, sDate, sAmount, sAgency, sSP, sCommis, sSignature, sNome, sPayBy, sEndTicket, sRecImpresso, sClickOK : String; MyIDLancamento : Integer; Quit : Boolean; procedure ImpHeaderReceipt(Date: TDateTime; Valor: Currency; Title, Pessoa : String; Reprint: Boolean); procedure ImpFooter; public { Public declarations } procedure Start(IDLancamento : Integer; Tipo : integer; Reprint: Boolean); end; implementation uses uDM, uPassword, XBase, uMsgBox, uMsgConstant, uNumericFunctions, uSqlFunctions, uDateTimeFunctions, uDMGlobal; {$R *.DFM} procedure TPrintComissReceipt.Start( IDLancamento : Integer; Tipo : integer; Reprint: Boolean); var Title : String; NotOk: Boolean; begin Quit := False; MyIDLancamento := IDLancamento; with quLancamento do begin Parameters.ParambyName('IDLancamento').Value := MyIDLancamento; Open; end; Show; Update; Application.ProcessMessages; NotOk := True; while NotOk do begin try DM.PrinterStart; NotOk := False; except if MsgBox(MSG_CRT_ERROR_PRINTING, vbCritical + vbYesNo) = vbYes then NotOk := True else begin Exit; end; end; end; case Tipo of COMIS_AGENCY : Title := sAgency; COMIS_SALESPRSON : Title := sSP; COMIS_OTHER : Title := sCommis; end; // ----------------------------------------------------------------- // Impressão do cabecalho do ticket ImpHeaderReceipt( quLancamentoDataLancamento.AsDateTime, quLancamentoValorNominal.AsCurrency, Title, quLancamentoPessoa.AsString, Reprint); // ----------------------------------------------------------------- // Impressão dos Totais ImpFooter; DM.PrintLine(Chr(27)+Chr(12)); DM.PrinterStop; lblPrint.Caption := sRecImpresso; btOk.Visible := True; AniPrint.Active := False; AniPrint.Visible := False; pnlPrinter.Caption := sClickOK; Close; end; procedure TPrintComissReceipt.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; procedure TPrintComissReceipt.ImpHeaderReceipt(Date: TDateTime; Valor: Currency ; Title, Pessoa : String; Reprint: Boolean); begin DM.PrintLine('========================================'); DM.PrintLine(sCommReceipt); DM.PrintLine(' ---------------------------------- '); DM.PrintLine(''); if Reprint then begin DM.PrintLine(''); DM.PrintLine(' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! '); DM.PrintLine(sReprint); DM.PrintLine(sNoPayable); DM.PrintLine(' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! '); DM.PrintLine(''); end; DM.PrintLine(Title + ' ' + Pessoa); DM.PrintLine(''); DM.PrintLine(sDate + DateToStr(Date) ); DM.PrintLine(sAmount + FormatCurr('#,##0.00', Valor)); DM.PrintLine(''); DM.PrintLine(''); end; procedure TPrintComissReceipt.ImpFooter(); begin DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(' ------------------------------------ '); DM.PrintLine(sSignature); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(' ------------------------------------ '); DM.PrintLine(sNome); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(' ------------------------------------ '); DM.PrintLine(sPayBy); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(sEndTicket); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(''); DM.PrintLine(''); end; procedure TPrintComissReceipt.FormShow(Sender: TObject); begin // Associa o fileName do Avi AniPrint.Active := True; btOk.Visible := False; end; procedure TPrintComissReceipt.btOkClick(Sender: TObject); begin Close; end; procedure TPrintComissReceipt.FormCreate(Sender: TObject); begin inherited; Case DMGlobal.IDLanguage of LANG_ENGLISH : begin sCommReceipt := ' C O M M I S S I O N R E C E I P T '; sReprint := ' !! R E P R I N T !! '; sNoPayable := ' !! N O T P A Y A B L E !! '; sDate := ' Date : '; sAmount := ' Amount : '; sSignature := ' Signature'; sNome := ' Name'; sPayBy := ' Payed By'; sEndTicket := '===============END OF TICKET============'; sAgency := 'Agency :'; sSP := 'Sales Person :'; sCommis := 'Commission :'; sRecImpresso := 'Receipt Printed'; sClickOK := 'Click OK to continue'; end; LANG_PORTUGUESE : begin sCommReceipt := ' R E C I B O DE C O M I S S A O '; sReprint := ' !! R E I M P R E S S O !! '; sNoPayable := ' !! N Ã O P A G A R !! '; sDate := ' Data : '; sAmount := ' Valor : '; sSignature := ' Assinatura'; sNome := ' Nome'; sPayBy := ' Pago por'; sEndTicket := '=============FINAL DO RECIBO============'; sAgency := 'Agencia :'; sSP := 'Vendedor :'; sCommis := 'Comissionado :'; sRecImpresso := 'Recibo Impresso'; sClickOK := 'Clique OK para continuar'; end; LANG_SPANISH : begin sCommReceipt := ' R E C I B O DE C O M I S I O N '; sReprint := ' !! D U P L I C A D O !! '; sNoPayable := ' !! N O P A G A R !! '; sDate := ' Fecha : '; sAmount := ' Valor : '; sSignature := ' Firma'; sNome := ' Nombre'; sPayBy := ' Pagado por'; sEndTicket := '==============FINAL DEL RECIBO=========='; sAgency := 'Agencia :'; sSP := 'Vendedor :'; sCommis := 'Comisión :'; sRecImpresso := 'Recibo Imprimido'; sClickOK := 'Clic OK para continuar'; end; end; end; end.