text
stringlengths
14
6.51M
// ================================================= // Main window form. Contains the frames with // players checker. // Form principal da aplicaço. Contem os frames com // as informações dos outros jogadores. // ================================================= unit uMainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, jpeg, Buttons, Menus, uFrameStatusPlayer; type TMainForm = class(TForm) MainPanel: TPanel; DefaultImage: TImage; QuitSpeedButton: TSpeedButton; PopupMenu1: TPopupMenu; AlwaysVisibleMenu: TMenuItem; QuitMenu: TMenuItem; FrameStatusPlayer1: TFrameStatusPlayer; FrameStatusPlayer2: TFrameStatusPlayer; FrameStatusPlayer3: TFrameStatusPlayer; FrameStatusPlayer4: TFrameStatusPlayer; TransparenceMenu: TMenuItem; procedure QuitSpeedButtonClick(Sender: TObject); procedure QuitMenuClick(Sender: TObject); procedure DefaultImageMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure TransparenceMenuClick(Sender: TObject); procedure AlwaysVisibleMenuClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FrameStatusPlayer2CheckStatusTimer(Sender: TObject); procedure FrameStatusPlayer2CheckPlayerHealthTimer(Sender: TObject); private { Private declarations } procedure WMNCHitTest(var Msg: TWMNCHitTest); message wm_NCHitTest; public { Public declarations } constructor Create(AOwner: TComponent); override; end; var MainForm: TMainForm; implementation uses uRedPhantom, uWhitePhantom, uDefaultPlayer, uBluePhantom; {$R *.dfm} //Procedure: Aways Visible Option //Procedure: Opção "Sempre Visível" procedure TMainForm.AlwaysVisibleMenuClick(Sender: TObject); begin if AlwaysVisibleMenu.Checked then begin AlwaysVisibleMenu.Checked := False; SetWindowPos(MainForm.Handle, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE or SWP_SHOWWINDOW); end else begin AlwaysVisibleMenu.Checked := True; SetWindowPos(MainForm.Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE or SWP_SHOWWINDOW); end; end; constructor TMainForm.Create(AOwner: TComponent); begin inherited; end; // Create the players for the frames // Instancia os jogadores para os frames procedure TMainForm.FormShow(Sender: TObject); begin FrameStatusPlayer1.Warrior := TDefaultPlayer.Create; FrameStatusPlayer2.Warrior := TRedPhantom.Create; FrameStatusPlayer3.Warrior := TBluePhantom.Create; FrameStatusPlayer4.Warrior := TWhitePhantom.Create; end; procedure TMainForm.FrameStatusPlayer2CheckPlayerHealthTimer(Sender: TObject); begin FrameStatusPlayer2.CheckPlayerHealthTimer(Sender); end; procedure TMainForm.FrameStatusPlayer2CheckStatusTimer(Sender: TObject); begin FrameStatusPlayer2.CheckStatusTimer(Sender); end; // Move the window by the mouse // Move a janela arrastando com o mouse procedure TMainForm.DefaultImageMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin ReleaseCapture; SendMessage(MainForm.Handle, WM_SYSCOMMAND, 61458, 0); end; // Option for transparency window (wrong grammar :( ) // Opção para transparencia procedure TMainForm.TransparenceMenuClick(Sender: TObject); var AlphaValueOp: String; begin if TransparenceMenu.Checked then begin TransparenceMenu.Checked := False; MainForm.AlphaBlend := False; end else begin TransparenceMenu.Checked := True; AlphaValueOp := InputBox('Transparência', 'Defina o valor de transparência (0-255)', '255'); try MainForm.AlphaBlendValue := StrToInt(AlphaValueOp); except MainForm.AlphaBlend := False; ShowMessage('Valor inválido'); TransparenceMenuClick(Sender); end; MainForm.AlphaBlend := True; end; end; // Exit application by calling speedbutton click // Sair da aplicação chamando o evento do speedbutton procedure TMainForm.QuitMenuClick(Sender: TObject); begin QuitSpeedButtonClick(nil); end; // Exit application // Sair da aplicação procedure TMainForm.QuitSpeedButtonClick(Sender: TObject); begin Application.Terminate; end; procedure TMainForm.WMNCHitTest(var Msg: TWMNCHitTest); begin inherited; if Msg.Result = htClient then Msg.Result := htCaption; end; end.
unit AutoLoadPicturesAndDocumentsFromLoadingDock; {To use this template: 1. Save the form it under a new name. 2. Rename the form in the Object Inspector. 3. Rename the table in the Object Inspector. Then switch to the code and do a blanket replace of "Table" with the new name. 4. Change UnitName to the new unit name.} interface uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, DBCtrls, DBTables, DB, Buttons, Grids, Wwdbigrd, Wwdbgrid, ExtCtrls, Wwtable, Wwdatsrc, Menus, RPCanvas, RPrinter, RPDefine, RPBase, RPFiler, locatdir, TMultiP, RenameDialog; type TImportPicturesFromLoadingDockForm = class(TForm) Panel2: TPanel; ScrollBox1: TScrollBox; ReportFiler: TReportFiler; PrintDialog: TPrintDialog; ReportPrinter: TReportPrinter; ParcelTable: TTable; LocateDirectoryDialog: TLocateDirectoryDlg; Panel1: TPanel; ImportButton: TBitBtn; Panel4: TPanel; ScrollBox: TScrollBox; ItemPanel1: TPanel; Panel7: TPanel; Image1: TPMultiImage; PicturesToImportLabel: TLabel; Label2: TLabel; Label3: TLabel; EditFileName1: TEdit; EditParcelID1: TEdit; Label4: TLabel; OptionsGroupBox: TGroupBox; Label1: TLabel; DirectoryEdit: TEdit; DirectoryLocateButton: TButton; ReportFilesNotLoadedCheckBox: TCheckBox; UseEndOfFileNameAsNotesCheckBox: TCheckBox; ErrorPanel1: TPanel; ItemPanel2: TPanel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Panel5: TPanel; Image2: TPMultiImage; EditFileName2: TEdit; EditParcelID2: TEdit; ErrorPanel2: TPanel; PictureTable: TTable; PictureLookupTable: TTable; RenameButton1: TBitBtn; LocateButton1: TBitBtn; LocateButton2: TBitBtn; RenameButton2: TBitBtn; RenameDialogBox: TRenameDialogBox; SwisCodeTable: TTable; Notes1: TEdit; Notes2: TEdit; ImportActionRadioGroup1: TRadioGroup; ImportActionRadioGroup2: TRadioGroup; ItemPanel3: TPanel; Label8: TLabel; Label9: TLabel; Label10: TLabel; Panel6: TPanel; Image3: TPMultiImage; EditFileName3: TEdit; EditParcelID3: TEdit; ErrorPanel3: TPanel; RenameButton3: TBitBtn; LocateButton3: TBitBtn; Notes3: TEdit; ImportActionRadioGroup3: TRadioGroup; ItemPanel4: TPanel; Label11: TLabel; Label12: TLabel; Label13: TLabel; Panel10: TPanel; Image4: TPMultiImage; EditFileName4: TEdit; EditParcelID4: TEdit; ErrorPanel4: TPanel; RenameButton4: TBitBtn; LocateButton4: TBitBtn; Notes4: TEdit; ImportActionRadioGroup4: TRadioGroup; ValidPicturesLabel: TLabel; ErrorPicturesLabel: TLabel; ItemPanel5: TPanel; Label14: TLabel; Label15: TLabel; Label16: TLabel; Panel8: TPanel; Image5: TPMultiImage; EditFileName5: TEdit; EditParcelID5: TEdit; ErrorPanel5: TPanel; RenameButton5: TBitBtn; LocateButton5: TBitBtn; Notes5: TEdit; ImportActionRadioGroup5: TRadioGroup; ItemPanel6: TPanel; Label17: TLabel; Label18: TLabel; Label19: TLabel; Panel12: TPanel; Image6: TPMultiImage; EditFileName6: TEdit; EditParcelID6: TEdit; ErrorPanel6: TPanel; RenameButton6: TBitBtn; LocateButton6: TBitBtn; Notes6: TEdit; ImportActionRadioGroup6: TRadioGroup; CloseButton: TBitBtn; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure ImportButtonClick(Sender: TObject); procedure ReportPrintHeader(Sender: TObject); procedure ReportPrint(Sender: TObject); procedure DirectoryLocateButtonClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure RenameButtonClick(Sender: TObject); procedure LocateButtonClick(Sender: TObject); procedure UseEndOfFileNameAsNotesCheckBoxClick(Sender: TObject); procedure ImportActionRadioGroupClick(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure CloseButtonClick(Sender: TObject); private { Private declarations } public { Public declarations } UnitName : String; AssessmentYear, OriginalFileName : String; ReportCancelled, ImportDone, PrintSubHeader, UseEndOfFileNameAsNotes : Boolean; PicturesLoadedList, PicturesDeletedList, PicturesNotLoadedList : TList; ItemPanel, ErrorPanel : TPanel; Image : TPMultiImage; EditFileName, EditParcelID, Notes : TEdit; RenameButton, LocateButton : TBitBtn; ImportActionRadioGroup : TRadioGroup; PicturesThisBatch : Integer; PicturesPrinted, PrintPicturesNotLoaded : Boolean; Procedure InitializeForm; {Open the tables and setup.} Procedure SetImportPictureCaption; Procedure LoadPicturesForPreview; Procedure GetComponentsForThisPicturePanel(I : Integer); Procedure ClearAllPanels; Procedure GetParcelIDForPictureName( PictureFileName : String; var SwisSBLKey : String; var PictureNote : String; var Error : Boolean; var ErrorMessage : String; var ErrorType : Integer); Procedure LoadOnePicture(PictureFileName : String; PictureFilePath : String; PictureNumber : Integer); Procedure PrintThePictureReport; Function CheckPictureFileName(NewFileName : String) : Boolean; Procedure ImportThePictures( PictureActionList : TStringList; PicturesLoadedList : TList; PicturesDeletedList : TList; PicturesNotLoadedList : TList; var Quit : Boolean); end; PictureListRecord = record SwisSBLKey : String; FileName : String; Notes : String; ImportAction : Integer; end; PPictureListPointer = ^PictureListRecord; implementation uses GlblVars, WinUtils, Utilitys, GlblCnst, PASUtils, Prog, Preview, Types, PASTypes; {$R *.DFM} const PicturesPerBatch = 6; {Error types} etNone = 0; etInvalidPictureType = 1; etBadParcelID = 2; etMultipleParcelID = 3; etPictureAlreadyExists = 4; {Action Types} acTransfer = 0; acLeaveInDirectory = 1; acDelete = 2; {========================================================} Procedure TImportPicturesFromLoadingDockForm.FormActivate(Sender: TObject); begin SetFormStateMaximized(Self); end; {========================================================} Function PictureInList( PictureList : TList; _FileName : String; var Index : Integer) : Boolean; var I : Integer; begin Index := -1; Result := False; For I := 0 to (PictureList.Count - 1) do If (PPictureListPointer(PictureList[I])^.FileName = _FileName) then begin Result := True; Index := I; end; end; {PictureInList} {========================================================} Procedure AddOnePictureListItem(PictureList : TList; _SwisSBLKey : String; _FileName : String; _Notes : String; _ImportAction : Integer); var PPictureListPtr : PPictureListPointer; Index : Integer; begin {FX04232004-1(2.07l3): Make sure that the picture does not already exist in the list.} If not PictureInList(PictureList, _FileName, Index) then begin New(PPictureListPtr); with PPictureListPtr^ do begin SwisSBLKey := _SwisSBLKey; FileName := _FileName; Notes := _Notes; ImportAction := _ImportAction; end; PictureList.Add(PPictureListPtr); end; {If not PictureInList(PictureList, _FileName, Index)} end; {AddOnePictureListItem} {========================================================} Function FindFileInPictureList(PicturesList : TList; _FileName : String) : Boolean; var I : Integer; begin Result := False; For I := 0 to (PicturesList.Count - 1) do If (Trim(PPictureListPointer(PicturesList[I])^.FileName) = Trim(_FileName)) then Result := True; end; {FindFileInPictureList} {========================================================} Procedure TImportPicturesFromLoadingDockForm.SetImportPictureCaption; var I, PicturesThisBatch, NumErrors, NumValid : Integer; begin PicturesThisBatch := 0; NumErrors := 0; NumValid := 0; For I := 1 to PicturesPerBatch do begin GetComponentsForThisPicturePanel(I); If ItemPanel.Visible then begin PicturesThisBatch := PicturesThisBatch + 1; If (Deblank(ErrorPanel.Caption) = '') then NumValid := NumValid + 1 else NumErrors := NumErrors + 1; end; {If ItemPanel.Visible} end; {For I := 1 to PicturesPerBatch do} PicturesToImportLabel.Caption := 'Pictures to Import (' + IntToStr(PicturesThisBatch) + ' this batch):'; ValidPicturesLabel.Caption := 'Valid Pictures: ' + IntToStr(NumValid); ErrorPicturesLabel.Caption := 'Pictures in Error: ' + IntToStr(NumErrors); end; {SetImportPictureCaption} {========================================================} Function FileExistsInPictureDirectory( PictureFileName : String; PictureDirectory : String; PictureDirectoryType : String; var ErrorMessage : String; var ErrorType : Integer) : Boolean; var FileAttributes, ReturnCode : Integer; TempFile : TSearchRec; begin Result := False; FileAttributes := SysUtils.faArchive + SysUtils.faReadOnly; ReturnCode := FindFirst(PictureDirectory + PictureFileName, FileAttributes, TempFile); If (ReturnCode = 0) then begin Result := True; ErrorMessage := 'Picture with this name already exists in ' + PictureDirectoryType + ' picture directory.'; ErrorType := etPictureAlreadyExists; end; end; {If not Error} {========================================================} Procedure TImportPicturesFromLoadingDockForm.GetParcelIDForPictureName( PictureFileName : String; var SwisSBLKey : String; var PictureNote : String; var Error : Boolean; var ErrorMessage : String; var ErrorType : Integer); {There are 3 errors to check for: 1. Can't match the parcel ID. 2. Can match multiple parcel IDs. 3. Picture with that name already exists.} var SBLRec : SBLRecord; _Found, ValidEntry, PictureNameAlreadyMatched : Boolean; TempFileName, LastPictureMatchedSwisSBLKey : String; PicturesMatched : TStringList; I : Integer; begin ErrorType := etNone; Error := False; ErrorMessage := ''; PicturesMatched := TStringList.Create; SwisSBLKey := ''; {This is how to determine if this is a valid picture name, if there are mulstiples and what the notes are: Take the first character of the file name, convert it to a swis sbl and attempt to look it up. If if matches a parcel exactly, make a note of the parcel and everything else in the picture is a note (if they selected this option). Then, take the first 2 characters and do the same. Continue until all characters in the name are being tested on. If multiple matches have been made, then mark this as an error picture and tell the user what parcels are matched.} TempFileName := PictureFileName[1]; PictureNameAlreadyMatched := False; LastPictureMatchedSwisSBLKey := ''; ParcelTable.IndexName := 'BYTAXROLLYR_SBLKEY'; {FXX03172004-1(2.08): Redo checking for duplicate matches. The way it should work is that once we find a match, we keep searching until it no longer matches. The last match is really the one we should use and the note is everything after it. This means that 100.20.1.43Front.jpg will have a note of 'Front' and be matched correctly even if there is also a 100.20.1.4 parcel and not be listed as duplicate.} For I := 2 to Length(PictureFileName) do begin SBLRec := ConvertDashDotSBLToSegmentSBL(TempFileName, ValidEntry); If ValidEntry then begin with SBLRec do _Found := FindKeyOld(ParcelTable, ['TaxRollYr', 'Section', 'Subsection', 'Block', 'Lot', 'Sublot', 'Suffix'], [AssessmentYear, Section, Subsection, Block, Lot, Sublot, Suffix]); If _Found then begin PictureNameAlreadyMatched := True; LastPictureMatchedSwisSBLKey := ExtractSSKey(ParcelTable); end else If PictureNameAlreadyMatched then begin PictureNameAlreadyMatched := False; PicturesMatched.Add(LastPictureMatchedSwisSBLKey); SwisSBLKey := LastPictureMatchedSwisSBLKey; If UseEndOfFileNameAsNotes then PictureNote := Trim(Copy(ChangeFileExt(PictureFileName, ''), (I - 1), 255)) else PictureNote := ''; end; {If PictureNameAlreadyMatched} end; {If ValidEntry} TempFileName := TempFileName + PictureFileName[I]; end; {For I := 2 to Length(PictureFileName);} ParcelTable.IndexName := 'BYTAXROLLYR_SWISSBLKEY'; If (PicturesMatched.Count = 0) then begin Error := True; ErrorMessage := 'No parcel could be matched to the picture file name.'; ErrorType := etBadParcelID; end; If (PicturesMatched.Count > 1) then begin Error := True; ErrorMessage := 'More than 1 parcel could be matched: (' + ConvertSwisSBLToDashDot(PicturesMatched[0]) + ' ' + ConvertSwisSBLToDashDot(PicturesMatched[1]) + ')'; ErrorType := etMultipleParcelID; end; {If (PicturesMatched.Count > 1)} {If everything is OK so far, then make sure this picture does not already exist in the main picture directory.} If not Error then Error := FileExistsInPictureDirectory(PictureFileName, GlblPictureDir, 'main', ErrorMessage, ErrorType); PicturesMatched.Free; end; {GetParcelIDForPictureName} {========================================================} Procedure TImportPicturesFromLoadingDockForm.GetComponentsForThisPicturePanel(I : Integer); var TempComponentName : String; begin TempComponentName := 'ItemPanel' + IntToStr(I); ItemPanel := TPanel(FindComponent(TempComponentName)); TempComponentName := 'Image' + IntToStr(I); Image := TPMultiImage(FindComponent(TempComponentName)); TempComponentName := 'EditFileName' + IntToStr(I); EditFileName := TEdit(FindComponent(TempComponentName)); TempComponentName := 'EditParcelID' + IntToStr(I); EditParcelID := TEdit(FindComponent(TempComponentName)); TempComponentName := 'Notes' + IntToStr(I); Notes := TEdit(FindComponent(TempComponentName)); TempComponentName := 'ErrorPanel' + IntToStr(I); ErrorPanel := TPanel(FindComponent(TempComponentName)); TempComponentName := 'ImportActionRadioGroup' + IntToStr(I); ImportActionRadioGroup := TRadioGroup(FindComponent(TempComponentName)); TempComponentName := 'RenameButton' + IntToStr(I); RenameButton := TBitBtn(FindComponent(TempComponentName)); TempComponentName := 'LocateButton' + IntToStr(I); LocateButton := TBitBtn(FindComponent(TempComponentName)); end; {GetComponentsForThisPicturePanel} {========================================================} Procedure TImportPicturesFromLoadingDockForm.ClearAllPanels; var I : Integer; begin For I := 1 to PicturesPerBatch do begin GetComponentsForThisPicturePanel(I); Image.ImageName := ''; EditFileName.Text := ''; EditParcelID.Text := ''; Notes.Text := ''; ErrorPanel.Caption := ''; ItemPanel.Color := clBtnFace; ItemPanel.Visible := False; end; {For I := 1 to PicturesPerBatch do} end; {ClearAllPanels} {========================================================} Procedure TImportPicturesFromLoadingDockForm.LoadOnePicture(PictureFileName : String; PictureFilePath : String; PictureNumber : Integer); var SwisSBLKey, PictureNote, ErrorMessage : String; Error, ValidPicture : Boolean; ErrorType : Integer; begin ErrorType := etNone; PictureFileName := Trim(PictureFileName); ValidPicture := True; GetComponentsForThisPicturePanel(PictureNumber); ItemPanel.Visible := True; ItemPanel.Color := clBtnFace; try Image.ImageName := PictureFilePath + PictureFileName; except Image.ImageName := ''; ErrorMessage := 'Not a valid picture file type.'; ErrorType := etInvalidPictureType; ValidPicture := False; end; EditFileName.Text := PictureFileName; If ValidPicture then GetParcelIDForPictureName(PictureFileName, SwisSBLKey, PictureNote, Error, ErrorMessage, ErrorType); If (Error or (not ValidPicture)) then begin ItemPanel.Color := $007C59E6; ErrorPanel.Visible := True; ErrorPanel.Caption := ErrorMessage; ImportActionRadioGroup.ItemIndex := acLeaveInDirectory; If (ErrorType = etPictureAlreadyExists) then EditParcelID.Text := ConvertSwisSBLToDashDot(SwisSBLKey); If ((ErrorType = etBadParcelID) or (ErrorType = etMultipleParcelID)) then EditParcelID.Text := ''; end else begin ErrorPanel.Visible := False; ErrorPanel.Caption := ''; ImportActionRadioGroup.ItemIndex := acTransfer; EditParcelID.Text := ConvertSwisSBLToDashDot(SwisSBLKey); If (Deblank(PictureNote) <> '') then Notes.Text := PictureNote; end; {If (Error or...} end; {LoadOnePicture} {========================================================} Procedure TImportPicturesFromLoadingDockForm.LoadPicturesForPreview; var TempComponentName, Directory : String; TempFile : TSearchRec; I, FileAttributes, ReturnCode : Integer; begin PicturesThisBatch := 0; Directory := DirectoryEdit.Text; ClearAllPanels; FileAttributes := SysUtils.faArchive + SysUtils.faReadOnly; ReturnCode := FindFirst(Directory + '*.*', FileAttributes, TempFile); while ((ReturnCode = 0) and (PicturesThisBatch < PicturesPerBatch)) do begin If ((TempFile.Name <> '.') and (TempFile.Name <> '..') and (not FindFileInPictureList(PicturesLoadedList, TempFile.Name))) then begin LoadOnePicture(StripPath(TempFile.Name), Directory, PicturesThisBatch + 1); PicturesThisBatch := PicturesThisBatch + 1; end; {If ((TempFile.Name <> '.') and} ReturnCode := FindNext(TempFile); end; {while (ReturnCode = 0) do} {Set Visible to False for any unused panels.} For I := (PicturesThisBatch + 1) to (PicturesPerBatch - 1) do begin TempComponentName := 'ItemPanel' + IntToStr(I + 1); TPanel(FindComponent(TempComponentName)).Visible := False; end; SetImportPictureCaption; ScrollBox.VertScrollBar.Position := 0; end; {LoadPicturesForPreview} {========================================================} Procedure TImportPicturesFromLoadingDockForm.InitializeForm; begin UnitName := 'AutoLoadPicturesAndDocumentsFromLoadingDock'; {mmm} ImportDone := False; OpenTablesForForm(Self, GlblProcessingType); AssessmentYear := GetTaxRlYr; DirectoryEdit.Text := AddDirectorySlashes(ExpandPASPath(GlblDefaultPictureLoadingDockDirectory)); UseEndOfFileNameAsNotes := UseEndOfFileNameAsNotesCheckBox.Checked; PicturesLoadedList := TList.Create; PicturesNotLoadedList := TList.Create; PicturesDeletedList := TList.Create; PicturesPrinted := False; If (Deblank(DirectoryEdit.Text) <> '') then LoadPicturesForPreview; end; {InitializeForm} {===================================================================} Procedure TImportPicturesFromLoadingDockForm.FormKeyPress( Sender: TObject; var Key: Char); begin If (Key = #13) then begin Key := #0; Perform(WM_NEXTDLGCTL, 0, 0); end; end; {FormKeyPress} {===================================================================} Procedure TImportPicturesFromLoadingDockForm.DirectoryLocateButtonClick(Sender: TObject); begin If (Deblank(DirectoryEdit.Text) <> '') then LocateDirectoryDialog.Directory := DirectoryEdit.Text; If LocateDirectoryDialog.Execute then DirectoryEdit.Text := LocateDirectoryDialog.Directory; end; {DirectoryLocateButtonClick} {===================================================================} Function GetImportActionName(ImportAction : Integer) : String; begin case ImportAction of acTransfer : Result := 'Imported'; acLeaveInDirectory : Result := 'Left in dock'; acDelete : Result := 'Deleted'; else Result := ''; end; {case ImportAction of} end; {GetImportActionName} {===================================================================} Procedure TImportPicturesFromLoadingDockForm.ReportPrintHeader(Sender: TObject); begin with Sender as TBaseReport do begin {Print the date and page number.} SectionTop := 0.25; SectionLeft := 0.5; SectionRight := PageWidth - 0.5; SetFont('Times New Roman',8); PrintHeader('Page: ' + IntToStr(CurrentPage), pjRight); PrintHeader('Date: ' + DateToStr(Date) + ' Time: ' + TimeToStr(Now), pjLeft); SectionTop := 0.5; SetFont('Arial',12); Bold := True; Home; PrintCenter('Pictures Automatically Loaded', (PageWidth / 2)); SetFont('Times New Roman', 9); CRLF; Println(''); Println('Directory to load from: ' + DirectoryEdit.Text); Println(''); end; {with Sender as TBaseReport do} end; {ReportPrintHeader} {===================================================================} Procedure PrintPageHeader(Sender : TObject); begin with Sender as TBaseReport do begin Bold := True; ClearTabs; SetTab(0.3, pjCenter, 1.5, 0, BOXLINEBottom, 0); {Parcel ID} SetTab(1.9, pjCenter, 2.0, 0, BOXLINEBottom, 0); {File name} SetTab(4.0, pjCenter, 3.1, 0, BOXLINEBottom, 0); {Notes} SetTab(7.2, pjCenter, 0.8, 0, BOXLINEBottom, 0); {Action} Println(#9 + 'Parcel ID' + #9 + 'File Name' + #9 + 'Notes' + #9 + 'Action'); ClearTabs; SetTab(0.3, pjLeft, 1.5, 0, BOXLINENONE, 0); {Parcel ID} SetTab(1.9, pjLeft, 2.0, 0, BOXLINENONE, 0); {File name} SetTab(4.0, pjLeft, 3.1, 0, BOXLINENONE, 0); {Notes} SetTab(7.2, pjLeft, 0.8, 0, BOXLINENONE, 0); {Action} Bold := False; end; {with Sender as TBaseReport do} end; {PrintPageHeader} {===================================================================} Procedure PrintSectionHeader(Sender : TObject; SectionHeader : String); begin with Sender as TBaseReport do begin Println(''); ClearTabs; SetTab(0.3, pjCenter, 1.5, 0, BOXLINEBottom, 0); {Parcel ID} Bold := True; Underline := True; Println(#9 + SectionHeader + ':'); Bold := False; Underline := False; Println(''); end; {with Sender as TBaseReport do} end; {PrintSectionHeader} {===================================================================} Procedure PrintOnePictureReportSection(Sender : TObject; PicturesList : TList; SectionHeader : String); var I : Integer; TempParcelID : String; begin with Sender as TBaseReport do begin PrintSectionHeader(Sender, SectionHeader); PrintPageHeader(Sender); For I := 0 to (PicturesList.Count - 1) do begin If (LinesLeft < 5) then begin NewPage; PrintSectionHeader(Sender, SectionHeader); PrintPageHeader(Sender); end; with PPictureListPointer(PicturesList[I])^ do begin If (Deblank(SwisSBLKey) = '') then TempParcelID := 'Unknown' else TempParcelID := ConvertSBLOnlyToDashDot(Copy(SwisSBLKey, 7, 20)); Println(#9 + TempParcelID + #9 + FileName + #9 + Notes + #9 + GetImportActionName(ImportAction)); end; {with PPictureListPointer(PicturesList)^ do} end; {with Sender as TBaseReport do} end; {with Sender as TBaseReport do} end; {PrintOnePictureReportSection} {===================================================================} Procedure TImportPicturesFromLoadingDockForm.ReportPrint(Sender: TObject); begin PicturesPrinted := True; PrintOnePictureReportSection(Sender, PicturesLoadedList, 'Pictures Loaded'); PrintOnePictureReportSection(Sender, PicturesDeletedList, 'Pictures Deleted'); If PrintPicturesNotLoaded then PrintOnePictureReportSection(Sender, PicturesNotLoadedList, 'Pictures Not Loaded'); end; {ReportPrint} {===================================================================} Procedure TImportPicturesFromLoadingDockForm.PrintThePictureReport; var NewFileName : String; TempFile : File; Quit : Boolean; begin SetPrintToScreenDefault(PrintDialog); Quit := False; If PrintDialog.Execute then begin {CHG10131998-1: Set the printer settings based on what printer they selected only - they no longer need to worry about paper or landscape mode.} AssignPrinterSettings(PrintDialog, ReportPrinter, ReportFiler, [ptLaser], False, Quit); {Now print the report.} If not (Quit or ReportCancelled) then begin {If they want to preview the print (i.e. have it go to the screen), then we need to come up with a unique file name to tell the ReportFiler component where to put the output. Once we have done that, we will execute the report filer which will print the report to that file. Then we will create and show the preview print form and give it the name of the file. When we are done, we will delete the file and make sure that we go back to the original directory.} If PrintDialog.PrintToFile then begin NewFileName := GetPrintFileName(Self.Caption, True); ReportFiler.FileName := NewFileName; try PreviewForm := TPreviewForm.Create(self); PreviewForm.FilePrinter.FileName := NewFileName; PreviewForm.FilePreview.FileName := NewFileName; ReportFiler.Execute; {FXX10111999-3: Make sure they know its done.} ProgressDialog.StartPrinting(PrintDialog.PrintToFile); PreviewForm.ShowModal; finally PreviewForm.Free; {Now delete the file.} try AssignFile(TempFile, NewFileName); OldDeleteFile(NewFileName); finally {We don't care if it does not get deleted, so we won't put up an error message.} ChDir(GlblProgramDir); end; end; {try PreviewForm := ...} end {If PrintDialog.PrintToFile} else ReportPrinter.Execute; ResetPrinter(ReportPrinter); end; {If not Quit} ClearTList(PicturesLoadedList, SizeOf(PictureListRecord)); ClearTList(PicturesNotLoadedList, SizeOf(PictureListRecord)); ClearTList(PicturesDeletedList, SizeOf(PictureListRecord)); PicturesPrinted := False; end; {If PrintDialog.Execute} end; {PrintThePictureReport} {===================================================================} Procedure TImportPicturesFromLoadingDockForm.ImportThePictures( PictureActionList : TStringList; PicturesLoadedList : TList; PicturesDeletedList : TList; PicturesNotLoadedList : TList; var Quit : Boolean); var I, PictureNumber, PictureAction : Integer; SwisSBLKey : String; _Found, ValidEntry : Boolean; SBLRec : SBLRecord; begin Quit := False; For I := 0 to (PictureActionList.Count - 1) do begin PictureAction := StrToInt(PictureActionList[I]); GetComponentsForThisPicturePanel(I + 1); case PictureAction of acTransfer : begin LockWindowUpdate(Handle); Image.ImageName := ''; SBLRec := ExtractSwisSBLFromSwisSBLKey(ConvertSwisDashDotToSwisSBL(EditParcelID.Text, SwisCodeTable, ValidEntry)); with SBLRec do _Found := FindKeyOld(ParcelTable, ['TaxRollYr', 'SwisCode', 'Section', 'Subsection', 'Block', 'Lot', 'Sublot', 'Suffix'], [AssessmentYear, SwisCode, Section, Subsection, Block, Lot, Sublot, Suffix]); If _Found then SwisSBLKey := ExtractSSKey(ParcelTable) else begin Quit := True; MessageDlg('Error relocating parcel in order to transfer.', mtError, [mbOK], 0); end; {First move the picture.} If not Quit then Quit := not CopyOneFile(AddDirectorySlashes(DirectoryEdit.Text) + EditFileName.Text, AddDirectorySlashes(GlblPictureDir) + EditFileName.Text); If not Quit then try OldDeleteFile(AddDirectorySlashes(DirectoryEdit.Text) + EditFileName.Text); except Quit := True; end; {Then add a record to the picture table.} If not Quit then begin SetRangeOld(PictureLookupTable, ['SwisSBLKey', 'PictureNumber'], [SwisSBLKey, '0'], [SwisSBLKey, '999']); PictureLookupTable.First; If PictureLookupTable.EOF then PictureNumber := 1 else begin PictureLookupTable.Last; PictureNumber := PictureLookupTable.FieldByName('PictureNumber').AsInteger + 1; end; with PictureTable do try Insert; FieldByName('SwisSBLKey').Text := SwisSBLKey; FieldByName('PictureNumber').AsInteger := PictureNumber; FieldByName('PictureLocation').Text := AddDirectorySlashes(GlblPictureDir) + EditFileName.Text; FieldByName('Date').AsDateTime := Date; FieldByName('Notes').Text := Notes.Text; Post; except Quit := True; end; AddOnePictureListItem(PicturesLoadedList, SwisSBLKey, EditFileName.Text, Notes.Text, acTransfer); end; {If not Quit} LockWindowUpdate(0); end; {acTransfer} acDelete : begin Image.ImageName := ''; try OldDeleteFile(AddDirectorySlashes(DirectoryEdit.Text) + EditFileName.Text); except Quit := True; end; AddOnePictureListItem(PicturesDeletedList, '', EditFileName.Text, '', acDelete); end; {acDelete} acLeaveInDirectory : AddOnePictureListItem(PicturesNotLoadedList, '', EditFileName.Text, '', acLeaveInDirectory); end; {case PictureAction of} end; {For I := 0 to (PictureActionList.Count - 1) do} end; {ImportThePictures} {===================================================================} Procedure TImportPicturesFromLoadingDockForm.UseEndOfFileNameAsNotesCheckBoxClick(Sender: TObject); begin UseEndOfFileNameAsNotes := UseEndOfFileNameAsNotesCheckBox.Checked; end; {===================================================================} Function DeterminePanelNumberForComponentName(ComponentName : String) : Integer; var I : Integer; TempStr : String; begin Result := -1; TempStr := ''; For I := 1 to Length(ComponentName) do If not (ComponentName[I] in Letters) then TempStr := TempStr + ComponentName[I]; try Result := StrToInt(TempStr); except end; end; {DeterminePanelNumberForComponentName} {===================================================================} Procedure TImportPicturesFromLoadingDockForm.ImportActionRadioGroupClick(Sender: TObject); {Don't let them switch to transfer if there are still errors.} var Index : Integer; begin Index := DeterminePanelNumberForComponentName(TComponent(Sender).Name); GetComponentsForThisPicturePanel(Index); with Sender as TRadioGroup do If ((ItemIndex = acTransfer) and (Trim(ErrorPanel.Caption) <> '')) then begin MessageDlg('Sorry, you cannot import a picture with errors.', mtError, [mbOK], 0); ItemIndex := acLeaveInDirectory; end; end; {ImportActionRadioGroupClick} {===================================================================} Procedure TImportPicturesFromLoadingDockForm.ImportButtonClick(Sender: TObject); var Continue, Quit, CancelImport : Boolean; TempComponentName : String; I, ActionThisPicture, TotalNumberPicturesToImport, TotalNumberPicturesToDelete : Integer; PictureActionList : TStringList; begin ImportDone := True; PictureActionList := TStringList.Create; ImportButton.Enabled := False; Application.ProcessMessages; CancelImport := False; TotalNumberPicturesToImport := 0; TotalNumberPicturesToDelete := 0; PrintPicturesNotLoaded := ReportFilesNotLoadedCheckBox.Checked; {First check the pictures to see if there are still any errors or pictures not accepted.} For I := 1 to PicturesThisBatch do begin GetComponentsForThisPicturePanel(I); ActionThisPicture := ImportActionRadioGroup.ItemIndex; If (ActionThisPicture = acTransfer) then TotalNumberPicturesToImport := TotalNumberPicturesToImport + 1; If (ActionThisPicture = acDelete) then TotalNumberPicturesToDelete := TotalNumberPicturesToDelete + 1; PictureActionList.Add(IntToStr(ActionThisPicture)); end; {For I := 1 to PicturesPerBatch do} Continue := False; Quit := False; If CancelImport then MessageDlg('The import has been cancelled.' + #13 + 'No pictures have been transferred or deleted.', mtWarning, [mbOK], 0) else If (MessageDlg('Do you want to import the ' + IntToStr(TotalNumberPicturesToImport) + ' valid pictures in this batch?' + #13 + '(In addition, ' + IntToStr(TotalNumberPicturesToDelete) + ' pictures will be deleted.', mtConfirmation, [mbYes, mbNo], 0) = idYes) then begin ImportThePictures(PictureActionList, PicturesLoadedList, PicturesDeletedList, PicturesNotLoadedList, Quit); If not Quit then Continue := True; end; {If (MessageDlg('Do you want ...} {If continue, then check for more files to import. If there are more, then go through the process again. If not, then print out the results.} If Continue then begin LoadPicturesForPreview; If (PicturesThisBatch = 0) then begin PrintSubHeader := True; ReportCancelled := False; For I := 0 to (PicturesPerBatch - 1) do begin TempComponentName := 'ItemPanel' + IntToStr(I + 1); TPanel(FindComponent(TempComponentName)).Visible := False; end; PrintThePictureReport; end; {If (PicturesThisBatch = 0)} end; {If Continue} ImportButton.Enabled := True; PictureActionList.Free; end; {ImportButtonClick} {===================================================================} Function TImportPicturesFromLoadingDockForm.CheckPictureFileName(NewFileName : String) : Boolean; var ErrorType : Integer; ErrorMessage : String; begin Result := True; If FileExists(NewFileName) then begin Result := False; MessageDlg('A file already exists with that name.' + #13 + 'Please choose a different name.', mtError, [mbOK], 0); end else If FileExistsInPictureDirectory(NewFileName, GlblPictureDir, 'main', ErrorMessage, ErrorType) then begin Result := False; MessageDlg('A picture with the new name already exists in the main picture directory.' + #13 + 'Please enter a different name.', mtError, [mbOK], 0); end else If FileExistsInPictureDirectory(NewFileName, DirectoryEdit.Text, 'loading dock', ErrorMessage, ErrorType) then begin Result := False; MessageDlg('A picture with the new name already exists in the loading dock picture directory.' + #13 + 'Please enter a different name.', mtError, [mbOK], 0); end else begin LockWindowUpdate(Handle); Image.ImageName := ''; EditFileName.ReadOnly := False; EditFileName.Text := NewFileName; EditFileName.ReadOnly := True; ChDir(AddDirectorySlashes(DirectoryEdit.Text)); RenameFile(RenameDialogBox.OriginalFileName, NewFileName); Image.ImageName := EditFileName.Text; LockWindowUpdate(0); ItemPanel.Color := clBtnFace; ErrorPanel.Caption := ''; ImportActionRadioGroup.ItemIndex := acTransfer; ErrorPanel.Visible := False; SetImportPictureCaption; end; {else of If FileExistsInMainPictureDirectory...} end; {CheckPictureFileName} {===================================================================} Procedure TImportPicturesFromLoadingDockForm.RenameButtonClick(Sender: TObject); var Index, ErrorType : Integer; SwisSBLKey, ErrorMessage, PictureNote : String; Error : Boolean; begin Index := DeterminePanelNumberForComponentName(TComponent(Sender).Name); GetComponentsForThisPicturePanel(Index); RenameDialogBox.OriginalFileName := EditFileName.Text; RenameDialogBox.NewFileName := EditFileName.Text; {In order to rename the file, we have to make sure that the file does not already exist. If it is OK, then disable the image, rename the file and then reset the image. Then, review for errors again.} If RenameDialogBox.Execute then begin CheckPictureFileName(RenameDialogBox.NewFileName); If not ErrorPanel.Visible then begin GetComponentsForThisPicturePanel(Index); GetParcelIDForPictureName(EditFileName.Text, SwisSBLKey, PictureNote, Error, ErrorMessage, ErrorType); If (Deblank(EditParcelID.Text) = '') then If Error then begin ItemPanel.Color := $007C59E6; ErrorPanel.Visible := True; ErrorPanel.Caption := ErrorMessage; ImportActionRadioGroup.ItemIndex := acLeaveInDirectory; end else begin EditParcelID.ReadOnly := False; EditParcelID.Text := ConvertSwisSBLToDashDot(SwisSBLKey); EditParcelID.ReadOnly := True; ItemPanel.Color := clBtnFace; ErrorPanel.Caption := ''; ErrorPanel.Visible := False; ImportActionRadioGroup.ItemIndex := acTransfer; SetImportPictureCaption; end; {else of If Error} end; {If not ErrorPanel.Visible} end; {If RenameDialogBox.Execute} end; {RenameButtonClick} {===================================================================} Procedure TImportPicturesFromLoadingDockForm.LocateButtonClick(Sender: TObject); var Index : Integer; SwisSBLKey : String; ValidEntry : Boolean; begin Index := DeterminePanelNumberForComponentName(TComponent(Sender).Name); GetComponentsForThisPicturePanel(Index); {Let them locate another parcel to go with this picture.} If (Deblank(EditParcelID.Text) = '') then SwisSBLKey := '' else SwisSBLKey := ConvertSwisDashDotToSwisSBL(EditParcelID.Text, SwisCodeTable, ValidEntry); If ValidEntry then begin GlblLastLocateInfoRec.LastLocatePage := 'P'; GlblLastLocateInfoRec.LastSwisSBLKey := SwisSBLKey; GlblLastLocateInfoRec.LastLocateKey := lcpParcelID; end else SwisSBLKey := ''; If ExecuteParcelLocateDialog(SwisSBLKey, True, False, 'Choose Parcel for Picture', False, nil) then begin EditParcelID.ReadOnly := False; EditParcelID.Text := ConvertSwisSBLToDashDot(SwisSBLKey); EditParcelID.ReadOnly := True; ItemPanel.Color := clBtnFace; ErrorPanel.Caption := ''; ErrorPanel.Visible := False; ImportActionRadioGroup.ItemIndex := acTransfer; SetImportPictureCaption; end; {If ExecuteParcelLocateDialog} end; {LocateButtonClick} {===================================================================} Procedure TImportPicturesFromLoadingDockForm.CloseButtonClick(Sender: TObject); begin Close; end; {CloseButtonClick} {===================================================================} Procedure TImportPicturesFromLoadingDockForm.FormCloseQuery( Sender: TObject; var CanClose: Boolean); var I, ActionThisPicture, TotalNumberPicturesToImport : Integer; begin PrintPicturesNotLoaded := ReportFilesNotLoadedCheckBox.Checked; TotalNumberPicturesToImport := 0; {When we go to close the form, make sure that all current items in the batch are in the picture action list.} For I := 1 to PicturesThisBatch do begin GetComponentsForThisPicturePanel(I); ActionThisPicture := ImportActionRadioGroup.ItemIndex; If (ActionThisPicture = acLeaveInDirectory) then AddOnePictureListItem(PicturesNotLoadedList, '', EditFileName.Text, '', acLeaveInDirectory); If (ActionThisPicture = acTransfer) then TotalNumberPicturesToImport := TotalNumberPicturesToImport + 1; end; {For I := 1 to PicturesPerBatch do} If (TotalNumberPicturesToImport > 0) then ImportButtonClick(Sender); If (ImportDone and (not PicturesPrinted) and ((PicturesLoadedList.Count > 0) or (PicturesNotLoadedList.Count > 0) or (PicturesDeletedList.Count > 0))) then begin MessageDlg('Before you exit a report will print detailing the pictures that you imported.', mtInformation, [mbOK], 0); PrintThePictureReport; end; CanClose := True; end; {FormCloseQuery} {===================================================================} Procedure TImportPicturesFromLoadingDockForm.FormClose( Sender: TObject; var Action: TCloseAction); begin FreeTList(PicturesLoadedList, SizeOf(PictureListRecord)); FreeTList(PicturesNotLoadedList, SizeOf(PictureListRecord)); FreeTList(PicturesDeletedList, SizeOf(PictureListRecord)); CloseTablesForForm(Self); {Free up the child window and set the ClosingAForm Boolean to true so that we know to delete the tab.} Action := caFree; GlblClosingAForm := True; GlblClosingFormCaption := Caption; end; {FormClose} end.
unit uiWnd_htmlResult; {$mode objfpc}{$H+} interface uses //IPIDEHTMLControl, Classes, SysUtils, FileUtil, IpHtml, Ipfilebroker, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, LConvEncoding, IpMsg; type { TMyIpHtmlDataProvider } TMyIpHtmlDataProvider = class(TIpHtmlDataProvider) protected function DoGetStream(const URL: string): TStream; override; public end; { TWnd_htmlResult } TWnd_htmlResult = class(TForm) Button1: TButton; Memo1: TMemo; Panel1: TPanel; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); public function DataProvider1CanHandle(Sender: TObject; const URL: string ): Boolean; procedure DataProvider1CheckURL(Sender: TObject; const URL: string; var Available: Boolean; var ContentType: string); procedure DataProvider1GetHtml(Sender: TObject; const URL: string; const PostData: TIpFormDataEntity; var Stream: TStream); procedure DataProvider1GetImage(Sender: TIpHtmlNode; const URL: string; var Picture: TPicture); procedure DataProvider1Leave(Sender: TIpHtml); procedure DataProvider1ReportReference(Sender: TObject; const URL: string); public IpHtmlPanel1: TIpHtmlPanel; DataProvider1: TMyIpHtmlDataProvider; private procedure ShowHTML(Src: string); end; var Wnd_htmlResult: TWnd_htmlResult; procedure uiWnd_htmlResult_SHOW; procedure uiWnd_htmlResult_SET(const Text:string); implementation // function TWnd_htmlResult.DataProvider1CanHandle(Sender: TObject; const URL: string ): Boolean; begin //debugln(['TWnd_htmlResult.DataProvider1CanHandle ',URL]); Result:=false; end; procedure TWnd_htmlResult.DataProvider1CheckURL(Sender: TObject; const URL: string; var Available: Boolean; var ContentType: string); begin //debugln(['TWnd_htmlResult.DataProvider1CheckURL ',URL]); Available:=false; ContentType:=''; end; procedure TWnd_htmlResult.DataProvider1GetHtml(Sender: TObject; const URL: string; const PostData: TIpFormDataEntity; var Stream: TStream); begin //debugln(['TWnd_htmlResult.DataProvider1GetHtml ',URL]); Stream:=nil; end; procedure TWnd_htmlResult.DataProvider1GetImage(Sender: TIpHtmlNode; const URL: string; var Picture: TPicture); begin //debugln(['TWnd_htmlResult.DataProvider1GetImage ',URL]); Picture:=nil; end; procedure TWnd_htmlResult.DataProvider1Leave(Sender: TIpHtml); begin // end; procedure TWnd_htmlResult.DataProvider1ReportReference(Sender: TObject; const URL: string ); begin //debugln(['TWnd_htmlResult.DataProvider1ReportReference ',URL]); end; // function TMyIpHtmlDataProvider.DoGetStream(const URL: string): TStream; var ms: TMemoryStream; begin Result:=nil; //debugln(['TMyIpHtmlDataProvider.DoGetStream ',URL]); if URL='lazdoc.css' then begin //debugln(['TMyIpHtmlDataProvider.DoGetStream ',FileExists(URL)]); ms:=TMemoryStream.Create; try ms.LoadFromFile('C:\DeVeLoP\lazarus32\docs\lazdoc.css'); ms.Position:=0; except ms.Free; end; Result:=ms; end; end; procedure uiWnd_htmlResult_SHOW; begin if not Assigned(Wnd_htmlResult) then begin Wnd_htmlResult:=TWnd_htmlResult.Create(Application); end; Wnd_htmlResult.Show; Wnd_htmlResult.BringToFront; end; procedure uiWnd_htmlResult_SET(const Text:string); var asdf:tStrings; s:string; begin { s:='<html><head><link rel="stylesheet" href="lazdoc.css" type="text/css">'+LineEnding +'<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head>'+LineEnding +'<body>'+LineEnding+Text+LineEnding+'</body>'; } s:=text; //--- if Assigned(Wnd_htmlResult) then begin Wnd_htmlResult.ShowHTML(UTF8ToUTF8BOM({AnsiToUtf8}(S))); end; //--- //Wnd_htmlResult.IpFileDataProvider1.o; //--- asdf:=TStringList.Create; asdf.Text:=UTF8ToUTF8BOM({AnsiToUtf8}(S)); asdf.SaveToFile('tst.html'); asdf.free; end; {$R *.lfm} { TWnd_htmlResult } procedure TWnd_htmlResult.FormCreate(Sender: TObject); begin DataProvider1:=TMyIpHtmlDataProvider.Create(Self); with DataProvider1 do begin Name:='DataProvider1'; OnCanHandle:=@DataProvider1CanHandle; OnGetHtml:=@DataProvider1GetHtml; OnGetImage:=@DataProvider1GetImage; OnLeave:=@DataProvider1Leave; OnCheckURL:=@DataProvider1CheckURL; OnReportReference:=@DataProvider1ReportReference; end; IpHtmlPanel1:=TIpHtmlPanel.Create(Self); with IpHtmlPanel1 do begin Name:='IpHtmlPanel1'; Parent:=Self; Align:=alClient; DefaultFontSize:=10; DataProvider:=DataProvider1; end; IpHtmlPanel1.SetHtmlFromStr('<html><body>sadf asdf asdf</body></html>'); end; procedure TWnd_htmlResult.Button1Click(Sender: TObject); begin if Assigned(IpHtmlPanel1) then begin // IpHtmlPanel1.TextColor:=; end; end; procedure TWnd_htmlResult.ShowHTML(Src: string); var ss: TStringStream; NewHTML: TIpHtml; begin ss := TStringStream.Create(Src); memo1.Text:=SRC; try NewHTML := TIpHtml.Create; // Beware: Will be freed automatically by IpHtmlPanel1 //debugln(['TForm1.ShowHTML BEFORE SETHTML']); IpHtmlPanel1.SetHtml(NewHTML); //debugln(['TForm1.ShowHTML BEFORE LOADFROMSTREAM']); NewHTML.LoadFromStream(ss); //if Anchor <> '' then IpHtmlPanel1.MakeAnchorVisible(Anchor); finally ss.Free; end; end; end.
unit Brickcamp.Repository.Redis; interface uses Redis.Client, Redis.NetLib.INDY, Redis.Commons, Spring.Container.Injection, Spring.Container.Common, BrickCamp.ISettings, BrickCamp.IRedisRepository, BrickCamp.IRedisClientProvider; type ///******** TRedisClientProvider *********/// ///Provide the a wrapper to create a Redis Client and provide the settings to it TRedisClientProvider = class(TInterfacedObject,IRedisClientProvider) protected [Inject] FSettings: IBrickCampSettings; FIpV4Address : string; public function NewRedisClient : IRedisClient; procedure Initialise; end; TRedisRepository = class(TInterfacedObject,IRedisRepository) protected var [Inject] FRedisClientProvider : IRedisClientProvider; FRedisClient : IRedisClient; public function Connnect : Boolean; function SetValue(Keyname : String; Value : String) : Boolean; function GetValue(Keyname : String; var Value : String) : Boolean; end; implementation { TRedisEmployeeRepository } function TRedisRepository.Connnect : boolean; begin FRedisClientProvider.Initialise; FRedisClient := FRedisClientProvider.NewRedisClient(); Result := Assigned(FRedisClient); end; { TRedisClientProvider } procedure TRedisClientProvider.Initialise; begin FIpV4Address := FSettings.GetRedisIpAddress; end; function TRedisClientProvider.NewRedisClient: IRedisClient; begin result := Redis.Client.NewRedisClient(FIpV4Address); end; function TRedisRepository.GetValue(Keyname: String; var Value: String): Boolean; begin result := FRedisClient.&GET(Keyname,Value); end; function TRedisRepository.SetValue(Keyname : String; Value: String): Boolean; begin result := FRedisClient.&SET(Keyname,Value); end; end.
unit UFLogRegisterDetails; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.Imaging.pngimage, Vcl.StdCtrls, Vcl.ComCtrls, ULogType; type TFLogRegisterDetails = class(TForm) pnlBackground: TPanel; edtMsg: TRichEdit; imgStatusLogRegister: TImage; imgTitle: TImage; lblDateTimeTitle: TLabel; lblDateTimeValue: TLabel; lblLogTitle: TLabel; lblLogValue: TLabel; lblMesageTitle: TLabel; lblTitle: TLabel; pnlDividerBottom: TPanel; pnlBtnOk: TPanel; pnlDividerTitle: TPanel; procedure pnlBtnOkClick(Sender: TObject); private { Private declarations } public { Public declarations } procedure LoadValues(TypeLog : Integer; Title, DateTime, Msg : String); end; var FLogRegisterDetails: TFLogRegisterDetails; implementation {$R *.dfm} { TFLogRegisterDetails } procedure TFLogRegisterDetails.LoadValues(TypeLog: Integer; Title, DateTime, Msg: String); begin if TypeLog = 1 then imgStatusLogRegister.Picture.LoadFromStream(TResourceStream.Create(HInstance,'Success96px',RT_RCDATA)) else if TypeLog = 2 then imgStatusLogRegister.Picture.LoadFromStream(TResourceStream.Create(HInstance,'Error96px',RT_RCDATA)) else imgStatusLogRegister.Picture.LoadFromStream(TResourceStream.Create(HInstance,'Warning96px',RT_RCDATA)); lblLogValue.Caption := Title; lblDateTimeValue.Caption := DateTime; edtMsg.Text := Msg; end; procedure TFLogRegisterDetails.pnlBtnOkClick(Sender: TObject); begin ModalResult := mrOk; Self.CloseModal; end; end.
unit Test.Devices.Tecon19.ReqCreator; interface uses Windows, TestFrameWork, GMGlobals, Test.Devices.Base.ReqCreator, GMConst, GmSqlQuery, SysUtils, Devices.Tecon; type TTecon19ReqCreatorForTest = class(TTecon19ReqCreator) protected function GetNeedSetTime: bool; override; end; TTecon19ReqCreatorTest = class(TDeviceReqCreatorTestBase) protected procedure SetUp; override; function GetDevType(): int; override; procedure DoCheckRequests; override; published procedure HourArrayTimeIndex(); end; implementation { TTecon19ReqCreatorTest } procedure TTecon19ReqCreatorTest.DoCheckRequests; begin CheckReqHexString(0, '10, 40, 1, 9, 1, 4, 0, 4F, 16'); CheckReqHexString(1, '10, 41, 1, 9, 2, 4, 0, 51, 16'); CheckReqHexString(2, '10, 42, 1, 9, 3, 4, 0, 53, 16'); CheckReqHexString(3, '10, 43, 1, 9, 7, 5, 0, 59, 16'); CheckReqHexString(4, '10, 44, 1, 9, 8, 5, 0, 5B, 16'); CheckReqHexString(5, '10, 45, 1, 9, 9, 5, 0, 5D, 16'); CheckReqHexString(6, '10, 46, 1, 9, A, 5, 0, 5F, 16'); CheckReqHexString(7, '10, 47, 1, 9, 9, 2, 0, 5C, 16'); CheckReqHexString(8, '10, 48, 1, 9, A, 2, 0, 5E, 16'); CheckReqHexString(9, '10, 49, 1, 9, B, 2, 0, 60, 16'); CheckReqHexString(10, '10, 4A, 1, 9, C, 2, 0, 62, 16'); CheckReqHexString(11, '10, 4B, 1, 9,23,80, 0, F8, 16'); CheckReqHexString(12, '10, 4C, 0,17, 2, 0, 0, 65, 16'); end; function TTecon19ReqCreatorTest.GetDevType: int; begin Result := DEVTYPE_TECON_19_01; end; procedure TTecon19ReqCreatorTest.HourArrayTimeIndex; var idx: int; begin idx := TTecon19ReqCreatorForTest(ReqCreator).HourArrayTimeIndex(EncodeDateTimeUTC(2000, 1, 1), 64); Check(idx = 5); // это точка отсчета, но часовой пояс наш, поэтому +5 idx := TTecon19ReqCreatorForTest(ReqCreator).HourArrayTimeIndex(EncodeDateTimeUTC(2015, 1, 10, 14, 00), 64); Check(idx = $048E); idx := TTecon19ReqCreatorForTest(ReqCreator).HourArrayTimeIndex(EncodeDateTimeUTC(2015, 1, 26, 00, 00), 32); Check(idx = 0); // полночь на 26.01.15 - это как раз день завершения 32-двухдневного цикла idx := TTecon19ReqCreatorForTest(ReqCreator).HourArrayTimeIndex(EncodeDateTimeUTC(2015, 1, 30, 00, 00), 32); Check(idx = $0060); end; procedure TTecon19ReqCreatorTest.SetUp; begin inherited; ExecSQL('update Devices set dt_updated = null where ID_Device = ' + IntToStr(ReqCreator.ReqDetails.ID_Device)); end; { TTecon19ReqCreatorForTest } function TTecon19ReqCreatorForTest.GetNeedSetTime: bool; begin Result := true; end; initialization RegisterTest('GMIOPSrv/Devices/Tecon', TTecon19ReqCreatorTest.Suite); end.
unit PCX; interface uses graph, ColrCtrl; procedure SaveScreen(x1, y1, x2, y2 : INTEGER; FileName : String); (*================================================== *) implementation CONST ColorOrMono : INTEGER = 1; GrayScale : INTEGER = 2; TYPE ModeType = (ModeDetect, Mono, CGA, EGA, VGA); filetype = TEXT; Chr2 = ARRAY[0..1] OF BYTE; { --------------------------------------------------------------- } PROCEDURE WriteInt(VAR pic : filetype; num : INTEGER); { write a 2-byte integer in a file of char} BEGIN write(pic,Chr2(Num)[0]); write(pic,Chr2(Num)[1]); END {WriteInt}; { --------------------------------------------------------------- } PROCEDURE WriteHeader(VAR pic: filetype); BEGIN write(pic,$0a); write(pic,$05); write(pic,$01); write(pic,$04); END {WriteHeader}; { --------------------------------------------------------------- } PROCEDURE WritePalette(VAR pic: filetype; GMode : ModeType); VAR pal : RGBArray; N : INTEGER; BEGIN GetVGAPalette(pal); FOR n := 0 TO 16 DO BEGIN write(pic,pal[n].RedVal*4); write(pic,pal[n].GreenVal*4); write(pic,pal[n].BlueVal*4); END; END {}; { --------------------------------------------------------------- } PROCEDURE WriteData(VAR pic: filetype); BEGIN END {}; { --------------------------------------------------------------- } procedure SaveScreen(x1, y1, x2, y2 : INTEGER; FileName : String); CONST BitPlanes = $04; var pic : filetype; Palette : array[0..15] OF BYTE; ch, ch1, old_ch : BYTE; red, green, blue : BYTE; n, startline, endline, BytesPerLine, endcount : INTEGER; begin assign(pic,FileName); rewrite(pic); WriteHeader(pic); { screen coords } WriteInt(pic,x1); WriteInt(pic,y1); WriteInt(pic,x2); WriteInt(pic,y2); WriteInt(pic,Graph.GetMaxX); WriteInt(pic,Graph.GetMaxy); WritePalette(pic,ModeDetect); { other picture data } write(pic,$00); { reserved } write(pic,$04); { number of bit planes } startline := X1 DIV 8; endline := X2 DIV 8 + 1; BytesPerLine := endline - startline; endcount := startline + BytesPerLine * 4 + 1; writeInt(pic,BytesPerLine); writeInt(pic,ColorOrMono); { pad to end of header block } FOR n := 70 to 127 DO write(pic,$00); WriteData(pic); END; BEGIN END.
unit main; interface uses SysUtils, Types, Classes, QGraphics, QControls, QForms, QDialogs, QStdCtrls, QTypes, QExtCtrls; type TForm1 = class(TForm) LCDNumber1: TLCDNumber; Timer1: TTimer; Button1: TButton; Button2: TButton; Button3: TButton; procedure Timer1Timer(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure LCDNumber1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); private { Private declarations } FRunning: Boolean; procedure SetRunning(Value: Boolean); public { Public declarations } StartTime: Extended; ElapsedTime: Extended; Reset: Boolean; property Running: Boolean read FRunning write SetRunning; end; var Form1: TForm1; implementation {$R *.xfm} procedure TForm1.SetRunning(Value: Boolean); begin if FRunning <> Value then begin FRunning := Value; StartTime := ElapsedTime; if Value then Reset := False; end; end; procedure TForm1.Timer1Timer(Sender: TObject); begin if Reset then ElapsedTime := Now else ElapsedTime := Now - StartTime; if Running then LCDNumber1.Value := FormatDateTime('nn:ss.zzz', ElapsedTime); end; procedure TForm1.Button1Click(Sender: TObject); begin Running := True; end; procedure TForm1.Button2Click(Sender: TObject); begin Running := not Running; end; procedure TForm1.Button3Click(Sender: TObject); begin if not Running then begin LCDNumber1.Value := '00:00.000'; Reset := True; end; end; procedure TForm1.LCDNumber1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var NewBorderStyle: Integer; NewSegmentStyle: Integer; begin case Button of mbLeft: begin NewBorderStyle := Ord(LCDNumber1.BorderStyle) + 1; if NewBorderStyle > Ord(High(TBorderStyle)) then NewBorderStyle := Ord(Low(TBorderStyle)); LCDNumber1.BorderStyle := TBorderStyle(NewBorderStyle); end; mbRight: begin NewSegmentStyle := Ord(LCDNumber1.SegmentStyle) + 1; if NewSegmentStyle > Ord(High(TLCDSegmentStyle)) then NewSegmentStyle := Ord(Low(TLCDSegmentStyle)); LCDNumber1.SegmentStyle := TLCDSegmentStyle(NewSegmentStyle); end; end; end; end.
unit MyOption; interface uses Classes, SysUtils, MyGlobal, System.IniFiles, Registry, Winapi.Windows, JdcGlobal; type TOption = class private FIniFile: TCustomIniFile; constructor Create; function GetAppName: string; procedure SetAppName(const Value: string); function GetUseCloudLog: boolean; procedure SetUseCloudLog(const Value: boolean); function GetAppCode: string; function GetProjectCode: string; procedure SetAppCode(const Value: string); procedure SetProjectCode(const Value: string); function GetLogServer: TConnInfo; procedure SetLogServer(const Value: TConnInfo); function GetUseDebug: boolean; procedure SetUseDebug(const Value: boolean); public class function Obj: TOption; destructor Destroy; override; property IniFile: TCustomIniFile read FIniFile; property AppName: string read GetAppName write SetAppName; property AppCode: string read GetAppCode write SetAppCode; property LogServer: TConnInfo read GetLogServer write SetLogServer; property ProjectCode: string read GetProjectCode write SetProjectCode; property UseCloudLog: boolean read GetUseCloudLog write SetUseCloudLog; property UseDebug: boolean read GetUseDebug write SetUseDebug; end; implementation var MyObj: TOption = nil; { TOption } constructor TOption.Create; var FileName: string; begin // IniFile... FileName := ChangeFileExt(TGlobal.Obj.ExeName, '.ini'); FIniFile := TIniFile.Create(FileName); // FIniFile := TMemIniFile.Create(FileName,TEncoding.UTF8); // Registry... // FileName:= ''SOFTWARE\PlayIoT\' + PROJECT_CODE; // FIniFile := TRegistryIniFile.Create(FileName); // TRegistryIniFile(FIniFile).RegIniFile.RootKey := HKEY_CURRENT_USER; // TRegistryIniFile(FIniFile).RegIniFile.OpenKey(FIniFile.FileName, True); end; destructor TOption.Destroy; begin if Assigned(FIniFile) then FIniFile.Free; inherited; end; function TOption.GetAppCode: string; begin result := FIniFile.ReadString('Config', 'AppCode', APPLICATION_CODE); end; function TOption.GetAppName: string; begin result := FIniFile.ReadString('Config', 'AppName', APPLICATION_TITLE); end; function TOption.GetLogServer: TConnInfo; begin result.StringValue := FIniFile.ReadString('CloudLog', 'IP', ''); result.IntegerValue := FIniFile.ReadInteger('CloudLog', 'Port', 8094); end; function TOption.GetProjectCode: string; begin result := FIniFile.ReadString('Config', 'ProjectCode', PROJECT_CODE); end; function TOption.GetUseCloudLog: boolean; begin result := FIniFile.ReadBool('CloudLog', 'Enable', False); end; function TOption.GetUseDebug: boolean; begin result := FIniFile.ReadBool('Config', 'UseDebug', False); end; class function TOption.Obj: TOption; begin if MyObj = nil then begin MyObj := TOption.Create; end; result := MyObj; end; procedure TOption.SetAppCode(const Value: string); begin FIniFile.WriteString('Config', 'AppCode', Value); end; procedure TOption.SetAppName(const Value: string); begin FIniFile.WriteString('Config', 'AppName', Value); end; procedure TOption.SetLogServer(const Value: TConnInfo); begin FIniFile.WriteString('CloudLog', 'IP', Value.StringValue); FIniFile.WriteInteger('CloudLog', 'Port', Value.IntegerValue); end; procedure TOption.SetProjectCode(const Value: string); begin FIniFile.WriteString('Config', 'ProjectCode', ProjectCode); end; procedure TOption.SetUseCloudLog(const Value: boolean); begin FIniFile.WriteBool('CloudLog', 'Enable', Value); end; procedure TOption.SetUseDebug(const Value: boolean); begin FIniFile.WriteBool('Config', 'UseDebug', Value); end; end.
FUNCTION F(m: MATRIX): REAL; Var i, j: integer; s: real; BEGIN s := 0.0; i := 1; While i <= rows do begin j := 1; While j <= cols do begin s := s + m[i,j] * m[i,j]; j := j + 1; end; i := i + 1; end; F := Sqrt(s); END; FUNCTION FShort(m: MATRIX): real; var i, j: integer; s: real; BEGIN s := 0.0; i := 1; j := 1; while i <= ROWS do begin s := s + m[i, j] * m[i, j]; j := j + 1; if j > COLS then begin j := 1; i := i + 1; end; end; FShort := Sqrt(s); END;
unit actfoto; {$mode objfpc}{$H+} interface uses BrookLogger, dmdatabase, sqldb, BaseAction, fpjson, fpjsonrtti, SysUtils, foto; type { TFotos } TFotos = class(specialize TBaseGAction<TFoto>) private procedure GetSmallFoto(APath: string); public procedure Get; override; procedure Post; override; procedure Put; override; procedure Delete; override; end; implementation procedure TFotos.GetSmallFoto(APath: string); begin Write(APath); end; procedure TFotos.Get; var lFoto: TFoto; lSql: TSQLQuery; lArray: TJSONArray; lItem: TJSONObject; lData: TJSONObject; lStreamer: TJSONStreamer; lWhere: string; begin lStreamer := TJSONStreamer.Create(nil); lData := TJsonObject.Create; lArray := TJSONArray.Create; try lSql := datamodule1.qryFotos; // filtros lFoto := Entity; lWhere := ''; if HttpRequest.QueryFields.IndexOfName('idarticulo') <> -1 then lWhere := 'IdArticulo = ' + HttpRequest.QueryFields.Values['idarticulo'] + ' and '; if Variable['IdFoto'] <> '' then begin lWhere := lWhere + 'IdFoto = ' + Variable['IdFoto'] + ' and '; end; if lWhere <> '' then begin // eliminamos el ultimo " and " lWhere := Copy(lWhere, 1, Length(lWhere) - 4); lSql.SQL.Add('where ' + lWhere); end; //lSql.SQL.Add(Format('limit %d offset %d', [lLength, lStart])); lSql.Open; try while not lSql.EOF do begin lFoto.IdFoto := lSql.FieldByName('idfoto').AsInteger; lFoto.IdArticulo := lSql.FieldByName('idarticulo').AsInteger; lFoto.Path := lSql.FieldByName('path').AsString; lFoto.Principal := lSql.FieldByName('principal').AsBoolean; lItem := lStreamer.ObjectToJSON(lFoto); lArray.Add(lItem); lSql.Next; end; except on E: exception do TBrookLogger.Service.Error(E.message); end; lSql.Close; // se convierte el objeto en JSON lData := TJsonObject.Create; try if Variable['IdFoto'] <> '' then Write(lItem.AsJSON) else Write(lArray.AsJSON); finally lData.Free; end; finally lStreamer.Free; end; end; procedure TFotos.Post; var lFoto: TFoto; lSql: TSQLQuery; lDestreamer: TJSONDeStreamer; lStreamer: TJSONStreamer; begin lFoto := Entity; lStreamer := TJSONStreamer.Create(nil); lDeStreamer := TJSONDeStreamer.Create(nil); lSql := TSQLQuery.Create(nil); try lDestreamer.JSONToObject(HttpRequest.Content, lFoto); lSql.DataBase := datamodule1.PGConnection1; lSql.SQL.Text:= 'insert into fotos(path, idarticulo) ' + 'values(''' + lFoto.Path + ''', ' + IntToStr(lFoto.IdArticulo); if not datamodule1.SQLTransaction1.Active then datamodule1.SQLTransaction1.StartTransaction; lSql.ExecSQL; lSql.SQL.Text:='select currval(''fotos_idfoto_seq'')'; lSql.Open; lFoto.IdFoto := lSql.Fields[0].AsInteger; datamodule1.SQLTransaction1.Commit; Write(lStreamer.ObjectToJSON(lFoto).AsJSON); finally lSql.Free; lStreamer.Free; lDestreamer.Free; end; end; procedure TFotos.Put; var lFoto: TFoto; lSql: TSQLQuery; lDestreamer: TJSONDeStreamer; lStreamer: TJSONStreamer; begin lFoto := Entity; lFoto.IdFoto:= StrToIntDef(Variable['IdFoto'], 0); lStreamer := TJSONStreamer.Create(nil); lDeStreamer := TJSONDeStreamer.Create(nil); lSql := TSQLQuery.Create(nil); try lDestreamer.JSONToObject(HttpRequest.Content, lFoto); lSql.DataBase := datamodule1.PGConnection1; lSql.SQL.Text:= 'update fotos set principal = ' + BoolToStr(lFoto.Principal, '1', '0') + ' where idfoto = ' + IntToStr(lFoto.IdFoto); if not datamodule1.SQLTransaction1.Active then datamodule1.SQLTransaction1.StartTransaction; lSql.ExecSQL; datamodule1.SQLTransaction1.Commit; Write(lStreamer.ObjectToJSON(lFoto).AsJSON); finally lSql.Free; lStreamer.Free; lDestreamer.Free; end; end; procedure TFotos.Delete; var lFoto: TFoto; lSql: TSQLQuery; lStreamer: TJSONStreamer; begin lFoto := Entity; lFoto.IdFoto:= StrToIntDef(Variable['IdFoto'], 0); // obtenemos los datos de la foto lSql := datamodule1.qryFotos; lSql.SQL.Add(' where ' + 'IdFoto = ' + Variable['IdFoto']); lSql.Open; lFoto.Path:= lSql.FieldByName('path').AsString; lSql.Close; // borramos las versiones viejas if not DeleteFile(cPathBig + lFoto.Path) then RaiseLastOSError(GetLastOSError); if not DeleteFile(cPathSmall + lFoto.Path) then RaiseLastOSError(GetLastOSError); lStreamer := TJSONStreamer.Create(nil); lSql := TSQLQuery.Create(nil); try lSql.DataBase := datamodule1.PGConnection1; if not datamodule1.SQLTransaction1.Active then datamodule1.SQLTransaction1.StartTransaction; lSql.SQL.Text:= 'delete from fotos ' + ' where IdFoto=' + IntToStr(lFoto.IdFoto); lSql.ExecSQL; datamodule1.SQLTransaction1.Commit; Write(lStreamer.ObjectToJSON(lFoto).AsJSON); finally lSql.Free; lStreamer.Free; end; end; initialization TFotos.Register('/foto'); TFotos.Register('/foto/:IdFoto'); end.
//http://msdn.microsoft.com/en-us/library/bb773190(VS.85).aspx#theme unit uWin7_redactor; interface uses uTypes, Graphics; const ICON_PC = 'CLSID\{20D04FE0-3AEA-1069-A2D8-08002B30309D}\DefaultIcon'; ICON_USER = 'CLSID\{59031A47-3F72-44A7-89C5-5595FE6B30EE}\DefaultIcon'; ICON_NETWORK = 'CLSID\{F02C1A0D-BE21-4350-88B0-7367FC96EF3C}\DefaultIcon'; ICON_RECYCLE = 'CLSID\{645FF040-5081-101B-9F08-00AA002F954E}\DefaultIcon'; CURSORS = 'Control Panel\Cursors'; DESKTOP = 'Control Panel\Desktop'; COLORS = 'Control Panel\Colors'; THEME_COLORS = 'VisualStyles'; SOUNDS = 'AppEvents\Schemes\Apps\.Default\%s'; THEME = 'Theme'; procedure SetTemeName_win7(Name: string); procedure ChangeDesktop_win7(ImagePath: string; WallpaperStyle: TWallpaperStyle); procedure ChangeLogWallpaper_win7(ImagePath: string); procedure ChangeIcon_win7(Icon: TIcon_type; Value: string); procedure ChangeCursor_win7(Cursor: string; Value: string); procedure ChangeColor_win7(Color: String; Value: TColor); procedure ChangeThemeColor_win7(Value: TColor); procedure ChangeSound_win7(Sound: String; Value: string); implementation uses SysUtils, Windows, Controls, Registry, Inifiles, uProcedure; procedure ChangeDesktop_win7(ImagePath: string; WallpaperStyle: TWallpaperStyle); begin // Изменяем картинку на роб столе SetStrToIni(DESKTOP, 'Wallpaper', ImagePath); // задаем параметры для картинки SetIntToIni(DESKTOP, 'WallpaperStyle', Integer(WallpaperStyle)) end; procedure ChangeLogWallpaper_win7(ImagePath: string); var Reg: TRegistry; tmp: string; begin // проверяем присутстивия файла if not FileExists(ImagePath) then Exit; //производим действия с реестром Reg := TRegistry.Create; Try Reg.RootKey := HKEY_LOCAL_MACHINE; Reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI\Background', True); Reg.WriteInteger('OEMBackground', 1); Finally Reg.Free; End; //Сосздаем нужные файли и папки tmp := GetSystem32Path; if not DirectoryExists( tmp + 'oobe\info') then CreateDir(tmp + 'oobe\info'); if not DirectoryExists( tmp + 'oobe\info\backgrounds') then CreateDir(tmp + 'oobe\info\backgrounds'); tmp := tmp + 'oobe\info\backgrounds\backgroundDefault.jpg'; CopyFile(Pchar(ImagePath), Pchar(tmp), false); //Вносим изминения в тему SetIntToIni('Theme','SetLogonBackground',1); end; procedure SetTemeName_win7(Name: string); begin SetStrToIni(THEME, 'DisplayName', Name); end; procedure SetIconPC(Name: string); begin SetStrToIni(THEME, 'DisplayName', Name); end; procedure ChangeIcon_win7(Icon: TIcon_type; Value: string); begin // Опредиляем тип иконки котурую будем менять case Icon of it_pc: SetStrToIni(ICON_PC, 'DefaultValue', Value); it_user: SetStrToIni(ICON_USER, 'DefaultValue', Value); it_network: SetStrToIni(ICON_NETWORK, 'DefaultValue', Value); it_recycle_full: SetStrToIni(ICON_RECYCLE, 'Full', Value); it_recycle_empty: SetStrToIni(ICON_RECYCLE, 'Empty', Value); end; end; procedure ChangeCursor_win7(Cursor: string; Value: string); begin if Cursor = 'crDefault' then SetStrToIni(CURSORS,'DefaultValue',Value) else SetStrToIni(CURSORS,Copy(Cursor,3,length(Cursor)),Value); end; procedure ChangeColor_win7(Color: String; Value: TColor); // превращаем цветовую схему в RGB function ColotToRGBText(AColor: TColor): string; var Color : Longint; r, g, b: Byte; begin Color := ColorToRGB(AColor); r := Color; g := Color shr 8; b := Color shr 16; Result := Format('%d %d %d',[r,g,b]); end; begin SetStrToIni(COLORS, Color, ColotToRGBText(Value)); end; procedure ChangeThemeColor_win7(Value: TColor); function ColotToHexText(AColor: TColor): string; begin Result := '0x' + IntToHex(GetRValue(AColor), 2) + IntToHex(GetGValue(AColor), 2) + IntToHex(GetBValue(AColor), 2) ; end; begin SetStrToIni(THEME_COLORS, 'ColorizationColor', ColotToHexText(Value)); end; procedure ChangeSound_win7(Sound: String; Value: string); begin SetStrToIni(Format(SOUNDS,[Sound]), 'DefaultValue', Value); end; end.
unit TMMain; { Aestan Tray Menu Made by Onno Broekmans; visit http://www.xs4all.nl/~broekroo/aetraymenu for more information. This work is hereby released into the Public Domain. To view a copy of the public domain dedication, visit: http://creativecommons.org/licenses/publicdomain/ or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA. This is the main unit of AeTrayMenu. } interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, BarMenus, JvComponent, JvTrayIcon, ExtCtrls, Contnrs, ImgList, TMStruct, TMSrvCtrl, JvComponentBase; type TMainForm = class(TForm) LeftClickPopup: TBcBarPopupMenu; RightClickPopup: TBcBarPopupMenu; TrayIcon: TJvTrayIcon; CheckServicesTimer: TTimer; ImageList: TImageList; procedure CheckServicesTimerTimer(Sender: TObject); procedure TrayIconDblClick(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure BuiltInActionExecute(Sender: TObject); procedure SelectMenuItem(Sender: TObject); procedure LeftRightClickPopupPopup(Sender: TObject); private { FIELDS } FServices: TObjectList; FVariables: TObjectList; FDoubleClickAction: TTMMultiAction; FStartupAction: TTMMultiAction; FTrayIconSomeRunning: Integer; FServiceGlyphStopped: Integer; FServiceGlyphRunning: Integer; FTrayIconNoneRunning: Integer; FServiceGlyphPaused: Integer; FTrayIconAllRunning: Integer; FSomeRunningHint: String; FAllRunningHint: String; FNoneRunningHint: String; FID: String; FCustomAboutVersion: String; FCustomAboutHeader: String; FCustomAboutText: TStrings; FHtmlActions: TStringList; { METHODS } procedure SetServices(const Value: TObjectList); procedure SetVariables(const Value: TObjectList); procedure SetCustomAboutText(const Value: TStrings); procedure SetHtmlAction(const Value: TStringList); protected { FIELDS } mutexHandle: THandle; public { PROPERTIES } property Services: TObjectList read FServices write SetServices; property Variables: TObjectList read FVariables write SetVariables; property HtmlActions: TStringList read FHtmlActions write SetHtmlAction; property DoubleClickAction: TTMMultiAction read FDoubleClickAction; property StartupAction: TTMMultiAction read FStartupAction; property TrayIconAllRunning: Integer read FTrayIconAllRunning write FTrayIconAllRunning; property TrayIconSomeRunning: Integer read FTrayIconSomeRunning write FTrayIconSomeRunning; property TrayIconNoneRunning: Integer read FTrayIconNoneRunning write FTrayIconNoneRunning; property AllRunningHint: String read FAllRunningHint write FAllRunningHint; property SomeRunningHint: String read FSomeRunningHint write FSomeRunningHint; property NoneRunningHint: String read FNoneRunningHint write FNoneRunningHint; property ServiceGlyphRunning: Integer read FServiceGlyphRunning write FServiceGlyphRunning; property ServiceGlyphPaused: Integer read FServiceGlyphPaused write FServiceGlyphPaused; property ServiceGlyphStopped: Integer read FServiceGlyphStopped write FServiceGlyphStopped; property ID: String read FID write FID; property CustomAboutHeader: String read FCustomAboutHeader write FCustomAboutHeader; property CustomAboutVersion: String read FCustomAboutVersion write FCustomAboutVersion; property CustomAboutText: TStrings read FCustomAboutText write SetCustomAboutText; { METHODS } procedure ClearMenus; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ExceptionMsgBox(Msg: String; E: Exception); procedure LoadBuiltInVariables; procedure ReadConfig; { Reads and applies the configuration file } end; var MainForm: TMainForm; implementation uses JclFileUtils, JclStrings, TMAbout, TMConfig, TMMsgs, TMCmnFunc; {$R *.dfm} procedure TMainForm.BuiltInActionExecute(Sender: TObject); var AboutDialog: TAboutDiag; ErrorCode: Integer; I: Integer; begin case (Sender as TTMBuiltInAction).BuiltInAction of biaAbout: begin AboutDialog := TAboutDiag.Create(Self); with AboutDialog do begin CustomAboutHeader := Self.CustomAboutHeader; CustomAboutVersion := Self.CustomAboutVersion; CustomAboutText := Self.CustomAboutText; ShowModal; end; //with aboutdialog FreeAndNil(AboutDialog); end; biaExit: Application.Terminate; biaReadConfig: ReadConfig; biaControlPanelServices: begin if not InstShellExec(ExpandVariables('%System%\services.msc', Variables), '/s', '', '', SW_SHOWNORMAL, ErrorCode) then raise Exception.Create('Could not open Services applet'); { DONE 3 : Improve ControlPanelServices built-in action } end; biaCloseServices: begin for I := 0 to Services.Count - 1 do (Services[I] as TTMService).Close; end; biaResetServices: begin for I := 0 to Services.Count - 1 do with (Services[I] as TTMService) do try Open; //if it's already open, it will be closed first except //Apparently, the service hasn't been installed; the menu items // will be disabled end; //for i with services[i] try..except end; else ShowMessage(SMainBuiltInNotImplemented); { DONE 4 -cMissing feaures : Implement all built-in actions } end; end; procedure TMainForm.CheckServicesTimerTimer(Sender: TObject); var I, runningCount: Integer; HintText: String; begin { Check if the configured services are still up & running } { DONE 3 : Implement TMainForm.CheckServicesTimerTimer } runningCount := 0; for I := 0 to Services.Count - 1 do with (Services[I] as TTMService) do begin if Active then if State = svsRunning then Inc(runningCount); end; //for i with services[i] as ttmservice do if runningCount = 0 then begin HintText := NoneRunningHint; if TrayIconNoneRunning <> -1 then TrayIcon.IconIndex := TrayIconNoneRunning; end else if runningCount < Services.Count then begin HintText := SomeRunningHint; if TrayIconSomeRunning <> -1 then TrayIcon.IconIndex := TrayIconSomeRunning; end else begin HintText := AllRunningHint; if TrayIconAllRunning <> -1 then TrayIcon.IconIndex := TrayIconAllRunning; end; StrReplace(HintText, '%n', IntToStr(runningCount), [rfIgnoreCase, rfReplaceAll]); StrReplace(HintText, '%t', IntToStr(Services.Count), [rfIgnoreCase, rfReplaceAll]); TrayIcon.Hint := ExpandVariables(HintText, Variables); end; procedure TMainForm.ClearMenus; procedure ClearItems(Item: TMenuItem); var I: Integer; begin for I := 0 to Item.Count - 1 do begin if Item.Items[0].Count > 0 then ClearItems(Item.Items[0]) else if Item.Items[0].Tag <> 0 then TTMAction(Item.Items[0].Tag).Free; Item.Items[0].Free; end; //for i end; begin ClearItems(LeftClickPopup.Items); ClearItems(RightClickPopup.Items); end; constructor TMainForm.Create(AOwner: TComponent); begin inherited; { Memory inits } mutexHandle := 0; FServices := TObjectList.Create(True); FVariables := TObjectList.Create(True); FHtmlActions := TStringList.Create; FDoubleClickAction := TTMMultiAction.Create; FStartupAction := TTMMultiAction.Create; FCustomAboutText := TStringList.Create; { General inits } with HtmlActions do begin CaseSensitive := False; Sorted := True; end; //with { Read and apply the configuration file } ReadConfig; { Run the startup action } StartupAction.ExecuteAction; end; destructor TMainForm.Destroy; var J: Integer; begin { Stop the timer } CheckServicesTimer.Enabled := False; { Clear menus } ClearMenus; { Memory cleanup } FreeAndNil(FCustomAboutText); FreeAndNil(FDoubleClickAction); FreeAndNil(FStartupAction); for J := 0 to (HtmlActions.Count - 1) do (HtmlActions.Objects[J] as TTMAction).Free; FreeAndNil(FHtmlActions); FreeAndNil(FVariables); FreeAndNil(FServices); inherited; end; procedure TMainForm.ExceptionMsgBox(Msg: String; E: Exception); begin Application.MessageBox(PChar(Msg + #13#10 + '[' + E.ClassName + '] ' + E.Message), 'Aestan Tray Menu', MB_OK + MB_ICONERROR); end; procedure TMainForm.LeftRightClickPopupPopup(Sender: TObject); procedure EnableItems(Item: TMenuItem); var I: Integer; begin for I := 0 to Item.Count - 1 do with Item.Items[I] do if Count > 0 then begin { DONE 3 : Use correct imageindex depending on service status } if Tag <> 0 then with TTMService(Tag) do begin if Active then begin if Caption = '' then Caption := DisplayName; case State of svsRunning: ImageIndex := ServiceGlyphRunning; svsPaused: ImageIndex := ServiceGlyphPaused; svsStopped: ImageIndex := ServiceGlyphStopped; else ImageIndex := -1; end; //case state end; //if active end; //if tag <> 0 then with ttmservice(tag) do EnableItems(Item.Items[I]); end else if Tag <> 0 then Enabled := TTMAction(Tag).CanExecute; end; begin { DONE 2 : Enable/disable service control menu items in LeftRightClickPopupPopup } EnableItems((Sender as TBcBarPopupMenu).Items); end; procedure TMainForm.LoadBuiltInVariables; procedure AddVar(AName, AValue: String; IsPath: Boolean = True); var NewVar: TVariable; begin NewVar := TVariable.Create; with NewVar do begin Name := AName; Value := AValue; if IsPath then Flags := [vfIsPath]; end; //with newvar Variables.Add(NewVar); end; begin { DONE 3 -cMissing feaures : Automatically add built-in variables } AddVar('AeTrayMenuPath', ExtractFilePath(Application.ExeName)); AddVar('Windows', GetWinDir); AddVar('System', GetSystemDir); AddVar('SysDrive', GetSystemDrive); AddVar('ProgramFiles', GetProgramFiles); AddVar('CommonFiles', GetCommonFiles); AddVar('Cmd', GetCmdFileName, False); AddVar('Temp', GetTempDir); end; procedure TMainForm.ReadConfig; var ConfigReader: TTMConfigReader; configFile: String; begin { Disable CheckServicesTimer } CheckServicesTimer.Enabled := False; ConfigReader := TTMConfigReader.Create; with ConfigReader do try { Clear the menus, services etc. } ClearMenus; FDoubleClickAction.Clear; FStartupAction.Clear; FServices.Clear; FVariables.Clear; { Initialize built-in variables } LoadBuiltInVariables; { Initialize the configuration reader } CheckServicesTimer := Self.CheckServicesTimer; DoubleClickAction := Self.DoubleClickAction; StartupAction := Self.StartupAction; ImageList := Self.ImageList; OnBuiltInActionExecute := BuiltInActionExecute; OnSelectMenuItem := SelectMenuItem; Services := Self.Services; TrayIcon := Self.TrayIcon; Variables := Self.Variables; HtmlActions := Self.HtmlActions; { Load the configuration file } try configFile := FindCmdSwitch('-scriptfile='); if configFile <> '' then begin //Load file specified on the command line if PathIsAbsolute(configFile) then Script.LoadFromFile(configFile) else Script.LoadFromFile(PathAppend(ExtractFileDir(Application.ExeName), configFile)); end else //The configuration file has the same file & path as this executable, // but has extension .ini instead of .exe Script.LoadFromFile(PathRemoveExtension(Application.ExeName) + '.ini'); except on E: Exception do begin ExceptionMsgBox(SMainCouldNotLoadConfig, E); Application.Terminate; Exit; end; end; { Read the configuration file } try ReadSettings; ReadBcBarPopupMenu(LeftClickPopup, 'Menu.Left'); ReadBcBarPopupMenu(RightClickPopup, 'Menu.Right'); except on E: EParseError do begin ExceptionMsgBox(Format(SReaderSyntaxError, [E.LineNumber]), E); Application.Terminate; Exit; end; end; Self.TrayIconAllRunning := TrayIconAllRunning; Self.TrayIconSomeRunning := TrayIconSomeRunning; Self.TrayIconNoneRunning := TrayIconNoneRunning; Self.AllRunningHint := AllRunningHint; Self.SomeRunningHint := SomeRunningHint; Self.NoneRunningHint := NoneRunningHint; Self.ServiceGlyphRunning := ServiceGlyphRunning; Self.ServiceGlyphPaused := ServiceGlyphPaused; Self.ServiceGlyphStopped := ServiceGlyphStopped; Self.ID := ID; Self.CustomAboutHeader := CustomAboutHeader; Self.CustomAboutVersion := CustomAboutVersion; Self.CustomAboutText := CustomAboutText; { DONE 3 : Read && apply all the other settings, too } finally FreeAndNil(ConfigReader); end; //with configreader try..finally { Handle the ID stuff } //Try creating a mutex if mutexHandle = 0 then begin mutexHandle := CreateMutex(nil, True, PChar(ID)); if GetLastError = ERROR_ALREADY_EXISTS then begin Application.Terminate; Exit; end; //Set the form caption Caption := 'AeTrayMenu[' + ID + ']'; end; //if mutexhandle = nil { Show the tray icon } TrayIcon.Active := True; { Start the timer } if CheckServicesTimer.Interval > 0 then begin CheckServicesTimer.Enabled := True; CheckServicesTimerTimer(Self); end; end; procedure TMainForm.SelectMenuItem(Sender: TObject); begin if Sender is TMenuItem then if (Sender as TMenuItem).Count = 0 then //submenus cannot have actions linked to them with Sender as TMenuItem do begin if Tag <> 0 then try TTMAction(Tag).ExecuteAction; except on E: Exception do ExceptionMsgBox(SMainCouldNotExecuteMenuItem, E); end; end; //if sender is tmenuitem then with sender as tmenuitem end; procedure TMainForm.SetCustomAboutText(const Value: TStrings); begin FCustomAboutText.Assign(Value); end; procedure TMainForm.SetHtmlAction(const Value: TStringList); begin FHtmlActions.Assign(Value); end; procedure TMainForm.SetServices(const Value: TObjectList); begin FServices.Assign(Value); end; procedure TMainForm.SetVariables(const Value: TObjectList); begin FVariables.Assign(Value); end; procedure TMainForm.TrayIconDblClick(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin { Respond to double-clicks } DoubleClickAction.ExecuteAction; end; end.
unit fODReleaseEvent; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ORFn, CheckLst, ORCtrls, fAutoSz, fBase508Form, VA508AccessibilityManager; type TfrmOrdersReleaseEvent = class(TfrmBase508Form) pnlMiddle: TPanel; pnlBottom: TPanel; btnOK: TButton; btnCancel: TButton; cklstOrders: TCaptionCheckListBox; lblRelease: TLabel; procedure btnCancelClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure cklstOrdersMeasureItem(Control: TWinControl; Index: Integer; var AHeight: Integer); procedure cklstOrdersDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure cklstOrdersMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); private { Private declarations } OKPressed: boolean; FLastHintItem: integer; FOldHintPause: integer; FOldHintHidePause: integer; FComplete: boolean; FCurrTS: string; public { Public declarations } property CurrTS: string read FCurrTS write FCurrTS; end; //procedure ExecuteReleaseEventOrders(AnOrderList: TList); function ExecuteReleaseEventOrders(AnOrderList: TList): boolean; implementation {$R *.DFM} uses rCore, rOrders, uConst, fOrdersPrint, uCore, uOrders, fOrders, rODLab, fRptBox, VAUtils, System.Types; const TX_SAVERR1 = 'The error, '; TX_SAVERR2 = ', occurred while trying to release:' + CRLF + CRLF; TC_SAVERR = 'Error Saving Order'; //procedure ExecuteReleaseEventOrders(AnOrderList: TList); function ExecuteReleaseEventOrders(AnOrderList: TList): boolean; const TXT_RELEASE = #13 + #13 + ' The following orders will be released to service:'; var i,j,idx: integer; AOrder: TOrder; OrdersLst: TStringlist; OrderText, LastCheckedPtEvt, SpeCap: string; frmOrdersReleaseEvent: TfrmOrdersReleaseEvent; AList: TStringList; function FindOrderText(const AnID: string): string; var i: Integer; begin Result := ''; with AnOrderList do for i := 0 to Count - 1 do with TOrder(Items[i]) do if ID = AnID then begin Result := Text; Break; end; end; begin frmOrdersReleaseEvent := TfrmOrdersReleaseEvent.Create(Application); try frmOrdersReleaseEvent.CurrTS := Piece(GetCurrentSpec(Patient.DFN),'^',1); if Length(frmOrdersReleaseEvent.CurrTS)>0 then SpeCap := #13 + ' The current treating specialty is ' + frmOrdersReleaseEvent.CurrTS else SpeCap := #13 + ' No treating specialty is available.'; ResizeFormToFont(TForm(frmOrdersReleaseEvent)); if Patient.Inpatient then frmOrdersReleaseEvent.lblRelease.Caption := ' ' + Patient.Name + ' is currently admitted to ' + Encounter.LocationName + SpeCap + TXT_RELEASE else begin if Encounter.Location > 0 then frmOrdersReleaseEvent.lblRelease.Caption := ' ' + Patient.Name + ' is currently at ' + Encounter.LocationName + SpeCap + TXT_RELEASE else frmOrdersReleaseEvent.lblRelease.Caption := ' ' + Patient.Name + ' is currently an outpatient.' + SpeCap + TXT_RELEASE; end; with frmOrdersReleaseEvent do cklstOrders.Caption := lblRelease.Caption; with AnOrderList do for i := 0 to Count - 1 do begin AOrder := TOrder(Items[i]); idx := frmOrdersReleaseEvent.cklstOrders.Items.AddObject(AOrder.Text,AOrder); frmOrdersReleaseEvent.cklstOrders.Checked[idx] := True; end; frmOrdersReleaseEvent.ShowModal; if frmOrdersReleaseEvent.OKPressed then begin OrdersLst := TStringList.Create; for j := 0 to frmOrdersReleaseEvent.cklstOrders.Items.Count - 1 do begin if frmOrdersReleaseEvent.cklstOrders.Checked[j] then OrdersLst.Add(TOrder(frmOrdersReleaseEvent.cklstOrders.Items.Objects[j]).ID); end; StatusText('Releasing Orders to Service...'); SendReleaseOrders(OrdersLst); LastCheckedPtEvt := ''; //CQ #15813 Modired code to look for error string mentioned in CQ and change strings to conts - JCS with OrdersLst do if Count > 0 then for i := 0 to Count - 1 do begin if Pos('E', Piece(OrdersLst[i], U, 2)) > 0 then begin OrderText := FindOrderText(Piece(OrdersLst[i], U, 1)); if Piece(OrdersLst[i],U,4) = TX_SAVERR_PHARM_ORD_NUM_SEARCH_STRING then InfoBox(TX_SAVERR1 + Piece(OrdersLst[i], U, 4) + TX_SAVERR2 + OrderText + CRLF + CRLF + TX_SAVERR_PHARM_ORD_NUM, TC_SAVERR, MB_OK) else if Piece(OrdersLst[i],U,4) = TX_SAVERR_IMAGING_PROC_SEARCH_STRING then InfoBox(TX_SAVERR1 + Piece(OrdersLst[i], U, 4) + TX_SAVERR2 + OrderText + CRLF + CRLF + TX_SAVERR_IMAGING_PROC, TC_SAVERR, MB_OK) else InfoBox(TX_SAVERR1 + Piece(OrdersLst[i], U, 4) + TX_SAVERR2 + OrderText, TC_SAVERR, MB_OK); end; end; // CQ 10226, PSI-05-048 - advise of auto-change from LC to WC on lab orders AList := TStringList.Create; try CheckForChangeFromLCtoWCOnRelease(AList, Encounter.Location, OrdersLst); if AList.Text <> '' then ReportBox(AList, 'Changed Orders', TRUE); finally AList.Free; end; PrintOrdersOnSignRelease(OrdersLst, NO_PROVIDER); with AnOrderList do for i := 0 to Count - 1 do with TOrder(Items[i]) do begin if EventPtr <> LastCheckedPtEvt then begin LastCheckedPtEvt := EventPtr; if CompleteEvt(EventPtr,EventName,False) then frmOrdersReleaseEvent.FComplete := True; end; end; StatusText(''); ordersLst.Free; with AnOrderList do for i := 0 to Count - 1 do UnlockOrder(TOrder(Items[i]).ID); if frmOrdersReleaseEvent.FComplete then begin frmOrders.InitOrderSheetsForEvtDelay; frmOrders.ClickLstSheet; end; frmOrdersReleaseEvent.FComplete := False; Result := True; end else Result := False; Except on E: exception do Result := false; end; {finally with AnOrderList do for i := 0 to Count - 1 do UnlockOrder(TOrder(Items[i]).ID); if frmOrdersReleaseEvent.FComplete then begin frmOrders.InitOrderSheetsForEvtDelay; frmOrders.ClickLstSheet; end; frmOrdersReleaseEvent.FComplete := False; end;} end; procedure TfrmOrdersReleaseEvent.btnCancelClick(Sender: TObject); begin Close; end; procedure TfrmOrdersReleaseEvent.FormCreate(Sender: TObject); begin inherited; OKPressed := False; FLastHintItem := -1; FComplete := False; FOldHintPause := Application.HintPause; FCurrTS := ''; Application.HintPause := 250; FOldHintHidePause := Application.HintHidePause; Application.HintHidePause := 30000; end; procedure TfrmOrdersReleaseEvent.btnOKClick(Sender: TObject); var i: integer; beSelected: boolean; begin beSelected := False; for i := 0 to cklstOrders.Items.Count - 1 do begin if cklstOrders.Checked[i] then begin beSelected := True; Break; end; end; if not beSelected then begin ShowMsg('You have to select at least one order!'); Exit; end; OKPressed := True; Close; end; procedure TfrmOrdersReleaseEvent.FormDestroy(Sender: TObject); begin inherited; Application.HintPause := FOldHintPause; Application.HintHidePause := FOldHintHidePause; end; procedure TfrmOrdersReleaseEvent.cklstOrdersMeasureItem( Control: TWinControl; Index: Integer; var AHeight: Integer); var x:string; ARect: TRect; begin inherited; AHeight := MainFontHeight + 2; with cklstOrders do if Index < Items.Count then begin x := FilteredString(Items[Index]); ARect := ItemRect(Index); AHeight := WrappedTextHeightByFont( cklstOrders.Canvas, Font, x, ARect); if AHeight > 255 then AHeight := 255; if AHeight < 13 then AHeight := 13; end; end; procedure TfrmOrdersReleaseEvent.cklstOrdersDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); var x: string; ARect: TRect; begin inherited; x := ''; ARect := Rect; with cklstOrders do begin Canvas.FillRect(ARect); Canvas.Pen.Color := Get508CompliantColor(clSilver); Canvas.MoveTo(0, ARect.Bottom - 1); Canvas.LineTo(ARect.Right, ARect.Bottom - 1); if Index < Items.Count then begin X := FilteredString(Items[Index]); DrawText(Canvas.handle, PChar(x), Length(x), ARect, DT_LEFT or DT_NOPREFIX or DT_WORDBREAK); end; end; end; procedure TfrmOrdersReleaseEvent.cklstOrdersMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); var Itm: integer; begin inherited; Itm := cklstOrders.ItemAtPos(Point(X, Y), TRUE); if (Itm >= 0) then begin if (Itm <> FLastHintItem) then begin Application.CancelHint; cklstOrders.Hint := TrimRight(cklstOrders.Items[Itm]); FLastHintItem := Itm; Application.ActivateHint(Point(X, Y)); end; end else begin cklstOrders.Hint := ''; FLastHintItem := -1; Application.CancelHint; end; end; end.
{ GMCircleVCL unit ES: contiene las clases VCL necesarias para mostrar círculos en un mapa de Google Maps mediante el componente TGMMap EN: includes the VCL classes needed to show circles on Google Map map using the component TGMMap ========================================================================= MODO DE USO/HOW TO USE ES: poner el componente en el formulario, linkarlo a un TGMMap y poner los círculos a mostrar EN: put the component into a form, link to a TGMMap and put the circled to show ========================================================================= History: ver 0.1.9 ES: nuevo: documentación nuevo: se hace compatible con FireMonkey EN: new: documentation new: now compatible with FireMonkey ========================================================================= IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras, ampliaciones, errores y/o cualquier otro tipo de sugerencia, envíame un correo a: gmlib@cadetill.com IMPORTANT PROGRAMMERS: please, if you have comments, improvements, enlargements, errors and/or any another type of suggestion, please send me a mail to: gmlib@cadetill.com ========================================================================= Copyright (©) 2012, by Xavier Martinez (cadetill) @author Xavier Martinez (cadetill) @web http://www.cadetill.com } {*------------------------------------------------------------------------------ The GMCircleVCL unit includes the VCL classes needed to show circles on Google Map map using the component TGMMap. @author Xavier Martinez (cadetill) @version 1.5.0 -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ La unit GMCircleVCL contiene las clases VCL necesarias para mostrar círculos en un mapa de Google Maps mediante el componente TGMMap @author Xavier Martinez (cadetill) @version 1.5.0 -------------------------------------------------------------------------------} unit GMCircleVCL; {$I ..\gmlib.inc} interface uses {$IFDEF DELPHIXE2} Vcl.Graphics, System.Classes, Vcl.ExtCtrls, {$ELSE} Graphics, Classes, ExtCtrls, {$ENDIF} GMCircle, GMLinkedComponents; type TCircle = class; {*------------------------------------------------------------------------------ VCL class for automatic enlarged circle. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Clase VCL para el agrandado automático del círculo. -------------------------------------------------------------------------------} TSizeable = class(TCustomSizeable) private FTimer: TTimer; // ES: TTimer para el control de eventos - EN: TTimer for events control protected procedure SetActive(const Value: Boolean); override; procedure SetSpeed(const Value: Integer); override; public {*------------------------------------------------------------------------------ Constructor class @param aOwner Owner. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Constructor de la clase @param aOwner Propietario. -------------------------------------------------------------------------------} constructor Create(aOwner: TCircle); reintroduce; virtual; {*------------------------------------------------------------------------------ Destructor class -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Destructor de la clase -------------------------------------------------------------------------------} destructor Destroy; override; end; {*------------------------------------------------------------------------------ VCL class for circles. More information at https://developers.google.com/maps/documentation/javascript/reference?hl=en#Circle -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Clase VCL para los círculos. Más información en https://developers.google.com/maps/documentation/javascript/reference?hl=en#Circle -------------------------------------------------------------------------------} TCircle = class(TCustomCircle) private {*------------------------------------------------------------------------------ The fill color. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Color de relleno. -------------------------------------------------------------------------------} FFillColor: TColor; {*------------------------------------------------------------------------------ The stroke color. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Color del trazo. -------------------------------------------------------------------------------} FStrokeColor: TColor; procedure SetFillColor(const Value: TColor); procedure SetStrokeColor(const Value: TColor); protected function GetFillColor: string; override; function GetStrokeColor: string; override; public constructor Create(Collection: TCollection); override; procedure Assign(Source: TPersistent); override; published property FillColor: TColor read FFillColor write SetFillColor default clRed; property StrokeColor: TColor read FStrokeColor write SetStrokeColor default clBlack; end; {*------------------------------------------------------------------------------ VCL class for circles collection. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Clase VCL para la colección de círculos. -------------------------------------------------------------------------------} TCircles = class(TCustomCircles) private procedure SetItems(I: Integer; const Value: TCircle); function GetItems(I: Integer): TCircle; protected function GetOwner: TPersistent; override; public function Add: TCircle; function Insert(Index: Integer): TCircle; {*------------------------------------------------------------------------------ Lists the circles in the collection. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Lista de círculos en la colección. -------------------------------------------------------------------------------} property Items[I: Integer]: TCircle read GetItems write SetItems; default; end; {*------------------------------------------------------------------------------ Class management of circles. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Clase para la gestión de círculos. -------------------------------------------------------------------------------} TGMCircle = class(TCustomGMCircle) protected function GetItems(I: Integer): TCircle; function GetCollectionItemClass: TLinkedComponentClass; override; function GetCollectionClass: TLinkedComponentsClass; override; public function Add(Lat: Real = 0; Lng: Real = 0; Radius: Integer = 0): TCircle; {*------------------------------------------------------------------------------ Array with the collection items. -------------------------------------------------------------------------------} {=------------------------------------------------------------------------------ Array con la colección de elementos. -------------------------------------------------------------------------------} property Items[I: Integer]: TCircle read GetItems; default; end; implementation uses {$IFDEF DELPHIXE2} System.SysUtils, {$ELSE} // ES: si la verisón es la XE2 o superior - EN: if version is XE2 or higher SysUtils, {$ENDIF} GMFunctionsVCL; { TCircle } procedure TCircle.Assign(Source: TPersistent); begin inherited; if Source is TCircle then begin FillColor := TCircle(Source).FillColor; StrokeColor := TCircle(Source).StrokeColor; end; end; constructor TCircle.Create(Collection: TCollection); begin inherited; FFillColor := clRed; FStrokeColor := clBlack; AutoResize := TSizeable.Create(Self); end; function TCircle.GetFillColor: string; begin Result := TTransform.TColorToStr(FFillColor); end; function TCircle.GetStrokeColor: string; begin Result := TTransform.TColorToStr(FStrokeColor); end; procedure TCircle.SetFillColor(const Value: TColor); begin if FFillColor = Value then Exit; FFillColor := Value; ChangeProperties; if Assigned(TGMCircle(TCircles(Collection).FGMLinkedComponent).OnFillColorChange) then TGMCircle(TCircles(Collection).FGMLinkedComponent).OnFillColorChange( TGMCircle(TCircles(Collection).FGMLinkedComponent), Index, Self); end; procedure TCircle.SetStrokeColor(const Value: TColor); begin if FStrokeColor = Value then Exit; FStrokeColor := Value; ChangeProperties; if Assigned(TGMCircle(TCircles(Collection).FGMLinkedComponent).OnStrokeColorChange) then TGMCircle(TCircles(Collection).FGMLinkedComponent).OnStrokeColorChange( TGMCircle(TCircles(Collection).FGMLinkedComponent), Index, Self); end; { TCircles } function TCircles.Add: TCircle; begin Result := TCircle(inherited Add); end; function TCircles.GetItems(I: Integer): TCircle; begin Result := TCircle(inherited Items[I]); end; function TCircles.GetOwner: TPersistent; begin Result := TGMCircle(inherited GetOwner); end; function TCircles.Insert(Index: Integer): TCircle; begin Result := TCircle(inherited Insert(Index)); end; procedure TCircles.SetItems(I: Integer; const Value: TCircle); begin inherited SetItem(I, Value); end; { TGMCircle } function TGMCircle.Add(Lat, Lng: Real; Radius: Integer): TCircle; begin Result := TCircle(inherited Add(Lat, Lng, Radius)); end; function TGMCircle.GetCollectionClass: TLinkedComponentsClass; begin Result := TCircles; end; function TGMCircle.GetCollectionItemClass: TLinkedComponentClass; begin Result := TCircle; end; function TGMCircle.GetItems(I: Integer): TCircle; begin Result := TCircle(inherited Items[i]); end; { TSizeable } constructor TSizeable.Create(aOwner: TCircle); begin inherited Create(aOwner); FTimer := TTimer.Create(nil); FTimer.Enabled := False; FTimer.OnTimer := OnTimer; end; destructor TSizeable.Destroy; begin if Assigned(FTimer) then FreeAndNil(FTimer); inherited; end; procedure TSizeable.SetActive(const Value: Boolean); begin inherited; //if Active = Value then Exit; if Active then begin GetOwner.Radius := Min; FTimer.Interval := Increment; FTimer.Enabled := True; end else FTimer.Enabled := False; end; procedure TSizeable.SetSpeed(const Value: Integer); begin inherited; //if Speed = Value then Exit; if Active then FTimer.Interval := Speed; end; end.
unit Unit1; interface uses System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.ExtCtrls, //GLS GLObjects, GLExtrusion, GLScene, GLCadencer, GLFireFX, GLWin32Viewer, GLGeomObjects, GLCrossPlatform, GLCoordinates, GLBaseClasses; type TForm1 = class(TForm) GLSceneViewer1: TGLSceneViewer; GLScene1: TGLScene; GLCamera1: TGLCamera; GLLightSource1: TGLLightSource; DummyCube1: TGLDummyCube; Candle: TGLCylinder; RevolutionSolid1: TGLRevolutionSolid; Lines1: TGLLines; GLFireFXManager1: TGLFireFXManager; GLCadencer1: TGLCadencer; GLProxyObject1: TGLProxyObject; GLProxyObject2: TGLProxyObject; TrackBar1: TTrackBar; Timer1: TTimer; Plane1: TGLPlane; DummyCube2: TGLDummyCube; procedure TrackBar1Change(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormResize(Sender: TObject); private { Private declarations } public { Public declarations } mx, my : Integer; end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.TrackBar1Change(Sender: TObject); begin GLFireFXManager1.FireDir.Z:=-TrackBar1.Position*0.1; end; procedure TForm1.Timer1Timer(Sender: TObject); var n : Integer; begin Caption := 'Candles - '+ Format('%.1f FPS', [GLSceneViewer1.FramesPerSecond]); GLSceneViewer1.ResetPerformanceMonitor; if TrackBar1.Position=0 then GLFireFXManager1.Disabled:=False else begin n:=Abs(TrackBar1.Position)-15; if n>0 then if Random/n<0.15 then GLFireFXManager1.Disabled:=True; end; end; procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin mx:=x; my:=y; end; procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if Shift<>[] then begin GLCamera1.MoveAroundTarget(my-y, mx-x); GLCadencer1.Progress; mx:=x; my:=y; end; end; procedure TForm1.FormResize(Sender: TObject); begin GLCamera1.FocalLength:=Height/3; end; end.
{*********************************************} { TeeBI Software Library } { FireDAC Database data import and export } { Copyright (c) 2015-2017 by Steema Software } { All Rights Reserved } {*********************************************} unit BI.DB.Fire; interface (* Just include this unit in the "uses" of any unit, to enable FireDAC as the "Engine" for all TeeBI database operations. Note: Better to not include BI.DB.ZeosLib or any other unit that also provides a different "Engine". When using multiple engines (optionally), the current one must be manually selected like: uses BI.DB; TBIDB.Engine:=TDBFireDACEngine.Create; <--- the desired engine class *) uses System.Classes, System.Types, Data.DB, BI.DataItem, BI.DB, BI.DataSource, BI.Persist, FireDAC.Comp.Client; type TDBFireDACEngine=class(TBIDBEngine) private class procedure SetQueryParameters(const Query:TFDQuery); static; public class function CloneConnection(const AConn:TCustomConnection): TCustomConnection; override; class function CreateConnection(const Definition:TDataDefinition):TCustomConnection; override; class function CreateDataSet(const AOwner:TComponent; const AData:TDataItem):TDataSet; override; class function CreateQuery(const AConnection:TCustomConnection; const SQL:String):TDataSet; override; class function DriverNames:TStringDynArray; override; class function DriverToName(const ADriver:String):String; override; class function FileFilter: TFileFilters; override; class function GetConnectionName(const AConnection:TCustomConnection):String; override; class function GetDriver(const AIndex:Integer):String; override; class function GetKeyFieldNames(const AConnection:TCustomConnection; const ATable:String):TStrings; override; class function GetSchemas(const AConnection:TCustomConnection):TStrings; class function GetTable(const AConnection:TCustomConnection; const AName:String):TDataSet; override; class function GetItemNames(const AConnection:TCustomConnection; const IncludeSystem,IncludeViews:Boolean):TStrings; override; class procedure GuessForeignKeys(const AName:String; const Table:TDataSet; const AData:TDataItem; const Source:TBISource); override; class function ImportFile(const Source:TBIDB; const AFileName:String):TDataArray; override; class procedure StartParallel; override; class function Supports(const Extension:String):Boolean; override; class function Tester:TBIDBTesterClass; override; end; implementation
program buildutil; {$mode objfpc}{$H+} uses {$IFDEF UNIX} {$IFDEF UseCThreads} cthreads, {$ENDIF} {$ENDIF} SysUtils, Classes, IniFiles, fileutil, LazFileUtils, uGetOpt, getopts, uBuildFile; const OptionsLong: array[1..4] of TOption = ( (Name: 'help'; Has_Arg: No_Argument; Flag: nil; Value: 'h'), (Name: 'file'; Has_Arg: Required_Argument; Flag: nil; Value: 'f'), (Name: 'suppress'; Has_Arg: Required_Argument; Flag: nil; Value: 's'), (Name: ''; Has_Arg: 0; Flag: nil; Value: #0) ); OptionShort = 'h?f:s:'; const TASK_DEFAULT = '*MAIN*'; var Buildfile: string = 'Buildfile'; Buildtask: string = TASK_DEFAULT; SuppressedTasks: string = ''; procedure ProcessOption(const opt: string; const OptArg: string); begin case opt of 'h', '?': begin WriteLn(ExtractFileName(ParamStr(0)),' [options] [TASK]'); WriteLn('Task: begin building at [TASK], otherwise starts at ',TASK_DEFAULT,' '); WriteLn('Options:'); WriteLn(' -f|--file "FILENAME"'); WriteLn(' Read Buildfile from FILENAME, defaults to Buildfile'); WriteLn(' -s|--suppress "TASK[,TASK]"'); WriteLn(' Do not execute TASKs, assume succeeded'); Halt(0); end; 'f': begin Buildfile:= OptArg; end; 's': begin if SuppressedTasks > '' then SuppressedTasks += ''; SuppressedTasks += OptArg; end else WriteLn(ErrOutput, 'Unknown option: ', opt); end; end; var lastopt: integer; bf: TBuildFile; begin Randomize; lastopt:= HandleAllOptions(OptionShort, @OptionsLong[1], @ProcessOption); if lastopt <= ParamCount then begin Buildtask:= ParamStr(lastopt); end; Buildfile:= ExpandFileName(Buildfile); if not FileExists(Buildfile) then begin WriteLn(ErrOutput, 'Buildfile ',Buildfile,' not found!'); Halt(ERROR_BUILD_FILE); end; bf:= TBuildFile.Create(Buildfile); try bf.SetSuppressed(SuppressedTasks); ExitCode:= bf.BuildTask(Buildtask); finally FreeAndNil(bf); end; end.
{ ************************************************************** Package: XWB - Kernel RPCBroker Date Created: Sept 18, 1997 (Version 1.1) Site Name: Oakland, OI Field Office, Dept of Veteran Affairs Developers: Joel Ivey, Herlan Westra Description: Contains TRPCBroker and related components. Unit: frmSignonMessage displays message from server after user signon. Current Release: Version 1.1 Patch 65 *************************************************************** } { ************************************************** Changes in v1.1.65 (HGW 11/10/2016) XWB*1.1*65 1. Added code to set up and assign form to current broker session to display a sign-on message upon connecting to a server. This is a VA Handbook Appendix F requirement (AC-8: System Use Notification). 2. Added lblConnection to bottom of form with: "Secured connection to ____ using IPv4" "Encrypted connection to ____ using IPv6" "Unsecured connection to ____ using IPv4" Changes in v1.1.60 (HGW 12/18/2013) XWB*1.1*60 1. None. Changes in v1.1.50 (JLI 09/01/2011) XWB*1.1*50 1. None. ************************************************** } unit frmSignonMessage; { VA Handbook Appendix F, AC-8: System Use Notification NIST SP 800-53 The information system: * Displays an approved system use notification message or banner before granting access to the system that provides privacy and security notices consistent with applicable Federal laws, Executive Orders, policies, regulations, standards, and guidance and states that: (i) users are accessing a U.S. Government information system; (ii) system usage may be monitored, recorded, and subject to audit; (iii) unauthorized use of the system is prohibited and subject to criminal and civil penalties; and (iv) use of the system indicates consent to monitoring and recording; * Retains the notification message or banner on the screen until users take explicit actions to log on to or further access the information system; and * For publicly accessible systems: (i) displays the system use information when appropriate, before granting further access; (ii) displays references, if any, to monitoring, recording, or auditing that are consistent with privacy accommodations for such systems that generally prohibit those activities; and (iii) includes in the notice given to public users of the information system, a description of the authorized uses of the system. } interface uses {System} Classes, SysUtils, UITypes, {WinApi} Messages, ShellApi, Windows, {VA} fRPCBErrMsg, MFunStr, SgnonCnf, Trpcb, XWBRich20, XWBut1, {Vcl} Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls; type TfrmSignonMsg = class(TForm) Panel1: TPanel; Panel2: TPanel; BitBtn1: TBitBtn; mmoMsg: XWBRich20.TXWBRichEdit; RPCbiBroker: TRPCBroker; lblConnection: TLabel; procedure Panel2Resize(Sender: TObject); procedure BitBtn1Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure introTextURLClick(Sender: TObject; URL: String); private OrigHelp : String; //Help filename of calling application. procedure WMSysCommand(var Message: TWMSysCommand); message WM_SYSCOMMAND; public DefaultSignonConfiguration: TSignonValues; end; procedure PrepareSignonMessage(AppBroker: TRPCBroker); function SetUpMessage : Boolean; overload; var MessagefrmSignOnBroker: TRPCBroker; frmSignonMsg: TfrmSignonMsg; const SC_Configure = 1; SC_About = 2; implementation var SysMenu: HMenu; {$R *.DFM} {--------------------- TfrmSignonMsg.PrepareSignonMessage -------- Assigns a TRPCBroker component to this session ------------------------------------------------------------------} procedure PrepareSignonMessage(AppBroker: TRPCBroker); begin MessagefrmSignonBroker := AppBroker; end; {--------------------- TfrmSignonMsg.SetUpMessage ---------------- Set up Message form. ------------------------------------------------------------------} function SetUpMessage: Boolean; var ConnectedUser: String; ConnectedSecurity: String; ConnectedServer: String; ConnectedIPprotocol: String; begin //MessagefrmSignonBroker supersedes RpcbiBroker if MessagefrmSignonBroker = nil then MessagefrmSignonBroker := frmSignonMsg.RpcbiBroker; with frmSignonMsg do begin ConnectedUser := ''; ConnectedSecurity := ''; ConnectedServer := ''; ConnectedIPprotocol := ''; try with frmSignonMsg do begin if MessagefrmSignonBroker.RPCBError = '' then begin if MessagefrmSignonBroker.SSOiLogonName <> '' then ConnectedUser := MessagefrmSignonBroker.SSOiLogonName + ' has '; if MessagefrmSignonBroker.IPsecSecurity = 1 then ConnectedSecurity := 'a secure connection to '; if MessagefrmSignonBroker.IPsecSecurity = 2 then ConnectedSecurity := 'an encrypted connection to '; if ConnectedSecurity = '' then ConnectedSecurity := 'a connection to '; ConnectedServer := MessagefrmSignonBroker.Login.DomainName + ' using '; if MessagefrmSignonBroker.IPprotocol = 4 then ConnectedIPProtocol := 'IPv4.'; if MessagefrmSignonBroker.IPprotocol = 6 then ConnectedIPProtocol := 'IPv6.'; if not (ConnectedUser = '') then frmSignonMsg.lblConnection.Caption := ConnectedUser + ConnectedSecurity + ConnectedServer + ConnectedIPprotocol; end; end; except end; end; Result := True; //By default Message is displayed (VA Handbook 6500 requirement). end; {--------------------- TfrmSignonMsg.FormClose ------------------- Close frmSignonMessage Form ------------------------------------------------------------------} procedure TfrmSignonMsg.FormClose(Sender: TObject; var Action: TCloseAction); begin if Piece(strSize,U,1) = '2' then begin strSize := '2^'+IntToStr(Width)+ U + IntToStr(Height); WriteRegData(HKCU, REG_SIGNON, 'SignonSiz', strSize); end; if Piece(strPosition,U,1) = '2' then begin strPosition := '2^'+IntToStr(Top)+ U + IntToStr(Left); WriteRegData(HKCU, REG_SIGNON, 'SignonPos', strPosition); end; Application.HelpFile := OrigHelp; // Restore helpfile. end; {--------------------- TfrmSignonMsg.FormCreate ------------------ Instantiate frmSignonMessage Form ------------------------------------------------------------------} procedure TfrmSignonMsg.FormCreate(Sender: TObject); var SignonConfiguration: TSignonConfiguration; begin if (Pos('LARGE',UpperCase(ReadRegDataDefault(HKCU, 'Control Panel\Appearance', 'Current',''))) > 0) or (Screen.Width < 800) then begin WindowState := wsMaximized; with Screen do begin if Width < 700 then // 640 mmoMsg.Font.Size := 9 else if Width < 750 then // 720 mmoMsg.Font.Size := 10 else if Width < 900 then // 800 mmoMsg.Font.Size := 11 else if Width < 1100 then // 1024 mmoMsg.Font.Size := 15 else if Width < 1200 then // 1152 mmoMsg.Font.Size := 16 else if Width < 1900 then mmoMsg.Font.Size := 19 // 1280 else mmoMsg.Font.Size := 28; // 1920 end; // with end; FormStyle := fsStayOnTop; // make form stay on top of others so it can be found {adjust appearance per user's preferences} SignonConfiguration := TSignonConfiguration.Create; try DefaultSignonConfiguration := TSignOnValues.Create; DefaultSignonConfiguration.BackColor := mmoMsg.Color; DefaultSignonConfiguration.Height := Height; DefaultSignonConfiguration.Width := Width; DefaultSignonConfiguration.Position := '0'; DefaultSignonConfiguration.Size := '0'; DefaultSignonConfiguration.Left := Left; DefaultSignonConfiguration.Top := Top; DefaultSignonConfiguration.Font := mmoMsg.Font; DefaultSignonConfiguration.TextColor := mmoMsg.Font.Color; DefaultSignonConfiguration.FontStyles := mmoMsg.Font.Style; SignonDefaults.SetEqual(DefaultSignonConfiguration); SignonConfiguration.ReadRegistrySettings; if InitialValues.Size = '0' then begin {restore defaults} Width:= DefaultSignonConfiguration.Width; Height := DefaultSignonConfiguration.Height; end else begin try Position := poDesigned; Width := StrToInt(Piece(strSize,U,2)); Height := StrToInt(Piece(strSize,U,3)); except Width:= DefaultSignonConfiguration.Width; Height := DefaultSignonConfiguration.Height; end; end; if InitialValues.Position = '0' then {restore defaults} Position := poScreenCenter else begin try Top:= StrToInt(Piece(strPosition,U,2)); Left := StrToInt(Piece(strPosition,U,3)); except Position := poScreenCenter end; end; if InitialValues.BackColor <> 0 then mmoMsg.Color := InitialValues.BackColor else mmoMsg.Color := clWindow; mmoMsg.Font := InitialValues.Font; mmoMsg.URLDetect := TRUE; lblConnection.Caption := ''; finally SignonConfiguration.Free; end; end; {--------------------- TfrmSignonMsg.FormShow ------------------- Show frmSignonMessage Form ------------------------------------------------------------------} procedure TfrmSignonMsg.FormShow(Sender: TObject); var Str: String; begin Str := 'RPCBroker'; {add Configure... to system menu} SysMenu := GetSystemMenu(Handle, False); AppendMenu(SysMenu, MF_Enabled + MF_String + MF_Unchecked, SC_Configure, '&Properties...'); AppendMenu(SysMenu, MF_Enabled + MF_String + MF_Unchecked, SC_About,PChar('&About '+Str)); with MessagefrmSignOnBroker do begin RemoteProcedure := 'XUS INTRO MSG'; lstCall(mmoMsg.Lines); end; OrigHelp := Application.HelpFile; // Save original helpfile. Application.HelpFile := ReadRegData(HKLM, REG_BROKER, 'BrokerDr') + '\clagent.hlp'; // Identify ConnectTo helpfile. end; procedure TfrmSignonMsg.Panel2Resize(Sender: TObject); begin BitBtn1.Left := (Panel2.Width - BitBtn1.Width) div 2; end; procedure TfrmSignonMsg.BitBtn1Click(Sender: TObject); begin Close; end; {--------------------- TfrmSignonMsg.introTextURLClick ----------- Implement 'click' on a URL in the introText box ------------------------------------------------------------------} procedure TfrmSignonMsg.introTextURLClick(Sender: TObject; URL: String); begin //URL := TIdURI.URLEncode(URL); //Indy IdURI unit ShellExecute(Application.Handle,'open',PChar(URL),nil,nil,SW_NORMAL); end; {--------------------- TfrmSignonMsg.WMSysCommand ------------------- 'Configure' or 'About' popup box (system commands) ------------------------------------------------------------------} procedure TfrmSignonMsg.WMSysCommand(var Message: TWMSysCommand); var Str: String; SignonConfiguration: TSignonConfiguration; frmErrMsg: TfrmErrMsg; begin if Message.CmdType = SC_Configure then begin SignonConfiguration := TSignonConfiguration.Create; try ShowApplicationAndFocusOK(Application); SignonConfiguration.ShowModal; finally SignonConfiguration.Free; Self.WindowState := wsNormal; end; end else if Message.CmdType = SC_About then begin frmErrMsg := TfrmErrMsg.Create(Application); try frmErrMsg.Caption := 'About RPCBroker'; Str := 'RPCBroker Version is '+RpcbiBroker.BrokerVersion; frmErrMsg.mmoErrorMessage.Lines.Add(Str); ShowApplicationAndFocusOK(Application); frmErrMsg.ShowModal; finally frmErrMsg.Free; end; end else inherited; end; end.
unit GmCfgMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ScktComp, GMGlobals, WinSock, StdCtrls, ExtCtrls, IniFiles, GMSocket, GMConst, GeomerLastValue, Threads.GMSocket; const WM_NCAR_FOUND = WM_USER + 1; WM_NCAR_DELETED = WM_USER + 2; WM_LOG_UPDATED = WM_USER + 3; type TCfgGeomerSocket = class (TGeomerSocket) private procedure WrapAndSend485Command(buf: array of byte; cnt: int); function MakeGM485Buf_OneRequest(var buf: array of Byte; bufSrc: array of byte; nCnt, Id485: int): int; protected procedure SetNCar(const Value: int); override; procedure slChanged(Sender: TObject); function DecodeGMDataBlock(buf: array of byte; cnt: int): int; override; procedure BuildReqList; override; public slProtocol: TStringList; constructor Create(Socket: TSocket; ServerWinSocket: TServerWinSocket; glvBuffer: TGeomerLastValuesBuffer); destructor Destroy; override; end; TGMCfgMainFrm = class(TForm) ssGM: TServerSocket; lCars: TListBox; Panel1: TPanel; mLog: TMemo; Panel2: TPanel; Button1: TButton; eFilename: TEdit; Button2: TButton; odProgram: TOpenDialog; eStrForSend: TEdit; Panel3: TPanel; Button3: TButton; Button4: TButton; eBlock: TEdit; Button5: TButton; btUBZ: TButton; Button6: TButton; procedure ssGMClientError(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer); procedure ssGMAccept(Sender: TObject; Socket: TCustomWinSocket); procedure ssGMClientConnect(Sender: TObject; Socket: TCustomWinSocket); procedure ssGMClientRead(Sender: TObject; Socket: TCustomWinSocket); procedure lCarsClick(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure ssGMClientDisconnect(Sender: TObject; Socket: TCustomWinSocket); procedure ssGMThreadEnd(Sender: TObject; Thread: TServerClientThread); procedure FormShow(Sender: TObject); procedure Button5Click(Sender: TObject); procedure eStrForSendKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure btUBZClick(Sender: TObject); procedure ssGMGetSocket(Sender: TObject; Socket: NativeInt; var ClientSocket: TServerClientWinSocket); procedure Button6Click(Sender: TObject); procedure ssGMGetThread(Sender: TObject; ClientSocket: TServerClientWinSocket; var SocketThread: TServerClientThread); private { Private declarations } LastWriteVer: WORD; glvBuffer: TGeomerLastValuesBuffer; procedure WMNCarFound(var Msg: TMessage); message WM_NCAR_FOUND; procedure WMNCarDeleted(var Msg: TMessage); message WM_NCAR_DELETED; procedure WMLogUpdated(var Msg: TMessage); message WM_LOG_UPDATED; procedure ReadINI; procedure SendTextToSocket(Name: string; Sckt: TCfgGeomerSocket; txt: string); public { Public declarations } end; var GMCfgMainFrm: TGMCfgMainFrm; implementation {$R *.dfm} procedure TGMCfgMainFrm.ssGMClientError(Sender: TObject; Socket: TCustomWinSocket; ErrorEvent: TErrorEvent; var ErrorCode: Integer); begin ErrorCode:=0; Socket.Close(); end; procedure WriteLnString(const s: string; bForceRewrite: bool = false); var f: TextFile; begin AssignFile(f, 'CfgLog.log'); if bForceRewrite or not FileExists('CfgLog.log') then Rewrite(f) else Append(f); Writeln(f, FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz ', Now()) + s); CloseFile(f); end; procedure TGMCfgMainFrm.ssGMGetSocket(Sender: TObject; Socket: NativeInt; var ClientSocket: TServerClientWinSocket); var //opt: integer; buf: array[0..100] of byte; s: string; begin ClientSocket:=TCfgGeomerSocket.Create(Socket, Sender as TServerWinSocket, glvBuffer); try TCfgGeomerSocket(ClientSocket).slProtocol.Add('Host - ' + ClientSocket.RemoteHost); except TCfgGeomerSocket(ClientSocket).slProtocol.Add('Host - ?'); end; try TCfgGeomerSocket(ClientSocket).slProtocol.Add('Address - ' + ClientSocket.RemoteAddress); except TCfgGeomerSocket(ClientSocket).slProtocol.Add('Address - ?'); end; // установим на всякий случай время, вдруг спутники не нашел s:=#13#10'TIME:'+FormatDateTime('ddmmyy,hhnnss', NowUTC())+#13#10; WriteString(buf, 0, s); ClientSocket.SendBuf(buf, Length(s)); WriteLnString('Get Socket'); { Sleep(1000); s:=#13#10'INFO:1'#13#10; WriteString(buf, 0, s); ClientSocket.SendBuf(buf, Length(s));} end; procedure TGMCfgMainFrm.ssGMGetThread(Sender: TObject; ClientSocket: TServerClientWinSocket; var SocketThread: TServerClientThread); begin SocketThread := TGMSocketThread.Create(false, ClientSocket); end; { TCfgGeomerSocket } procedure TCfgGeomerSocket.BuildReqList; begin // Do nothing end; constructor TCfgGeomerSocket.Create(Socket: TSocket; ServerWinSocket: TServerWinSocket; glvBuffer: TGeomerLastValuesBuffer); begin inherited Create(Socket, ServerWinSocket, glvBuffer); slProtocol:=TStringList.Create(); slProtocol.OnChange:=slChanged; end; destructor TCfgGeomerSocket.Destroy; begin PostMessage(Application.MainForm.Handle, WM_NCAR_DELETED, WParam(self), 0); slProtocol.Free(); inherited; end; function TCfgGeomerSocket.MakeGM485Buf_OneRequest(var buf: array of Byte; bufSrc: array of byte; nCnt: int; Id485: int): int; begin Result := WriteString(buf, 0, #13#10'RS485:P'); // заголовок пакетной передачи Result := WriteByte(buf, Result, 1); // к-во запросов Result := WriteByte(buf, Result, Id485); // ID первого запроса Result := WriteByte(buf, Result, nCnt and $FF); // длина первого запроса // ... ID и длины остальных запросов ... Result := WriteBuf(buf, Result, bufSrc, nCnt); // первый запрос // ... остальные запросы ... Result := WriteString(buf, Result, #13#10); end; procedure TCfgGeomerSocket.WrapAndSend485Command(buf: array of byte; cnt: int); var nPos: int; bufSend: array [0..100] of byte; begin if FSocketObjectType = OBJ_TYPE_GM then begin nPos := MakeGM485Buf_OneRequest(bufSend, buf, cnt, 0); SendBuf(bufSend, nPos); end else begin SendBuf(buf, cnt); end; end; function TCfgGeomerSocket.DecodeGMDataBlock(buf: array of byte; cnt: int): int; var i, j, n, c485: int; s: string; f: TFileStream; bufFLK: array[0..37] of Byte; begin WriteLnString('DecodeGMDataBlock cnt = ' + IntToStr(cnt)); if (cnt>=37) and (buf[0]=$55) and (buf[1]=$FF) then begin WriteLnString('DecodeGMDataBlock.FLK'); Result:=37; FSocketObjectType := OBJ_TYPE_GM; try f:=TFileStream.Create(ChangeFileExt(GMCfgMainFrm.eFilename.Text, '.flk'), fmOpenRead); n:=f.Read(bufFLK, 38); s:='Нехватка блоков: '; if n=38 then begin for i:=0 to 31 do for j:=0 to 7 do begin if (buf[i+5] and (1 shl j)=0) and (bufFlk[i+2] and (1 shl j)>0) then begin s:=s+IntToStr(i*8+j)+', '; end; end; slProtocol.Add(s); end; except end; TryFreeAndNil(f); end else if CheckGMWithUBZBlock(buf, cnt, Result) then begin // длинный блок c УБЗ WriteLnString('DecodeGMDataBlock.длинный блок c УБЗ'); FSocketObjectType := OBJ_TYPE_GM; N_Car:=ReadWord(buf, 2); end else if (cnt>=90) and (buf[0]=$55) and (buf[1]=$19) then begin // длинный блок c ISCO WriteLnString('DecodeGMDataBlock.длинный блок c ISCO'); Result:=90; FSocketObjectType := OBJ_TYPE_GM; N_Car:=ReadWord(buf, 2); end else if (cnt>=46) and (buf[0]=$55) and (buf[1]=$18) then begin // длинный блок WriteLnString('DecodeGMDataBlock.длинный блок'); Result:=46; FSocketObjectType := OBJ_TYPE_GM; N_Car:=ReadWord(buf, 2); end else if (cnt>=24) and (buf[0]=$55) and (buf[1]=$17) then begin // короткий блок WriteLnString('DecodeGMDataBlock.короткий блок'); Result:=24; FSocketObjectType := OBJ_TYPE_GM; N_Car:=ReadWord(buf, 2); end else if (cnt>=4) and (buf[0]=$55) and (buf[1]=$85) then begin //485 WriteLnString('DecodeGMDataBlock.485'); c485:=buf[3]; FSocketObjectType := OBJ_TYPE_GM; Result:=c485+4; end else // INFO:1 if (cnt>=123) and (buf[0]=$55) and (buf[1]=1) then begin WriteLnString('DecodeGMDataBlock.INFO:1'); N_Car:=ReadWORD(buf, 108); FSocketObjectType := OBJ_TYPE_GM; Result:=123; end else if (cnt>=27) and (buf[0]=$55) and (buf[1]=0) then begin WriteLnString('DecodeGMDataBlock.X3'); Result:=27; FSocketObjectType := OBJ_TYPE_GM; s:=''; for i:=2 to 9 do s:=s+Chr(buf[i]); s:=s+' '; for i:=11 to 26 do s:=s+Chr(buf[i]); slProtocol.Add(s); WriteLnString('DecodeGMDataBlock.Done'); Exit; end else begin WriteLnString('DecodeGMDataBlock.Unrecognized'); Result:=cnt; end; WriteLnString('DecodeGMDataBlock.ToProtocol'); slProtocol.Add(ArrayToString(buf, Result, true)); WriteLnString('DecodeGMDataBlock.Done'); end; procedure TCfgGeomerSocket.SetNCar(const Value: int); begin inherited SetNCar(Value); if Value >= 0 then PostMessage(Application.MainForm.Handle, WM_NCAR_FOUND, WParam(self), N_Car); end; procedure TGMCfgMainFrm.ssGMAccept(Sender: TObject; Socket: TCustomWinSocket); begin //opt:=1; //SetSockOpt(Socket.SocketHandle,SOL_SOCKET,SO_KEEPALIVE,PChar(@opt),SizeOf(opt)); // установим на всякий случай время, вдруг спутники не нашел end; procedure TGMCfgMainFrm.ssGMClientConnect(Sender: TObject; Socket: TCustomWinSocket); begin Socket.OnErrorEvent:=ssGMClientError; end; procedure TGMCfgMainFrm.ssGMClientRead(Sender: TObject; Socket: TCustomWinSocket); var Sckt: TCfgGeomerSocket; cnt: int; buf: array [0..102400] of byte; iProcessed: int; begin WriteLnString('ssGMClientRead'); Sckt:=TCfgGeomerSocket(Socket); cnt:=Sckt.ReceiveBuf(buf, High(Buf)); WriteLnString(ArrayToString(buf, cnt)); if cnt > 0 then try repeat iProcessed := Sckt.DecodeGMDataBlock(buf, cnt); if (iProcessed=0) or (iProcessed>cnt) then break; CopyMemory(@buf, @buf[iProcessed], cnt-iProcessed); cnt:=cnt-iProcessed; until (cnt<=0) or (iProcessed<=0); except on e: Exception do begin WriteLnString('Sckt.DecodeGMDataBlock ' + e.Message); end; end; WriteLnString('ssGMClientRead Done'); end; procedure TGMCfgMainFrm.WMNCarFound(var Msg: TMessage); var i: int; begin WriteLnString('WMNCarFound'); for i:=lCars.Count-1 downto 0 do begin if lCars.Items.Objects[i]=TObject(Msg.WParam) then Exit else if lCars.Items[i]=IntToStr(Msg.LParam) then lCars.Items.Delete(i); end; lCars.Items.AddObject(IntToStr(Msg.LParam), TObject(Msg.WParam)); WriteLnString('WMNCarFound Done'); end; procedure TGMCfgMainFrm.lCarsClick(Sender: TObject); begin try mLog.Lines.BeginUpdate(); mLog.Lines.Assign(TCfgGeomerSocket(lCars.Items.Objects[lCars.ItemIndex]).slProtocol); finally mLog.Lines.EndUpdate(); end; end; procedure TGMCfgMainFrm.Button2Click(Sender: TObject); begin if odProgram.Execute() then eFilename.Text:=odProgram.FileName; end; procedure TGMCfgMainFrm.Button1Click(Sender: TObject); var Sckt: TCfgGeomerSocket; fs: TFileStream; nPos, cnt, nBlock: int; buf, bufSend: array [0..600] of byte; begin if lCars.ItemIndex<0 then Exit; Sckt:=TCfgGeomerSocket(lCars.Items.Objects[lCars.ItemIndex]); if not Sckt.Connected then begin ShowMessageBox('Not connected', MB_ICONERROR); Exit; end; if not FileExists(eFilename.Text) then begin ShowMessageBox('File Not Found', MB_ICONERROR); Exit; end; lCars.Enabled:=false; fs:=TFileStream.Create(eFilename.Text, fmOpenRead); try repeat cnt:=fs.Read(buf, 520); if cnt<>520 then break; nBlock:=ReadWORD(buf, 0); LastWriteVer:=ReadWORD(buf, 2); nPos:=0; nPos:=WriteString(bufSend, nPos, #13#10'ROM:'); nPos:=WriteBuf(bufSend, nPos, buf, 520); if (Trim(eBlock.Text)='') or (nBlock=StrToInt(eBlock.Text)) then begin Sckt.slProtocol.Add('ROM '+IntToStr(nBlock)); Sckt.SendBuf(bufSend, nPos); Sleep(1000); end; Application.ProcessMessages(); until false; // теперь печать TryFreeAndNil(fs); fs:=TFileStream.Create(ChangeFileExt(eFilename.Text, '.flk'), fmOpenRead); fs.Read(buf, 38); TryFreeAndNil(fs); nPos:=WriteString(bufSend, 0, #13#10'ROM KEY:'); nPos:=WriteBuf(bufSend, nPos, buf, 38); Sckt.SendBuf(bufSend, nPos); finally lCars.Enabled:=true; if fs<>nil then TryFreeAndNil(fs); eBlock.Text := ''; end; end; procedure TGMCfgMainFrm.WMNCarDeleted(var Msg: TMessage); var i: int; begin for i:=0 to lCars.Count-1 do if lCars.Items.Objects[i]=TObject(Msg.WParam) then begin lCars.Items.Delete(i); Exit; end; end; procedure TCfgGeomerSocket.slChanged(Sender: TObject); begin SendMessage(Application.MainForm.Handle, WM_LOG_UPDATED, WParam(self), 0); end; procedure TGMCfgMainFrm.WMLogUpdated(var Msg: TMessage); var i: int; begin WriteLnString('WMLogUpdated'); if (lCars.ItemIndex>=0) and (lCars.Items.Objects[lCars.ItemIndex]=TObject(Msg.WParam)) then begin for i:=mLog.Lines.Count to TCfgGeomerSocket(Msg.WParam).slProtocol.Count-1 do mLog.Lines.Add(TCfgGeomerSocket(Msg.WParam).slProtocol[i]); end; WriteLnString('WMLogUpdated Done'); end; procedure TGMCfgMainFrm.SendTextToSocket(Name: string; Sckt: TCfgGeomerSocket; txt: string); var bufSend: array [0..600] of byte; nPos: int; begin if not Sckt.Connected then begin ShowMessageBox(Name+' Not connected', MB_ICONERROR); Exit; end; txt := StringReplace(txt, '|', #13, [rfReplaceAll]); nPos := WriteString(bufSend, 0, #13#10+txt+#13#10); Sckt.SendBuf(bufSend, nPos); end; procedure TGMCfgMainFrm.Button3Click(Sender: TObject); begin if lCars.ItemIndex<0 then Exit; SendTextToSocket( lCars.Items[lCars.ItemIndex], TCfgGeomerSocket(lCars.Items.Objects[lCars.ItemIndex]), eStrForSend.Text); end; procedure TGMCfgMainFrm.Button5Click(Sender: TObject); var i: int; begin for i:=0 to lCars.Count-1 do SendTextToSocket( lCars.Items[i], TCfgGeomerSocket(lCars.Items.Objects[i]), eStrForSend.Text); end; procedure TGMCfgMainFrm.Button6Click(Sender: TObject); var buf: ArrayOfByte; begin if lCars.ItemIndex<0 then Exit; buf := TextNumbersStringToArray(eStrForSend.Text); TCfgGeomerSocket(lCars.Items.Objects[lCars.ItemIndex]).WrapAndSend485Command(buf, Length(buf)); end; procedure TGMCfgMainFrm.Button4Click(Sender: TObject); var bufSend: array [0..600] of byte; nPos: int; Sckt: TCfgGeomerSocket; begin if lCars.ItemIndex<0 then Exit; Sckt:=TCfgGeomerSocket(lCars.Items.Objects[lCars.ItemIndex]); if not Sckt.Connected then begin ShowMessageBox('Not connected', MB_ICONERROR); Exit; end; nPos:=WriteString(bufSend, 0, #13#10'ROM TEST:'); nPos:=WriteWORD(bufSend, nPos, {LastWriteVer}78); Sckt.SendBuf(bufSend, nPos); end; procedure TGMCfgMainFrm.FormClose(Sender: TObject; var Action: TCloseAction); begin ssGM.Active:=false; end; procedure TGMCfgMainFrm.FormCreate(Sender: TObject); begin LastWriteVer:=0; glvBuffer := TGeomerLastValuesBuffer.Create(); lstSockets := TSocketList.Create(ssGM.Socket); end; procedure TGMCfgMainFrm.ssGMClientDisconnect(Sender: TObject; Socket: TCustomWinSocket); begin PostMessage(Application.MainForm.Handle, WM_NCAR_DELETED, WPARAM(Socket), 0); end; procedure TGMCfgMainFrm.ssGMThreadEnd(Sender: TObject; Thread: TServerClientThread); begin PostMessage(Application.MainForm.Handle, WM_NCAR_DELETED, WPARAM(nil), 0); end; procedure TGMCfgMainFrm.ReadINI(); var f: TINIFile; s, fn: string; nPort, c: int; begin f:=nil; fn:=ExpandFileName('GMIOSrv.ini'); nPort:=0; try if not FileExists(fn) then begin end else try f:=TIniFile.Create(fn); nPort:=f.ReadInteger('COMMON', 'PORT', 0); finally TryFreeAndNil(f); end; except on e: Exception do begin end; end; repeat if nPort=0 then begin s:='65500'; repeat if not InputQuery('Порт', Application.Title, s) then begin Application.Terminate; Exit; end; Val(s, nPort, c); until (c<=0) and (nPort>0); end; try ssGM.Port:=nPort; ssGM.Open(); except on e: exception do begin nPort:=0; ShowMessageBox(e.Message, MB_ICONSTOP); end; end; until ssGM.Active; end; procedure TGMCfgMainFrm.FormShow(Sender: TObject); begin ReadINI(); WriteLnString('CfgStart', true); end; procedure TGMCfgMainFrm.eStrForSendKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then Button3Click(Button3); end; procedure TGMCfgMainFrm.btUBZClick(Sender: TObject); var Num, Addr, Cmd, n: int; s: string; begin s := Trim(eStrForSend.Text); n := Pos(' ', s); if n <= 0 then Exit; Num := StrToInt(Trim(Copy(s, 1, n))); Delete(s, 1, n); n := Pos(' ', s); if n <= 0 then Exit; Addr := StrToInt(Trim(Copy(s, 1, n))); Delete(s, 1, n); if Trim(s) = '' then Exit; Cmd := StrToInt(Trim(Copy(s, 1, n))); Delete(s, 1, n); // !!!!!! TCfgGeomerSocket(lCars.Items.Objects[lCars.ItemIndex]).SendCommandToUBZ(Num, Addr, Cmd); raise Exception.CreateFmt('Not supported ! %d, %d, %d', [Num, Addr, Cmd]); end; end.
unit mGMV_EditTemplate; { ================================================================================ * * Application: Vitals * Revision: $Revision: 1 $ $Modtime: 3/05/09 10:31a $ * Developer: doma.user@domain.ext * Site: Hines OIFO * * Description: Frame used to edit/save vitals templates * * Notes: Used on the Vitals User and Manager application * ================================================================================ * $Archive: /Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/VITALSCOMMON/mGMV_EditTemplate.pas $ * * $History: mGMV_EditTemplate.pas $ * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 8/12/09 Time: 8:29a * Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/VITALSCOMMON * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 3/09/09 Time: 3:38p * Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_6/Source/VITALSCOMMON * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 1/13/09 Time: 1:26p * Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_4/Source/VITALSCOMMON * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 5/14/07 Time: 10:29a * Created in $/Vitals GUI 2007/Vitals-5-0-18/VITALSCOMMON * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 5/16/06 Time: 5:43p * Created in $/Vitals/VITALS-5-0-18/VitalsCommon * GUI v. 5.0.18 updates the default vital type IENs with the local * values. * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 5/16/06 Time: 5:33p * Created in $/Vitals/Vitals-5-0-18/VITALS-5-0-18/VitalsCommon * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 5/24/05 Time: 3:33p * Created in $/Vitals/Vitals GUI v 5.0.2.1 -5.0.3.1 - Patch GMVR-5-7 (CASMed, No CCOW) - Delphi 6/VitalsCommon * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 4/16/04 Time: 4:18p * Created in $/Vitals/Vitals GUI Version 5.0.3 (CCOW, CPRS, Delphi 7)/VITALSCOMMON * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 1/26/04 Time: 1:06p * Created in $/Vitals/Vitals GUI Version 5.0.3 (CCOW, Delphi7)/V5031-D7/Common * * ***************** Version 1 ***************** * User: Zzzzzzandria Date: 10/29/03 Time: 4:14p * Created in $/Vitals503/Common * Version 5.0.3 * * ***************** Version 11 ***************** * User: Zzzzzzandria Date: 5/02/03 Time: 9:33a * Updated in $/Vitals GUI Version 5.0/Common * Sentillion CCOW Immersion updates * * ***************** Version 10 ***************** * User: Zzzzzzandria Date: 11/04/02 Time: 9:15a * Updated in $/Vitals GUI Version 5.0/Common * Version 5.0.0.0 * * ***************** Version 9 ***************** * User: Zzzzzzandria Date: 10/04/02 Time: 4:50p * Updated in $/Vitals GUI Version 5.0/Common * Version T32 * * ***************** Version 8 ***************** * User: Zzzzzzandria Date: 9/06/02 Time: 3:58p * Updated in $/Vitals GUI Version 5.0/Common * Version T31 * * ***************** Version 7 ***************** * User: Zzzzzzandria Date: 7/12/02 Time: 5:01p * Updated in $/Vitals GUI Version 5.0/Common * GUI Version T28 * * ***************** Version 6 ***************** * User: Zzzzzzandria Date: 6/13/02 Time: 5:14p * Updated in $/Vitals GUI Version 5.0/Common * * ***************** Version 5 ***************** * User: Zzzzzzandria Date: 6/11/02 Time: 4:47p * Updated in $/Vitals GUI Version 5.0/Common * * ***************** Version 4 ***************** * User: Zzzzzzpetitd Date: 6/06/02 Time: 11:08a * Updated in $/Vitals GUI Version 5.0/Common * Roll-up to 5.0.0.27 * * ***************** Version 3 ***************** * User: Zzzzzzpetitd Date: 4/26/02 Time: 11:31a * Updated in $/Vitals GUI Version 5.0/Common * * ***************** Version 2 ***************** * User: Zzzzzzpetitd Date: 4/15/02 Time: 12:16p * Updated in $/Vitals GUI Version 5.0/Common * * ***************** Version 1 ***************** * User: Zzzzzzpetitd Date: 4/04/02 Time: 4:01p * Created in $/Vitals GUI Version 5.0/Common * * * ================================================================================ } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Buttons, StdCtrls, ExtCtrls, ComCtrls, CheckLst, uGMV_Common, fGMV_AddVCQ , uGMV_QualifyBox , uGMV_Template , ActnList, ImgList, System.Actions, System.ImageList; type TfraGMV_EditTemplate = class(TFrame) pnlQualifiers: TPanel; pnlVitals: TPanel; rgMetric: TRadioGroup; Splitter1: TSplitter; pnlHeader: TPanel; pnlNameDescription: TPanel; edtTemplateDescription: TEdit; Label2: TLabel; Label1: TLabel; edtTemplateName: TEdit; pnlListView: TPanel; ActionList1: TActionList; acUp: TAction; acDown: TAction; acAdd: TAction; acDelete: TAction; Panel1: TPanel; Panel3: TPanel; lblVitals: TLabel; Panel5: TPanel; ImageList1: TImageList; Panel7: TPanel; pnlDefaults: TPanel; Panel8: TPanel; lblQualifiers: TLabel; pnlDefaultQualifiers: TPanel; Panel2: TPanel; SpeedButton1: TSpeedButton; SpeedButton2: TSpeedButton; SpeedButton3: TSpeedButton; SpeedButton4: TSpeedButton; gb: TGroupBox; Panel4: TPanel; lvVitals: TListView; procedure QBCheck(Sender: TObject); procedure lvVitalsSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure pnlQualifiersResize(Sender: TObject); procedure rgMetricClick(Sender: TObject); procedure pnlListViewResize(Sender: TObject); procedure ChangeMade(Sender: TObject); procedure edtTemplateNameKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure acUpExecute(Sender: TObject); procedure acDownExecute(Sender: TObject); procedure acAddExecute(Sender: TObject); procedure acDeleteExecute(Sender: TObject); procedure edtTemplateNameEnter(Sender: TObject); procedure edtTemplateNameExit(Sender: TObject); procedure edtTemplateDescriptionEnter(Sender: TObject); procedure edtTemplateDescriptionExit(Sender: TObject); procedure lvVitalsExit(Sender: TObject); procedure lvVitalsEnter(Sender: TObject); procedure rgMetricEnter(Sender: TObject); procedure rgMetricExit(Sender: TObject); procedure gbDefaultEnter(Sender: TObject); procedure gbDefaultExit(Sender: TObject); private fQualBoxes: TList; fEditTemplate: TGMV_Template; fIgnore:Boolean; fChangingOrder: Boolean; fChangesMade: Boolean; fQCanvas: TWinControl; procedure AddVital(Vital: TGMV_TemplateVital); procedure ClearAllQualBoxes(Keep:Boolean=False); procedure LoadQualifiers(VitalIEN: string); function GetEditTemplate: TGMV_Template; procedure SetEditTemplate(const Value: TGMV_Template); procedure getTemplate(Selected:Boolean;aCaption:String;aTemplate:TGMV_TemplateVital); procedure btnMoveUp; procedure btnMoveDown; procedure btnAddVital; procedure btnDeleteVital; procedure WMDestroy(var Msg: TWMDestroy); message WM_DESTROY; Procedure CleanUp; Procedure ClearList(); public procedure SaveTemplate; procedure SaveTemplateIfChanged; published property EditTemplate: TGMV_Template read GetEditTemplate write SetEditTemplate; property ChangesMade: Boolean read FChangesMade; end; implementation uses uGMV_GlobalVars, uGMV_Const, uGMV_FileEntry , uGMV_Engine, mGMV_DefaultSelector, System.UITypes; {$R *.DFM} //AAN 06/11/02------------------------------------------------------------Begin function MetricCaption(sVitalName:String;bVitalMetric:Boolean):String; begin if pos(UpperCase(sVitalName),upperCase(MetricList)) <> 0 then result :=BOOLEANUM[bVitalMetric] else result := 'N/A'; end; //AAN 06/11/02--------------------------------------------------------------End procedure TfraGMV_EditTemplate.AddVital(Vital: TGMV_TemplateVital); begin try with lvVitals.Items.Add do begin Caption := Vital.VitalName; SubItems.Add(MetricCaption(Caption,Vital.Metric));//AAN 06/11/02 try SubItems.Add(Vital.DisplayQualifiers); Data := Vital; except Data := nil; end; end; except end; end; procedure TfraGMV_EditTemplate.ClearAllQualBoxes(Keep:Boolean=False); var pnlQB: TPanel; begin if fQualBoxes <> nil then while fQualBoxes.Count > 0 do begin pnlQB := TPanel(fQualBoxes[0]); fQualBoxes.Delete(0); FreeAndNil(pnlQB); end else fQualBoxes := TList.Create; rgMetric.ItemIndex := -1; end; procedure TfraGMV_EditTemplate.QBCheck(Sender: TObject); var i, j: integer; s, defQuals: string; defQualsText: string; begin for i := 0 to FQualBoxes.Count - 1 do with TGMV_TemplateQualifierBox(FQualBoxes[i]) do begin s := DefaultQualifierIEN; if StrToIntDef(s, -1) > 0 then begin j := GMVQuals.IndexOfIEN(DefaultQualifierIEN); if j > -1 then begin if defQuals <> '' then defQuals := defQuals + '~'; if defQualsText <> '' then defQualsText := defQualsText + ','; defQuals := defQuals + CategoryIEN + ',' + DefaultQualifierIEN; defQualsText := defQualsText + GMVQuals.Entries[GMVQuals.IndexOfIEN(DefaultQualifierIEN)]; end; end end; TGMV_TemplateVital(lvVitals.Selected.Data).Qualifiers := defQuals; lvVitals.Selected.SubItems[1] := TGMV_TemplateVital(lvVitals.Selected.Data).DisplayQualifiers; FChangesMade := True; GetParentForm(Self).Perform(CM_TEMPLATEUPDATED, 0, 0) //AAN 06/11/02 end; function TfraGMV_EditTemplate.GetEditTemplate: TGMV_Template; begin Result := FEditTemplate; end; procedure TfraGMV_EditTemplate.SaveTemplate; var x: string; i: integer; begin {Is it renamed?} if edtTemplateName.Text <> FEditTemplate.TemplateName then if not FEditTemplate.Rename(edtTemplateName.Text) then begin MessageDlg('Sorry, ' + edtTemplateName.Text + ' is not a valid template name.', mtError, [mbok], 0); edtTemplateName.Text := FEditTemplate.TemplateName; Exit; end; x := edtTemplateDescription.Text + '|'; for i := 0 to lvVitals.Items.Count - 1 do with TGMV_TemplateVital(lvVitals.Items[i].Data) do begin if i > 0 then x := x + ';'; x := x + IEN + ':' + IntToStr(BOOLEAN01[Metric]); if Qualifiers <> '' then x := x + ':' + Qualifiers; end; FEditTemplate.XPARValue := x; FChangesMade := False; GetParentForm(Self).Perform(CM_TEMPLATEREFRESHED, 0, 0) //AAN 06/11/02 end; procedure TfraGMV_EditTemplate.pnlQualifiersResize(Sender: TObject); var i: integer; begin Exit; if FQualBoxes <> nil then for i := 0 to FQualBoxes.Count - 1 do TGMV_TemplateQualifierBox(FQualBoxes[i]).Width := (pnlQualifiers.Width div FQualBoxes.Count); end; procedure TfraGMV_EditTemplate.btnMoveUp; var tmpItem: TGMV_TemplateVital; i: integer; begin lvVitals.Items.BeginUpdate; FChangingOrder := True; FChangesMade := True; GetParentForm(Self).Perform(CM_TEMPLATEUPDATED, 0, 0); //AAN 06/11/02 if lvVitals.Selected.Index > 0 then begin i := lvVitals.Items.IndexOf(lvVitals.Selected); tmpItem := lvVitals.Items[i].Data; lvVitals.Items[i].Data := lvVitals.Items[i - 1].Data; lvVitals.Items[i - 1].Data := tmpItem; with TGMV_TemplateVital(lvVitals.Items[i].Data) do begin lvVitals.Items[i].Caption := VitalName; lvVitals.Items[i].SubItems[1] := DisplayQualifiers; lvVitals.Items[i].SubItems[0] := MetricCaption( //AAN 06/11/02 VitalName, //AAN 06/11/02 Metric); //AAN 06/11/02 end; with TGMV_TemplateVital(lvVitals.Items[i - 1].Data) do begin lvVitals.Items[i - 1].Caption := VitalName; lvVitals.Items[i - 1].SubItems[1] := DisplayQualifiers; lvVitals.Items[i - 1].SubItems[0] := MetricCaption( //AAN 06/11/02 VitalName, //AAN 06/11/02 Metric); //AAN 06/11/02 end; lvVitals.Items[i].Selected := False; lvVitals.Items[i - 1].Selected := True; lvVitals.UpdateItems(i - 1, i); lvVitals.ItemFocused := lvVitals.Items[i - 1]; end; FChangingOrder := False; lvVitals.Items.EndUpdate; end; procedure TfraGMV_EditTemplate.btnMoveDown; var tmpItem: TGMV_TemplateVital; i: integer; begin lvVitals.Items.BeginUpdate; FChangingOrder := True; FChangesMade := True; GetParentForm(Self).Perform(CM_TEMPLATEUPDATED, 0, 0); //AAN 06/11/02 if lvVitals.Selected.Index < lvVitals.Items.Count - 1 then begin i := lvVitals.Items.IndexOf(lvVitals.Selected); tmpItem := lvVitals.Items[i].Data; lvVitals.Items[i].Data := lvVitals.Items[i + 1].Data; lvVitals.Items[i + 1].Data := tmpItem; with TGMV_TemplateVital(lvVitals.Items[i].Data) do begin lvVitals.Items[i].Caption := VitalName; lvVitals.Items[i].SubItems[1] := DisplayQualifiers; lvVitals.Items[i].SubItems[0] := MetricCaption( //AAN 06/11/02 VitalName, //AAN 06/11/02 Metric); //AAN 06/11/02 end; with TGMV_TemplateVital(lvVitals.Items[i + 1].Data) do begin lvVitals.Items[i + 1].Caption := VitalName; lvVitals.Items[i + 1].SubItems[1] := DisplayQualifiers; lvVitals.Items[i + 1].SubItems[0] := MetricCaption( //AAN 06/11/02 VitalName, //AAN 06/11/02 Metric); //AAN 06/11/02 end; lvVitals.Items[i].Selected := False; lvVitals.Items[i + 1].Selected := True; lvVitals.UpdateItems(i, i + 1); lvVitals.ItemFocused := lvVitals.Items[i + 1]; end; FChangingOrder := False; lvVitals.Items.EndUpdate; end; procedure TfraGMV_EditTemplate.btnAddVital; var i: integer; begin with TfrmGMV_AddVCQ.Create(Self) do try LoadVitals; ShowModal; if ModalResult = mrOk then for i := 0 to lbxVitals.Items.Count - 1 do if lbxVitals.Selected[i] then AddVital(TGMV_TemplateVital.CreateFromXPAR( TGMV_FileEntry(lbxVitals.Items.Objects[i]).IEN + ':' + lbxVitals.Items[i] + '::') ); FChangesMade := True; GetParentForm(Self).Perform(CM_TEMPLATEUPDATED, 0, 0) //AAN 06/11/02 finally free; end; end; procedure TfraGMV_EditTemplate.btnDeleteVital; var i: integer; begin i := lvVitals.Items.IndexOf(lvVitals.Selected); {Where are we now} if lvVitals.Selected <> nil then begin FChangesMade := True; GetParentForm(Self).Perform(CM_TEMPLATEUPDATED, 0, 0); //AAN 06/11/02 if lvVitals.Selected.Data <> nil then TGMV_TemplateVital(lvVitals.Selected.Data).Free; lvVitals.Selected.Delete; if i > lvVitals.Items.Count - 1 then i := lvVitals.Items.Count - 1; {Deleted last one, get new last item} if i > -1 then lvVitals.Items[i].Selected := True; end; end; procedure TfraGMV_EditTemplate.rgMetricClick(Sender: TObject); begin if lvVitals.Selected <> nil then begin FChangesMade := True; GetParentForm(Self).Perform(CM_TEMPLATEUPDATED, 0, 0); //AAN 06/11/02 //AAN 06/11/02 lvVitals.Selected.SubItems[0] := rgMetric.Items[rgMetric.ItemIndex]; TGMV_TemplateVital(lvVitals.Selected.Data).Metric := (rgMetric.ItemIndex = 1); lvVitals.Selected.SubItems[0] := MetricCaption( //AAN 06/11/02 TGMV_TemplateVital(lvVitals.Selected.Data).VitalName, //AAN 06/11/02 TGMV_TemplateVital(lvVitals.Selected.Data).Metric); //AAN 06/11/02 end; end; procedure TfraGMV_EditTemplate.pnlListViewResize(Sender: TObject); begin lvVitals.Width := pnlListView.Width - (lvVitals.Left * 2); lvVitals.Height := pnlListView.Height - (lvVitals.Top * 2); end; procedure TfraGMV_EditTemplate.ChangeMade(Sender: TObject); begin FChangesMade := True; GetParentForm(Self).Perform(CM_TEMPLATEUPDATED, 0, 0) //AAN 06/11/02 end; //AAN 06/11/02 ---------------------------------------------------------- Begin procedure TfraGMV_EditTemplate.edtTemplateNameKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key <> VK_Escape then ChangeMade(Sender); end; procedure TfraGMV_EditTemplate.SaveTemplateIfChanged; begin if FChangesMade then if MessageDlg('The template <' + FEditTemplate.TemplateName + '> has been changed.'+ #13#10+ 'Save changes?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then SaveTemplate; end; //AAN 06/11/02 ------------------------------------------------------------ End procedure TfraGMV_EditTemplate.acUpExecute(Sender: TObject); begin btnMoveUp; end; procedure TfraGMV_EditTemplate.acDownExecute(Sender: TObject); begin btnMoveDown; end; procedure TfraGMV_EditTemplate.acAddExecute(Sender: TObject); begin btnAddVital; end; procedure TfraGMV_EditTemplate.acDeleteExecute(Sender: TObject); begin if MessageDlg('Are you sure you want to delete'+#13+ '<'+lvVitals.Selected.Caption+'>?' , mtConfirmation, [mbYes, mbNo], 0) = mrYes then btnDeleteVital; end; procedure TfraGMV_EditTemplate.edtTemplateNameEnter(Sender: TObject); begin label1.Font.Style := [fsBold]; end; procedure TfraGMV_EditTemplate.edtTemplateNameExit(Sender: TObject); begin label1.Font.Style := []; end; procedure TfraGMV_EditTemplate.edtTemplateDescriptionEnter( Sender: TObject); begin label2.Font.Style := [fsBold]; end; procedure TfraGMV_EditTemplate.edtTemplateDescriptionExit(Sender: TObject); begin label2.Font.Style := []; end; procedure TfraGMV_EditTemplate.lvVitalsExit(Sender: TObject); begin lblVitals.Font.Style := []; end; procedure TfraGMV_EditTemplate.lvVitalsEnter(Sender: TObject); begin lblVitals.Font.Style := [fsBold]; end; procedure TfraGMV_EditTemplate.gbDefaultEnter(Sender: TObject); begin gb.Font.Style := [fsBold]; end; procedure TfraGMV_EditTemplate.gbDefaultExit(Sender: TObject); begin gb.Font.Style := []; end; procedure TfraGMV_EditTemplate.rgMetricExit(Sender: TObject); begin rgMetric.Font.Style := []; end; procedure TfraGMV_EditTemplate.rgMetricEnter(Sender: TObject); var i: Integer; begin rgMetric.font.Style := [fsBold]; for i := 0 to rgMetric.ControlCount - 1 do if rgMetric.Controls[i] is TRadioButton then TRadioButton(rgMetric.Controls[i]).Font.Style := []; end; procedure TfraGMV_EditTemplate.LoadQualifiers(VitalIEN: string); var iOrder, i: integer; retList: TStrings; function AddQualifierBox(QBVitalIEN: string; QBCatIEN: string; DefaultQualIEN: string = ''): TGMV_TemplateQualifierBox; begin if FQualBoxes = nil then FQualBoxes := TList.Create; Result := TGMV_TemplateQualifierBox.CreateParented(Self,fQCanvas, QBVitalIEN, QBCatIEN, DefaultQualIEN); // zzzzzzandria 20090219 Result.OnClick := QBCheck; Result.Visible := True; Result.setDDWidth; FQualBoxes.Add(Result); end; begin fQCanvas := gb; lblQualifiers.Caption := 'Default Qualifiers: (Loading...)'; Application.ProcessMessages; ClearAllQualBoxes; Application.ProcessMessages; RetList := getCategoryQualifiers(VitalIEN); for i := RetList.Count - 1 downto 1 do AddQualifierBox(VitalIEN, Piece(RetList[i], '^', 1)); RetList.Free; for i := 0 to fQCanvas.ControlCount - 1 do if fQCanvas.Controls[i] is tGMV_TemplateQualifierBox then begin iOrder := fQCanvas.ControlCount - 1 - i; TGMV_TemplateQualifierBox(fQCanvas.Controls[i]).TabOrder := iOrder; end; lblQualifiers.Caption := 'Default Qualifiers:'; if not FChangesMade then //AAN 06/12/02 GetParentForm(Self).Perform(CM_TEMPLATEREFRESHED, 0, 0) //AAN 06/11/02 end; procedure TfraGMV_EditTemplate.getTemplate(Selected:Boolean;aCaption:String;aTemplate:TGMV_TemplateVital); var CatIEN: string; QualIEN: string; i, j: integer; bTmp: Boolean; //AAN 06/12/02 begin lvVitals.Enabled := False; if not fChangingOrder then if Selected then begin lblQualifiers.Caption := aCaption + ' Default Qualifiers'; with aTemplate do begin LoadQualifiers(IEN); i := 1; while Piece(Qualifiers, '~', i) <> '' do begin CatIEN := Piece(Piece(Qualifiers, '~', i), ',', 1); QualIEN := Piece(Piece(Qualifiers, '~', i), ',', 2); for j := 0 to fQualBoxes.Count - 1 do with TGMV_TemplateQualifierBox(fQualBoxes[j]) do begin if CategoryIEN = CatIEN then DefaultQualifierIEN := QualIEN; OnQualExit(nil); end; inc(i); end; bTmp := FChangesMade; //AAN 06/12/02 rgMetric.ItemIndex := BOOLEAN01[Metric]; rgMetric.Enabled := True; fChangesMade := bTmp; //AAN 06/12/02 end; end else ClearAllQualBoxes; acUp.Enabled := Selected; acDown.Enabled := Selected; acDelete.Enabled := Selected; rgMetric.Enabled := Selected; //AAN 06/11/02 -----------------------------------------------------------Begin try rgMetric.Enabled := (pos(aTemplate.VitalName,MetricList) <> 0); except end; if not fChangesMade then GetParentForm(Self).Perform(CM_TEMPLATEREFRESHED, 0, 0); //AAN 06/11/02 //AAN 06/11/02 -------------------------------------------------------------End try lvVitals.Enabled := True; lvVitals.SetFocus; except end; end; procedure TfraGMV_EditTemplate.SetEditTemplate(const Value: TGMV_Template); var XPAR: string; i: integer; begin if FChangesMade then if MessageDlg('Save template ' + FEditTemplate.TemplateName + '?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then SaveTemplate; ClearAllQualBoxes; fIgnore := True; ClearList; fIgnore := False; rgMetric.ItemIndex := -1; rgMetric.Enabled := False; acUp.Enabled := False; acDown.Enabled := False; acDelete.Enabled := False; if Value <> nil then begin fEditTemplate := Value; fChangingOrder := False; XPAR := FEditTemplate.XPARValue; edtTemplateName.Text := FEditTemplate.TemplateName; edtTemplateDescription.Text := Piece(XPAR, '|', 1); XPAR := Piece(XPAR, '|', 2); i := 1; while Piece(XPAR, ';', i) <> '' do begin AddVital(TGMV_TemplateVital.CreateFromXPAR(Piece(XPAR, ';', i))); inc(i); end; if lvVitals.Items.Count > 0 then lvVitals.Items[0].Selected := True; // results in call to reload end else begin edtTemplateName.Text := ''; edtTemplateDescription.Text := ''; end; Enabled := (Value <> nil); fChangesMade := False; GetParentForm(Self).Perform(CM_TEMPLATEREFRESHED, 0, 0); //AAN 06/11/02 end; procedure TfraGMV_EditTemplate.lvVitalsSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); begin if fIgnore then exit else fIgnore := True; getTemplate(Selected,Item.Caption,TGMV_TemplateVital(Item.Data)); fIgnore := False; end; procedure TfraGMV_EditTemplate.WMDestroy(var Msg: TWMDestroy); begin if (csDestroying in ComponentState) then CleanUp; inherited; end; Procedure TfraGMV_EditTemplate.CleanUp; begin ClearList; ClearAllQualBoxes; FreeandNil(fQualBoxes); end; Procedure TfraGMV_EditTemplate.ClearList(); Var I: integer; begin for I := 0 to lvVitals.Items.Count - 1 do begin if Assigned(lvVitals.Items[i].Data) then TGMV_TemplateVital(lvVitals.Items[i].Data).Free; end; lvVitals.Items.Clear; end; end.
{ *************************************************************************** } { } { Kylix and Delphi Cross-Platform Visual Component Library } { } { Copyright (c) 1997, 2001 Borland Software Corporation } { } { *************************************************************************** } unit SyncObjs; {$H+,X+} interface uses {$IFDEF MSWINDOWS} Windows, Messages, {$ENDIF} {$IFDEF LINUX} Libc, {$ENDIF} SysUtils, Classes; type {$IFNDEF MSWINDOWS} PSecurityAttributes = pointer; {$ENDIF} TSynchroObject = class(TObject) public procedure Acquire; virtual; procedure Release; virtual; end; THandleObject = class(TSynchroObject) {$IFDEF MSWINDOWS} private FHandle: THandle; FLastError: Integer; public destructor Destroy; override; property LastError: Integer read FLastError; property Handle: THandle read FHandle; {$ENDIF} end; TWaitResult = (wrSignaled, wrTimeout, wrAbandoned, wrError); TEvent = class(THandleObject) {$IFDEF LINUX} private FEvent: TSemaphore; {$ENDIF} public constructor Create(EventAttributes: PSecurityAttributes; ManualReset, InitialState: Boolean; const Name: string); function WaitFor(Timeout: LongWord): TWaitResult; procedure SetEvent; procedure ResetEvent; end; TSimpleEvent = class(TEvent) public constructor Create; end; TCriticalSection = class(TSynchroObject) protected FSection: TRTLCriticalSection; public constructor Create; destructor Destroy; override; procedure Acquire; override; procedure Release; override; procedure Enter; procedure Leave; end; implementation { TSynchroObject } procedure TSynchroObject.Acquire; begin end; procedure TSynchroObject.Release; begin end; { THandleObject } {$IFDEF MSWINDOWS} destructor THandleObject.Destroy; begin CloseHandle(FHandle); inherited Destroy; end; {$ENDIF} { TEvent } constructor TEvent.Create(EventAttributes: PSecurityAttributes; ManualReset, InitialState: Boolean; const Name: string); {$IFDEF MSWINDOWS} begin FHandle := CreateEvent(EventAttributes, ManualReset, InitialState, PChar(Name)); end; {$ENDIF} {$IFDEF LINUX} var Value: Integer; begin if InitialState then Value := 1 else Value := 0; sem_init(FEvent, False, Value); end; {$ENDIF} function TEvent.WaitFor(Timeout: LongWord): TWaitResult; begin {$IFDEF MSWINDOWS} case WaitForSingleObject(Handle, Timeout) of WAIT_ABANDONED: Result := wrAbandoned; WAIT_OBJECT_0: Result := wrSignaled; WAIT_TIMEOUT: Result := wrTimeout; WAIT_FAILED: begin Result := wrError; FLastError := GetLastError; end; else Result := wrError; end; {$ENDIF} {$IFDEF LINUX} if Timeout = LongWord($FFFFFFFF) then begin sem_wait(FEvent); Result := wrSignaled; end else Result := wrError; {$ENDIF} end; procedure TEvent.SetEvent; {$IFDEF MSWINDOWS} begin Windows.SetEvent(Handle); end; {$ENDIF} {$IFDEF LINUX} var I: Integer; begin sem_getvalue(FEvent, I); if I = 0 then sem_post(FEvent); end; {$ENDIF} procedure TEvent.ResetEvent; begin {$IFDEF MSWINDOWS} Windows.ResetEvent(Handle); {$ENDIF} {$IFDEF LINUX} // All events on Linux are auto-reset {$ENDIF} end; { TSimpleEvent } constructor TSimpleEvent.Create; begin inherited Create(nil, True, False, ''); end; { TCriticalSection } constructor TCriticalSection.Create; begin inherited Create; InitializeCriticalSection(FSection); end; destructor TCriticalSection.Destroy; begin DeleteCriticalSection(FSection); inherited Destroy; end; procedure TCriticalSection.Acquire; begin EnterCriticalSection(FSection); end; procedure TCriticalSection.Release; begin LeaveCriticalSection(FSection); end; procedure TCriticalSection.Enter; begin Acquire; end; procedure TCriticalSection.Leave; begin Release; end; end.
{******************************************************************************} { } { CBVCLStylePreviewForm: Example Preview of a VCL Style } { based on: VCLStylePreview Vcl.Styles.Ext } { https://github.com/RRUZ/vcl-styles-utils/ } { } { Copyright (c) 2020 (Ethea S.r.l.) } { Author: Carlo Barazzetta } { } { https://github.com/EtheaDev/VCLThemeSelector } { } {******************************************************************************} { } { 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 CBVCLStylePreviewForm; {$Include VCLThemeSelector.inc} interface Uses System.Classes, System.Sysutils, System.Generics.Collections, System.Types, Winapi.Windows, Vcl.Styles, Vcl.Themes, Vcl.Forms, vcl.Menus, Vcl.Graphics, Vcl.Controls, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls; const PREVIEW_HEIGHT = 190; //At 96 DPI PREVIEW_WIDTH = 300; //At 96 DPI type TCBVCLPreviewForm = class(TForm) MainMenu: TMainMenu; FMenu1: TMenuItem; FMenu2: TMenuItem; FMenu3: TMenuItem; FMenu4: TMenuItem; TabControl: TTabControl; FNormalTextEdit: TEdit; FButtonNormal: TButton; FButtonDisabled: TButton; FRequiredTextEdit: TEdit; FReadOnlyTextEdit: TEdit; CheckBox: TCheckBox; procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FButtonNormalMouseEnter(Sender: TObject); procedure FButtonNormalMouseLeave(Sender: TObject); procedure FButtonNormalMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FButtonNormalMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); private FButtonNormalCaption: string; FButtonHotCaption: string; FButtonPressedCaption: string; FCustomStyle: TCustomStyleServices; { Private declarations } public procedure SetCaptions(const ACaptions: string); property CustomStyle: TCustomStyleServices read FCustomStyle Write FCustomStyle; end; implementation {$R *.dfm} { TCBVCLPreviewForm } procedure TCBVCLPreviewForm.FButtonNormalMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin FButtonNormal.Caption := FButtonPressedCaption; end; procedure TCBVCLPreviewForm.FButtonNormalMouseEnter(Sender: TObject); begin FButtonNormal.Caption := FButtonHotCaption; end; procedure TCBVCLPreviewForm.FButtonNormalMouseLeave(Sender: TObject); begin FButtonNormal.Caption := FButtonNormalCaption; end; procedure TCBVCLPreviewForm.FButtonNormalMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin FButtonNormal.Caption := FButtonHotCaption; end; procedure TCBVCLPreviewForm.FormCreate(Sender: TObject); begin ; end; procedure TCBVCLPreviewForm.FormShow(Sender: TObject); begin Self.StyleName := FCustomStyle.Name; Visible := True; end; procedure TCBVCLPreviewForm.SetCaptions(const ACaptions: string); var LCaptions: TStringList; begin LCaptions := TStringList.Create; LCaptions.Text := ACaptions; try if LCaptions.Count > 0 then //File FMenu1.Caption := LCaptions.Strings[0]; if LCaptions.Count > 1 then //Edit FMenu2.Caption := LCaptions.Strings[1]; if LCaptions.Count > 2 then //View FMenu3.Caption := LCaptions.Strings[2]; if LCaptions.Count > 3 then //Help FMenu4.Caption := LCaptions.Strings[3]; if LCaptions.Count > 4 then //Text editor FNormalTextEdit.Text := LCaptions.Strings[4]; if LCaptions.Count > 5 then //Normal begin FButtonNormalCaption := LCaptions.Strings[5]; FButtonNormal.Caption := FButtonNormalCaption; end; if LCaptions.Count > 6 then //Hot FButtonHotCaption := LCaptions.Strings[6]; if LCaptions.Count > 7 then //Pressed FButtonPressedCaption := LCaptions.Strings[7]; if LCaptions.Count > 8 then //Disabled FButtonDisabled.Caption := LCaptions.Strings[8]; if LCaptions.Count > 9 then //Required FRequiredTextEdit.Text := LCaptions.Strings[9]; if LCaptions.Count > 10 then //Readonly FReadOnlyTextEdit.Text := LCaptions.Strings[10]; if LCaptions.Count > 11 then //Check CheckBox.Caption := LCaptions.Strings[11]; if LCaptions.Count > 12 then //Page 1 Tabcontrol.Tabs[0] := LCaptions.Strings[12]; if LCaptions.Count > 13 then //Page 2 Tabcontrol.Tabs[1] := LCaptions.Strings[13]; if LCaptions.Count > 14 then //Page 3 Tabcontrol.Tabs[2] := LCaptions.Strings[14]; finally LCaptions.Free; end; end; end.
unit SettingsController; interface uses Settings, SettingsView; type TSettingsController = class private FModel: ISettings; FView: ISettingsView; procedure OnViewCloseQuery(Sender: TObject; var CanClose: Boolean); public constructor Create(const Model: ISettings; const View: ISettingsView); destructor Destroy; override; procedure ShowSettings; end; implementation { TSettingsController } constructor TSettingsController.Create(const Model: ISettings; const View: ISettingsView); begin FModel:= Model; FView:= View; FView.ShowSettings(FModel); FView.SetOnCloseQueryEvent(OnViewCloseQuery); end; destructor TSettingsController.Destroy; begin FView.SetOnCloseQueryEvent(nil); inherited; end; procedure TSettingsController.OnViewCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose:= true; try FModel.SetDotMarkerColor(FView.GetDotMarkerColor); FModel.SetDotMarkerStrokeWidth(FView.GetDotMarkerStrokeWidth); FModel.SetDotMarkerStrokeLength(FView.GetDotMarkerStrokeLength); FModel.SetSavepathRelativeTo(TSavepathRelativeTo(FView.GetSavePathRelativeTo)); FModel.SetSavePathForMarkers(FView.GetSavePathMarkers); FModel.SetSavePathForMasks(FView.GetSavePathMasks); except CanClose:= false; end; end; procedure TSettingsController.ShowSettings; begin FView.ShowModal; end; end.
unit IdThreadMgr; interface uses Classes, IdException, IdBaseComponent, IdThread, SyncObjs; type TIdThreadMgr = class(TIdBaseComponent) protected FActiveThreads: TList; FLock: TCriticalSection; FThreadClass: TIdThreadClass; public constructor Create(AOwner: TComponent); override; function CreateNewThread: TIdThread; virtual; destructor Destroy; override; function GetThread: TIdThread; virtual; abstract; procedure ReleaseThread(AThread: TIdThread); virtual; abstract; procedure TerminateThreads(Threads: TList); property ActiveThreads: TList read FActiveThreads; property Lock: TCriticalSection read FLock; property ThreadClass: TIdThreadClass read FThreadClass write FThreadClass; end; EIdThreadMgrError = class(EIdException); EIdThreadClassNotSpecified = class(EIdThreadMgrError); implementation uses IdGlobal, IdResourceStrings, IdTCPServer, SysUtils; constructor TIdThreadMgr.Create(AOwner: TComponent); begin inherited; FActiveThreads := TList.Create; FLock := TCriticalSection.Create; end; function TIdThreadMgr.CreateNewThread: TIdThread; begin if ThreadClass = nil then begin raise EIdThreadClassNotSpecified.create(RSThreadClassNotSpecified); end; result := TIdThreadClass(ThreadClass).Create; end; destructor TIdThreadMgr.Destroy; begin FreeAndNil(FActiveThreads); FreeAndNil(FLock); inherited; end; procedure TIdThreadMgr.TerminateThreads(Threads: TList); var Thread: TIdThread; i: integer; begin for i := Threads.Count - 1 downto 0 do begin Thread := TObject(Threads[i]) as TIdThread; if Thread is TIdPeerThread then begin TIdPeerThread(Thread).Connection.Disconnect; end; ReleaseThread(Thread); Threads.Delete(i); end; end; end.
unit uCommon; interface function FileSizeToStr(Size: UInt64): String; implementation uses System.SysUtils; function FileSizeToStr(Size: UInt64): String; const SIZE_KB = 1024; SIZE_MB = 1024*SIZE_KB; SIZE_GB = 1024*SIZE_MB; begin if Size > SIZE_GB then Result := FormatFloat('#.## GB', Size/SIZE_GB) else if Size > SIZE_MB then Result := FormatFloat('#.## MB', Size/SIZE_MB) else if Size > SIZE_KB then Result := FormatFloat('#.## KB', Size/SIZE_KB) else result := FormatFloat('#.## B', Size); end; end.
unit UcaFuncionario2; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ComCtrls, IBDatabase, DB, IBCustomDataSet, IBStoredProc, ExtCtrls, Mask, DBCtrls, RxToolEdit, RxCurrEdit, RxDBCurrEdit, RxLookup, IdBaseComponent, IdComponent, IdCustomTCPServer, IdMappedPortTCP, Spin; type TcaFuncionario2 = class(TForm) b1: TBitBtn; b2: TBitBtn; barra: TStatusBar; Panel1: TPanel; PageControl: TPageControl; TabSheet1: TTabSheet; edNome: TEdit; Label2: TLabel; Label8: TLabel; edEmail: TEdit; Label16: TLabel; edCodigo: TEdit; Label1: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label10: TLabel; Label11: TLabel; Label9: TLabel; Label12: TLabel; Label22: TLabel; Label23: TLabel; edEndereco: TEdit; edNumero: TEdit; edBairro: TEdit; cbCidade: TDBLookupComboBox; edCPF: TMaskEdit; edTelefone: TMaskEdit; edCelular: TMaskEdit; dtNascimento: TDateEdit; dtCadastro: TDateEdit; rgSexo: TRadioGroup; edCTPS: TEdit; edPIS: TEdit; procedure fundo; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure b2Click(Sender: TObject); procedure FormKeyPress(Sender: TObject; var Key: Char); procedure edCodigoEnter(Sender: TObject); procedure FormShow(Sender: TObject); procedure edNomeEnter(Sender: TObject); procedure edCPFEnter(Sender: TObject); procedure b1Click(Sender: TObject); procedure edNumeroEnter(Sender: TObject); procedure edBairroEnter(Sender: TObject); procedure cbCidadeEnter(Sender: TObject); procedure edEmailEnter(Sender: TObject); procedure e9Enter(Sender: TObject); procedure edTelefoneEnter(Sender: TObject); procedure edCelularEnter(Sender: TObject); procedure dtCadastroEnter(Sender: TObject); procedure e13Enter(Sender: TObject); private { Private declarations } public { Public declarations } end; var caFuncionario2: TcaFuncionario2; implementation uses UGlobal, Udm, UcaFuncionario, Udm2; {$R *.dfm} procedure TcaFuncionario2.fundo; var Mf: integer; begin // Atualizando for Mf := 0 to componentcount -1 do begin if (components[Mf].ClassName = 'TEdit') then begin TEdit(Components[Mf]).color := clwhite; TEdit(Components[Mf]).font.color := clblack; end // else if (components[Mf].ClassName = 'TCurrencyEdit') then begin TCurrencyEdit(Components[Mf]).color := clwhite; TCurrencyEdit(Components[Mf]).font.color := clblack; end // else if (components[Mf].ClassName = 'TDateEdit') then begin TDateEdit(Components[Mf]).color := clwhite; TDateEdit(Components[Mf]).font.color := clblack; end else if (components[Mf].ClassName = 'TDBLookupComboBox') then begin TDBLookupComboBox(Components[Mf]).color := clwhite; TDBLookupComboBox(Components[Mf]).font.color := clblack; end else if (components[Mf].ClassName = 'TComboBox') then begin TComboBox(Components[Mf]).color := clwhite; TComboBox(Components[Mf]).font.color := clblack; end else if (components[Mf].ClassName = 'TMaskEdit') then begin TMaskEdit(Components[Mf]).color := clwhite; TMaskEdit(Components[Mf]).font.color := clblack; end // else if (components[Mf].ClassName = 'TDBEdit') then begin TDBEdit(Components[Mf]).color := clwhite; TDBEdit(Components[Mf]).font.color := clblack; end; end; { pintando } for Mf := 0 to ComponentCount -1 do begin if components[Mf].ClassName = 'TEdit' then begin if TEDit(components[mf]).focused then begin TEdit(Components[Mf]).color := clSkyBlue; TEdit(Components[Mf]).font.color := clblack; end end { else if components[Mf].ClassName = 'TCurrencyEdit' then begin if TCurrencyEdit(components[mf]).focused then begin TCurrencyEdit(Components[Mf]).color := clSkyBlue; TCurrencyEdit(Components[Mf]).font.color := clblack; end end else if components[Mf].ClassName = 'TDateEdit' then begin if TDateEdit(components[mf]).focused then begin TDateEdit(Components[Mf]).color := clSkyBlue; TDateEdit(Components[Mf]).font.color := clblack; end end } else if components[Mf].ClassName = 'TDBLookupComboBox' then begin if TDBLookupComboBox(components[mf]).focused then begin TDBLookupComboBox(Components[Mf]).color := clSkyBlue; TDBLookupComboBox(Components[Mf]).font.color := clblack; end end { else if components[Mf].ClassName = 'TComboBox' then begin if TComboBox(components[mf]).focused then begin TComboBox(Components[Mf]).color := clSkyBlue; TComboBox(Components[Mf]).font.color := clblack; end end } else if components[Mf].ClassName = 'TMaskEdit' then begin if TMaskEdit(components[mf]).focused then begin TMaskEdit(Components[Mf]).color := clSkyBlue; TMaskEdit(Components[Mf]).font.color := clblack; end end { else if components[Mf].ClassName = 'TDBEdit' then begin if TDBEdit(components[mf]).focused then begin TDBEdit(Components[Mf]).color := clSkyBlue; TDBEdit(Components[Mf]).font.color := clblack; end end; } end; end; procedure TcaFuncionario2.FormClose(Sender: TObject; var Action: TCloseAction); begin dm2.cdsCidade.Close; CaFuncionario2 := nil; action := cafree; end; procedure TcaFuncionario2.b2Click(Sender: TObject); begin close; end; procedure TcaFuncionario2.FormKeyPress(Sender: TObject; var Key: Char); begin if key = #27 then close else if key = #13 then begin key := #0; if edCelular.focused then begin b1.click end else perform(wm_nextdlgctl,0,0); end; end; procedure TcaFuncionario2.edCodigoEnter(Sender: TObject); begin edNome.SetFocus; end; procedure TcaFuncionario2.FormShow(Sender: TObject); begin dm2.cdsCidade.Close; dm2.cdsCidade.Open; PageControl.TabIndex := 0; edNome.SetFocus; end; procedure TcaFuncionario2.edNomeEnter(Sender: TObject); begin fundo; end; procedure TcaFuncionario2.edCPFEnter(Sender: TObject); begin fundo; end; procedure TcaFuncionario2.b1Click(Sender: TObject); begin if (trim(edNome.text) = '') then begin som; informe('CAMPO OBRIGATÓRIO'); edNome.setfocus; exit; end; if (trim(edCPF.text) = '') then begin som; informe('CAMPO OBRIGATÓRIO'); edCPF.setfocus; exit; end; if (dtNascimento.Date = 0) then begin som; informe('CAMPO OBRIGATÓRIO'); dtNascimento.setfocus; exit; end; if (trim(cbCidade.text) = '') then begin som; informe('CAMPO OBRIGATÓRIO'); cbCidade.setfocus; exit; end; {} if edCodigo.Text= 'Novo' then begin if Application.messageBox('CONFIRMA INCLUSÃO?','Confirmação',mb_iconquestion + mb_YesNo) = idYes then begin //verificando se já existe com o mesmo nome dm2.cdsTemp2.Close; dm2.SQLTemp2.Close; dm2.SQLTemp2.Params.Clear; dm2.SQLTemp2.SQL.Clear; dm2.SQLTemp2.SQL.Add('select funcod from funcionario where funnome = :var0 and ativo = ''S'''); dm2.SQLTemp2.Params[0].Value:=edNome.Text; dm2.cdsTemp2.Open; if dm2.cdsTemp2.RecordCount > 0 then begin if Application.messageBox('ATENÇÃO! JÁ EXISTE REGISTRO COM ESTE NOME, DESEJA CONTINUAR?','Confirmação',mb_iconquestion + mb_YesNo) <> idYes then exit; end; exibem; {generator} dm2.SQLFunc.Close; dm2.SQLFunc.Params.Clear; dm2.SQLFunc.SQL.Clear; sql := ''; sql := sql +' INSERT INTO FUNCIONARIO (FUNNOME, FUNCPF, FUNEND, FUNNUM, '; sql := sql +' FUNBAIRRO, CIDCOD, FUNEMAIL, FUNFONE, FUNCELULAR, FUNSEXO, FUNNASCIMENTO, '; sql := sql +' FUNDTCAD, ATIVO, FUNPIS, FUNCTPS )'; sql := sql +' VALUES (:FUNNOME, :FUNCPF, :FUNEND, :FUNNUM, '; sql := sql +' :FUNBAIRRO, :CIDCOD, :FUNEMAIL, :FUNFONE, :FUNCELULAR, :FUNSEXO, :FUNNASCIMENTO, '; sql := sql +' :FUNDTCAD, :ATIVO, :FUNPIS, :FUNCTPS) '; dm2.SQLFunc.SQL.Text := sql; dm2.SQLFunc.ParamByName('FUNNOME').AsString := edNome.Text; dm2.SQLFunc.ParamByName('FUNCPF').AsString := edCPF.Text; dm2.SQLFunc.ParamByName('FUNEND').AsString := edEndereco.Text; dm2.SQLFunc.ParamByName('FUNNUM').AsString := edNumero.Text; dm2.SQLFunc.ParamByName('FUNBAIRRO').AsString := edBairro.Text; dm2.SQLFunc.ParamByName('CIDCOD').AsInteger := cbCidade.KeyValue; dm2.SQLFunc.ParamByName('FUNEMAIL').AsString := edEmail.Text; dm2.SQLFunc.ParamByName('FUNFONE').AsString := edTelefone.Text; dm2.SQLFunc.ParamByName('FUNCELULAR').AsString := edCelular.Text; if rgSexo.ItemIndex = 0 then dm2.SQLFunc.ParamByName('FUNSEXO').AsString := 'M' else dm2.SQLFunc.ParamByName('FUNSEXO').AsString := 'F'; dm2.SQLFunc.ParamByName('FUNNASCIMENTO').AsDate := dtNascimento.Date; dm2.SQLFunc.ParamByName('FUNDTCAD').AsDate := dtCadastro.Date; dm2.SQLFunc.ParamByName('ATIVO').AsString := 'S'; dm2.SQLFunc.ParamByName('FUNPIS').AsString := edPIS.Text; dm2.SQLFunc.ParamByName('FUNCTPS').AsString := edCTPS.Text; try dm2.SQLFunc.ExecSQL(False); dm2.cdsFuncionario.Close; dm2.cdsFuncionario.Open; dm2.cdsFuncionario.Last; close; caFuncionario.b1.SetFocus; except on e: Exception do begin MessageDlg(e.Message, mterror, [mbOk],0); Abort; end; end; end; inherited; ocultam; end else begin if Application.messageBox('CONFIRMA ALTERAÇÃO?','Confirmação',mb_iconquestion + mb_YesNo) = idYes then begin exibem; dm2.SQLFunc.Close; dm2.SQLFunc.Params.Clear; dm2.SQLFunc.SQL.Clear; sql := ''; sql := sql +' UPDATE FUNCIONARIO '; sql := sql +' SET FUNTIPO = :FUNTIPO, '; sql := sql +' FUNNOME = :FUNNOME, '; sql := sql +' FUNCPF = :FUNCPF, '; sql := sql +' FUNEND = :FUNEND, '; sql := sql +' FUNNUM = :FUNNUM, '; sql := sql +' FUNBAIRRO = :FUNBAIRRO, '; sql := sql +' CIDCOD = :CIDCOD, '; sql := sql +' FUNEMAIL = :FUNEMAIL, '; sql := sql +' FUNFONE = :FUNFONE, '; sql := sql +' FUNCELULAR = :FUNCELULAR, '; sql := sql +' FUNSEXO = :FUNSEXO, '; sql := sql +' FUNNASCIMENTO = :FUNNASCIMENTO, '; sql := sql +' FUNDTCAD = :FUNDTCAD, '; sql := sql +' ATIVO = :ATIVO, '; sql := sql +' FUNPIS = :FUNPIS, '; sql := sql +' FUNCTPS = :FUNCTPS '; sql := sql +' WHERE FUNCOD = :FUNCOD '; dm2.SQLFunc.SQL.Text := sql; dm2.SQLFunc.ParamByName('FUNCOD').AsString := edCodigo.Text; dm2.SQLFunc.ParamByName('FUNNOME').AsString := edNome.Text; dm2.SQLFunc.ParamByName('FUNCPF').AsString := edCPF.Text; dm2.SQLFunc.ParamByName('FUNEND').AsString := edEndereco.Text; dm2.SQLFunc.ParamByName('FUNNUM').AsString := edNumero.Text; dm2.SQLFunc.ParamByName('FUNBAIRRO').AsString := edBairro.Text; dm2.SQLFunc.ParamByName('CIDCOD').AsInteger := cbCidade.KeyValue; dm2.SQLFunc.ParamByName('FUNEMAIL').AsString := edEmail.Text; dm2.SQLFunc.ParamByName('FUNFONE').AsString := edTelefone.Text; dm2.SQLFunc.ParamByName('FUNCELULAR').AsString := edCelular.Text; if rgSexo.ItemIndex = 0 then dm2.SQLFunc.ParamByName('FUNSEXO').AsString := 'M' else dm2.SQLFunc.ParamByName('FUNSEXO').AsString := 'F'; dm2.SQLFunc.ParamByName('FUNNASCIMENTO').AsDate := dtNascimento.Date; dm2.SQLFunc.ParamByName('FUNDTCAD').AsDate := dtCadastro.Date; dm2.SQLFunc.ParamByName('ATIVO').AsString := 'S'; dm2.SQLFunc.ParamByName('FUNPIS').AsString := edPIS.Text; dm2.SQLFunc.ParamByName('FUNCTPS').AsString := edCTPS.Text; try dm2.SQLFunc.ExecSQL(False); dm2.cdsFuncionario.Close; dm2.cdsFuncionario.Open; dm2.cdsFuncionario.locate('FUNCOD',edCodigo.text,[lopartialkey]); close; caFuncionario.b1.SetFocus; except on e: Exception do begin MessageDlg(e.Message, mterror, [mbOk],0); Abort; end; end; end; ocultam; end; end; procedure TcaFuncionario2.edNumeroEnter(Sender: TObject); begin fundo; end; procedure TcaFuncionario2.edBairroEnter(Sender: TObject); begin fundo; end; procedure TcaFuncionario2.cbCidadeEnter(Sender: TObject); begin fundo; end; procedure TcaFuncionario2.edEmailEnter(Sender: TObject); begin fundo; end; procedure TcaFuncionario2.e9Enter(Sender: TObject); begin fundo; end; procedure TcaFuncionario2.edTelefoneEnter(Sender: TObject); begin fundo; end; procedure TcaFuncionario2.edCelularEnter(Sender: TObject); begin fundo; end; procedure TcaFuncionario2.dtCadastroEnter(Sender: TObject); begin fundo; end; procedure TcaFuncionario2.e13Enter(Sender: TObject); begin fundo; end; end.
unit Text; interface uses {$IFDEF FPC} LResources, {$ENDIF} {$IFNDEF LINUX} Windows, Messages, {$ENDIF} Classes, SysUtils, DB, Graphics, Controls, Forms, Dialogs, DBCtrls, ExtCtrls, Grids, DBGrids, StdCtrls, ToolWin, ComCtrls, UniDacVcl, Buttons, {$IFNDEF FPC} MemDS, {$ELSE} MemDataSet, {$ENDIF} DBAccess, Uni, DemoFrame; type TTextFrame = class(TDemoFrame) DBGrid: TDBGrid; DataSource: TDataSource; ToolBar: TPanel; meComments: TDBMemo; Query: TUniQuery; Splitter1: TSplitter; ToolBar1: TPanel; OpenDialog: TOpenDialog; SaveDialog: TSaveDialog; Panel1: TPanel; Panel2: TPanel; Panel8: TPanel; btOpen: TSpeedButton; btClose: TSpeedButton; DBNavigator: TDBNavigator; btLoad: TSpeedButton; btSave: TSpeedButton; btClear: TSpeedButton; procedure btOpenClick(Sender: TObject); procedure btCloseClick(Sender: TObject); procedure btLoadClick(Sender: TObject); procedure btSaveClick(Sender: TObject); procedure btClearClick(Sender: TObject); procedure DataSourceStateChange(Sender: TObject); private { Private declarations } public procedure SetControlsState; // Demo management procedure Initialize; override; procedure SetDebug(Value: boolean); override; end; implementation {$IFNDEF FPC} {$IFDEF CLR} {$R *.nfm} {$ELSE} {$R *.dfm} {$ENDIF} {$ENDIF} procedure TTextFrame.SetControlsState; begin btLoad.Enabled := Query.Active; btSave.Enabled := Query.Active; btClear.Enabled := Query.Active; end; procedure TTextFrame.btOpenClick(Sender: TObject); begin Query.Open; end; procedure TTextFrame.btCloseClick(Sender: TObject); begin Query.Close; end; procedure TTextFrame.btLoadClick(Sender: TObject); begin if Query.Active and OpenDialog.Execute then begin if Query.State = dsBrowse then Query.Edit; TBlobField(Query.FieldByName('TextField')).LoadFromFile(OpenDialog.FileName); end; end; procedure TTextFrame.btSaveClick(Sender: TObject); begin if not Query.EOF and SaveDialog.Execute then TBlobField(Query.FieldByName('TextField')).SaveToFile(SaveDialog.FileName); end; procedure TTextFrame.btClearClick(Sender: TObject); begin if Query.Active then begin if Query.State = dsBrowse then Query.Edit; Query.FieldByName('TextField').Clear; end; end; procedure TTextFrame.DataSourceStateChange(Sender: TObject); begin inherited; SetControlsState; end; // Demo management procedure TTextFrame.Initialize; begin Query.Connection := Connection as TUniConnection; SetControlsState end; procedure TTextFrame.SetDebug(Value: boolean); begin Query.Debug := Value; end; {$IFDEF FPC} initialization {$i Text.lrs} {$ENDIF} end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { Copyright(c) 2014-2019 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit RSConsole.Wait; interface uses System.SysUtils, System.Types, System.UITypes, System.Rtti, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Objects, FMX.Controls.Presentation; type TWait = class(TForm) LabelStatus: TLabel; Image1: TImage; private class var FInstance: TWait; FWaitEnabled: Integer; class function Instance: TWait; static; class function WaitEnabled: Boolean; static; class constructor Create; public class procedure Start(const AMessage: string = ''); class procedure Done; end; implementation {$R *.fmx} class constructor TWait.Create; begin FWaitEnabled := -1; end; class function TWait.WaitEnabled: Boolean; begin if FWaitEnabled < 0 then {$WARNINGS OFF} if not FindCmdLineSwitch('nw') and (DebugHook = 0) then {$WARNINGS ON} FWaitEnabled := 1 else FWaitEnabled := 0; Result := FWaitEnabled = 1; end; // Simplistic Singleton/Lazyloader class procedure TWait.Done; begin if not WaitEnabled then Exit; if Assigned(FInstance) then begin FInstance.DisposeOf; FInstance := nil; end; end; class function TWait.Instance: TWait; begin if not Assigned(FInstance) then begin FInstance := TWait.Create(Application.MainForm); // center manually, as poOwnerFormCenter appears to be broken in XE4 FInstance.Top := Application.MainForm.Top + Trunc(Application.MainForm.Height / 2) - Trunc(FInstance.Height / 2); FInstance.Left := Application.MainForm.Left + Trunc(Application.MainForm.Width / 2) - Trunc(FInstance.Width / 2); end; Result := FInstance; end; class procedure TWait.Start(const AMessage: string = ''); begin if not WaitEnabled then Exit; if AMessage <> '' then Instance.LabelStatus.Text := AMessage; Instance.Show; Application.ProcessMessages; end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit System.Win.OleControls; interface uses System.Variants, System.Types, Winapi.Windows, Winapi.Messages, Winapi.ActiveX, System.SysUtils, System.Classes, System.UITypes, System.Win.ComObj; {$IFDEF CPUX64} {$DEFINE PUREPASCAL} {$ENDIF CPUX64} type TDelegatedOleControl = class; TEventDispatch = class(TObject, IUnknown, IDispatch) private FControl: TDelegatedOleControl; protected { IUnknown } function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; { IDispatch } /// <summary> /// Retrieves the number of type information interfaces that an object provides (either 0 or 1). /// </summary> function GetTypeInfoCount(out Count: Integer): HResult; stdcall; /// <summary> /// Retrieves the type information for an object, which can then be used to get the type information for an /// interface. /// </summary> function GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult; stdcall; /// <summary> /// Maps a single member and an optional set of argument names to a corresponding set of integer DISPIDs, which /// can be used on subsequent calls to Invoke /// </summary> function GetIDsOfNames(const IID: TGUID; Names: Pointer; NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; stdcall; /// <summary> /// Provides access to properties and methods exposed by an object. /// </summary> function Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; virtual; stdcall; /// <summary> /// Provide access to OLE control /// </summary> property Control: TDelegatedOleControl read FControl; public constructor Create(Control: TDelegatedOleControl); end; TArgKind = (akDWord, akSingle, akDouble); PEventArg = ^TEventArg; TEventArg = record Kind: TArgKind; Data: array[0..1] of Integer; end; TEventInfo = record Method: TMethod; Sender: TObject; ArgCount: Integer; Args: array[0..MaxDispArgs - 1] of TEventArg; end; PControlData = ^TControlData; TControlData = record ClassID: TGUID; EventIID: TGUID; EventCount: Longint; EventDispIDs: Pointer; LicenseKey: Pointer; Flags: DWORD; Version: Integer; FontCount: Integer; FontIDs: PDispIDList; PictureCount: Integer; PictureIDs: PDispIDList; Reserved: Integer; InstanceCount: Integer; EnumPropDescs: TList; end; PControlData2 = ^TControlData2; TControlData2 = record ClassID: TGUID; EventIID: TGUID; EventCount: Longint; EventDispIDs: Pointer; LicenseKey: Pointer; Flags: DWORD; Version: Integer; FontCount: Integer; FontIDs: PDispIDList; PictureCount: Integer; PictureIDs: PDispIDList; Reserved: Integer; InstanceCount: Integer; EnumPropDescs: TList; FirstEventOfs: Cardinal; end; /// <summary> /// Interface for OLE delegate. All controls that would work with OLE should support it /// </summary> IOLEFrameworkDelegate = interface ['{5240182A-FED7-41D3-B121-68E983247B1E}'] /// <summary> /// Set the procedure that invokes the default window procedure associated with this window. /// </summary> procedure SetDefWndProc(const AWndProc: Pointer); /// <summary> /// Get the procedure that invokes the default window procedure associated with this window. /// </summary> function GetDefWndProc: Pointer; /// <summary> /// Get the address of the procedure that invokes the default window procedure associated with this window. /// </summary> function InitWindowProc: Pointer; /// <summary> /// Set handle to the OLE Control /// </summary> procedure SetHandle(const AHandle: HWND); /// <summary> /// Get handle to the OLE control /// </summary> function GetHandle: HWND; /// <summary> /// Get handle to parent control /// </summary> function GetParentHandle: THandle; /// <summary> /// Get the bounds rect as set of integer values /// </summary> function GetBoundsRect: TRect; /// <summary> /// Get value of visibilities /// </summary> function GetVisible: Boolean; /// <summary> /// Set visibility /// </summary> procedure SetVisible(const AVisible: Boolean); /// <summary> /// Set OLE control as CreationControl for using in InitWndProc /// </summary> procedure SetCreationControl; /// <summary> /// Return the top parent handle for OLE control /// </summary> function GetTopParentHandle: HWND; property Visible: Boolean read GetVisible write SetVisible; property DefWndProc: Pointer read GetDefWndProc write SetDefWndProc; property Handle: HWND read GetHandle write SetHandle; /// <summary> /// Setting the method that would be used for dispatching /// </summary> procedure SetDispatcher(const ADisp: TEventDispatchInvoker); /// <summary> /// Get window handle /// </summary> function GetWindowHandle: HWND; /// <summary> /// Set window handle /// </summary> procedure SetWindowHandle(AValue: HWND); property WindowHandle: HWND read GetWindowHandle write SetWindowHandle; end; TServiceQuery = function(const rsid, iid: TGuid; out obj): HResult of object; TDelegatedOleControl = class(TComponent, IUnknown, IOleClientSite, IOleControlSite, IOleInPlaceSite, IOleInPlaceFrame, IDispatch, IPropertyNotifySink, ISimpleFrameSite, IServiceProvider) private FDelegate: IOLEFrameworkDelegate; FControlData: PControlData; FRefCount: Longint; FEventDispatch: TEventDispatch; FObjectData: HGlobal; FOleObject: IOleObject; FPersistStream: IPersistStreamInit; FOleControl: IOleControl; FControlDispatch: IDispatch; FPropBrowsing: IPerPropertyBrowsing; FOleInPlaceObject: IOleInPlaceObject; FOleInPlaceActiveObject: IOleInPlaceActiveObject; FPropConnection: Longint; FEventsConnection: Longint; FMiscStatus: Longint; FServiceQuery: TServiceQuery; FControlInfo: TControlInfo; procedure SetUIActive(Active: Boolean); function GetOleObject: Variant; procedure CreateControl; procedure DestroyControl; procedure DestroyStorage; procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND; procedure WMPaint(var Message: TWMPaint); message WM_PAINT; {IUnknown } protected function QueryInterface(const IID: TGUID; out Obj): HResult; override; private function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; {IOleControlSite} function OnControlInfoChanged: HResult; stdcall; function LockInPlaceActive(fLock: BOOL): HResult; stdcall; function GetExtendedControl(out disp: IDispatch): HResult; stdcall; function TransformCoords(var ptlHimetric: TPoint; var ptfContainer: TPointF; flags: Longint): HResult; stdcall; function IOleControlSite.TranslateAccelerator = OleControlSite_TranslateAccelerator; function OleControlSite_TranslateAccelerator(msg: PMsg; grfModifiers: Longint): HResult; stdcall; function OnFocus(fGotFocus: BOOL): HResult; stdcall; function ShowPropertyFrame: HResult; stdcall; {IDispatch} function GetTypeInfoCount(out Count: Integer): HResult; stdcall; function GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult; stdcall; function GetIDsOfNames(const IID: TGUID; Names: Pointer; NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; stdcall; function Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; stdcall; {IPropertyNotifySink} function OnChanged(dispid: TDispID): HResult; stdcall; function OnRequestEdit(dispid: TDispID): HResult; stdcall; {ISimpleFrameSite} function PreMessageFilter(wnd: HWnd; msg: UInt; wp: WPARAM; lp: LPARAM; out res: LRESULT; out Cookie: DWORD): HResult; stdcall; function PostMessageFilter(wnd: HWnd; msg: UInt; wp: WPARAM; lp: LPARAM; out res: LRESULT; Cookie: DWORD): HResult; stdcall; {IServiceProvider} function QueryService(const rsid, iid: TGuid; out Obj): HResult; stdcall; {IOleInPlaceUIWindow} function GetBorder(out rectBorder: TRect): HResult; stdcall; function RequestBorderSpace(const borderwidths: TRect): HResult; stdcall; function SetBorderSpace(pborderwidths: PRect): HResult; stdcall; function SetActiveObject(const activeObject: IOleInPlaceActiveObject; pszObjName: POleStr): HResult; stdcall; {IOleInPlaceFrame} function InsertMenus(hmenuShared: HMenu; var menuWidths: TOleMenuGroupWidths): HResult; stdcall; function SetMenu(hmenuShared: HMenu; holemenu: HMenu; hwndActiveObject: HWnd): HResult; stdcall; function RemoveMenus(hmenuShared: HMenu): HResult; stdcall; function SetStatusText(pszStatusText: POleStr): HResult; stdcall; function EnableModeless(fEnable: BOOL): HResult; stdcall; function IOleInPlaceFrame.TranslateAccelerator = OleInPlaceFrame_TranslateAccelerator; function OleInPlaceFrame_TranslateAccelerator(var msg: TMsg; wID: Word): HResult; stdcall; {IOleInPlaceSite} function CanInPlaceActivate: HResult; stdcall; function OnInPlaceActivate: HResult; stdcall; function OnUIActivate: HResult; stdcall; function GetWindowContext(out frame: IOleInPlaceFrame; out doc: IOleInPlaceUIWindow; out rcPosRect: TRect; out rcClipRect: TRect; out frameInfo: TOleInPlaceFrameInfo): HResult; stdcall; function Scroll(scrollExtent: TPoint): HResult; stdcall; function OnUIDeactivate(fUndoable: BOOL): HResult; stdcall; function OnInPlaceDeactivate: HResult; stdcall; function DiscardUndoState: HResult; stdcall; function DeactivateAndUndo: HResult; stdcall; function OnPosRectChange(const rcPosRect: TRect): HResult; stdcall; {IOleInPlaceSite, IOleWindow} function GetWindow(out wnd: HWnd): HResult; stdcall; function ContextSensitiveHelp(fEnterMode: BOOL): HResult; stdcall; {IOleClientSite} function SaveObject: HResult; stdcall; function GetMoniker(dwAssign: Longint; dwWhichMoniker: Longint; out mk: IMoniker): HResult; stdcall; function GetContainer(out container: IOleContainer): HResult; stdcall; function ShowObject: HResult; stdcall; function OnShowWindow(fShow: BOOL): HResult; stdcall; function RequestNewObjectLayout: HResult; stdcall; procedure HookControlWndProc; procedure FrameworksDispatcher(DispId: Integer; var Params: TOleVariantArray); procedure CreateInstance; protected procedure StandardEvent(DispID: TDispID; var Params: TDispParams); virtual; procedure InvokeEvent(DispID: TDispID; var Params: TDispParams); virtual; {$IFDEF CPUX86} procedure D2InvokeEvent(DispID: TDispID; var Params: TDispParams); {$ENDIF} procedure GetEventMethod(DispID: TDispID; var Method: TMethod); procedure InitControlInterface(const Obj: IUnknown); virtual; function GetByteProp(Index: Integer): Byte; function GetColorProp(Index: Integer): TColor; function GetTColorProp(Index: Integer): TColor; function GetCompProp(Index: Integer): Comp; function GetCurrencyProp(Index: Integer): Currency; function GetDoubleProp(Index: Integer): Double; function GetIDispatchProp(Index: Integer): IDispatch; function GetIntegerProp(Index: Integer): Integer; function GetIUnknownProp(Index: Integer): IUnknown; function GetWordBoolProp(Index: Integer): WordBool; function GetTDateTimeProp(Index: Integer): TDateTime; function GetOleBoolProp(Index: Integer): TOleBool; function GetOleDateProp(Index: Integer): TOleDate; function GetOleEnumProp(Index: Integer): TOleEnum; function GetTOleEnumProp(Index: Integer): TOleEnum; function GetOleVariantProp(Index: Integer): OleVariant; procedure GetProperty(Index: Integer; var Value: TVarData); function GetShortIntProp(Index: Integer): ShortInt; function GetSingleProp(Index: Integer): Single; function GetSmallintProp(Index: Integer): Smallint; function GetStringProp(Index: Integer): string; function GetVariantProp(Index: Integer): Variant; function GetWideStringProp(Index: Integer): WideString; function GetWordProp(Index: Integer): Word; procedure SetByteProp(Index: Integer; Value: Byte); procedure SetColorProp(Index: Integer; Value: TColor); procedure SetTColorProp(Index: Integer; Value: TColor); procedure SetCompProp(Index: Integer; const Value: Comp); procedure SetCurrencyProp(Index: Integer; const Value: Currency); procedure SetDoubleProp(Index: Integer; const Value: Double); procedure SetIDispatchProp(Index: Integer; const Value: IDispatch); procedure SetIntegerProp(Index: Integer; Value: Integer); procedure SetIUnknownProp(Index: Integer; const Value: IUnknown); procedure SetName(const Value: TComponentName); override; procedure SetWordBoolProp(Index: Integer; Value: WordBool); procedure SetTDateTimeProp(Index: Integer; const Value: TDateTime); procedure SetOleBoolProp(Index: Integer; Value: TOleBool); procedure SetOleDateProp(Index: Integer; const Value: TOleDate); procedure SetOleEnumProp(Index: Integer; Value: TOleEnum); procedure SetTOleEnumProp(Index: Integer; Value: TOleEnum); procedure SetOleVariantProp(Index: Integer; const Value: OleVariant); procedure SetProperty(Index: Integer; const Value: TVarData); procedure SetShortIntProp(Index: Integer; Value: Shortint); procedure SetSingleProp(Index: Integer; const Value: Single); procedure SetSmallintProp(Index: Integer; Value: Smallint); procedure SetStringProp(Index: Integer; const Value: string); procedure SetVariantProp(Index: Integer; const Value: Variant); procedure SetWideStringProp(Index: Integer; const Value: WideString); procedure SetWordProp(Index: Integer; Value: Word); procedure InitControlData; virtual; abstract; procedure CreateWnd; virtual; procedure DestroyWnd; virtual; abstract; procedure DestroyHandle; virtual; procedure DestroyWindowHandle; virtual; procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); virtual; public property ControlData: PControlData read FControlData write FControlData; property OleObject: Variant read GetOleObject; constructor Create(ADelegate: IOLEFrameworkDelegate); reintroduce; procedure DoObjectVerb(Verb: Integer); destructor Destroy; override; property MiscStatus: LongInt read FMiscStatus; end; function CreateOleVarArray(const Args: array of OleVariant): TOleVariantArray; implementation uses System.Win.ComConst; const // The following flags may be or'd into the TControlData.Reserved field to override // default behaviors. // cdForceSetClientSite: // Call SetClientSite early (in constructor) regardless of misc status flags cdForceSetClientSite = 1; // cdDeferSetClientSite: // Don't call SetClientSite early. Takes precedence over cdForceSetClientSite and misc status flags cdDeferSetClientSite = 2; function CreateOleVarArray(const Args: array of OleVariant): TOleVariantArray; var I: Integer; begin SetLength(Result, Length(Args)); for I :=0 to Length(Args) - 1 do Result[I] := Args[I]; end; { TDelegatedOleControl } function TDelegatedOleControl.GetOleBoolProp(Index: Integer): TOleBool; var Temp: TVarData; begin GetProperty(Index, Temp); Result := Temp.VBoolean; end; function TDelegatedOleControl.GetOleDateProp(Index: Integer): TOleDate; var Temp: TVarData; begin GetProperty(Index, Temp); Result := Temp.VDate; end; function TDelegatedOleControl.GetOleEnumProp(Index: Integer): TOleEnum; begin Result := GetIntegerProp(Index); end; function TDelegatedOleControl.GetOleObject: Variant; begin CreateControl; Result := Variant(FOleObject as IDispatch); end; function TDelegatedOleControl.GetOleVariantProp(Index: Integer): OleVariant; begin VarClear(Result); GetProperty(Index, TVarData(Result)); end; var // init to zero, never written to DispParams: TDispParams = (); procedure TDelegatedOleControl.GetProperty(Index: Integer; var Value: TVarData); var Status: HResult; ExcepInfo: TExcepInfo; begin CreateControl; Value.VType := varEmpty; Status := FControlDispatch.Invoke(Index, GUID_NULL, 0, DISPATCH_PROPERTYGET, DispParams, @Value, @ExcepInfo, nil); if Status <> 0 then DispatchInvokeError(Status, ExcepInfo); end; function TDelegatedOleControl.GetShortIntProp(Index: Integer): ShortInt; begin Result := GetIntegerProp(Index); end; function TDelegatedOleControl.GetSingleProp(Index: Integer): Single; var Temp: TVarData; begin GetProperty(Index, Temp); Result := Temp.VSingle; end; function TDelegatedOleControl.GetSmallintProp(Index: Integer): Smallint; var Temp: TVarData; begin GetProperty(Index, Temp); Result := Temp.VSmallint; end; function TDelegatedOleControl.GetStringProp(Index: Integer): string; begin Result := GetVariantProp(Index); end; function TDelegatedOleControl.GetTColorProp(Index: Integer): TColor; begin Result := GetIntegerProp(Index); end; function TDelegatedOleControl.GetTDateTimeProp(Index: Integer): TDateTime; var Temp: TVarData; begin GetProperty(Index, Temp); Result := Temp.VDate; end; function TDelegatedOleControl.GetTOleEnumProp(Index: Integer): TOleEnum; begin Result := GetIntegerProp(Index); end; function TDelegatedOleControl.GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult; begin Pointer(TypeInfo) := nil; Result := E_NOTIMPL; end; function TDelegatedOleControl.GetTypeInfoCount(out Count: Integer): HResult; begin Count := 0; Result := S_OK; end; function TDelegatedOleControl.GetVariantProp(Index: Integer): Variant; begin Result := GetOleVariantProp(Index); end; function TDelegatedOleControl.GetWideStringProp(Index: Integer): WideString; var Temp: TVarData; begin Result := ''; GetProperty(Index, Temp); Pointer(Result) := Temp.VOleStr; end; function TDelegatedOleControl.GetWindow(out wnd: HWnd): HResult; begin Result := S_OK; wnd := FDelegate.GetParentHandle; if wnd = 0 then Result := E_FAIL; end; function TDelegatedOleControl.GetWindowContext(out frame: IOleInPlaceFrame; out doc: IOleInPlaceUIWindow; out rcPosRect, rcClipRect: TRect; out frameInfo: TOleInPlaceFrameInfo): HResult; begin frame := Self; doc := nil; rcPosRect := FDelegate.GetBoundsRect; SetRect(rcClipRect, 0, 0, 32767, 32767); with frameInfo do begin fMDIApp := False; hWndFrame := FDelegate.GetTopParentHandle; hAccel := 0; cAccelEntries := 0; end; Result := S_OK; end; function TDelegatedOleControl.GetWordBoolProp(Index: Integer): WordBool; var Temp: TVarData; begin GetProperty(Index, Temp); Result := Temp.VBoolean; end; function TDelegatedOleControl.GetWordProp(Index: Integer): Word; begin Result := GetIntegerProp(Index); end; procedure TDelegatedOleControl.HookControlWndProc; var WndHandle: HWnd; begin if (FOleInPlaceObject <> nil) and (FDelegate.WindowHandle = 0) then begin WndHandle := 0; FOleInPlaceObject.GetWindow(WndHandle); if WndHandle = 0 then raise EOleError.CreateRes(@SNoWindowHandle); FDelegate.WindowHandle := WndHandle; FDelegate.DefWndProc := Pointer(GetWindowLong(FDelegate.WindowHandle, GWL_WNDPROC)); FDelegate.SetCreationControl; SetWindowLong(FDelegate.WindowHandle, GWL_WNDPROC, Longint(FDelegate.InitWindowProc)); SendMessage(FDelegate.WindowHandle, WM_NULL, 0, 0); end; end; {$IFDEF CPUX86} type PVarArg = ^TVarArg; TVarArg = array[0..3] of DWORD; procedure TDelegatedOleControl.D2InvokeEvent(DispID: TDispID; var Params: TDispParams); type TStringDesc = record PStr: Pointer; BStr: PBStr; end; var I, J, K, ArgType, ArgCount, StrCount: Integer; ArgPtr: PEventArg; ParamPtr: PVarArg; Strings: array[0..MaxDispArgs - 1] of TStringDesc; EventInfo: TEventInfo; begin GetEventMethod(DispID, EventInfo.Method); if Integer(EventInfo.Method.Code) >= $10000 then begin StrCount := 0; try ArgCount := Params.cArgs; EventInfo.Sender := Self; EventInfo.ArgCount := ArgCount; if ArgCount <> 0 then begin ParamPtr := @Params.rgvarg^[EventInfo.ArgCount]; ArgPtr := @EventInfo.Args; I := 0; repeat Dec(PByte(ParamPtr), SizeOf(TVarArg)); ArgType := ParamPtr^[0] and $0000FFFF; if ArgType and varTypeMask = varOleStr then begin ArgPtr^.Kind := akDWord; with Strings[StrCount] do begin PStr := nil; if ArgType and varByRef <> 0 then begin OleStrToStrVar(PBStr(ParamPtr^[2])^, AnsiString(PStr)); BStr := PBStr(ParamPtr^[2]); ArgPtr^.Data[0] := Integer(@PStr); end else begin OleStrToStrVar(TBStr(ParamPtr^[2]), AnsiString(PStr)); BStr := nil; ArgPtr^.Data[0] := Integer(PStr); end; end; Inc(StrCount); end else begin case ArgType of varSingle: begin ArgPtr^.Kind := akSingle; ArgPtr^.Data[0] := ParamPtr^[2]; end; varDouble..varDate: begin ArgPtr^.Kind := akDouble; ArgPtr^.Data[0] := ParamPtr^[2]; ArgPtr^.Data[1] := ParamPtr^[3]; end; varDispatch: begin ArgPtr^.Kind := akDWord; ArgPtr^.Data[0] := Integer(ParamPtr) end; else ArgPtr^.Kind := akDWord; if (ArgType and varArray) <> 0 then ArgPtr^.Data[0] := Integer(ParamPtr) else ArgPtr^.Data[0] := ParamPtr^[2]; end; end; Inc(PByte(ArgPtr), SizeOf(TEventArg)); Inc(I); until I = EventInfo.ArgCount; end; J := StrCount; while J <> 0 do begin Dec(J); with Strings[J] do if BStr <> nil then BStr^ := StringToOleStr(string(PStr)); end; except raise; end; K := StrCount; while K <> 0 do begin Dec(K); string(Strings[K].PStr) := ''; end; end; end; {$ENDIF CPUX86} procedure TDelegatedOleControl.InitControlInterface(const Obj: IInterface); begin end; function TDelegatedOleControl.InsertMenus(hmenuShared: HMenu; var menuWidths: TOleMenuGroupWidths): HResult; begin Result := E_NOTIMPL; end; function StringToVarOleStr(const S: string): Variant; begin VarClear(Result); TVarData(Result).VOleStr := StringToOleStr(S); TVarData(Result).VType := varOleStr; end; function TDelegatedOleControl.Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; begin if (Flags and DISPATCH_PROPERTYGET <> 0) and (VarResult <> nil) then begin Result := S_OK; case DispID of DISPID_AMBIENT_DISPLAYNAME: PVariant(VarResult)^ := StringToVarOleStr(Name); DISPID_AMBIENT_LOCALEID: PVariant(VarResult)^ := Integer(GetUserDefaultLCID); DISPID_AMBIENT_MESSAGEREFLECT: PVariant(VarResult)^ := True; DISPID_AMBIENT_USERMODE: PVariant(VarResult)^ := not (csDesigning in ComponentState); DISPID_AMBIENT_UIDEAD: PVariant(VarResult)^ := csDesigning in ComponentState; DISPID_AMBIENT_SHOWGRABHANDLES: PVariant(VarResult)^ := False; DISPID_AMBIENT_SHOWHATCHING: PVariant(VarResult)^ := False; DISPID_AMBIENT_SUPPORTSMNEMONICS: PVariant(VarResult)^ := True; DISPID_AMBIENT_AUTOCLIP: PVariant(VarResult)^ := True; else Result := DISP_E_MEMBERNOTFOUND; end; end else Result := DISP_E_MEMBERNOTFOUND; end; procedure TDelegatedOleControl.GetEventMethod(DispID: TDispID; var Method: TMethod); {$IFDEF PUREPASCAL} const ALIGN_VAL = $8; var P2: PControlData2; Index: Integer; Size: LongInt; PID: ^LongInt; PHandler: Pointer; begin PID := FControlData^.EventDispIDs; for Index := 0 to FControlData^.EventCount-1 do begin if DispID = PID^ then break; Inc(PID); end; if Index = FControlData^.EventCount then begin Method.Code := nil; Method.Data := nil; Exit; end; Assert(Index >= 0); Assert(Index < FControlData^.EventCount); PHandler := nil; if (FControlData^.Version >= 401) then begin P2 := PControlData2(FControlData); if (P2^.FirstEventOfs <> 0) then PHandler := PByte(Self) + P2^.FirstEventOfs; end; if (PHandler = nil) then begin Size := Self.ClassParent.InstanceSize; Size := Size - SizeOf(Pointer); // TMonitor Size := Size + ALIGN_VAL; Size := Size and (not ALIGN_VAL); PHandler := PByte(Self) + Size; end; Assert(PHandler <> nil); // Size of any closure will do here! PHandler := PByte(PHandler) + (Index*Sizeof(TNotifyEvent)); Method.Code := PPointer(PHandler)^; Method.Data := PPointer(PByte(PHandler) + Sizeof(Pointer))^; end; {$ENDIF} {$IFDEF CPUX86} asm PUSH EBX PUSH ESI PUSH EDI PUSH ECX MOV EBX,EAX MOV ECX,[EBX].TDelegatedOleControl.FControlData MOV EDI,[ECX].TControlData.EventCount MOV ESI,[ECX].TControlData.EventDispIDs XOR EAX,EAX JMP @@1 @@0: CMP EDX,[ESI].Integer[EAX*4] JE @@2 INC EAX @@1: CMP EAX,EDI JNE @@0 XOR EAX,EAX XOR EDX,EDX JMP @@3 @@2: PUSH EAX CMP [ECX].TControlData.Version, 401 JB @@2a MOV EAX, [ECX].TControlData2.FirstEventOfs TEST EAX, EAX JNE @@2b @@2a: MOV EAX, [EBX] CALL TObject.ClassParent CALL TObject.InstanceSize ADD EAX, 7 AND EAX, not 7 // 8 byte alignment @@2b: ADD EBX, EAX POP EAX MOV EDX,[EBX][EAX*8].TMethod.Data MOV EAX,[EBX][EAX*8].TMethod.Code @@3: POP ECX MOV [ECX].TMethod.Code,EAX MOV [ECX].TMethod.Data,EDX POP EDI POP ESI POP EBX end; {$ENDIF CPUX86} {$IFDEF CPUX64} type PParamBlock = ^TParamBlock; TParamBlock = record RegRCX: Int64; RegRDX: Int64; RegR8: Int64; RegR9: Int64; StackData: PByte; StackDataSize: Integer; OutRAX: Int64; OutXMM0: Double; end; procedure RawInvoke(CodeAddress: Pointer; ParamBlock: PParamBlock); procedure InvokeError; begin raise Exception.CreateRes(@sParameterCountExceeded); end; asm .PARAMS 62 // There's actually room for 64, assembler is saving locals for CodeAddress & ParamBlock MOV [RBP+$210], CodeAddress MOV [RBP+$218], ParamBlock MOV EAX, [ParamBlock].TParamBlock.StackDataSize TEST EAX, EAX JZ @@skip_push CMP EAX, 480 // (64-4) params * 8 bytes. JBE @@valid_frame Call InvokeError @@valid_frame: // All items on stack should be 16 byte aligned. Caller should // have handled that, just copy data here. MOV RCX, [ParamBlock].TParamBlock.StackData LEA RDX, [RBP+$20] MOVSX R8, EAX CALL Move // RCX: source, RDX: dest, R8, count MOV RDX, [RBP+$218] @@skip_push: MOV RCX, [RDX].TParamBlock.RegRCX MOV R8, [RDX].TParamBlock.RegR8 MOV R9, [RDX].TParamBlock.RegR9 MOVSD XMM0,[RDX].TParamBlock.RegRCX MOVSD XMM1,[RDX].TParamBlock.RegRDX MOVSD XMM2,[RDX].TParamBlock.RegR8 MOVSD XMM3,[RDX].TParamBlock.RegR9 MOV RDX, [RDX].TParamBlock.RegRDX CALL [RBP+$210] MOV RDX, [RBP+$218] MOV [RDX].TParamBlock.OutRAX, RAX MOVSD [RDX].TParamBlock.OutXMM0, XMM0 end; {$ENDIF CPUX64} procedure TDelegatedOleControl.InvokeEvent(DispID: TDispID; var Params: TDispParams); {$IFDEF CPUX64} var EventMethod: TMethod; ParamBlock : TParamBlock; i : Integer; StackParams2 : array of Int64; begin GetEventMethod(DispID, EventMethod); if Integer(EventMethod.Code) < $10000 then Exit; ParamBlock.RegRCX := Int64(EventMethod.Data); ParamBlock.RegRDX := Int64(Self); if Params.cArgs > 2 then begin SetLength(StackParams2, Params.cArgs-2); end; for i := 1 to Params.cArgs do case i of 1: ParamBlock.RegR8 := Int64(Params.rgvarg[Params.cArgs-1].unkVal); 2: ParamBlock.RegR9 := Int64(Params.rgvarg[Params.cArgs-2].unkVal); else StackParams2[i-3] := Int64(Params.rgvarg[Params.cArgs-i].unkVal); end; ParamBlock.StackDataSize := Length(StackParams2) * sizeof(Pointer); if Length(StackParams2) > 0 then ParamBlock.StackData := @StackParams2[0]; RawInvoke(EventMethod.Code, @ParamBlock); end; {$ELSE !CPUX64} {$IFDEF CPUX86} var EventMethod: TMethod; begin if ControlData.Version < 300 then D2InvokeEvent(DispID, Params) else begin GetEventMethod(DispID, EventMethod); if Integer(EventMethod.Code) < $10000 then Exit; try asm PUSH EBX PUSH ESI MOV ESI, Params MOV EBX, [ESI].TDispParams.cArgs TEST EBX, EBX JZ @@7 MOV ESI, [ESI].TDispParams.rgvarg MOV EAX, EBX SHL EAX, 4 // count * sizeof(TVarArg) XOR EDX, EDX ADD ESI, EAX // EDI = Params.rgvarg^[ArgCount] @@1: SUB ESI, 16 // Sizeof(TVarArg) MOV EAX, dword ptr [ESI] CMP AX, varSingle // 4 bytes to push JA @@3 JE @@5 @@2: TEST DL,DL JNE @@2a MOV ECX, ESI INC DL TEST EAX, varArray JNZ @@6 MOV ECX, dword ptr [ESI+8] // arg3 JMP @@6 @@2a: TEST EAX, varArray JZ @@5 PUSH ESI JMP @@6 @@3: CMP AX, varDate // 8 bytes to push JA @@2 @@4: PUSH dword ptr [ESI+12] @@5: PUSH dword ptr [ESI+8] @@6: DEC EBX JNE @@1 @@7: MOV EDX, Self // arg2 MOV EAX, EventMethod.Data // arg1 CALL EventMethod.Code POP ESI POP EBX end; except raise; end; end; end; {$ENDIF CPUX86} {$ENDIF !CPUX64} function TDelegatedOleControl.LockInPlaceActive(fLock: BOOL): HResult; begin Result := E_NOTIMPL; end; function TDelegatedOleControl.OleControlSite_TranslateAccelerator(msg: PMsg; grfModifiers: Integer): HResult; begin Result := E_NOTIMPL; end; function TDelegatedOleControl.OleInPlaceFrame_TranslateAccelerator(var msg: TMsg; wID: Word): HResult; begin Result := S_FALSE; end; function TDelegatedOleControl.OnChanged(dispid: TDispID): HResult; begin Result := S_OK; end; procedure TDelegatedOleControl.WMEraseBkgnd(var Message: TWMEraseBkgnd); begin end; procedure TDelegatedOleControl.WMPaint(var Message: TWMPaint); var DC: HDC; PS: TPaintStruct; begin if FMiscStatus and OLEMISC_INVISIBLEATRUNTIME <> 0 then begin DC := Message.DC; if DC = 0 then DC := BeginPaint(FDelegate.Handle, PS); {$IFDEF MSWINDOWS} OleDraw(FOleObject, DVASPECT_CONTENT, DC, FDelegate.GetBoundsRect); {$ENDIF} if Message.DC = 0 then EndPaint(FDelegate.Handle, PS); end else inherited; end; {IUnknown } function TDelegatedOleControl.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then Result := S_OK else Result := E_NOINTERFACE; end; function TDelegatedOleControl._AddRef: Integer; stdcall; begin Inc(FRefCount); Result := FRefCount; end; function TDelegatedOleControl._Release: Integer; stdcall; begin Dec(FRefCount); Result := FRefCount; end; function TDelegatedOleControl.OnControlInfoChanged: HResult; begin Result := E_NOTIMPL; end; function TDelegatedOleControl.OnFocus(fGotFocus: BOOL): HResult; begin Result := E_NOTIMPL; end; function TDelegatedOleControl.OnInPlaceActivate: HResult; begin FOleObject.QueryInterface(IOleInPlaceObject, FOleInPlaceObject); FOleObject.QueryInterface(IOleInPlaceActiveObject, FOleInPlaceActiveObject); Result := S_OK; end; function TDelegatedOleControl.OnInPlaceDeactivate: HResult; begin FOleInPlaceActiveObject := nil; FOleInPlaceObject := nil; Result := S_OK; end; function TDelegatedOleControl.OnPosRectChange(const rcPosRect: TRect): HResult; begin FOleInPlaceObject.SetObjectRects(rcPosRect, Rect(0, 0, 32767, 32767)); Result := S_OK; end; function TDelegatedOleControl.OnRequestEdit(dispid: TDispID): HResult; begin Result := S_OK; end; function TDelegatedOleControl.OnShowWindow(fShow: BOOL): HResult; begin Result := S_OK; end; procedure TDelegatedOleControl.SetUIActive(Active: Boolean); begin end; function TDelegatedOleControl.OnUIActivate: HResult; begin SetUIActive(True); Result := S_OK; end; function TDelegatedOleControl.OnUIDeactivate(fUndoable: BOOL): HResult; begin SetMenu(0, 0, 0); SetUIActive(False); Result := S_OK; end; function TDelegatedOleControl.PostMessageFilter(wnd: HWnd; msg: UInt; wp: WPARAM; lp: LPARAM; out res: LRESULT; Cookie: DWORD): HResult; begin Result := S_OK; end; function TDelegatedOleControl.PreMessageFilter(wnd: HWnd; msg: UInt; wp: WPARAM; lp: LPARAM; out res: LRESULT; out Cookie: DWORD): HResult; begin Result := S_OK; end; function TDelegatedOleControl.QueryService(const rsid, iid: TGuid; out Obj): HResult; begin if Assigned(FServiceQuery) then Result := FServiceQuery(rsid, iid, Obj) else Result := E_NOTIMPL; end; function TDelegatedOleControl.RemoveMenus(hmenuShared: HMenu): HResult; begin while GetMenuItemCount(hmenuShared) > 0 do RemoveMenu(hmenuShared, 0, MF_BYPOSITION); Result := S_OK; end; function TDelegatedOleControl.RequestBorderSpace(const borderwidths: TRect): HResult; begin Result := INPLACE_E_NOTOOLSPACE; end; function TDelegatedOleControl.RequestNewObjectLayout: HResult; var Extent: TPoint; begin Result := FOleObject.GetExtent(DVASPECT_CONTENT, Extent); end; function TDelegatedOleControl.SaveObject: HResult; begin Result := S_OK; end; function TDelegatedOleControl.Scroll(scrollExtent: TPoint): HResult; begin Result := E_NOTIMPL; end; function TDelegatedOleControl.SetActiveObject(const activeObject: IOleInPlaceActiveObject; pszObjName: POleStr): HResult; begin Result := S_OK; end; function TDelegatedOleControl.SetBorderSpace(pborderwidths: PRect): HResult; begin Result := E_NOTIMPL; end; procedure TDelegatedOleControl.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); var LRect: TRect; {$IFDEF WIN64} Temp: TPoint; {$ENDIF} begin LRect := FDelegate.GetBoundsRect; LRect := RectF(LRect.Left, LRect.Top, LRect.Left+AWidth, LRect.Top+AHeight).Round; if FOleInPlaceObject <> nil then FOleInplaceObject.SetObjectRects(LRect, LRect); if ((AWidth <> LRect.Width) and (LRect.Width > 0)) or ((AHeight <> LRect.Height) and (LRect.Height > 0)) then begin {$IFDEF WIN64} Temp := Point(MulDiv(AWidth, 2540, 100), MulDiv(AHeight, 2540, 100)); if (FMiscStatus and OLEMISC_INVISIBLEATRUNTIME <> 0) or ((FOleObject.SetExtent(DVASPECT_CONTENT, @Temp) <> S_OK)) then {$ELSE} if (FMiscStatus and OLEMISC_INVISIBLEATRUNTIME <> 0) or ((FOleObject.SetExtent(DVASPECT_CONTENT, Point( MulDiv(AWidth, 2540, 100), MulDiv(AHeight, 2540, 100))) <> S_OK)) then {$ENDIF} if FOleInplaceObject <> nil then FOleInplaceObject.SetObjectRects(LRect, LRect); end; end; procedure TDelegatedOleControl.SetByteProp(Index: Integer; Value: Byte); begin SetIntegerProp(Index, Value); end; procedure TDelegatedOleControl.SetColorProp(Index: Integer; Value: TColor); begin SetIntegerProp(Index, Value); end; procedure TDelegatedOleControl.SetCompProp(Index: Integer; const Value: Comp); var Temp: TVarData; begin Temp.VType := VT_I8; Temp.VDouble := Value; SetProperty(Index, Temp); end; procedure TDelegatedOleControl.SetCurrencyProp(Index: Integer; const Value: Currency); var Temp: TVarData; begin Temp.VType := varCurrency; Temp.VCurrency := Value; SetProperty(Index, Temp); end; procedure TDelegatedOleControl.SetDoubleProp(Index: Integer; const Value: Double); var Temp: TVarData; begin Temp.VType := varDouble; Temp.VDouble := Value; SetProperty(Index, Temp); end; procedure TDelegatedOleControl.SetIDispatchProp(Index: Integer; const Value: IDispatch); var Temp: TVarData; begin Temp.VType := varDispatch; Temp.VDispatch := Pointer(Value); SetProperty(Index, Temp); end; procedure TDelegatedOleControl.SetIntegerProp(Index, Value: Integer); var Temp: TVarData; begin Temp.VType := varInteger; Temp.VInteger := Value; SetProperty(Index, Temp); end; procedure TDelegatedOleControl.SetIUnknownProp(Index: Integer; const Value: IInterface); var Temp: TVarData; begin Temp.VType := VT_UNKNOWN; Temp.VUnknown := Pointer(Value); SetProperty(Index, Temp); end; function TDelegatedOleControl.SetMenu(hmenuShared, holemenu: HMenu; hwndActiveObject: HWnd): HResult; begin // requires the implementation Result := S_OK; end; procedure TDelegatedOleControl.SetName(const Value: TComponentName); begin inherited; end; procedure TDelegatedOleControl.SetOleBoolProp(Index: Integer; Value: TOleBool); var Temp: TVarData; begin Temp.VType := varBoolean; if Value then Temp.VBoolean := WordBool(-1) else Temp.VBoolean := WordBool(0); SetProperty(Index, Temp); end; procedure TDelegatedOleControl.SetOleDateProp(Index: Integer; const Value: TOleDate); var Temp: TVarData; begin Temp.VType := varDate; Temp.VDate := Value; SetProperty(Index, Temp); end; procedure TDelegatedOleControl.SetOleEnumProp(Index: Integer; Value: TOleEnum); begin SetIntegerProp(Index, Value); end; procedure TDelegatedOleControl.SetOleVariantProp(Index: Integer; const Value: OleVariant); begin SetProperty(Index, TVarData(Value)); end; procedure TDelegatedOleControl.SetProperty(Index: Integer; const Value: TVarData); const DispIDArgs: Longint = DISPID_PROPERTYPUT; var Status, InvKind: Integer; DispParams: TDispParams; ExcepInfo: TExcepInfo; begin CreateControl; DispParams.rgvarg := @Value; DispParams.rgdispidNamedArgs := @DispIDArgs; DispParams.cArgs := 1; DispParams.cNamedArgs := 1; if Value.VType <> varDispatch then InvKind := DISPATCH_PROPERTYPUT else InvKind := DISPATCH_PROPERTYPUTREF; Status := FControlDispatch.Invoke(Index, GUID_NULL, 0, InvKind, DispParams, nil, @ExcepInfo, nil); if Status <> 0 then DispatchInvokeError(Status, ExcepInfo); end; procedure TDelegatedOleControl.SetShortIntProp(Index: Integer; Value: Shortint); begin SetIntegerProp(Index, Value); end; procedure TDelegatedOleControl.SetSingleProp(Index: Integer; const Value: Single); var Temp: TVarData; begin Temp.VType := varSingle; Temp.VSingle := Value; SetProperty(Index, Temp); end; procedure TDelegatedOleControl.SetSmallintProp(Index: Integer; Value: Smallint); var Temp: TVarData; begin Temp.VType := varSmallint; Temp.VSmallint := Value; SetProperty(Index, Temp); end; function TDelegatedOleControl.SetStatusText(pszStatusText: POleStr): HResult; begin Result := S_OK; end; procedure TDelegatedOleControl.SetStringProp(Index: Integer; const Value: string); var Temp: TVarData; begin Temp.VType := varOleStr; Temp.VOleStr := StringToOleStr(Value); try SetProperty(Index, Temp); finally SysFreeString(Temp.VOleStr); end; end; procedure TDelegatedOleControl.SetTColorProp(Index: Integer; Value: TColor); begin SetIntegerProp(Index, Value); end; procedure TDelegatedOleControl.SetTDateTimeProp(Index: Integer; const Value: TDateTime); var Temp: TVarData; begin Temp.VType := varDate; Temp.VDate := Value; SetProperty(Index, Temp); end; procedure TDelegatedOleControl.SetTOleEnumProp(Index: Integer; Value: TOleEnum); begin SetIntegerProp(Index, Value); end; procedure TDelegatedOleControl.SetVariantProp(Index: Integer; const Value: Variant); begin SetOleVariantProp(Index, Value); end; procedure TDelegatedOleControl.SetWideStringProp(Index: Integer; const Value: WideString); var Temp: TVarData; begin Temp.VType := varOleStr; if Value <> '' then Temp.VOleStr := PWideChar(Value) else Temp.VOleStr := nil; SetProperty(Index, Temp); end; procedure TDelegatedOleControl.SetWordBoolProp(Index: Integer; Value: WordBool); var Temp: TVarData; begin Temp.VType := varBoolean; if Value then Temp.VBoolean := WordBool(-1) else Temp.VBoolean := WordBool(0); SetProperty(Index, Temp); end; procedure TDelegatedOleControl.SetWordProp(Index: Integer; Value: Word); begin SetIntegerProp(Index, Value); end; function TDelegatedOleControl.ShowObject: HResult; begin HookControlWndProc; Result := S_OK; end; function TDelegatedOleControl.ShowPropertyFrame: HResult; begin Result := E_NOTIMPL; end; procedure TDelegatedOleControl.StandardEvent(DispID: TDispID; var Params: TDispParams); begin end; function TDelegatedOleControl.TransformCoords(var ptlHimetric: TPoint; var ptfContainer: TPointF; flags: Integer): HResult; begin // requires the implementation Result := S_OK; end; function TDelegatedOleControl.CanInPlaceActivate: HResult; begin Result := S_OK; end; function TDelegatedOleControl.ContextSensitiveHelp(fEnterMode: BOOL): HResult; begin Result := S_OK; end; procedure TDelegatedOleControl.DoObjectVerb(Verb: Integer); var ActiveWindow: HWnd; begin CreateControl; ActiveWindow := GetActiveWindow; try OleCheck(FOleObject.DoVerb(Verb, nil, Self, 0, FDelegate.GetParentHandle, FDelegate.GetBoundsRect)); finally SetActiveWindow(ActiveWindow); Winapi.Windows.SetFocus(ActiveWindow); end; end; constructor TDelegatedOleControl.Create(ADelegate: IOLEFrameworkDelegate); begin FDelegate := ADelegate; FDelegate.SetDispatcher(FrameworksDispatcher); InitControlData; Inc(FControlData^.InstanceCount); FEventDispatch := TEventDispatch.Create(Self); CreateInstance; InitControlInterface(FOleObject); OleCheck(FOleObject.GetMiscStatus(DVASPECT_CONTENT, FMiscStatus)); if (FControlData^.Reserved and cdDeferSetClientSite) = 0 then if ((FMiscStatus and OLEMISC_SETCLIENTSITEFIRST) <> 0) or ((FControlData^.Reserved and cdForceSetClientSite) <> 0) then OleCheck(FOleObject.SetClientSite(Self)); OleCheck(FOleObject.QueryInterface(IPersistStreamInit, FPersistStream)); if FMiscStatus and OLEMISC_INVISIBLEATRUNTIME <> 0 then FDelegate.Visible := False; OleCheck(RequestNewObjectLayout); end; procedure TDelegatedOleControl.CreateControl; var Stream: IStream; CS: IOleClientSite; X: Integer; begin FOleControl := nil; if FOleControl = nil then try try // work around ATL bug X := FOleObject.GetClientSite(CS); except X := -1; end; if (X <> 0) or (CS = nil) then OleCheck(FOleObject.SetClientSite(Self)); if (FObjectData = 0) and Assigned(FPersistStream) then OleCheck(FPersistStream.InitNew) else begin OleCheck(CreateStreamOnHGlobal(FObjectData, False, Stream)); OleCheck(FPersistStream.Load(Stream)); DestroyStorage; end; OleCheck(FOleObject.QueryInterface(IOleControl, FOleControl)); FControlInfo.cb := SizeOf(FControlInfo); FOleControl.GetControlInfo(FControlInfo); OleCheck(FOleObject.QueryInterface(IDispatch, FControlDispatch)); InterfaceConnect(FOleObject, IPropertyNotifySink, Self, FPropConnection); InterfaceConnect(FOleObject, FControlData^.EventIID, FEventDispatch, FEventsConnection); { if FControlData^.Flags then OnChanged(DISPID_BACKCOLOR); if FControlData^.Flags and cfEnabled <> 0 then OnChanged(DISPID_ENABLED); if FControlData^.Flags and cfFont <> 0 then OnChanged(DISPID_FONT); if FControlData^.Flags and cfForeColor <> 0 then OnChanged(DISPID_FORECOLOR); } FOleControl.OnAmbientPropertyChange(DISPID_UNKNOWN); RequestNewObjectLayout; except DestroyControl; raise; end; end; procedure TDelegatedOleControl.CreateInstance; var ClassFactory2: IClassFactory2; LicKeyStr: WideString; procedure LicenseCheck(Status: HResult; const Ident: string); begin if Status = CLASS_E_NOTLICENSED then raise EOleError.CreateFmt(Ident, [ClassName]); OleCheck(Status); end; begin if (FControlData^.LicenseKey <> nil) then begin OleCheck(CoGetClassObject(FControlData^.ClassID, CLSCTX_INPROC_SERVER or CLSCTX_LOCAL_SERVER, nil, IClassFactory2, ClassFactory2)); LicKeyStr := PWideChar(FControlData^.LicenseKey); LicenseCheck(ClassFactory2.CreateInstanceLic(nil, nil, IOleObject, LicKeyStr, FOleObject), SInvalidLicense); end else LicenseCheck(CoCreateInstance(FControlData^.ClassID, nil, CLSCTX_INPROC_SERVER or CLSCTX_LOCAL_SERVER, IOleObject, FOleObject), SNotLicensed); end; procedure TDelegatedOleControl.CreateWnd; begin CreateControl; if FMiscStatus and OLEMISC_INVISIBLEATRUNTIME = 0 then begin FOleObject.DoVerb(OLEIVERB_INPLACEACTIVATE, nil, Self, 0, FDelegate.GetParentHandle, FDelegate.GetBoundsRect); if FOleInPlaceObject = nil then raise EOleError.CreateRes(@SCannotActivate); HookControlWndProc; if not FDelegate.Visible and IsWindowVisible(FDelegate.Handle) then ShowWindow(FDelegate.Handle, SW_HIDE); end; end; function TDelegatedOleControl.DeactivateAndUndo: HResult; begin FOleInPlaceObject.UIDeactivate; Result := S_OK; end; destructor TDelegatedOleControl.Destroy; procedure FreeList(var L: TList); var I: Integer; begin if L <> nil then begin for I := 0 to L.Count-1 do TObject(L[I]).Free; L.Free; L := nil; end; end; begin // jmt. Comment out SetUIActive because it usually doesn't do anything. // SetUIActive is intended to clear the parent // form's reference (if any) to this control. Usually // TWinControl.Destroy has been called on the parent, clearing // this control's parent property. So SetUIActive won't be // able to find the parent form. // TCustomForm now adds a FreeNotification on // FActiveOleControl for clearing the reference. if FOleObject <> nil then FOleObject.Close(OLECLOSE_NOSAVE); DestroyControl; DestroyStorage; Dec(FControlData^.InstanceCount); DestroyWindowHandle; FEventDispatch.Free; inherited Destroy; end; procedure TDelegatedOleControl.DestroyControl; begin InterfaceDisconnect(FOleObject, FControlData^.EventIID, FEventsConnection); InterfaceDisconnect(FOleObject, IPropertyNotifySink, FPropConnection); FPropBrowsing := nil; FControlDispatch := nil; FOleControl := nil; end; procedure TDelegatedOleControl.DestroyHandle; begin end; procedure TDelegatedOleControl.DestroyStorage; begin if FObjectData <> 0 then begin GlobalFree(FObjectData); FObjectData := 0; end; end; procedure TDelegatedOleControl.DestroyWindowHandle; begin SetWindowLong(FDelegate.WindowHandle, GWL_WNDPROC, NativeInt(FDelegate.DefWndProc)); if FOleObject <> nil then FOleObject.Close(OLECLOSE_NOSAVE); FDelegate.WindowHandle := 0; end; function TDelegatedOleControl.DiscardUndoState: HResult; begin Result := E_NOTIMPL; end; function TDelegatedOleControl.EnableModeless(fEnable: BOOL): HResult; begin Result := S_OK; end; procedure TDelegatedOleControl.FrameworksDispatcher(DispId: Integer; var Params: TOleVariantArray); begin case TInvoke(DispId) of TInvoke.CreateWnd: Self.CreateWnd; TInvoke.SetBounds: Self.SetBounds( Params[0], Params[1], Params[2], Params[3]); TInvoke.DestroyWindowHandle:; else Assert(False,'Unknown identifier DispId'); end; end; function TDelegatedOleControl.GetBorder(out rectBorder: TRect): HResult; begin Result := INPLACE_E_NOTOOLSPACE; end; function TDelegatedOleControl.GetByteProp(Index: Integer): Byte; begin Result := GetIntegerProp(Index); end; function TDelegatedOleControl.GetColorProp(Index: Integer): TColor; begin Result := GetIntegerProp(Index); end; function TDelegatedOleControl.GetCompProp(Index: Integer): Comp; begin Result := GetDoubleProp(Index); end; function TDelegatedOleControl.GetContainer(out container: IOleContainer): HResult; begin Result := E_NOINTERFACE; end; function TDelegatedOleControl.GetCurrencyProp(Index: Integer): Currency; var Temp: TVarData; begin GetProperty(Index, Temp); Result := Temp.VCurrency; end; function TDelegatedOleControl.GetDoubleProp(Index: Integer): Double; var Temp: TVarData; begin GetProperty(Index, Temp); Result := Temp.VDouble; end; function TDelegatedOleControl.GetExtendedControl(out disp: IDispatch): HResult; begin Result := E_NOTIMPL; end; function TDelegatedOleControl.GetIDispatchProp(Index: Integer): IDispatch; var Temp: TVarData; begin GetProperty(Index, Temp); Result := IDispatch(Temp.VDispatch); IDispatch(Temp.VDispatch) := nil; end; function TDelegatedOleControl.GetIDsOfNames(const IID: TGUID; Names: Pointer; NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; begin Result := E_NOTIMPL; end; function TDelegatedOleControl.GetIntegerProp(Index: Integer): Integer; var Temp: TVarData; begin GetProperty(Index, Temp); Result := Temp.VInteger; end; function TDelegatedOleControl.GetIUnknownProp(Index: Integer): IUnknown; var Temp: TVarData; begin GetProperty(Index, Temp); Result := IUnknown(Temp.VUnknown); IUnknown(Temp.VUnknown) := nil; end; function TDelegatedOleControl.GetMoniker(dwAssign, dwWhichMoniker: Integer; out mk: IMoniker): HResult; begin Result := E_NOTIMPL; end; { TEventDispatch } constructor TEventDispatch.Create(Control: TDelegatedOleControl); begin FControl := Control; end; function TEventDispatch.GetIDsOfNames(const IID: TGUID; Names: Pointer; NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; begin Result := E_NOTIMPL; end; function TEventDispatch.GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult; begin Pointer(TypeInfo) := nil; Result := E_NOTIMPL; end; function TEventDispatch.GetTypeInfoCount(out Count: Integer): HResult; begin Count := 0; Result := S_OK; end; function TEventDispatch.Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; begin if (DispID >= DISPID_MOUSEUP) and (DispID <= DISPID_CLICK) then Control.StandardEvent(DispID, TDispParams(Params)) else Control.InvokeEvent(DispID, TDispParams(Params)); Result := S_OK; end; function TEventDispatch.QueryInterface(const IID: TGUID; out Obj): HResult; begin if GetInterface(IID, Obj) then begin Result := S_OK; Exit; end; if Assigned(FControl) and IsEqualIID(IID, FControl.FControlData^.EventIID) then begin GetInterface(IDispatch, Obj); Result := S_OK; Exit; end; Result := E_NOINTERFACE; end; function TEventDispatch._AddRef: Integer; begin Result := FControl._AddRef; end; function TEventDispatch._Release: Integer; begin Result := FControl._Release; end; end.
unit TestExchangeCurrency; interface uses TestFramework; type TTestCurrencyExchange = class(TTestCase) published procedure TestCurrencyExchange; procedure TestCurrencyExchangeUSDtoGBP; end; implementation uses Money, CurrencyExchange, SysUtils; { TTestCurrencyExchange } procedure TTestCurrencyExchange.TestCurrencyExchange; var FromMoney : IMoney; ToMoney : IMoney; begin FromMoney := TMoney.Create(36.48, TFormatSettings.Create(2057)); ToMoney := TCurrencyExchange.ChangeCurrency(FromMoney, TFormatSettings.Create, 1.58); //57.6384 //5764 CheckEquals(5764, ToMoney.Amount); CheckEqualsString('$57.64', ToMoney.ToString); end; procedure TTestCurrencyExchange.TestCurrencyExchangeUSDtoGBP; var FromMoney : IMoney; ToMoney : IMoney; begin FromMoney := TMoney.Create(36.48); ToMoney := TCurrencyExchange.ChangeCurrency(FromMoney, TFormatSettings.Create(2057), 1.58); CheckEquals(5764, ToMoney.Amount); CheckEqualsString('£57.64', ToMoney.ToString); end; initialization RegisterTest(TTestCurrencyExchange.Suite); end.
unit Buf.Zoom; interface uses Winapi.Windows, System.SysUtils, System.Classes, System.Math, System.Types, Vcl.Forms, Vcl.Controls; type TZoomController = class private FMain: TRect; FChild: TRect; FOldRect: TRect; FOnChange: TNotifyEvent; FValue: Integer; FCenter: TPoint; FOriginalSize: TSize; FUpdates: Integer; FMoveCenter: Boolean; FSaveViewPoint: Boolean; FChildMousePos: TPoint; FSavedXY: TPoint; FCursorUpdate: Boolean; FChangeControl: TWinControl; procedure SetChild(const Value: TRect); procedure SetMain(const Value: TRect); procedure SetOnChange(const Value: TNotifyEvent); procedure SetValue(const Value: Integer); procedure SetOriginalSize(const Value: TSize); procedure SetCenter(const Value: TPoint); procedure SetCursorUpdate(const Value: Boolean); function GetIsMoving: Boolean; procedure SetChangeControl(const Value: TWinControl); procedure DoChange; public T:TPoint; procedure AroundChange; procedure BeginUpdate; procedure EndUpdate; procedure MovingStart; procedure Moving; procedure MovingEnd; constructor Create; procedure Reset; procedure SaveViewPoint(Value: TPoint); property Main: TRect read FMain write SetMain; property Child: TRect read FChild write SetChild; property OriginalSize: TSize read FOriginalSize write SetOriginalSize; property OnChange: TNotifyEvent read FOnChange write SetOnChange; property Value: Integer read FValue write SetValue; property Center: TPoint read FCenter write SetCenter; property CursorUpdate: Boolean read FCursorUpdate write SetCursorUpdate; property IsMoving: Boolean read GetIsMoving; property ChangeControl: TWinControl read FChangeControl write SetChangeControl; end; implementation { TZoom } procedure TZoomController.AroundChange; var R: TRect; W, H, DH, DW, PW, PH: Integer; NewRct: TRect; function ScaleRect(Src: TRect; Center: TPoint; Scale: Integer): TRect; begin Result := Src; Result.Left := Trunc(Center.X - ((Src.Width * Scale) / 2)); Result.Top := Trunc(Center.Y - ((Src.Height * Scale) / 2)); Result.Width := Src.Width * Scale; Result.Height := Src.Height * Scale; end; begin if FUpdates > 0 then Exit; R := FMain; W := OriginalSize.Width; H := OriginalSize.Height; if (W <> 0) and (H <> 0) then begin DH := FMain.Height; DW := FMain.Width; // PW := DW; PH := Round(PW * (H / W)); if PH > DH then begin PH := DH; PW := Round(PH * (W / H)); end; NewRct.Left := DW div 2 - PW div 2; NewRct.Top := DH div 2 - PH div 2; NewRct.Width := PW; NewRct.Height := PH; //Сброс центра, если зума нет if FValue = 1 then FCenter := Point(DW div 2, DH div 2); //Установка размеров видео с зумом NewRct := ScaleRect(NewRct, FCenter, FValue); //Ограничения на передвижение при зуме if FValue > 1 then begin PW := NewRct.Width; PH := NewRct.Height; NewRct.Left := Min(0, NewRct.Left); NewRct.Right := NewRct.Left + PW; NewRct.Right := Max(DW, NewRct.Right); NewRct.Left := NewRct.Right - PW; NewRct.Top := Min(0, NewRct.Top); NewRct.Bottom := NewRct.Top + PH; NewRct.Bottom := Max(DH, NewRct.Bottom); NewRct.Top := NewRct.Bottom - PH; FCenter := NewRct.CenterPoint; end; R := NewRct; end; if FValue > 1 then begin if FSaveViewPoint then begin T := Point(FOldRect.CenterPoint.X - FChildMousePos.X, FOldRect.CenterPoint.Y - FChildMousePos.Y); //NewRct.Location := //NewRct.Location := Point(NewRct.Location.X + (FChildMousePos.X), NewRct.Location.Y + (FChildMousePos.Y)); end; //По центру, если меньше if R.Width < FMain.Width then R.Location := Point(FMain.Width div 2 - R.Width div 2, R.Top); if R.Height < FMain.Height then R.Location := Point(R.Left, FMain.Height div 2 - R.Height div 2); end; Child := R; end; procedure TZoomController.BeginUpdate; begin Inc(FUpdates); end; constructor TZoomController.Create; begin inherited; FSavedXY := Point(0, 0); FChildMousePos := Point(0, 0); FMoveCenter := False; FUpdates := 0; FCursorUpdate := False; FValue := 1; end; procedure TZoomController.DoChange; begin if Assigned(FChangeControl) then begin with Child do FChangeControl.SetBounds(Left, Top, Width, Height); FChangeControl.Width := FChangeControl.Width - 1; FChangeControl.Width := FChangeControl.Width + 1; end; if Assigned(FOnChange) then FOnChange(Self); end; procedure TZoomController.EndUpdate; begin Dec(FUpdates); if FUpdates < 0 then FUpdates := 0; end; function TZoomController.GetIsMoving: Boolean; begin Result := FMoveCenter; end; procedure TZoomController.Moving; var Offs: TPoint; begin if IsMoving then begin if FMoveCenter and (Value > 1) then begin Offs := Center; Offs.Offset(Mouse.CursorPos.X - FSavedXY.X, Mouse.CursorPos.Y - FSavedXY.Y); FSavedXY := Point(Mouse.CursorPos.X, Mouse.CursorPos.Y); Center := Offs; end; end; end; procedure TZoomController.MovingEnd; begin FMoveCenter := False; if FCursorUpdate then Screen.Cursor := crDefault; end; procedure TZoomController.MovingStart; begin if Value > 1 then begin FMoveCenter := True; if FCursorUpdate then Screen.Cursor := crSizeAll; FSavedXY := Point(Mouse.CursorPos.X, Mouse.CursorPos.Y); end; end; procedure TZoomController.Reset; begin FValue := 1; MovingEnd; end; procedure TZoomController.SetChangeControl(const Value: TWinControl); begin FChangeControl := Value; end; procedure TZoomController.SetChild(const Value: TRect); begin FChild := Value; FOldRect := FChild; DoChange; end; procedure TZoomController.SetCursorUpdate(const Value: Boolean); begin FCursorUpdate := Value; end; procedure TZoomController.SetMain(const Value: TRect); begin FMain := Value; AroundChange; end; procedure TZoomController.SetOnChange(const Value: TNotifyEvent); begin FOnChange := Value; end; procedure TZoomController.SetOriginalSize(const Value: TSize); begin if FOriginalSize = Value then Exit; FOriginalSize := Value; AroundChange; end; procedure TZoomController.SetValue(const Value: Integer); begin FValue := Value; if FValue <= 0 then FValue := 1; AroundChange; FSaveViewPoint := False; end; procedure TZoomController.SaveViewPoint(Value: TPoint); begin FSaveViewPoint := True; FOldRect := Child; FChildMousePos := Value; end; procedure TZoomController.SetCenter(const Value: TPoint); begin if FCenter = Value then Exit; FCenter := Value; AroundChange; end; end.
// // Created by the DataSnap proxy generator. // 2016-01-28 ¿ÀÀü 2:00:36 // unit Unit1; interface uses System.JSON, Data.DBXCommon, Data.DBXClient, Data.DBXDataSnap, Data.DBXJSON, Datasnap.DSProxy, System.Classes, System.SysUtils, Data.DB, Data.SqlExpr, Data.DBXDBReaders, Data.DBXCDSReaders, Data.DBXJSONReflect; type TFlowerServerMethodsClient = class(TDSAdminClient) private FEchoStringCommand: TDBXCommand; FReverseStringCommand: TDBXCommand; FLoginCommand: TDBXCommand; FFSearchCommand: TDBXCommand; public constructor Create(ADBXConnection: TDBXConnection); overload; constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload; destructor Destroy; override; function EchoString(Value: string): string; function ReverseString(Value: string): string; function Login(I: string; P: string): string; procedure FSearch(S: string); end; implementation function TFlowerServerMethodsClient.EchoString(Value: string): string; begin if FEchoStringCommand = nil then begin FEchoStringCommand := FDBXConnection.CreateCommand; FEchoStringCommand.CommandType := TDBXCommandTypes.DSServerMethod; FEchoStringCommand.Text := 'TFlowerServerMethods.EchoString'; FEchoStringCommand.Prepare; end; FEchoStringCommand.Parameters[0].Value.SetWideString(Value); FEchoStringCommand.ExecuteUpdate; Result := FEchoStringCommand.Parameters[1].Value.GetWideString; end; function TFlowerServerMethodsClient.ReverseString(Value: string): string; begin if FReverseStringCommand = nil then begin FReverseStringCommand := FDBXConnection.CreateCommand; FReverseStringCommand.CommandType := TDBXCommandTypes.DSServerMethod; FReverseStringCommand.Text := 'TFlowerServerMethods.ReverseString'; FReverseStringCommand.Prepare; end; FReverseStringCommand.Parameters[0].Value.SetWideString(Value); FReverseStringCommand.ExecuteUpdate; Result := FReverseStringCommand.Parameters[1].Value.GetWideString; end; function TFlowerServerMethodsClient.Login(I: string; P: string): string; begin if FLoginCommand = nil then begin FLoginCommand := FDBXConnection.CreateCommand; FLoginCommand.CommandType := TDBXCommandTypes.DSServerMethod; FLoginCommand.Text := 'TFlowerServerMethods.Login'; FLoginCommand.Prepare; end; FLoginCommand.Parameters[0].Value.SetWideString(I); FLoginCommand.Parameters[1].Value.SetWideString(P); FLoginCommand.ExecuteUpdate; Result := FLoginCommand.Parameters[2].Value.GetWideString; end; procedure TFlowerServerMethodsClient.FSearch(S: string); begin if FFSearchCommand = nil then begin FFSearchCommand := FDBXConnection.CreateCommand; FFSearchCommand.CommandType := TDBXCommandTypes.DSServerMethod; FFSearchCommand.Text := 'TFlowerServerMethods.FSearch'; FFSearchCommand.Prepare; end; FFSearchCommand.Parameters[0].Value.SetWideString(S); FFSearchCommand.ExecuteUpdate; end; constructor TFlowerServerMethodsClient.Create(ADBXConnection: TDBXConnection); begin inherited Create(ADBXConnection); end; constructor TFlowerServerMethodsClient.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); begin inherited Create(ADBXConnection, AInstanceOwner); end; destructor TFlowerServerMethodsClient.Destroy; begin FEchoStringCommand.DisposeOf; FReverseStringCommand.DisposeOf; FLoginCommand.DisposeOf; FFSearchCommand.DisposeOf; inherited; end; end.
unit ncaConnMgr; interface uses SysUtils, Classes, SyncObjs, Windows, Messages, nxtwWinsockTransport, madTools, madTypes, idHttp; type TConnMgr = class private FCS : TCriticalSection; FServidor : String; FAuto : TStrings; FLastConn : String; FLastConnOk : Boolean; FLastRefresh : Cardinal; FAutoRemote : TStrings; FAutoLocal : TStrings; FOnUpdate : TNotifyEvent; FHandle : HWND; function GetAuto: Boolean; procedure SetAuto(const Value: Boolean); function ArqAuto: String; procedure LoadAuto; procedure SaveAuto; procedure SetServidor(const Value: String); function GetAutoRemote: String; procedure SetAutoRemote(const Value: String); function GetAutoLocal: String; procedure SetAutoLocal(const Value: String); procedure wmUpdate(window: HWND; msg: cardinal; wParam, lParam: madTypes.NativeInt; var result: madTypes.NativeInt); procedure MergeLocalAndRemote; property AutoLocal: String read GetAutoLocal write SetAutoLocal; property AutoRemote: String read GetAutoRemote write SetAutoRemote; public constructor Create; destructor Destroy; override; procedure LoadConfig; procedure SaveConfig; property Handle: HWND read FHandle; procedure SetLastConnOk(aServ: String); procedure RefreshAutoInfo; function ObtemServidor: String; procedure Conectou(aServ: String); procedure NaoConectou(aServ: String); property OnUpdate: TNotifyEvent read FOnUpdate write FOnUpdate; property LastConn: String read FLastConn; property LastConnOk: Boolean read FLastConnOk; property AutoServers: TStrings read FAuto; property Servidor: String read FServidor write SetServidor; property Auto: Boolean read GetAuto write SetAuto; end; var gConnMgr : TConnMgr = nil; csRem : TCriticalSection; csLoc : TCriticalSection; LastRem : Cardinal = 0; LastLoc : Cardinal = 0; gConnMgrStopRetry : Boolean = False; implementation uses ncaDM, ncDebug, MD5, nexUrls; { TConnMgr } function GetRemoteServerNames: String; var H : TidHttp; sl : TStrings; Chave : String; Ok : Boolean; NextTry : Cardinal; begin Result := ''; if not csRem.TryEnter then Exit; try if (LastRem>0) and ((GetTickCount-LastRem)<120000) then Exit; DebugMsg('GetRemoteServerNames 1'); sl := TStringList.Create; try H := TidHttp.Create(nil); try H.HandleRedirects := True; DebugMsg('GetRemoteServerNames 2'); Chave := IntToStr(Random(999999)); Ok := False; NextTry := 0; while (not Ok) and (not gConnMgrStopRetry) do begin if NextTry>0 then Sleep(500); if GetTickCount>=NextTry then try try sl.Text := H.Get(gUrls.Url('autoconninfo', 'chave='+Chave)); except on e: exception do DebugMsg('GetRemoteServerNames - Exception 1: '+E.Message); end; if (sl.Text>'') and (sl[0]=getMD5Str(Chave)) then begin Ok := True; LastRem := GetTickCount; sl.Delete(0); Result := sl.Text; DebugMsg('GetRemoteServerNames - OK - ' + Result); end else NextTry := GetTickCount + 10000; except end; end; DebugMsg('GetRemoteServerNames 3'); finally H.Free; end; except on E: Exception do DebugMsg('GetRemoteServerNames - Exception 2: '+E.Message); end; sl.Free; finally csRem.Leave; end; end; function GetLocalServerNames: String; var sl : TStrings; i : integer; s : string; NextTry : Cardinal; begin Result := ''; if not csLoc.TryEnter then Exit; try DebugMsg('GetLocalServerNames 1'); with TnxWinsockTransport.Create(nil) do try Port := 16200; sl := TStringList.Create; try NextTry := 0; while (Result='') and (not gConnmgrStopRetry) do begin if NextTry>0 then Sleep(500); if GetTickCount>=NextTry then begin try GetServerNames(sl, 1500); except end; if sl.Count>0 then begin for i := 0 to sl.Count-1 do begin s := sl[i]; Delete(s, 1, Pos('@', s)); sl[i] := s; end; Result := sl.Text; DebugMsg('GetLocalServerNames OK - ' + Result); end else begin NextTry := GetTickCount+5000; DebugMsg('GetLocalServerNames FAIL'); end; end; end; finally sl.Free; end; finally Free; end; finally csLoc.Leave; end; end; function TConnMgr.ArqAuto: String; begin Result := ExtractFilePath(ParamStr(0))+'autoconn.ini'; end; procedure TConnMgr.Conectou(aServ: String); begin FLastConn := aServ; FLastConnOk := True; slConfig.Values['UltimoServidor'] := aServ; Self.SaveConfig; DebugMsg('TConnMgr.Conectou - ' + slConfig.text); end; constructor TConnMgr.Create; begin FCS := TCriticalSection.Create; FLastRefresh := 0; FAuto := TStringList.Create; FServidor := '127.0.0.1'; FAutoRemote := TStringList.Create; FAutoLocal := TStringList.Create; FOnUpdate := nil; FLastConn := ''; FLastConnOk := False; LoadAuto; AddMsgHandler(wmUpdate, wm_user); FHandle := MsgHandlerWindow; end; destructor TConnMgr.Destroy; begin FAuto.Free; FAutoRemote.Free; FAutoLocal.Free; FCS.Free; inherited; end; function TConnMgr.GetAutoRemote: String; begin FCS.Enter; try Result := FAutoRemote.Text; finally FCS.Leave; end; end; function TConnMgr.GetAuto: Boolean; begin Result := SameText(FServidor, 'auto'); end; function TConnMgr.GetAutoLocal: String; begin FCS.Enter; try Result := FAutoLocal.Text; finally FCS.Leave; end; end; procedure TConnMgr.LoadAuto; begin if FileExists(ArqAuto) then FAuto.LoadFromFile(ArqAuto); end; procedure TConnMgr.LoadConfig; begin if slConfig.Values['servidor']='' then slConfig.Values['servidor'] := '127.0.0.1'; gConnMgr.Servidor := slConfig.Values['servidor']; gConnMgr.SetLastConnOk(slConfig.Values['ultimoservidor']); end; procedure TConnMgr.MergeLocalAndRemote; var sl : TStrings; i : Integer; begin DebugMsg('TConnMgr - MergeLocalAndRemote'); sl := TStringList.Create; try sl.Text := FAutoLocal.Text; for I := 0 to FAutoRemote.Count-1 do if sl.IndexOf(FAutoRemote[I])<0 then sl.Add(FAutoRemote[I]); PostMessage(FHandle, wm_user, wParam(sl), 0); except sl.Free; end; end; procedure TConnMgr.NaoConectou(aServ: String); begin FLastConn := aServ; FLastConnOk := False; end; function TConnMgr.ObtemServidor: String; var I : Integer; begin if not Auto then Result := FServidor else if FLastConnOk then Result := FLastConn else if FAuto.Count=0 then begin RefreshAutoInfo; if FAuto.Count>0 then Result := FAuto[0] else Result := ''; end else begin I := FAuto.IndexOf(FLastConn); Inc(I); if I > (FAuto.Count-1) then begin RefreshAutoInfo; I := 0; end; Result := FAuto[I]; end; if Result='' then Result := '127.0.0.1'; end; type TThreadAutoRemote = class ( TThread ) protected FHWND : HWND; procedure Execute; override; public constructor Create; end; procedure TThreadAutoRemote.Execute; var S: String; begin S := GetRemoteServerNames; if S>'' then try gConnMgr.AutoRemote := S; except end; end; constructor TThreadAutoRemote.Create; begin inherited Create(True); FreeOnTerminate := True; Resume; end; type TThreadAutoLocal = class ( TThread ) protected procedure Execute; override; public constructor Create; end; {procedure TConnMgr.RefreshAuto(const aForce: Boolean = False); var S: String; I : Integer; sl, sl2 : TStrings; function Normalizesl2: String; var k, p: integer; begin Result := ''; for k := 0 to sl2.count-1 do begin p := Pos('@', sl2[k]); if Result>'' then Result := Result + sLineBreak; Result := Result + Copy(sl2[k], 1, P-1) + sLineBreak + Copy(sl2[k], P+1, 300); end; end; begin DebugMsg('TConnMsg.RefreshAuto 1'); if (not aForce) and (not ACIExpired) and FACIOk and ((GetTickCount-FLastRefresh)<120000) then Exit; DebugMsg('TConnMsg.RefreshAuto 2'); FLastRefresh := GetTickCount; sl := TStringList.Create; sl2 := TStringList.Create; try TThreadAutoRemote.Create; Sleep(500); sl.Text := ACIStr; FACIOk := (sl.Text>''); DebugMsg('TConnMsg.RefreshAuto 3 - Sl.Text: '+Sl.Text); try FrmPri.nxTCPIP.GetServerNames(sl2, 1500); except on E: Exception do DebugMsg('TConnMsg.RefreshAuto - Exception: '+E.Message); end; sl2.Text := Normalizesl2; DebugMsg('TConnMsg.RefreshAuto 4 - Sl2.Text: '+Sl2.Text); for I := 0 to sl2.Count-1 do if sl.IndexOf(sl2[I])=-1 then sl.Add(sl2[I]); DebugMsg('TConnMsg.RefreshAuto 5 - Sl.Text: '+Sl.Text); if sl.Count>0 then begin DebugMsg('TConnMsg.RefreshAuto 6 - Sl.Text: '+Sl.Text); FLastRefresh := GetTickCount; FAuto.Text := sl.Text; FAuto.SaveToFile(ArqAuto); DebugMsg('TConnMsg.RefreshAuto 7 - Sl.Text: '+Sl.Text); FLastConn := ''; FLastConnOk := False; end; finally sl.free; sl2.Free; end; end;} procedure TConnMgr.RefreshAutoInfo; begin TThreadAutoRemote.Create; TThreadAutoLocal.Create; end; procedure TConnMgr.SaveAuto; begin DebugMsg('TConnMgr.SaveAuto - ' + FAuto.Text); FAuto.SaveToFile(ArqAuto); end; procedure TConnMgr.SaveConfig; begin slConfig.Values['servidor'] := Servidor; ncaDM.SaveConfig; end; procedure TConnMgr.SetAutoRemote(const Value: String); begin FCS.Enter; try DebugMsg('TConnMgr.SetAutoRemote - Value: '+Value); if Value <> FAutoRemote.Text then begin FAutoRemote.Text := Value; MergeLocalAndRemote; end; finally FCS.Leave; end; end; procedure TConnMgr.SetAuto(const Value: Boolean); begin if Value then FServidor := 'auto'; end; procedure TConnMgr.SetLastConnOk(aServ: String); begin FLastConn := aServ; FLastConnOk := (aServ>''); end; procedure TConnMgr.SetAutoLocal(const Value: String); begin FCS.Enter; try DebugMsg('TConnMgr.SetAutoLocal - Value: '+Value); if Value <> FAutoLocal.Text then begin FAutoLocal.Text := Value; MergeLocalAndRemote; end; finally FCS.Leave; end; end; procedure TConnMgr.SetServidor(const Value: String); begin if Value='' then FServidor := 'auto' else FServidor := Value; end; procedure TConnMgr.wmUpdate(window: HWND; msg: cardinal; wParam, lParam: madTypes.NativeInt; var result: madTypes.NativeInt); begin try DebugMsg('TConnMgr.wmUpdate'); if FAuto.Text <> TStrings(wParam).Text then begin FAuto.Text := TStrings(wParam).Text; SaveAuto; if Assigned(FOnUpdate) then FOnUpdate(Self); end; finally try TObject(wParam).Free; except end; end; end; { TThreadAutoLocal } constructor TThreadAutoLocal.Create; begin inherited Create(True); FreeOnTerminate := True; Resume; end; procedure TThreadAutoLocal.Execute; var s : string; begin S := GetLocalServerNames; if S>'' then try gConnMgr.AutoLocal := S; except on E: Exception do DebugMsg('TThreadAutoLocal.Execute - Exception: ' + E.Message); end; end; initialization csRem := TCriticalSection.Create; csLoc := TCriticalSection.Create; gConnMgr := TConnMgr.Create; gConnMgr.RefreshAutoInfo; finalization if Assigned(gConnMgr) then FreeAndNil(gConnMgr); csRem.Free; csLoc.Free; end.
unit Threads.Sound; interface uses Windows, Threads.Base, Classes; type TGMSoundThread = class(TGMThread) private FAlarm: bool; FAlarmFileName: string; FAlarmSound: TMemoryStream; procedure SetAlarm(const Value: bool); procedure SetAlarmFileName(const Value: string); protected procedure SafeExecute(); override; public procedure Stop; property Alarm: bool read FAlarm write SetAlarm; property AlarmFileName: string read FAlarmFileName write SetAlarmFileName; constructor Create(); destructor Destroy; override; end; implementation uses GMMP3, MMSystem, SysUtils; { TGMSoundThread } procedure TGMSoundThread.Stop(); begin PlaySound(nil, 0, 0); end; constructor TGMSoundThread.Create; begin inherited Create(false); FAlarmSound := TMemoryStream.Create(); end; destructor TGMSoundThread.Destroy; begin Stop(); FAlarmSound.Free(); inherited; end; procedure TGMSoundThread.SafeExecute; begin while not Terminated do begin if FAlarm and (FAlarmSound.Size > 0) then PlaySound(FAlarmSound.Memory, 0, SND_MEMORY or SND_ASYNC or SND_NOSTOP) else Stop(); Sleep(50); end; PlaySound(nil, 0, 0); end; procedure TGMSoundThread.SetAlarm(const Value: bool); begin FAlarm := Value; if not FAlarm then Stop(); end; procedure TGMSoundThread.SetAlarmFileName(const Value: string); var b: bool; fs: TFileStream; begin if FAlarmFileName = Value then Exit; b := FAlarm; FAlarm := false; Stop(); FAlarmFileName := Value; FAlarmSound.Clear(); if (FAlarmFileName <> '') and FileExists(FAlarmFileName) then try fs := TFileStream.Create(FAlarmFileName, fmOpenRead or fmShareDenyNone); try ConvertMp3ToWav(fs, FAlarmSound); finally fs.Free(); end; except end; SetAlarm(b); end; end.
unit UnitTBotonesPermisos; interface uses SysUtils, ZDataset, ZConnection, Classes, frm_barra, Dialogs, Menus, DB, Buttons, AdvGlowButton,cxButtons; type ListaPermisos = record btnAdd: boolean; btnEdit: boolean; btnDelete: boolean; btnPrinter: boolean; sAlerta: string; end; TBotonesPermisos=class private pdbError: string; pError: boolean; pPermisos: ListaPermisos; pConexion: TZConnection; pGrupo: string; pModulo: string; pMenu: TPopupMenu; Owner: TComponent; pDataSet: TDataSet; ListaInsert: Array of TMenuItem; ListaEdit: Array of TMenuItem; ListaDelete: Array of TMenuItem; ListaPrint: Array of TMenuItem; OldBeforePost: Procedure(DataSet: TDataSet) of Object; OldBeforeDelete: Procedure(DataSet: TDataSet) of Object; function dbConsulta(sSQLCommand: string; paramNames, paramValues: TStringList): TZReadOnlyQuery; function adaptarMenu: boolean; function permisosMenu: boolean; function darAlerta: boolean; function permisoInsercion: boolean; function permisoEdicion: boolean; function permisoEliminacion: boolean; function permisoImpresion: boolean; procedure NewBeforePost(DataSet: TDataSet); procedure NewBeforeDelete(DataSet: TDataSet); public property agregar: boolean read permisoInsercion; property editar: boolean read permisoEdicion; property borrar: boolean read permisoEliminacion; property imprimir: boolean read permisoImpresion; property dbError:string read pdbError; constructor Create(AOwner: TComponent; Conexion: TZConnection; grupo, modulo: string; Menu: TPopupMenu = nil);overload; constructor Create(AOwner: TComponent; Conexion: TZConnection; grupo, modulo: string; DataSet: TDataSet);overload; function definirPermisos: boolean; function permisosBotones(barra: TfrmBarra): boolean; function permisosBotones2(btnAgr, btnEdt, btnBor, btnImp: TBitBtn): boolean; function permisosBotones3(btnAgr, btnEdt, btnBor, btnImp: TAdvGlowButton): boolean; end; implementation { TBotonesPermisos } function TBotonesPermisos.adaptarMenu: boolean; var ii: integer; begin result := true; if Assigned(pMenu) then begin try for ii := 0 to pMenu.Items.Count - 1 do begin if pMenu.Items[ii].Tag = 1 then//el numero asignado a los derechos de insercion es 1 begin SetLength(ListaInsert, Length(ListaInsert) + 1); ListaInsert[Length(ListaInsert) - 1] := pMenu.Items[ii]; end; if pMenu.Items[ii].Tag = 2 then//el numero asignado a los derechos de edicion es 2 begin SetLength(ListaEdit, Length(ListaEdit) + 1); ListaEdit[Length(ListaEdit) - 1] := pMenu.Items[ii]; end; if pMenu.Items[ii].Tag = 3 then//el numero asignado a los derechos de eliminacion es 3 begin SetLength(ListaDelete, Length(ListaDelete) + 1); ListaDelete[Length(ListaDelete) - 1] := pMenu.Items[ii]; end; if pMenu.Items[ii].Tag = 4 then//el numero asignado a los derechos de impresion es 4 begin SetLength(ListaPrint, Length(ListaPrint) + 1); ListaPrint[Length(ListaPrint) - 1] := pMenu.Items[ii]; end; end; except result := false; end; end; end; constructor TBotonesPermisos.Create(AOwner: TComponent; Conexion: TZConnection; grupo, modulo: string; Menu: TPopupMenu = nil); begin //asignar atributos Owner := AOwner; pConexion := Conexion; pGrupo := grupo; pModulo := modulo; pMenu := Menu; pdbError := ''; pError := False; //inicializar record pPermisos.btnAdd := True; pPermisos.btnEdit := True; pPermisos.btnDelete := True; pPermisos.btnPrinter := True; pPermisos.sAlerta := ''; //generar el record de permisos if not definirPermisos() then pError := True; if not adaptarMenu then pError := True; //if pPermisos.sAlerta <> '' then //darAlerta(); end; constructor TBotonesPermisos.Create(AOwner: TComponent; Conexion: TZConnection; grupo, modulo: string; DataSet: TDataSet); begin //asignar atributos Owner := AOwner; pConexion := Conexion; pGrupo := grupo; pModulo := modulo; pDataSet := DataSet; pdbError := ''; pError := False; //inicializar record pPermisos.btnAdd := True; pPermisos.btnEdit := True; pPermisos.btnDelete := True; pPermisos.btnPrinter := True; pPermisos.sAlerta := ''; //generar el record de permisos if not definirPermisos() then pError := True; //Administrar el evento befor post OldBeforePost := dataset.BeforePost; dataset.BeforePost := NewBeforePost; OldBeforeDelete := dataset.BeforeDelete; dataset.BeforeDelete := NewBeforeDelete; end; function TBotonesPermisos.darAlerta: boolean; var sSQL: string; ZQuery: TZReadOnlyQuery; paramNames, paramValues: TStringList; begin result := false; MessageDlg(pPermisos.sAlerta, mtWarning, [mbOk], 0); sSQL := 'UPDATE usuarios SET sAlerta = "" WHERE sIdUsuario = :usuario'; paramNames := TStringList.Create;paramNames.Add('usuario'); paramValues := TStringList.Create;paramValues.Add(pGrupo); ZQuery := dbConsulta(sSQL, paramNames, paramValues); ZQuery.Free; if pdbError = '' then result := true; end; function TBotonesPermisos.dbConsulta(sSQLCommand: string; paramNames, paramValues: TStringList): TZReadOnlyQuery; var ZQuery: TZReadOnlyQuery; ii: integer; begin pdbError := '';//reiniciar el error DB ZQuery := TZReadOnlyQuery.Create(Owner); //crear el componente ZQuery.Connection := pConexion; ZQuery.Active := false; ZQuery.SQL.Clear; ZQuery.SQL.Add(sSQLCommand);//agregar la instruccion if (paramNames <> nil) and (paramValues <> nil) then begin for ii := 0 to paramNames.Count - 1 do begin //agregar los parametros ZQuery.ParamByName(paramNames[ii]).Value := paramValues[ii]; end; end; try ZQuery.Open; except on E: exception do begin //se registra el error pdbError := E.Message; end; end; result := ZQuery; end; function TBotonesPermisos.definirPermisos: boolean; var sSQL: string; paramNames, paramValues: TStringList; ZQuery: TZReadOnlyQuery; prueba: TStrings; begin result := True; //consultar los permisos del usuario sSQL := 'SELECT eInsertar, eEditar, eEliminar, eImprimir ' + 'FROM gruposxprograma ' + 'WHERE sIdGrupo = :grupo AND sIdPrograma = :modulo'; paramNames := TStringList.Create;paramNames.Add('grupo');paramNames.Add('modulo'); paramValues := TStringList.Create;paramValues.Add(pGrupo);paramValues.Add(pModulo); ZQuery := dbConsulta(sSQL, paramNames, paramValues); //sino hay error if pdbError = '' then begin if ZQuery.RecordCount > 0 then begin pPermisos.btnAdd := ZQuery.FieldByName('eInsertar').AsString = 'Si'; pPermisos.btnEdit := ZQuery.FieldByName('eEditar').AsString = 'Si'; pPermisos.btnDelete := ZQuery.FieldByName('eEliminar').AsString = 'Si'; pPermisos.btnPrinter := ZQuery.FieldByName('eImprimir').AsString = 'Si'; ZQuery.Free; end else begin result := False; end; end else begin result := False; end; end; function TBotonesPermisos.permisosBotones(barra: TfrmBarra): boolean; begin result := not pError; if result then begin try if Assigned(barra) then begin if barra.btnAdd.Enabled then barra.btnAdd.Enabled := pPermisos.btnAdd; if barra.btnEdit.Enabled then barra.btnEdit.Enabled := pPermisos.btnEdit; if barra.btnDelete.Enabled then barra.btnDelete.Enabled := pPermisos.btnDelete; if barra.btnPrinter.Enabled then barra.btnPrinter.Enabled := pPermisos.btnPrinter; end; except result := False; end; permisosMenu; end; end; function TBotonesPermisos.permisosBotones2(btnAgr, btnEdt, btnBor, btnImp: TBitBtn): boolean; begin result := not pError; if result then begin try if Assigned(btnAgr) then begin if btnAgr.Enabled then btnAgr.Enabled := pPermisos.btnAdd; end; if Assigned(btnEdt) then begin if btnEdt.Enabled then btnEdt.Enabled := pPermisos.btnEdit; end; if Assigned(btnBor) then begin if btnBor.Enabled then btnBor.Enabled := pPermisos.btnDelete; end; if Assigned(btnImp) then begin if btnImp.Enabled then btnImp.Enabled := pPermisos.btnPrinter; end; except result := False; end; end; end; function TBotonesPermisos.permisosBotones3(btnAgr, btnEdt, btnBor, btnImp: TAdvGlowButton): boolean; begin result := not pError; if result then begin try if Assigned(btnAgr) then begin if btnAgr.Enabled then btnAgr.Enabled := pPermisos.btnAdd; end; if Assigned(btnEdt) then begin if btnEdt.Enabled then btnEdt.Enabled := pPermisos.btnEdit; end; if Assigned(btnBor) then begin if btnBor.Enabled then btnBor.Enabled := pPermisos.btnDelete; end; if Assigned(btnImp) then begin if btnImp.Enabled then btnImp.Enabled := pPermisos.btnPrinter; end; except result := False; end; end; end; function TBotonesPermisos.permisosMenu: boolean; var ii: integer; begin result := true; if Assigned(pMenu) then begin try for ii := 0 to Length(ListaInsert) - 1 do begin if ListaInsert[ii].Enabled then ListaInsert[ii].Enabled := pPermisos.btnAdd; end; for ii := 0 to Length(ListaEdit) - 1 do begin if ListaEdit[ii].Enabled then ListaEdit[ii].Enabled := pPermisos.btnEdit; end; for ii := 0 to Length(ListaDelete) - 1 do begin if ListaDelete[ii].Enabled then ListaDelete[ii].Enabled := pPermisos.btnDelete; end; for ii := 0 to Length(ListaPrint) - 1 do begin if ListaPrint[ii].Enabled then ListaPrint[ii].Enabled := pPermisos.btnPrinter; end; except result := false; end; end; end; procedure TBotonesPermisos.NewBeforePost(DataSet: TDataSet); begin if pDataSet.State = dsInsert then begin if pPermisos.btnAdd then begin if Assigned(OldBeforePost) then OldBeforePost(DataSet) end else begin abort; pDataSet.Cancel; end; end else if pDataSet.State = dsEdit then begin if pPermisos.btnEdit then begin if Assigned(OldBeforePost) then OldBeforePost(DataSet) end else begin abort; pDataSet.Cancel; end; end; end; procedure TBotonesPermisos.NewBeforeDelete(DataSet: TDataSet); begin if pPermisos.btnDelete then begin if Assigned(OldBeforeDelete) then OldBeforeDelete(DataSet) end else abort; end; function TBotonesPermisos.permisoInsercion: boolean; begin result := pPermisos.btnAdd; end; function TBotonesPermisos.permisoEdicion: boolean; begin result := pPermisos.btnEdit; end; function TBotonesPermisos.permisoEliminacion: boolean; begin result := pPermisos.btnDelete; end; function TBotonesPermisos.permisoImpresion: boolean; begin result := pPermisos.btnPrinter; end; end.
unit JD.Weather.ApiSvr; interface uses Winapi.Windows, Winapi.ActiveX, System.Classes, System.SysUtils, System.TypInfo, JD.Weather.Intf, JD.Weather.SuperObject, IdBaseComponent, IdComponent, IdCustomTCPServer, IdCustomHTTPServer, IdHTTPServer, IdContext, IdTCPConnection, IdYarn, Data.DB, Data.Win.ADODB; type TJDWeatherApiSvrThread = class; TLogEvent = procedure(Sender: TObject; const Timestamp: TDateTime; const Msg: String) of object; TWeatherContext = class(TIdServerContext) private FThread: TJDWeatherApiSvrThread; FDB: TADOConnection; FKey: WideString; FUserID: Integer; FLocType: WideString; FLoc1: WideString; FLoc2: WideString; FUnits: WideString; FDet: WideString; FDoc: TStringList; FWeather: IJDWeather; FServices: IWeatherMultiService; procedure HandleGet( ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); procedure HandleServiceList( ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); procedure HandleServiceSupport( ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); procedure HandleNoRequest( ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); procedure HandleConditions( ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); procedure HandleNoKey(ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); procedure HandleInvalidKey(ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); procedure HandleRequest(ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); public constructor Create(AConnection: TIdTCPConnection; AYarn: TIdYarn; AList: TIdContextThreadList = nil); override; destructor Destroy; override; procedure Log(const Msg: String); function NewQuery: TADOQuery; end; TJDWeatherApiSvrThread = class(TThread) private FLib: HMODULE; FCreateLib: TCreateJDWeather; FServer: TIdHTTPServer; FOnLog: TLogEvent; FLogTime: TDateTime; FLogMsg: String; FConnStr: String; procedure Init; procedure UnInit; procedure Process; procedure SvrCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); procedure SvrContextCreated(AContext: TIdContext); procedure SetConnStr(const Value: String); protected procedure Execute; override; procedure SYNC_OnLog; public constructor Create; reintroduce; destructor Destroy; override; procedure Log(const Msg: String); property OnLog: TLogEvent read FOnLog write FOnLog; property ConnStr: String read FConnStr write SetConnStr; end; implementation function StrToLocationType(const S: String): TWeatherLocationType; begin if SameText(S, '') then Result:= TWeatherLocationType.wlAutoIP else if SameText(S, 'city') then Result:= TWeatherLocationType.wlCityState else if SameText(S, 'coords') then Result:= TWeatherLocationType.wlCoords else if SameText(S, 'zip') then Result:= TWeatherLocationType.wlZip else if SameText(S, 'ip') then Result:= TWeatherLocationType.wlAutoIP else if SameText(S, 'countrycity') then Result:= TWeatherLocationType.wlCountryCity else if SameText(S, 'airport') then Result:= TWeatherLocationType.wlAirportCode else if SameText(S, 'pws') then Result:= TWeatherLocationType.wlPWS else Result:= TWeatherLocationType.wlAutoIP; end; function StrToUnits(const S: String): TWeatherUnits; begin if SameText(S, '') then Result:= wuImperial else if SameText(S, 'imperial') then Result:= wuImperial else if SameText(S, 'metric') then Result:= wuMetric else if SameText(S, 'kelvin') then Result:= wuKelvin else Result:= wuImperial; end; { TJDWeatherApiSvrThread } constructor TJDWeatherApiSvrThread.Create; begin inherited Create(True); end; destructor TJDWeatherApiSvrThread.Destroy; begin inherited; end; procedure TJDWeatherApiSvrThread.Init; var E: Integer; begin CoInitialize(nil); FServer:= TIdHTTPServer.Create(nil); FServer.ContextClass:= TWeatherContext; FServer.DefaultPort:= 8664; FServer.OnCommandGet:= Self.SvrCommandGet; FServer.OnContextCreated:= Self.SvrContextCreated; FServer.Active:= True; FLib:= LoadLibrary('JDWeather.dll'); if FLib <> 0 then begin FCreateLib:= GetProcAddress(FLib, 'CreateJDWeather'); if Assigned(FCreateLib) then begin try except on E: Exception do begin raise Exception.Create('Failed to create new instance of "IJDWeather": '+E.Message); end; end; end else begin raise Exception.Create('Function "CreateJDWeather" not found!'); end; end else begin E:= GetLastError; raise Exception.Create('Failed to load library "JDWeather.dll" with error code '+IntToStr(E)); end; end; procedure TJDWeatherApiSvrThread.Log(const Msg: String); begin FLogTime:= Now; FLogMsg:= Msg; Synchronize(SYNC_OnLog); end; procedure TJDWeatherApiSvrThread.UnInit; begin //FreeLibrary(FLib); FServer.Active:= False; FreeAndNil(FServer); CoUninitialize; end; procedure TJDWeatherApiSvrThread.Process; begin Sleep(10); end; procedure TJDWeatherApiSvrThread.Execute; begin while not Terminated do begin try Init; try while not Terminated do begin Process; end; finally Uninit; end; Sleep(10); except on E: Exception do begin //TODO end; end; end; end; procedure TJDWeatherApiSvrThread.SvrContextCreated(AContext: TIdContext); var C: TWeatherContext; Dir: String; begin C:= TWeatherContext(AContext); Dir:= ExtractFilePath(ParamStr(0)); C.FWeather:= FCreateLib(Dir); C.FThread:= Self; C.FDB.ConnectionString:= FConnStr; C.FDB.Connected:= True; end; procedure TJDWeatherApiSvrThread.SYNC_OnLog; begin if Assigned(FOnLog) then FOnLog(Self, FLogTime, FLogMsg); end; procedure TJDWeatherApiSvrThread.SetConnStr(const Value: String); begin FConnStr := Value; end; procedure TJDWeatherApiSvrThread.SvrCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var C: TWeatherContext; begin C:= TWeatherContext(AContext); C.HandleGet(ARequestInfo, AResponseInfo); end; { TWeatherContext } constructor TWeatherContext.Create(AConnection: TIdTCPConnection; AYarn: TIdYarn; AList: TIdContextThreadList); begin inherited; CoInitialize(nil); FDB:= TADOConnection.Create(nil); FDB.LoginPrompt:= False; FServices:= TWeatherMultiService.Create; FServices._AddRef; FDoc:= TStringList.Create; FWeather:= nil; end; destructor TWeatherContext.Destroy; begin if Assigned(FWeather) then begin FWeather._Release; FWeather:= nil; end; FServices._Release; FServices:= nil; FreeAndNil(FDoc); FDB.Connected:= False; FDB.Free; CoUninitialize; inherited; end; procedure TWeatherContext.HandleRequest( ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var X: Integer; D, T: String; P: Integer; Q: TADOQuery; begin Q:= NewQuery; try //Parse service list FWeather.Services.LoadServices(ExtractFilePath(ParamStr(0))); D:= ARequestInfo.Params.Values['s']+','; while Length(D) > 0 do begin P:= Pos(',', D); T:= Copy(D, 1, P-1); Delete(D, 1, P); for X := 0 to FWeather.Services.Count-1 do begin if SameText(FWeather.Services[X].Info.Name, T) then begin Q.Parameters.Clear; Q.SQL.Text:= 'select * from ServiceKeys where UserID = :u and ServiceID = (select ID from Services where Name = :s)'; Q.Parameters.ParamValues['u']:= FUserID; Q.Parameters.ParamValues['s']:= T; Q.Open; try FWeather.Services[X].Key:= Q.FieldByName('ApiKey').AsString; FWeather.Services[X].Units:= StrToUnits(FUnits); FWeather.LocationType:= StrToLocationType(FLocType); FWeather.LocationDetail1:= FLoc1; FWeather.LocationDetail2:= FLoc2; FServices.Add(FWeather.Services[X]); finally Q.Close; end; Break; end; end; end; if SameText(FDoc[1], 'services') then begin HandleServiceList(ARequestInfo, AResponseInfo); end else if SameText(FDoc[1], 'support') then begin HandleServiceSupport(ARequestInfo, AResponseInfo); end else if SameText(FDoc[1], 'conditions') then begin HandleConditions(ARequestInfo, AResponseInfo); end else begin HandleNoRequest(ARequestInfo, AResponseInfo); end; finally Q.Free; end; end; procedure TWeatherContext.HandleGet( ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var X: Integer; D, T: String; P: Integer; Q: TADOQuery; begin ARequestInfo.Params.Delimiter:= '&'; Log('GET '+ARequestInfo.RemoteIP+' - '+ARequestInfo.URI+'?'+ARequestInfo.Params.DelimitedText); //Read Params FLocType:= ARequestInfo.Params.Values['l']; FLoc1:= ARequestInfo.Params.Values['l1']; FLoc2:= ARequestInfo.Params.Values['l2']; FUnits:= ARequestInfo.Params.Values['u']; FDet:= ARequestInfo.Params.Values['d']; //Read Requested Document(s) FDoc.Clear; D:= ARequestInfo.Document; Delete(D, 1, 1); D:= D + '/'; while Length(D) > 0 do begin P:= Pos('/', D); T:= Copy(D, 1, P-1); Delete(D, 1, P); FDoc.Append(T); end; FServices.Clear; Q:= NewQuery; try if FDoc.Count > 0 then begin if FDoc.Count > 1 then begin FKey:= FDoc[0]; Q.SQL.Text:= 'select * from ApiKeys where ApiKey = :key and Status = 1'; Q.Parameters.ParamValues['key']:= FKey; Q.Open; try if not Q.IsEmpty then begin FUserID:= Q.FieldByName('UserID').AsInteger; HandleRequest(ARequestInfo, AResponseInfo); end else begin HandleInvalidKey(ARequestInfo, AResponseInfo); end; finally Q.Close; end; end else begin if SameText(FDoc[0], 'favicon.ico') then begin //TODO: Return favicon end else begin HandleNoKey(ARequestInfo, AResponseInfo); end; end; end else begin HandleNoRequest(ARequestInfo, AResponseInfo); end; finally Q.Free; end; end; procedure TWeatherContext.HandleServiceSupport( ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var Svc: IWeatherService; O, O2: ISuperObject; Loc: TWeatherLocationType; Inf: TWeatherInfoType; Uni: TWeatherUnits; Alt: TWeatherAlertType; Alp: TWeatherAlertProp; Fop: TWeatherPropType; Map: TWeatherMapType; begin O:= SO; try if FServices.Count > 0 then begin Svc:= FServices[0]; O.S['caption']:= Svc.Info.Caption; O.S['name']:= Svc.Info.Name; O.S['serviceuid']:= Svc.Info.UID; O2:= SA([]); try for Loc := Low(TWeatherLocationType) to High(TWeatherLocationType) do begin if Loc in Svc.Info.Support.SupportedLocations then O2.AsArray.Add(SO(GetEnumName(TypeInfo(TWeatherLocationType), Ord(Loc)))); end; finally O.O['supported_locations']:= O2; end; O2:= SA([]); try for Inf := Low(TWeatherInfoType) to High(TWeatherInfoType) do begin if Inf in Svc.Info.Support.SupportedInfo then O2.AsArray.Add(SO(GetEnumName(TypeInfo(TWeatherInfoType), Ord(Inf)))); end; finally O.O['supported_info']:= O2; end; O2:= SA([]); try for Uni := Low(TWeatherUnits) to High(TWeatherUnits) do begin if Uni in Svc.Info.Support.SupportedUnits then O2.AsArray.Add(SO(GetEnumName(TypeInfo(TWeatherUnits), Ord(Uni)))); end; finally O.O['supported_units']:= O2; end; O2:= SA([]); try for Alt := Low(TWeatherAlertType) to High(TWeatherAlertType) do begin if Alt in Svc.Info.Support.SupportedAlerts then O2.AsArray.Add(SO(GetEnumName(TypeInfo(TWeatherAlertType), Ord(Alt)))); end; finally O.O['supported_alerts']:= O2; end; O2:= SA([]); try for Alp := Low(TWeatherAlertProp) to High(TWeatherAlertProp) do begin if Alp in Svc.Info.Support.SupportedAlertProps then O2.AsArray.Add(SO(GetEnumName(TypeInfo(TWeatherAlertProp), Ord(Alp)))); end; finally O.O['supported_alert_props']:= O2; end; O2:= SA([]); try for Fop := Low(TWeatherPropType) to High(TWeatherPropType) do begin if Fop in Svc.Info.Support.SupportedForecastSummaryProps then O2.AsArray.Add(SO(GetEnumName(TypeInfo(TWeatherPropType), Ord(Fop)))); end; finally O.O['supported_forecast_summary_props']:= O2; end; O2:= SA([]); try for Fop := Low(TWeatherPropType) to High(TWeatherPropType) do begin if Fop in Svc.Info.Support.SupportedForecastHourlyProps then O2.AsArray.Add(SO(GetEnumName(TypeInfo(TWeatherPropType), Ord(Fop)))); end; finally O.O['supported_forecast_hourly_props']:= O2; end; O2:= SA([]); try for Fop := Low(TWeatherPropType) to High(TWeatherPropType) do begin if Fop in Svc.Info.Support.SupportedForecastDailyProps then O2.AsArray.Add(SO(GetEnumName(TypeInfo(TWeatherPropType), Ord(Fop)))); end; finally O.O['supported_forecast_daily_props']:= O2; end; O2:= SA([]); try for Map := Low(TWeatherMapType) to High(TWeatherMapType) do begin if Map in Svc.Info.Support.SupportedMaps then O2.AsArray.Add(SO(GetEnumName(TypeInfo(TWeatherMapType), Ord(Map)))); end; finally O.O['supported_maps']:= O2; end; end else begin O.S['error']:= 'No services were specified.'; end; finally AResponseInfo.ContentText:= O.AsJSon(True); AResponseInfo.ContentType:= 'text/json'; end; end; procedure TWeatherContext.Log(const Msg: String); begin if Assigned(FThread) then FThread.Log(Msg); end; function TWeatherContext.NewQuery: TADOQuery; begin Result:= TADOQuery.Create(nil); Result.Connection:= FDB; end; procedure TWeatherContext.HandleServiceList( ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var O, O2: ISuperObject; X: Integer; S: IWeatherService; begin O:= SO; try O.O['services']:= SA([]); for X := 0 to FWeather.Services.Count-1 do begin S:= FWeather.Services[X]; O2:= SO; try O2.S['caption']:= S.Info.Caption; O2.S['name']:= S.Info.Name; O2.S['uid']:= S.Info.UID; O2.S['url_main']:= S.Info.URLs.MainURL; O2.S['url_api']:= S.Info.URLs.ApiURL; O2.S['url_login']:= S.Info.URLs.LoginURL; O2.S['url_register']:= S.Info.URLs.RegisterURL; O2.S['url_legal']:= S.Info.URLs.LegalURL; finally O.O['services'].AsArray.Add(O2); end; end; finally AResponseInfo.ContentText:= O.AsJSon(True); AResponseInfo.ContentType:= 'text/json'; end; end; procedure TWeatherContext.HandleConditions( ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var O: ISuperObject; C: IWeatherProps; procedure ChkD(const N: String; Prop: TWeatherPropType; const V: Double); begin if Prop in C.Support then O.D[N]:= V; end; begin O:= SO; try C:= FServices.GetCombinedConditions; if Assigned(C) then begin { wpIcon: ; wpCaption: ; wpDescription: ; wpDetails: ; wpURL: ; wpStation: ; wpPropsMin: ; wpPropsMax: ; } O.S['timestamp']:= FormatDateTime('mm-dd-yyyy hh:nn AMPM', C.DateTime); O.S['caption']:= C.Caption; O.S['description']:= C.Description; O.S['details']:= C.Details; O.S['url']:= C.URL; O.S['station']:= C.Station; O.S['icon_url']:= ''; //TODO ChkD('temp', wpTemp, C.Temp); ChkD('temp_min', wpTempMin, C.TempMin); ChkD('temp_max', wpTempMax, C.TempMax); ChkD('feels_like', wpFeelsLike, C.FeelsLike); ChkD('feels_like_sun', wpFeelsLikeSun, C.FeelsLikeSun); ChkD('feels_like_shade', wpFeelsLikeShade, C.FeelsLikeShade); ChkD('rel_humidity', wpHumidity, C.Humidity); ChkD('visibility', wpVisibility, C.Visibility); ChkD('dew_point', wpDewPoint, C.DewPoint); ChkD('wind_dir', wpWindDir, C.WindDir); ChkD('wind_speed', wpWindSpeed, C.WindSpeed); ChkD('wind_gusts', wpWindGust, C.WindGusts); ChkD('wind_chill', wpWindChill, C.WindChill); ChkD('heat_index', wpHeatIndex, C.HeatIndex); ChkD('pressure', wpPressure, C.Pressure); ChkD('pressure_ground', wpPressureGround, C.PressureGround); ChkD('pressure_sea', wpPressureSea, C.PressureSea); ChkD('solar_radiation', wpSolarRad, C.SolarRad); ChkD('uv_index', wpUVIndex, C.UVIndex); ChkD('cloud_cover', wpCloudCover, C.CloudCover); ChkD('precip_amt', wpPrecipAmt, C.PrecipAmt); ChkD('rain_amt', wpRainAmt, C.RainAmt); ChkD('snow_amt', wpSnowAmt, C.SnowAmt); ChkD('ice_amt', wpIceAmt, C.IceAmt); ChkD('sleet_amt', wpSleetAmt, C.SleetAmt); ChkD('fog_amt', wpFogAmt, C.FogAmt); ChkD('storm_amt', wpStormAmt, C.StormAmt); ChkD('precip_pred', wpPrecipPred, C.PrecipPred); ChkD('rain_pred', wpRainPred, C.RainPred); ChkD('snow_pred', wpSnowPred, C.SnowPred); ChkD('ice_pred', wpIcePred, C.IcePred); ChkD('sleet_pred', wpSleetPred, C.SleetPred); ChkD('fog_pred', wpFogPred, C.FogPred); ChkD('storm_pred', wpStormPred, C.StormPred); ChkD('wet_bulb', wpWetBulb, C.WetBulb); ChkD('ceiling', wpCeiling, C.Ceiling); //ChkD('sunrise', wpSunrise, C); //ChkD('sunset', wpSunset, C); ChkD('daylight', wpDaylight, C.Daylight); end else begin O.S['error']:= 'Conditions object was not assigned!'; end; finally AResponseInfo.ContentText:= O.AsJSon(True); AResponseInfo.ContentType:= 'text/json'; end; end; procedure TWeatherContext.HandleInvalidKey( ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var O: ISuperObject; begin O:= SO; try O.S['error']:= 'Invalid API Key.'; finally AResponseInfo.ContentText:= O.AsJSon(True); AResponseInfo.ContentType:= 'text/json'; end; end; procedure TWeatherContext.HandleNoRequest( ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var O: ISuperObject; begin O:= SO; try O.S['error']:= 'No document was requested. Please include at least one document in the request.'; finally AResponseInfo.ContentText:= O.AsJSon(True); AResponseInfo.ContentType:= 'text/json'; end; end; procedure TWeatherContext.HandleNoKey( ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); var O: ISuperObject; begin O:= SO; try O.S['error']:= 'No API Key was specified.'; finally AResponseInfo.ContentText:= O.AsJSon(True); AResponseInfo.ContentType:= 'text/json'; end; end; end.
unit uModuleInterface; interface uses Classes, Graphics, uDSConfigInterface, uSecurityInterface; type IModuleInterface = interface(IInterface) ['{565323C5-D253-4A98-920E-A62BF4B12076}'] function GetToolBarCount: Integer; function GetToolBarGUID(Index: Integer): TGUID; function GetGUID: TGUID; function GetModuleName: WideString; // function GetucPath: WideString; // procedure SetucPath(const Value: WideString); // function GetdscPath: WideString; // procedure SetdscPath(const Value: WideString); procedure SetIDSConfig(const Value: IDSConfigInterface); function GetIDSConfig: IDSConfigInterface; function GetISecMod: IsmzInterface; procedure SetISecMod(const Value: IsmzInterface); procedure SetNotifyWindowHandle(const Value: THandle); function GetNotifyWindowHandle: THandle; function GetIToolBarList: IInterfaceList; function ModuleInitialize: Boolean; procedure ReleaseAllRefs; // procedure uMSInfo; function GetlStr: WideString; property ToolBarGUIDs[Index: Integer]: TGUID read GetToolBarGUID; property ToolBarCount: Integer read GetToolBarCount; property GUID : TGUID read GetGUID; // property dscPath : WideString read GetdscPath write SetdscPath; //dsc - Diana Studio Config // property ucPath: WideString read GetucPath write SetucPath; // uc - User Config property IDSConfig: IDSConfigInterface read GetIDSConfig write SetIDSConfig; property ModuleName: WideString read GetModuleName; property ISecMod: IsmzInterface read GetISecMod write SetISecMod; property NotifyWindowHandle: THandle read GetNotifyWindowHandle write SetNotifyWindowHandle; property IToolBarList: IInterfaceList read GetIToolBarList; end; IModuleContainerInterface = Interface(IInterface) ['{2058DC5E-E1D4-4AE4-BD35-E67C35ED8840}'] procedure SetGUID(const Value: TGUID); procedure SetIModule(const Value: IModuleInterface); function GetGUID: TGUID; function GetIModule: IModuleInterface; property GUID : TGUID read GetGUID write SetGUID; property IModule : IModuleInterface read GetIModule write SetIModule; End; implementation end.
unit fClinicWardMeds; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, fAutoSz, StdCtrls, ExtCtrls, ORCtrls,ORFn, rCore, uCore, oRNet, Math, VA508AccessibilityManager; type TfrmClinicWardMeds = class(TfrmAutoSz) stxtLine3: TStaticText; stxtLine2: TStaticText; stxtLine1: TStaticText; btnClinic: TButton; btnWard: TButton; procedure btnClinicClick(Sender: TObject); procedure btnWardClick(Sender: TObject); private { Private declarations } procedure StartLocationCheck; procedure rpcChangeOrderLocation(pOrderList:TStringList); procedure BuildMessage(MsgSw:string); function BuildOrderLocList(pOrderList:TStringList; pLocation:integer):TStringList; public { Public declarations } // passes order list and selected locations to rpc to be saved with order. procedure ClinicOrWardLocation(pOrderList:TStringList; pEncounterLoc: integer; pEncounterLocName: string; var RetLoc: integer); overload; // returns Location selected by user. function ClinicOrWardLocation(pEncounterLoc: integer):integer;overLoad; function rpcIsPatientOnWard(Patient: string): boolean; function SelectPrintLocation(pEncounterLoc:integer):integer; end; var frmClinicWardMeds: TfrmClinicWardMeds; ALocation,AWardLoc, AClinicLoc : integer; ASelectedLoc: integer; AName, ASvc, AWardName, AClinicName: string; AOrderLocList: TStringList; AMsgSw: string; const LOCATION_CHANGE_1 = 'This patient is currently admitted to ward'; LOCATION_CHANGE_2 = 'These orders are written at clinic'; LOCATION_CHANGE_3 = 'Where do you want the orders administered?'; //GE CQ9537 - Message text PRINT_LOCATION_1 = 'The patient has been admitted to Ward '; PRINT_LOCATION_2 = 'Should the orders be printed using the new location?'; LOC_PRINT_MSG = 'P'; LOC_MSG = 'L'; implementation uses fFrame; {$R *.dfm} //entry point function TfrmClinicWardMeds.ClinicOrWardLocation(pEncounterLoc:integer):integer; begin // Patient's current location AClinicLoc := pEncounterLoc; AClinicName := Encounter.LocationName; AMsgSw := LOC_MSG; StartLocationCheck; Result := ASelectedLoc; frmClinicWardMeds.Close; end; //entry point procedure TfrmClinicWardMeds.ClinicOrWardLocation(pOrderList:TStringList;pEncounterLoc:integer;pEncounterLocName:string; var RetLoc: integer); begin AClinicLoc := pEncounterLoc; AClinicName := pEncounterLocName; AOrderLocList := TStringList.create; AOrderLocList.Clear; AMsgSw := LOC_MSG; StartLocationCheck; if pOrderList.Count > 0 then begin rpcChangeOrderLocation(BuildOrderLocList(pOrderList, ASelectedLoc)); RetLoc := ASelectedLoc end; if Assigned(AOrderLocList) then FreeAndNil(AOrderLocList); frmClinicWardMeds.Close; end; // returns button selected by user - ward or clinic. print location //entry point - function TfrmClinicWardMeds.SelectPrintLocation(pEncounterLoc:integer):integer; begin AClinicLoc := pEncounterLoc; AMsgSw := LOC_PRINT_MSG; StartLocationCheck; Result := ASelectedLoc; frmClinicWardMeds.Close; end; procedure TfrmClinicWardMeds.StartLocationCheck; begin frmClinicWardMeds := TfrmClinicWardMeds.Create(Application); // ResizeFormToFont(TForm(frmClinicWardMeds)); CurrentLocationForPatient(Patient.DFN, ALocation, AName, ASvc); AWardLoc := ALocation; //current location AWardName := AName; // current location name if AMsgSW = LOC_PRINT_MSG then BuildMessage(AMsgSw) else if (ALocation > 0) and (ALocation <> AClinicLoc) then BuildMessage(AMsgSw); //Location has changed, patient admitted end; procedure TfrmClinicWardMeds.btnClinicClick(Sender: TObject); begin inherited; ASelectedLoc := AClinicLoc; frmClinicWardMeds.Close; end; procedure TfrmClinicWardMeds.btnWardClick(Sender: TObject); begin inherited; ASelectedLoc := AWardLoc; frmClinicWardMeds.Close; end; procedure TfrmClinicWardMeds.BuildMessage(MsgSw:string); var ALine1Len, ALine2Len, ALine3Len, ALongLine: integer; begin with frmClinicWardMeds do begin btnWard.Caption := 'Ward'; btnClinic.Caption := 'Clinic'; // message text if MsgSw = LOC_MSG then begin //AClinicName := 'this is my long test clinic Name'; stxtLine1.Caption := LOCATION_CHANGE_1 + ' :' + AWardName; stxtLine2.Caption := LOCATION_CHANGE_2+ ' :' + AClinicName; stxtLine3.Caption := LOCATION_CHANGE_3; end else begin stxtLine1.Caption := PRINT_LOCATION_1 + ':' + AWardName; stxtLine2.Caption := PRINT_LOCATION_2; stxtLine3.Caption := ''; end; stxtLine2.Left := stxtLine1.left; stxtLine3.Left := stxtLine1.left; ALine1Len := TextWidthByFont(frmClinicWardMeds.stxtLine1.Font.Handle, frmClinicWardMeds.stxtLine1.Caption); ALine2Len := TextWidthByFont(frmClinicWardMeds.stxtLine2.Font.Handle, frmClinicWardMeds.stxtLine2.Caption); ALine3Len := TextWidthByFont(frmClinicWardMeds.stxtLine3.Font.Handle, frmClinicWardMeds.stxtLine3.Caption)+25; ALongLine := Max(ALine1Len,ALine2Len); ALongLine := Max(ALine3Len,ALongLine); frmClinicWardMeds.Width := (ALongLine + frmClinicWardMeds.stxtLine1.Left + 15); end; frmClinicWardMeds.ShowModal; frmClinicWardMeds.Release; end; function TfrmClinicWardMeds.BuildOrderLocList(pOrderList:TStringList; pLocation:integer):TStringList; var i:integer; AOrderLoc: string; begin AOrderLocList.clear; for i := 0 to pOrderList.Count -1 do begin AOrderLoc := Piece(pOrderList.Strings[i],U,1) + U + IntToStr(pLocation); AOrderLocList.Add(AOrderLoc); end; Result := AOrderLocList; //return value end; procedure TfrmClinicWardMeds.rpcChangeOrderLocation(pOrderList:TStringList); begin // OrderIEN^Location^1 -- used to alter location if ward is selected RPC expected third value to determine if // order is an IMO order. If it is being called from here assumed IMO order. CallVistA('ORWDX CHANGE',[pOrderList, Patient.DFN, '1']); end; function TfrmClinicWardMeds.rpcIsPatientOnWard(Patient: string): boolean; var aStr: string; begin CallVistA('ORWDX1 PATWARD', [Patient], aStr); Result := (aStr = '1'); end; end.
unit uPageControlClose; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.ImageList, Vcl.ImgList, System.Actions, Vcl.ActnList, Vcl.Menus, Vcl.ComCtrls, Vcl.ToolWin, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Styles, Vcl.Themes; type TTabControlStyleHookBtnClose = class(TTabControlStyleHook) private FHotIndex : Integer; FWidthModified : Boolean; procedure WMMouseMove(var Message: TMessage); message WM_MOUSEMOVE; procedure WMLButtonUp(var Message: TWMMouse); message WM_LBUTTONUP; function GetButtonCloseRect(Index: Integer):TRect; strict protected procedure DrawTab(Canvas: TCanvas; Index: Integer); override; procedure MouseEnter; override; procedure MouseLeave; override; public constructor Create(AControl: TWinControl); override; end; implementation constructor TTabControlStyleHookBtnClose.Create(AControl: TWinControl); begin inherited; FHotIndex:=-1; FWidthModified:=False; end; procedure TTabControlStyleHookBtnClose.DrawTab(Canvas: TCanvas; Index: Integer); var Details: TThemedElementDetails; ButtonR: TRect; FButtonState: TThemedWindow; begin inherited; if (FHotIndex >= 0) and (Index = FHotIndex) then FButtonState := twSmallCloseButtonHot else if Index = TabIndex then FButtonState := twSmallCloseButtonNormal else FButtonState := twSmallCloseButtonDisabled; Details := StyleServices.GetElementDetails(FButtonState); ButtonR := GetButtonCloseRect(Index); if ButtonR.Bottom - ButtonR.Top > 0 then StyleServices.DrawElement(Canvas.Handle, Details, ButtonR); end; procedure TTabControlStyleHookBtnClose.WMLButtonUp(var Message: TWMMouse); var LPoint: TPoint; LIndex: Integer; begin LPoint := Message.Pos; for LIndex := 0 to TabCount - 1 do if PtInRect(GetButtonCloseRect(LIndex), LPoint) then begin if Control is TPageControl then begin TPageControl(Control).Pages[LIndex].Parent := nil; TPageControl(Control).Pages[LIndex].Free; end; break; end; end; procedure TTabControlStyleHookBtnClose.WMMouseMove(var Message: TMessage); var LPoint: TPoint; LIndex: Integer; LHotIndex: Integer; begin inherited; LHotIndex := -1; LPoint := TWMMouseMove(Message).Pos; for LIndex := 0 to TabCount - 1 do if PtInRect(GetButtonCloseRect(LIndex), LPoint) then begin LHotIndex := LIndex; break; end; if (FHotIndex <> LHotIndex) then begin FHotIndex := LHotIndex; Invalidate; end; end; function TTabControlStyleHookBtnClose.GetButtonCloseRect(Index: Integer): TRect; var FButtonState: TThemedWindow; Details: TThemedElementDetails; R, ButtonR: TRect; begin R := TabRect[Index]; if R.Left < 0 then Exit; if TabPosition in [tpTop, tpBottom] then begin if Index = TabIndex then InflateRect(R, 0, 2); end else if Index = TabIndex then Dec(R.Left, 2) else Dec(R.Right, 2); Result := R; FButtonState := twSmallCloseButtonNormal; Details := StyleServices.GetElementDetails(FButtonState); if not StyleServices.GetElementContentRect(0, Details, Result, ButtonR) then ButtonR := Rect(0, 0, 0, 0); Result.Left := Result.Right - (ButtonR.Width) - 5; Result.Width := ButtonR.Width; end; procedure TTabControlStyleHookBtnClose.MouseEnter; begin inherited; FHotIndex := -1; end; procedure TTabControlStyleHookBtnClose.MouseLeave; begin inherited; if FHotIndex >= 0 then begin FHotIndex := -1; Invalidate; end; end; end.
unit MediaProcessing.Common.Processor.FPS; interface uses SysUtils,Windows,Classes,MediaProcessing.Definitions,MediaProcessing.Global, MediaProcessing.Common.SettingsDialog.FPS,MediaProcessing.Common.Processor.CustomSettings; type TChangeFPSMode = (cfmNone,cfmAbsolute, cfmVIFrameOnly); TMediaProcessor_Fps<T: TfmMediaProcessingSettingsFps,constructor>=class (TMediaProcessor_CustomSettings<T>) protected FChangeFPSMode : TChangeFPSMode; FFPSValue: integer; FVIFramesOnly: boolean; //Process FPrevFrameTimeStampMs: int64; protected procedure SaveCustomProperties(const aWriter: IPropertiesWriter); override; procedure LoadCustomProperties(const aReader: IPropertiesReader); override; procedure OnLoadPropertiesToDialog(aDialog: T); override; procedure OnSavePropertiesFromDialog(aDialog: T); override; function Process_Fps(const aInFormat: TMediaStreamDataHeader): boolean; public constructor Create; override; destructor Destroy; override; end; implementation uses Controls,uBaseClasses; { TMediaProcessor_Fps } constructor TMediaProcessor_Fps<T>.Create; begin inherited; end; destructor TMediaProcessor_Fps<T>.Destroy; begin inherited; end; procedure TMediaProcessor_Fps<T>.LoadCustomProperties(const aReader: IPropertiesReader); begin inherited; FChangeFPSMode:=TChangeFPSMode(aReader.ReadInteger('FPS.ChangeMode',0)); FFPSValue:=aReader.ReadInteger('FPS.Value',25); FVIFramesOnly:=aReader.ReadBool('FPS.VIFramesOnly',false) end; procedure TMediaProcessor_Fps<T>.SaveCustomProperties(const aWriter: IPropertiesWriter); begin inherited; aWriter.WriteInteger('FPS.ChangeMode',integer(FChangeFPSMode)); aWriter.WriteInteger('FPS.Value',FFPSValue); aWriter.WriteBool ('FPS.VIFramesOnly',FVIFramesOnly); end; procedure TMediaProcessor_Fps<T>.OnLoadPropertiesToDialog(aDialog: T); begin aDialog.ckChangeFPS.Checked:=FChangeFPSMode<>cfmNone; aDialog.ckChangeFPSAbsolute.Checked:=FChangeFPSMode in [cfmAbsolute,cfmNone]; aDialog.ckFPSVIFramesOnly.Checked:=FChangeFPSMode=cfmVIFrameOnly; aDialog.edFPSValue.Value:=FFPSValue; end; procedure TMediaProcessor_Fps<T>.OnSavePropertiesFromDialog( aDialog: T); begin FChangeFPSMode:=cfmNone; if aDialog.ckChangeFPS.Checked then begin if aDialog.ckChangeFPSAbsolute.Checked then begin FChangeFPSMode:=cfmAbsolute; FFPSValue:=aDialog.edFPSValue.Value end else begin FChangeFPSMode:=cfmVIFrameOnly; end; end; end; function TMediaProcessor_Fps<T>.Process_Fps(const aInFormat: TMediaStreamDataHeader): boolean; var aMinDelta: double; begin result:=false; //Прореживание кадров if FChangeFPSMode=cfmVIFrameOnly then begin if not (ffKeyFrame in aInFormat.biFrameFlags) then exit; end else if FChangeFPSMode=cfmAbsolute then begin if (FPrevFrameTimeStampMs<>0) then begin aMinDelta:=1000/FFPSValue; if (aInFormat.TimeStampMs-FPrevFrameTimeStampMs)<aMinDelta then exit; end; end; FPrevFrameTimeStampMs:=aInFormat.TimeStampMs; result:=true; end; end.
program Celsius_to_Fahrenheit; var i, Celsius, Fahrenheit : Word; begin Writeln('Таблица соотвествия между температурамми шкалами'); Writeln('Цельсия и Фаренгейта'); Writeln; for i := 0 to 20 do begin Celsius := 5 * i; Fahrenheit := 32 + Celsius * 9 div 5; Write(' C = ', Celsius); Write(' F = ', Fahrenheit); Writeln; end; Writeln('Нажмите <Enter>'); Readln; end.
unit UFrmAgendaVacina; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UFrmCRUD, Menus, Buttons, StdCtrls, ExtCtrls , URepositorioProximaVacina , URegraCrudProximaVacina , UProximaVacina , UUtilitarios , UDM , Mask, Grids, DBGrids, DBXFirebird, FMTBcd, DB, DBClient, Provider, SqlExpr ; type TFrmAgendaVacina = class(TFrmCRUD) gbProximaVacina: TGroupBox; edSusRetorno: TLabeledEdit; edNomeRetorno: TLabeledEdit; edDataRetorno: TMaskEdit; cbVacinaRetorno: TComboBox; cbDoseRetorno: TComboBox; lbData: TLabel; lbDose: TLabel; lbVacina: TLabel; procedure FormCreate(Sender: TObject); protected FProximaVacina: TProximaVacina; FRepositorioProximaVacina : TRepositorioProximaVacina; FRegraCRUDProximaVacina: TRegraCRUDProximaVacina; procedure Inicializa; override; procedure PreencheEntidade; override; procedure PreencheFormulario; override; procedure PosicionaCursorPrimeiroCampo; override; procedure HabilitaCampos(const ceTipoOperacaoUsuario: TTipoOperacaoUsuario); override; end; var FrmAgendaVacina: TFrmAgendaVacina; implementation uses UOpcaoPesquisa , UEntidade , UFrmPesquisa , UDialogo ; const CNT_SELECIONA_VAC_RETORNO = 'select vacina from vacina_nova group by Vacina'; CNT_SELECIONA_DOSE_RETORNO = 'select dose from vacina_nova group by dose'; {$R *.dfm} { TFrmAgendaVacina } procedure TFrmAgendaVacina.FormCreate(Sender: TObject); begin inherited; dmEntra21.SQLSelect.Close; dmEntra21.SQLSelect.CommandText := CNT_SELECIONA_VAC_RETORNO; dmEntra21.SQLSelect.Open; while not dmEntra21.SQLSelect.Eof do begin cbVacinaRetorno.Items.Add(dmEntra21.SQLSelect.FieldByName('vacina').AsString); dmEntra21.SQLSelect.Next; end; dmEntra21.SQLSelect.Close; dmEntra21.SQLSelect.CommandText := CNT_SELECIONA_DOSE_RETORNO; dmEntra21.SQLSelect.Open; while not dmEntra21.SQLSelect.Eof do begin cbDoseRetorno.Items.Add(dmEntra21.SQLSelect.FieldByName('Dose').AsString); dmEntra21.SQLSelect.Next; end; dmEntra21.SQLSelect.Close; end; procedure TFrmAgendaVacina.HabilitaCampos( const ceTipoOperacaoUsuario: TTipoOperacaoUsuario); begin inherited; gbProximaVacina.Enabled := FTipoOperacaoUsuario In [touInsercao, touAtualizacao]; end; procedure TFrmAgendaVacina.Inicializa; begin inherited; DefineEntidade(@FPROXIMAVACINA, TPROXIMAVACINA); DefineRegraCRUD(@FregraCRUDPROXIMAVACINA, TRegraCRUDPROXIMAVACINA); AdicionaOpcaoPesquisa(TOpcaoPesquisa .Create .AdicionaFiltro(FLD_NOME) .DefineNomeCampoRetorno(FLD_ENTIDADE_ID) .DefineNomePesquisa(STR_PROX_VACINA) .DefineVisao(TBL_PROX_VACINA)); end; procedure TFrmAgendaVacina.PosicionaCursorPrimeiroCampo; begin inherited; edNomeRetorno.SetFocus; end; procedure TFrmAgendaVacina.PreencheEntidade; begin inherited; FPROXIMAVACINA.SUS_CODIGO := edSusRetorno.Text; FPROXIMAVACINA.NOME := edNomeRetorno.Text; FPROXIMAVACINA.DATA_RETORNO := StrToDate(edSusRetorno.Text); FPROXIMAVACINA.VACINA_RETORNO := cbVacinaRetorno.Text; FPROXIMAVACINA.DOSE := cbDoseRetorno.Text; end; procedure TFrmAgendaVacina.PreencheFormulario; begin inherited; edSusRetorno.Text := FPROXIMAVACINA.SUS_CODIGO; edNomeRetorno.Text := FPROXIMAVACINA.NOME ; edDataRetorno.Text := DateToStr(FPROXIMAVACINA.DATA_RETORNO); cbVacinaRetorno.Text := FPROXIMAVACINA.VACINA_RETORNO ; cbDoseRetorno.Text := FPROXIMAVACINA.DOSE; end; end.
unit Form.SQLMonitoring; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, Form.BaseForm, cxLookAndFeelPainters, cxContainer, cxEdit, dxSkinsCore, dxSkinMetropolis, cxTextEdit, cxMemo, dxBevel, cxClasses, dxSkinsForm, Vcl.Menus, Vcl.StdCtrls, cxButtons, Vcl.ExtCtrls, System.Generics.Collections, Aurelius.Drivers.Interfaces, Aurelius.Commands.Listeners, System.ImageList, Vcl.ImgList, cxCheckBox, Aurelius.Events.Manager, Aurelius.Mapping.Explorer; type TfrmSQLMonitoring = class(TfrmBase) mmoLog: TcxMemo; pnlButton: TPanel; btnClear: TcxButton; chkEnableMonitor: TcxCheckBox; procedure btnClearClick(Sender: TObject); procedure chkEnableMonitorClick(Sender: TObject); private class var FInstance: TfrmSqlMonitoring; private FSqlExecutingProc: TSQLExecutingProc; procedure SqlExecutingHandler(Args: TSQLExecutingArgs); private procedure Log(const S: string); procedure BreakLine; procedure SubscribeListeners; procedure UnsubscribeListeners; public class function GetInstance: TfrmSQLMonitoring; constructor Create(AOwner: TComponent); override; end; implementation {$R *.dfm} { TfrmSQLMonitoring } procedure TfrmSQLMonitoring.BreakLine; begin mmoLog.Lines.Add('================================================'); end; procedure TfrmSQLMonitoring.btnClearClick(Sender: TObject); begin mmoLog.Clear; end; procedure TfrmSQLMonitoring.chkEnableMonitorClick(Sender: TObject); begin if chkEnableMonitor.Checked then SubscribeListeners else UnsubscribeListeners; end; constructor TfrmSQLMonitoring.Create(AOwner: TComponent); begin inherited; FSqlExecutingProc := SqlExecutingHandler; SubscribeListeners; end; class function TfrmSQLMonitoring.GetInstance: TfrmSQLMonitoring; begin if FInstance = nil then FInstance := TfrmSQLMonitoring.Create(Application); Result := FInstance; end; procedure TfrmSQLMonitoring.Log(const S: string); begin mmoLog.Lines.Add(S); end; procedure TfrmSQLMonitoring.SqlExecutingHandler(Args: TSQLExecutingArgs); var Param: TDBParam; begin Log(Args.SQL); if Args.Params <> nil then for Param in Args.Params do Log(Param.ToString); BreakLine; end; procedure TfrmSQLMonitoring.SubscribeListeners; var E: TManagerEvents; begin E := TMappingExplorer.Default.Events; E.OnSQLExecuting.Subscribe(FSqlExecutingProc); end; procedure TfrmSQLMonitoring.UnsubscribeListeners; var E: TManagerEvents; begin E := TMappingExplorer.Default.Events; E.OnSqlExecuting.Unsubscribe(FSqlExecutingProc); end; end.
unit uCommandHandler; interface uses uTokenizer, Contnrs, Classes, dmConnection; type TCommandHandler = class public function HandleCommand(const AConnection: TConnectionData; const ATarget: string; const ATokenizer: TTokenizer): string; virtual; abstract; end; TCommandHandlerClass = class of TCommandHandler; TCommandHandlerFactory = class private FCommandList: TStrings; FClassList: TList; FObjectList: TObjectList; class var FInstance: TCommandHandlerFactory; function GetCommandHandler(const AClass: TCommandHandlerClass): TCommandHandler; public class function GetInstance: TCommandHandlerFactory; procedure RegisterClass(const ACommand: string; const AClass: TCommandHandlerClass); constructor Create; virtual; destructor Destroy; override; procedure HandleCommand(const AConnection: TConnectionData; const ACommand, ATarget: string; const ATokenizer: TTokenizer); end; implementation uses SysUtils; { TCommandHandlerFactory } constructor TCommandHandlerFactory.Create; begin //this is a singleton class and should be accessed via GetInstance if Assigned(TCommandHandlerFactory.FInstance) then raise Exception.Create('Use GetInstance to retrieve an instance of TCommandHandlerFactory.'); FClassList := TList.Create; FObjectList := TObjectList.Create; FCommandList := TStringList.Create; end; destructor TCommandHandlerFactory.Destroy; begin FCommandList.Free; FObjectList.Free; FClassList.Free; inherited; end; class function TCommandHandlerFactory.GetInstance: TCommandHandlerFactory; begin if not Assigned(FInstance) then FInstance := TCommandHandlerFactory.Create; Result := FInstance; end; procedure TCommandHandlerFactory.HandleCommand(const AConnection: TConnectionData; const ACommand, ATarget: string; const ATokenizer: TTokenizer); var I: Integer; Handler: TCommandHandler; Handled: Boolean; Line: string; begin Handled := False; for I := 0 to FCommandList.Count - 1 do begin if SameText(FCommandList[I], ACommand) then begin Handler := GetCommandHandler(TCommandHandlerClass(FClassList[I])); Handler.HandleCommand(AConnection, ATarget, ATokenizer); Handled := True; end; end; if not Handled then begin Line := Copy(ACommand, 2, Length(ACommand) - 1); while ATokenizer.HasMoreTokens do begin Line := Line + ' ' + ATokenizer.NextToken; end; AConnection.SendRaw(Line); end; end; function TCommandHandlerFactory.GetCommandHandler(const AClass: TCommandHandlerClass): TCommandHandler; var I: Integer; begin //try to find an object in our pool for I := 0 to FObjectList.Count - 1 do begin if TCommandHandler(FObjectList[I]) is AClass then begin Result := TCommandHandler(FObjectList[I]); Exit; end; end; //create our object and add it to our pool Result := AClass.Create; FObjectList.Add(Result); end; procedure TCommandHandlerFactory.RegisterClass(const ACommand: string; const AClass: TCommandHandlerClass); begin FCommandList.Add(ACommand); FClassList.Add(AClass); end; initialization finalization TCommandHandlerFactory.FInstance.Free; end.
unit Initializer; interface uses Forms, SysUtils, StdCtrls, ExtCtrls, Windows, Classes, Graphics, Controls, WinCodec, OS.EnvironmentVariable, Global.LanguageString, Getter.OS.Version; procedure InitializeMainForm; procedure RefreshOptimizeList; implementation uses Form.Main; type THackControl = class(TControl); THackMainForm = class(TfMain); TMainformInitializer = class public constructor Create(MainformToInitialize: TfMain); procedure InitializeMainform; private const LogoPath = 'Image\logo.png'; BackgroundPath = 'Image\bg.png'; private Mainform: THackMainForm; procedure RefreshOptimizeList; procedure LoadBackground; procedure LoadIcons; procedure SetFormSize; procedure SetIcon; procedure AddButtonsToButtonGroup; procedure SetMessageFontAsApplicationFont; procedure FixFontToApplicationFont; procedure FixMainformSize; procedure LoadLogoImage; procedure LoadAndProportionalStretchLogo; procedure LoadAndProportionalStretchLogoXP; function StretchImage(ImagePath: String; NewWidth, NewHeight: Integer): TPersistent; procedure LoadAndProportionalStretchBackground; procedure LoadAndProportionalStretchBackgroundXP; end; procedure InitializeMainForm; var MainformInitializer: TMainformInitializer; begin MainformInitializer := TMainformInitializer.Create(fMain); MainformInitializer.InitializeMainform; FreeAndNil(MainformInitializer); end; procedure RefreshOptimizeList; var MainformInitializer: TMainformInitializer; begin MainformInitializer := TMainformInitializer.Create(fMain); MainformInitializer.RefreshOptimizeList; FreeAndNil(MainformInitializer); end; { TMainformInitializer } constructor TMainformInitializer.Create(MainformToInitialize: TfMain); begin Mainform := THackMainForm(MainformToInitialize); end; procedure TMainformInitializer.InitializeMainform; begin AddButtonsToButtonGroup; LoadBackground; LoadLogoImage; LoadIcons; SetFormSize; SetIcon; RefreshOptimizeList; SetMessageFontAsApplicationFont; FixFontToApplicationFont; FixMainformSize; end; procedure TMainformInitializer.AddButtonsToButtonGroup; begin Mainform.AddEntryToButtonGroup( False, Mainform.iFirmUp, Mainform.lFirmUp, Mainform.gFirmware, nil); Mainform.AddEntryToButtonGroup( False, Mainform.iErase, Mainform.lErase, Mainform.gErase, nil); Mainform.AddEntryToButtonGroup( False, Mainform.iAnalytics, Mainform.lAnalytics, Mainform.gAnalytics, nil); Mainform.AddEntryToButtonGroup( False, Mainform.iTrim, Mainform.lTrim, Mainform.gTrim, nil); Mainform.AddEntryToButtonGroup( False, Mainform.iOptimize, Mainform.lOptimize, Mainform.gOpt, nil); end; procedure TMainformInitializer.SetFormSize; begin Mainform.Constraints.MaxHeight := 0; Mainform.Constraints.MinHeight := 0; Mainform.ClientHeight := MinimumSize; Mainform.Constraints.MaxHeight := Mainform.Height; Mainform.Constraints.MinHeight := Mainform.Height; end; procedure TMainformInitializer.SetIcon; begin Mainform.Icon := Application.Icon; end; procedure TMainformInitializer.RefreshOptimizeList; var CurrItem: Integer; begin Mainform.lList.Items.Assign(Mainform.GetOptimizer.GetDescriptions); for CurrItem := 0 to (Mainform.GetOptimizer.GetDescriptions.Count - 1) do begin Mainform.lList.Checked[CurrItem] := (not Mainform.GetOptimizer.GetApplied[CurrItem]) and (not Mainform.GetOptimizer.GetIsOptional[CurrItem]); if Mainform.GetOptimizer.GetApplied[CurrItem] then Mainform.lList.Items[CurrItem] := Mainform.lList.Items[CurrItem] + CapAlreadyCompleted[CurrLang]; end; end; procedure TMainformInitializer.SetMessageFontAsApplicationFont; begin Application.DefaultFont := Screen.MessageFont; end; procedure TMainformInitializer.FixFontToApplicationFont; procedure SetFontName(Control: TControl; const FontName: String); begin THackControl(Control).Font.Name := FontName; end; var CurrCompNum: Integer; CurrComponent: TComponent; begin Mainform.Font.Name := Application.DefaultFont.Name; for CurrCompNum := 0 to Mainform.ComponentCount - 1 do begin CurrComponent := Mainform.Components[CurrCompNum]; if CurrComponent is TControl then SetFontName(TControl(CurrComponent), Mainform.Font.Name); end; end; procedure TMainformInitializer.FixMainformSize; begin Mainform.Constraints.MaxWidth := Mainform.Width; Mainform.Constraints.MaxHeight := Mainform.Height; Mainform.Constraints.MinWidth := Mainform.Width; Mainform.Constraints.MinHeight := Mainform.Height; end; function TMainformInitializer.StretchImage(ImagePath: String; NewWidth, NewHeight: Integer): TPersistent; var ImageToStretch: TWICImage; Scaler: IWICBitmapScaler; ScaledImage: IWICBitmap; begin if fMain.WICImage <> nil then ImageToStretch := fMain.WICImage else ImageToStretch := TWICImage.Create; ImageToStretch.LoadFromFile(ImagePath); ImageToStretch.ImagingFactory.CreateBitmapScaler (Scaler); Scaler.Initialize(ImageToStretch.Handle, NewWidth, NewHeight, WICBitmapInterpolationModeFant); ImageToStretch.ImagingFactory.CreateBitmapFromSourceRect( Scaler, 0, 0, NewWidth, NewHeight, ScaledImage); ImageToStretch.Handle := ScaledImage; result := ImageToStretch; fMain.WICImage := ImageToStretch; end; procedure TMainformInitializer.LoadAndProportionalStretchBackgroundXP; begin fMain.iBG.Proportional := true; if FileExists(EnvironmentVariable.AppPath + BackgroundPath) then fMain.iBG.Picture.LoadFromFile( EnvironmentVariable.AppPath + BackgroundPath); end; procedure TMainformInitializer.LoadAndProportionalStretchBackground; begin fMain.iBG.Picture.Bitmap.Assign( StretchImage(EnvironmentVariable.AppPath + BackgroundPath, fMain.ClientWidth, fMain.ClientHeight)); end; procedure TMainformInitializer.LoadBackground; begin if VersionHelper.Version.FMajorVer = 5 then LoadAndProportionalStretchBackgroundXP else LoadAndProportionalStretchBackground; end; procedure TMainformInitializer.LoadIcons; const FirmUpPath = 'Image\firmup.png'; ErasePath = 'Image\erase.png'; OptimizePath = 'Image\optimize.png'; TrimPath = 'Image\trim.png'; HelpPath = 'Image\help.png'; AnalyticsPath = 'Image\analytics.png'; begin if FileExists(EnvironmentVariable.AppPath + FirmUpPath) then fMain.iFirmUp.Picture.LoadFromFile( EnvironmentVariable.AppPath + FirmUpPath); if FileExists(EnvironmentVariable.AppPath + ErasePath) then fMain.iErase.Picture.LoadFromFile( EnvironmentVariable.AppPath + ErasePath); if FileExists(EnvironmentVariable.AppPath + OptimizePath) then fMain.iOptimize.Picture.LoadFromFile( EnvironmentVariable.AppPath + OptimizePath); if FileExists(EnvironmentVariable.AppPath + TrimPath) then fMain.iTrim.Picture.LoadFromFile( EnvironmentVariable.AppPath + TrimPath); if FileExists(EnvironmentVariable.AppPath + HelpPath) then fMain.iHelp.Picture.LoadFromFile( EnvironmentVariable.AppPath + HelpPath); if FileExists(EnvironmentVariable.AppPath + AnalyticsPath) then fMain.iAnalytics.Picture.LoadFromFile( EnvironmentVariable.AppPath + AnalyticsPath); end; procedure TMainformInitializer.LoadAndProportionalStretchLogo; begin fMain.iLogo.Picture.Bitmap.Assign( StretchImage(EnvironmentVariable.AppPath + LogoPath, fMain.iLogo.Width, fMain.iLogo.Height)); end; procedure TMainformInitializer.LoadAndProportionalStretchLogoXP; begin fMain.iLogo.Proportional := true; if FileExists(EnvironmentVariable.AppPath + LogoPath) then fMain.iLogo.Picture.LoadFromFile(EnvironmentVariable.AppPath + LogoPath); end; procedure TMainformInitializer.LoadLogoImage; begin if VersionHelper.Version.FMajorVer = 5 then LoadAndProportionalStretchLogoXP else LoadAndProportionalStretchLogo; end; end.
unit Security.Matrix.Interfaces; interface Type TMatrixNotifyEvent = procedure(aID: Int64; aName: String; aEmail: String; aActive: Boolean; aPassword: String; aMatrixID: Integer; aIsMatrix: Boolean; var aError: string; var aChanged: Boolean) of Object; TResultNotifyEvent = procedure(const aResult: Boolean = false) of Object; Type iPrivateMatrixEvents = interface ['{3023A08C-1ED5-4A65-B127-1FF9D340EB3B}'] { Strict private declarations } procedure setID(Value: Int64); function getID: Int64; function getUpdatedAt: TDateTime; procedure setUpdatedAt(const Value: TDateTime); procedure setNameMatrix(Value: String); function getNameMatrix: String; procedure setEmail(Value: String); function getEmail: String; procedure setActive(Value: Boolean); function getActive: Boolean; procedure setPassword(Value: String); function getPassword: String; procedure setMatrixID(Value: Integer); function getMatrixID: Integer; procedure setIsMatrix(Value: Boolean); function getIsMatrix: Boolean; procedure setOnMatrix(const Value: TMatrixNotifyEvent); function getOnMatrix: TMatrixNotifyEvent; procedure setOnResult(const Value: TResultNotifyEvent); function getOnResult: TResultNotifyEvent; end; iMatrixViewEvents = interface(iPrivateMatrixEvents) ['{7F0739A8-F041-4DBB-8A3C-235C8FE5325A}'] { Published declarations - Properties } property ID: Int64 read getID write setID; property UpdatedAt: TDateTime read getUpdatedAt write setUpdatedAt; property NameMatrix: String read getNameMatrix write setNameMatrix; property Email: String read getEmail write setEmail; property Active: Boolean read getActive write setActive; property Password: String read getPassword write setPassword; property MatrixID: Integer read getMatrixID write setMatrixID; property IsMatrix: Boolean read getIsMatrix write setIsMatrix; { Published declarations - Events } property OnMatrix: TMatrixNotifyEvent read getOnMatrix write setOnMatrix; property OnResult: TResultNotifyEvent read getOnResult write setOnResult; end; iPrivateMatrixViewProperties = interface ['{E58223C7-8FCF-48C4-B2EB-D93EB6FB84ED}'] { Private declarations } function getComputerIP: string; function getServerIP: string; function getSigla: string; function getUpdatedAt: string; function getVersion: string; procedure setComputerIP(const Value: string); procedure setServerIP(const Value: string); procedure setSigla(const Value: string); procedure setUpdatedAt(const Value: string); procedure setVersion(const Value: string); end; iMatrixViewProperties = interface(iPrivateMatrixViewProperties) ['{487E4F2B-62DD-4353-AC0C-7E43CB4FDA8C}'] { Public declarations } property ComputerIP: string read getComputerIP write setComputerIP; property ServerIP: string read getServerIP write setServerIP; property Sigla: string read getSigla write setSigla; property Version: string read getVersion write setVersion; property UpdatedAt: string read getUpdatedAt write setUpdatedAt; end; iMatrixView = interface ['{134C82E6-CCD9-4C0C-BB57-6A2E978CBEA2}'] // function Properties: iPermissionViewProperties; function Events: iMatrixViewEvents; end; implementation end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { } { Implementation Notification Center for Android } { } { Copyright(c) 2013-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit System.Android.Notification; interface {$SCOPEDENUMS ON} uses System.Notification; /// <summary>Common ancestor used to instantiate platform implementation</summary> type TPlatformNotificationCenter = class(TBaseNotificationCenter) protected class function GetInstance: TBaseNotificationCenter; override; end; implementation uses System.SysUtils, System.DateUtils, System.Classes, System.Messaging, System.TimeSpan, Androidapi.JNI.Embarcadero, Androidapi.JNI.App, Androidapi.JNI.Support, Androidapi.JNI.JavaTypes, Androidapi.JNI.Media, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNIBridge, Androidapi.JNI.Net, Androidapi.Helpers; type { TNotificationCenterAndroid } TAndroidPreferenceAdapter = class strict private FPreference: JSharedPreferences; function FindNotification(const AName: string; out AIndex: Integer; out AID: Integer): Boolean; function ExtractName(const AStr: string): string; function ExtractID(const AStr: string): Integer; public constructor Create; destructor Destroy; override; procedure SaveNotification(const ANotification: TNotification; const AID: Integer); procedure RemoveNotification(const AName: string); function IndexOf(const AName: string): Integer; function Find(const AName: string; out Index: Integer): Boolean; function GetID(const AName: string): Integer; function Contains(const AName: string): Boolean; function GetAllNotificationsNames: TStringList; end; TNotificationCenterAndroid = class(TPlatformNotificationCenter) private class var FNotificationCenterSingleton: TNotificationCenterAndroid; strict private FExternalStore: TAndroidPreferenceAdapter; FNotificationManager: JNotificationManager; function CreateNativeNotification(const ANotification: TNotification): JNotification; procedure SaveNotificationIntoIntent(var AIntent: JIntent; const ANotification: TNotification; const AID: Integer = -1); function LoadNotificationFromIntent(const AIntent: JIntent): TNotification; function CreateChannel(const AChannel: JNotificationChannel): TChannel; overload; function CreateChannel(const AChannel: TChannel): JNotificationChannel; overload; procedure CancelScheduledNotification(const AName: string); { Global FMX event } procedure DidFormsLoad; procedure DidReceiveNotification(const Sender: TObject; const M: TMessage); class function GetNotificationCenter: TNotificationCenterAndroid; static; class destructor Destroy; public constructor Create; destructor Destroy; override; procedure DoScheduleNotification(const ANotification: TNotification); override; procedure DoPresentNotification(const ANotification: TNotification); override; procedure DoCancelNotification(const AName: string); overload; override; procedure DoCancelNotification(const ANotification: TNotification); overload; override; procedure DoCancelAllNotifications; override; procedure DoCreateOrUpdateChannel(const AChannel: TChannel); override; procedure DoDeleteChannel(const AChannelId: string); override; procedure DoGetAllChannels(const AChannels: TChannels); override; { Not supported } procedure DoSetIconBadgeNumber(const ACount: Integer); override; function DoGetIconBadgeNumber: Integer; override; procedure DoResetIconBadgeNumber; override; procedure DoLoaded; override; class property NotificationCenter: TNotificationCenterAndroid read GetNotificationCenter; end; TGeneratorUniqueID = class const SettingsNotificationUniquiID = 'SETTINGS_NOTIFICATION_UNIQUE_ID'; strict private class var FNextUniqueID: Int64; class var FPreference: JSharedPreferences; public class constructor Create; class function GenerateID: Integer; end; function GetNotificationService: JNotificationManager; var NotificationServiceNative: JObject; begin NotificationServiceNative := TAndroidHelper.Context.getSystemService(TJContext.JavaClass.NOTIFICATION_SERVICE); Result := TJNotificationManager.Wrap((NotificationServiceNative as ILocalObject).GetObjectID); end; {$REGION 'TNotificationCenterAndroid'} function DateTimeLocalToUnixMSecGMT(const ADateTime: TDateTime): Int64; begin Result := DateTimeToUnix(ADateTime) * MSecsPerSec - Round(TTimeZone.Local.UtcOffset.TotalMilliseconds); end; function TNotificationCenterAndroid.CreateNativeNotification(const ANotification: TNotification): JNotification; function GetDefaultNotificationSound: Jnet_Uri; begin Result := TJRingtoneManager.JavaClass.getDefaultUri(TJRingtoneManager.JavaClass.TYPE_NOTIFICATION); end; function GetDefaultIconID: Integer; begin Result := TAndroidHelper.GetResourceID('drawable/ic_notification'); if Result = 0 then Result := TAndroidHelper.Context.getApplicationInfo.icon; end; function GetContentTitle: JCharSequence; begin if ANotification.Title.IsEmpty then Result := StrToJCharSequence(TAndroidHelper.ApplicationTitle) else Result := StrToJCharSequence(ANotification.Title); end; function GetContentText: JCharSequence; begin Result := StrToJCharSequence(ANotification.AlertBody); end; function GetContentIntent: JPendingIntent; var Intent: JIntent; begin Intent := TAndroidHelper.Context.getPackageManager().getLaunchIntentForPackage(TAndroidHelper.Context.getPackageName()); Intent.setFlags(TJIntent.JavaClass.FLAG_ACTIVITY_SINGLE_TOP or TJIntent.JavaClass.FLAG_ACTIVITY_CLEAR_TOP); SaveNotificationIntoIntent(Intent, ANotification); Result := TJPendingIntent.JavaClass.getActivity(TAndroidHelper.Context, TGeneratorUniqueID.GenerateID, Intent, TJPendingIntent.JavaClass.FLAG_UPDATE_CURRENT); end; var Builder: JNotificationCompat_Builder; ChannelsManager: JChannelsManager; AccentColorResId: Integer; AccentColor: Integer; begin Builder := TJNotificationCompat_Builder.JavaClass.init(TAndroidHelper.Context); Builder.setDefaults(TJNotification.JavaClass.DEFAULT_LIGHTS) .setSmallIcon(GetDefaultIconID) .setContentTitle(GetContentTitle) .setContentText(GetContentText) .setTicker(GetContentText) .setContentIntent(GetContentIntent) .setNumber(ANotification.Number) .setAutoCancel(True) .setWhen(TJDate.Create.getTime); if ANotification.EnableSound then if ANotification.SoundName.IsEmpty then Builder := Builder.setSound(GetDefaultNotificationSound) else Builder := Builder.setSound(StrToJURI(ANotification.SoundName)); if TOSVersion.Check(5) then begin AccentColorResId := TAndroidHelper.GetResourceID('color/notification_accent_color'); if AccentColorResId <> 0 then begin AccentColor := TJContextCompat.JavaClass.getColor(TAndroidHelper.Activity, AccentColorResId); Builder.setColor(AccentColor); end; end; if TOSVersion.Check(8, 0) then begin if ANotification.ChannelId.IsEmpty then begin ChannelsManager := TJChannelsManager.JavaClass.init(TAndroidHelper.Context); Builder.setChannelId(ChannelsManager.getDefaultChannelId); end else Builder.setChannelId(StringToJString(ANotification.ChannelId)); end; // Action buttons won't appear on platforms prior to Android 4.1!!! // http://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#addAction Result := Builder.Build; end; procedure TNotificationCenterAndroid.SaveNotificationIntoIntent(var AIntent: JIntent; const ANotification: TNotification; const AID: Integer); var LaunchIntent: JIntent; begin AIntent.setAction(TJNotificationInfo.JavaClass.ACTION_NOTIFICATION); AIntent.putExtra(TJNotificationInfo.JavaClass.EXTRA_UNIQUE_ID, AID); AIntent.putExtra(TJNotificationInfo.JavaClass.EXTRA_NAME, StringToJString(ANotification.Name)); if ANotification.Title.IsEmpty then AIntent.putExtra(TJNotificationInfo.JavaClass.EXTRA_TITLE, StringToJString(TAndroidHelper.ApplicationTitle)) else AIntent.putExtra(TJNotificationInfo.JavaClass.EXTRA_TITLE, StringToJString(ANotification.Title)); AIntent.putExtra(TJNotificationInfo.JavaClass.EXTRA_ALERT_BODY, StringToJString(ANotification.AlertBody)); AIntent.putExtra(TJNotificationInfo.JavaClass.EXTRA_ALERT_ACTION, StringToJString(ANotification.AlertAction)); AIntent.putExtra(TJNotificationInfo.JavaClass.EXTRA_NUMBER, ANotification.Number); AIntent.putExtra(TJNotificationInfo.JavaClass.EXTRA_FIRE_DATE, ANotification.FireDate); AIntent.putExtra(TJNotificationInfo.JavaClass.EXTRA_FIRE_GMT_DATE, DateTimeLocalToUnixMSecGMT(ANotification.FireDate)); AIntent.putExtra(TJNotificationInfo.JavaClass.EXTRA_REPEAT_INTERVAL, Integer(ANotification.RepeatInterval)); AIntent.putExtra(TJNotificationInfo.JavaClass.EXTRA_ENABLE_SOUND, ANotification.EnableSound); AIntent.putExtra(TJNotificationInfo.JavaClass.EXTRA_SOUND_NAME, StringToJString(ANotification.SoundName)); AIntent.putExtra(TJNotificationInfo.JavaClass.EXTRA_HAS_ACTION, ANotification.HasAction); AIntent.putExtra(TJNotificationInfo.JavaClass.EXTRA_CHANNEL_ID, StringToJString(ANotification.ChannelId)); LaunchIntent := TAndroidHelper.Context.getPackageManager().getLaunchIntentForPackage(TAndroidHelper.Context.getPackageName()); AIntent.putExtra(TJNotificationInfo.JavaClass.EXTRA_ACTIVITY_CLASS_NAME, LaunchIntent.getComponent().getClassName()); end; function TNotificationCenterAndroid.LoadNotificationFromIntent(const AIntent: JIntent): TNotification; begin Result := TNotification.Create; Result.Name := JStringToString(AIntent.getStringExtra(TJNotificationInfo.JavaClass.EXTRA_NAME)); Result.Title := JStringToString(AIntent.getStringExtra(TJNotificationInfo.JavaClass.EXTRA_TITLE)); Result.AlertBody := JStringToString(AIntent.getStringExtra(TJNotificationInfo.JavaClass.EXTRA_ALERT_BODY)); Result.AlertAction := JStringToString(AIntent.getStringExtra(TJNotificationInfo.JavaClass.EXTRA_ALERT_ACTION)); Result.Number := AIntent.getIntExtra(TJNotificationInfo.JavaClass.EXTRA_NUMBER, 0); Result.FireDate := AIntent.getDoubleExtra(TJNotificationInfo.JavaClass.EXTRA_FIRE_DATE, Now); Result.RepeatInterval := TRepeatInterval(AIntent.getIntExtra(TJNotificationInfo.JavaClass.EXTRA_REPEAT_INTERVAL, Integer(TRepeatInterval.None))); Result.EnableSound := AIntent.getBooleanExtra(TJNotificationInfo.JavaClass.EXTRA_ENABLE_SOUND, True); Result.SoundName := JStringToString(AIntent.getStringExtra(TJNotificationInfo.JavaClass.EXTRA_SOUND_NAME)); Result.HasAction := AIntent.getBooleanExtra(TJNotificationInfo.JavaClass.EXTRA_HAS_ACTION, True); Result.ChannelId := JStringToString(AIntent.getStringExtra(TJNotificationInfo.JavaClass.EXTRA_CHANNEL_ID)); end; class destructor TNotificationCenterAndroid.Destroy; begin FNotificationCenterSingleton.Free; end; procedure TNotificationCenterAndroid.DidFormsLoad; function IsIntentWithNotification(const Intent: JIntent): Boolean; begin Result := (Intent <> nil) and (Intent.getAction <> nil) and Intent.getAction.equals(TJNotificationInfo.JavaClass.ACTION_NOTIFICATION); end; var InputIntent: JIntent; Notification: TNotification; begin if System.DelphiActivity <> nil then // This code will be executed if we have an activity begin InputIntent := TAndroidHelper.Activity.getIntent; if IsIntentWithNotification(InputIntent) then begin Notification := LoadNotificationFromIntent(InputIntent); try TMessageManager.DefaultManager.SendMessage(Self, TMessage<TNotification>.Create(Notification)); finally Notification.DisposeOf; end; end; end; end; procedure TNotificationCenterAndroid.DidReceiveNotification(const Sender: TObject; const M: TMessage); function IsIntentWithNotification(Intent: JIntent): Boolean; begin Result := (Intent <> nil) and (Intent.getAction <> nil) and Intent.getAction.equals(TJNotificationInfo.JavaClass.ACTION_NOTIFICATION); end; var InputIntent: JIntent; Notification: TNotification; begin if M is TMessageReceivedNotification then begin InputIntent := (M as TMessageReceivedNotification).Value; if IsIntentWithNotification(InputIntent) then begin Notification := LoadNotificationFromIntent(InputIntent); try TMessageManager.DefaultManager.SendMessage(Self, TMessage<TNotification>.Create(Notification)); finally Notification.DisposeOf; end; end; end; end; constructor TNotificationCenterAndroid.Create; begin FExternalStore := TAndroidPreferenceAdapter.Create; FNotificationManager := GetNotificationService; { Subscription } TMessageManager.DefaultManager.SubscribeToMessage(TMessageReceivedNotification, DidReceiveNotification); end; function TNotificationCenterAndroid.CreateChannel(const AChannel: TChannel): JNotificationChannel; function AsNativeImportance(const AImportance: TImportance): Integer; begin case AImportance of TImportance.Unspecified: Result := TJNotificationManager.JavaClass.IMPORTANCE_UNSPECIFIED; TImportance.None: Result := TJNotificationManager.JavaClass.IMPORTANCE_NONE; TImportance.Default: Result := TJNotificationManager.JavaClass.IMPORTANCE_DEFAULT; TImportance.Min: Result := TJNotificationManager.JavaClass.IMPORTANCE_MIN; TImportance.Low: Result := TJNotificationManager.JavaClass.IMPORTANCE_MIN; TImportance.High: Result := TJNotificationManager.JavaClass.IMPORTANCE_HIGH; else Result := TJNotificationManager.JavaClass.IMPORTANCE_UNSPECIFIED; end; end; function AsNativeLockscreenVisibility(const ALockscreenVisibility: TLockscreenVisibility): Integer; begin case ALockscreenVisibility of TLockscreenVisibility.Public: Result := TJNotification.JavaClass.VISIBILITY_PUBLIC; TLockscreenVisibility.Private: Result := TJNotification.JavaClass.VISIBILITY_PRIVATE; TLockscreenVisibility.Secret: Result := TJNotification.JavaClass.VISIBILITY_SECRET; else Result := TJNotification.JavaClass.VISIBILITY_PUBLIC; end; end; begin Result := TJNotificationChannel.JavaClass.init(StringToJString(AChannel.Id), StrToJCharSequence(AChannel.Title), AsNativeImportance(ACHannel.Importance)); Result.setDescription(StringToJString(AChannel.Description)); Result.setLockscreenVisibility(AsNativeLockscreenVisibility(AChannel.LockscreenVisibility)); Result.setShowBadge(AChannel.ShouldShowBadge); Result.enableLights(AChannel.ShouldShowLights); Result.enableVibration(AChannel.ShouldVibrate); end; function TNotificationCenterAndroid.CreateChannel(const AChannel: JNotificationChannel): TChannel; function ExtractLockscreenVisibility(const ALockscreenVisibility: Integer): TLockscreenVisibility; begin if ALockscreenVisibility = TJNotification.JavaClass.VISIBILITY_PRIVATE then Result := TLockscreenVisibility.Private else if ALockscreenVisibility = TJNotification.JavaClass.VISIBILITY_PUBLIC then Result := TLockscreenVisibility.Public else if ALockscreenVisibility = TJNotification.JavaClass.VISIBILITY_SECRET then Result := TLockscreenVisibility.Secret else Result := TLockscreenVisibility.Public; end; function ExtractImportance(const AImportance: Integer): TImportance; begin if AImportance = TJNotificationManager.JavaClass.IMPORTANCE_DEFAULT then Result := TImportance.Default else if AImportance = TJNotificationManager.JavaClass.IMPORTANCE_HIGH then Result := TImportance.High else if AImportance = TJNotificationManager.JavaClass.IMPORTANCE_LOW then Result := TImportance.Low else if AImportance = TJNotificationManager.JavaClass.IMPORTANCE_MIN then Result := TImportance.Min else if AImportance = TJNotificationManager.JavaClass.IMPORTANCE_NONE then Result := TImportance.None else if AImportance = TJNotificationManager.JavaClass.IMPORTANCE_UNSPECIFIED then Result := TImportance.Unspecified else Result := TImportance.Unspecified; end; begin Result := TChannel.Create; Result.Id := JStringToString(AChannel.getId); Result.Title := JCharSequenceToStr(AChannel.getName); Result.Description := JStringToString(AChannel.getDescription); Result.LockscreenVisibility := ExtractLockscreenVisibility(AChannel.getLockscreenVisibility); Result.Importance := ExtractImportance(AChannel.getImportance); Result.ShouldShowLights := AChannel.shouldShowLights; Result.ShouldVibrate := AChannel.shouldVibrate; Result.ShouldShowBadge := AChannel.canShowBadge; end; destructor TNotificationCenterAndroid.Destroy; begin FExternalStore.DisposeOf; FNotificationManager := nil; { Unsibscribe } TMessageManager.DefaultManager.Unsubscribe(TMessageReceivedNotification, DidReceiveNotification); inherited; end; procedure TNotificationCenterAndroid.DoPresentNotification(const ANotification: TNotification); var NativeNotification: JNotification; begin NativeNotification := CreateNativeNotification(ANotification); if ANotification.Name.IsEmpty then FNotificationManager.notify(TGeneratorUniqueID.GenerateID, NativeNotification) else FNotificationManager.notify(StringToJString(ANotification.Name), 0, NativeNotification); NativeNotification := nil; end; procedure TNotificationCenterAndroid.DoScheduleNotification(const ANotification: TNotification); function CreateNotificationAlarmIntent(const AID: Integer): JPendingIntent; var Intent: JIntent; Alarm: JNotificationAlarm; begin Alarm := TJNotificationAlarm.Create; Intent := TJIntent.Create; Intent.setClass(TAndroidHelper.Context, Alarm.getClass); Intent.setAction(TJNotificationInfo.JavaClass.ACTION_NOTIFICATION); SaveNotificationIntoIntent(Intent, ANotification, AID); Result := TJPendingIntent.JavaClass.getBroadcast(TAndroidHelper.Context, AID, Intent, TJPendingIntent.JavaClass.FLAG_UPDATE_CURRENT); end; var PendingIntent: JPendingIntent; ID: Integer; begin if not ANotification.Name.IsEmpty and FExternalStore.Contains(ANotification.Name) then CancelNotification(ANotification.Name); ID := TGeneratorUniqueID.GenerateID; PendingIntent := CreateNotificationAlarmIntent(ID); FExternalStore.SaveNotification(ANotification, ID); TAndroidHelper.AlarmManager.&set(TJAlarmManager.JavaClass.RTC_WAKEUP, DateTimeLocalToUnixMSecGMT(ANotification.FireDate), PendingIntent); end; procedure TNotificationCenterAndroid.DoCancelAllNotifications; var Notifications: TStringList; NotificationName: string; begin // Cancel all Presented notification FNotificationManager.cancelAll; // Cancel all scheduled notifications Notifications := FExternalStore.GetAllNotificationsNames; try for NotificationName in Notifications do begin CancelScheduledNotification(NotificationName); FExternalStore.RemoveNotification(NotificationName); end; finally Notifications.Free; end; end; procedure TNotificationCenterAndroid.DoCancelNotification(const ANotification: TNotification); begin DoCancelNotification(ANotification.Name); end; procedure TNotificationCenterAndroid.DoCreateOrUpdateChannel(const AChannel: TChannel); var NativeChannel: JNotificationChannel; begin if not TOSVersion.Check(8, 0) then Exit; NativeChannel := CreateChannel(AChannel); FNotificationManager.createNotificationChannel(NativeChannel); end; procedure TNotificationCenterAndroid.DoDeleteChannel(const AChannelId: string); begin if not TOSVersion.Check(8, 0) then Exit; FNotificationManager.deleteNotificationChannel(StringToJString(AChannelId)); end; procedure TNotificationCenterAndroid.CancelScheduledNotification(const AName: string); var ID: Integer; Intent: JIntent; Alarm: JNotificationAlarm; PendingIntent: JPendingIntent; begin if FExternalStore.Contains(AName) then begin ID := FExternalStore.GetID(AName); try Alarm := TJNotificationAlarm.Create; Intent := TJIntent.Create; Intent.setClass(TAndroidHelper.Context, Alarm.getClass); Intent.setAction(TJNotificationInfo.JavaClass.ACTION_NOTIFICATION); PendingIntent := TJPendingIntent.JavaClass.getBroadcast(TAndroidHelper.Context, ID, Intent, TJPendingIntent.JavaClass.FLAG_UPDATE_CURRENT); TAndroidHelper.AlarmManager.cancel(PendingIntent); finally FExternalStore.RemoveNotification(AName); end; end; end; procedure TNotificationCenterAndroid.DoCancelNotification(const AName: string); begin FNotificationManager.cancel(StringToJString(AName), 0); CancelScheduledNotification(AName); end; procedure TNotificationCenterAndroid.DoSetIconBadgeNumber(const ACount: Integer); begin // Android doesn't have Number icon on application Icon end; class function TNotificationCenterAndroid.GetNotificationCenter: TNotificationCenterAndroid; begin if FNotificationCenterSingleton = nil then FNotificationCenterSingleton := TNotificationCenterAndroid.Create; Result := FNotificationCenterSingleton; end; procedure TNotificationCenterAndroid.DoGetAllChannels(const AChannels: TChannels); var Channels: JList; I: Integer; NativeChannel: JNotificationChannel; begin if not TOSVersion.Check(8, 0) then Exit; Channels := FNotificationManager.getNotificationChannels; for I := 0 to Channels.size - 1 do begin NativeChannel := TJNotificationChannel.Wrap(Channels.get(I)); AChannels.Add(CreateChannel(NativeChannel)); end; end; function TNotificationCenterAndroid.DoGetIconBadgeNumber: Integer; begin // Android doesn't have Number icon on application Icon Result := 0; end; procedure TNotificationCenterAndroid.DoLoaded; begin inherited; // DoLoaded is invoked before TForm.OnCreate. However, we have to process receiving of the Local Notification // strictly after the form is fully loaded, because we need to invoke TNotificationCenter.OnReceiveLocalNotification // after TForm.OnCreate. TThread.ForceQueue(nil, procedure begin DidFormsLoad; end); end; procedure TNotificationCenterAndroid.DoResetIconBadgeNumber; begin // Android doesn't have Number icon on application Icon end; {$ENDREGION} { TGeneratorUniqueID } class constructor TGeneratorUniqueID.Create; begin FPreference := TAndroidHelper.Context.getSharedPreferences(TJNotificationAlarm.JavaClass.NOTIFICATION_CENTER, TJContext.JavaClass.MODE_PRIVATE); FNextUniqueID := FPreference.getInt(StringToJString(SettingsNotificationUniquiID), 0); end; class function TGeneratorUniqueID.GenerateID: Integer; var PreferenceEditor: JSharedPreferences_Editor; begin PreferenceEditor := FPreference.edit; try PreferenceEditor.putInt(StringToJString(SettingsNotificationUniquiID), FNextUniqueID); finally PreferenceEditor.commit; end; Result := FNextUniqueID; Inc(FNextUniqueID); end; { TAndroidStorageAdapter } function TAndroidPreferenceAdapter.FindNotification(const AName: string; out AIndex, AID: Integer): Boolean; var Found: Boolean; Notifications: TStringList; NotificationPair: string; NotificationName: string; NotificationID: Integer; NotificationsStr: JString; I: Integer; begin AIndex := -1; AID := -1; Notifications := TStringList.Create; try NotificationsStr := FPreference.getString(TJNotificationAlarm.JavaClass.SETTINGS_NOTIFICATION_IDS, nil); Notifications.Text := JStringToString(NotificationsStr); Found := False; I := 0; while (I < Notifications.Count) and not Found do begin NotificationPair := Notifications[I]; NotificationName := ExtractName(NotificationPair); NotificationID := ExtractID(NotificationPair); if (NotificationID > -1) and (NotificationName = AName) then begin AIndex := I; Found := True; end; Inc(I); end; Result := Found; finally Notifications.DisposeOf; end; end; function TAndroidPreferenceAdapter.ExtractName(const AStr: string): string; begin Result := AStr.Substring(0, AStr.LastIndexOf('=')); end; function TAndroidPreferenceAdapter.ExtractID(const AStr: string): Integer; var StrTmp: string; begin StrTmp := AStr.Substring(AStr.LastIndexOf('=') + 1); if not TryStrToInt(StrTmp, Result) then Result := -1; end; constructor TAndroidPreferenceAdapter.Create; begin FPreference := TAndroidHelper.Context.getSharedPreferences(TJNotificationAlarm.JavaClass.NOTIFICATION_CENTER, TJContext.JavaClass.MODE_PRIVATE); end; destructor TAndroidPreferenceAdapter.Destroy; begin FPreference := nil; inherited; end; procedure TAndroidPreferenceAdapter.SaveNotification(const ANotification: TNotification; const AID: Integer); var PreferenceEditor: JSharedPreferences_Editor; NotificationsList: TStringList; Index: Integer; Notifications: JString; begin if not ANotification.Name.IsEmpty then begin Notifications := FPreference.getString(TJNotificationAlarm.JavaClass.SETTINGS_NOTIFICATION_IDS, nil); NotificationsList := TStringList.Create; try NotificationsList.Text := JStringToString(Notifications); if Find(ANotification.Name, Index) then NotificationsList.Delete(Index); NotificationsList.Add(ANotification.Name + '=' + AID.ToString); PreferenceEditor := FPreference.edit; try PreferenceEditor.putString(TJNotificationAlarm.JavaClass.SETTINGS_NOTIFICATION_IDS, StringToJString(NotificationsList.Text)); finally PreferenceEditor.commit; end; finally NotificationsList.DisposeOf; end; end; end; procedure TAndroidPreferenceAdapter.RemoveNotification(const AName: string); var NotificationsList: TStringList; Notifications: JString; I: Integer; Found: Boolean; PreferenceEditor: JSharedPreferences_Editor; begin NotificationsList := TStringList.Create; try Notifications := FPreference.getString(TJNotificationAlarm.JavaClass.SETTINGS_NOTIFICATION_IDS, nil); NotificationsList.Text := JStringToString(Notifications); I := 0; Found := False; while not Found and (I < NotificationsList.Count) do if ExtractName(NotificationsList[I]) = AName then Found := True else Inc(I); if Found then begin PreferenceEditor := FPreference.edit; try NotificationsList.Delete(I); PreferenceEditor.putString(TJNotificationAlarm.JavaClass.SETTINGS_NOTIFICATION_IDS, StringToJString(NotificationsList.Text)); finally PreferenceEditor.commit; end; end; finally NotificationsList.DisposeOf; end; end; function TAndroidPreferenceAdapter.IndexOf(const AName: string): Integer; var ID: Integer; begin FindNotification(AName, Result, ID); end; function TAndroidPreferenceAdapter.Find(const AName: string; out Index: Integer): Boolean; var ID: Integer; begin Result := FindNotification(AName, Index, ID); end; function TAndroidPreferenceAdapter.GetAllNotificationsNames: TStringList; var Notifications: TStringList; NotificationsStr: JString; I: Integer; begin Notifications := TStringList.Create; NotificationsStr := FPreference.getString(TJNotificationAlarm.JavaClass.SETTINGS_NOTIFICATION_IDS, nil); Notifications.Text := JStringToString(NotificationsStr); for I := 0 to Notifications.Count - 1 do Notifications[I] := ExtractName(Notifications[I]); Result := Notifications; end; function TAndroidPreferenceAdapter.GetID(const AName: string): Integer; var NotificationsStr: JString; Notifications: TStringList; IDStr: string; Notification: string; begin Notifications := TStringList.Create; try NotificationsStr := FPreference.getString(TJNotificationAlarm.JavaClass.SETTINGS_NOTIFICATION_IDS, nil); Notifications.Text := JStringToString(NotificationsStr); for Notification in Notifications do begin IDStr := Notification.Substring(Notification.IndexOf('=') + 1); if TryStrToInt(IDStr, Result) then Break else Result := -1; end; finally Notifications.DisposeOf; end; end; function TAndroidPreferenceAdapter.Contains(const AName: string): Boolean; begin Result := IndexOf(AName) > -1; end; { TPlatformNotificationCenter } class function TPlatformNotificationCenter.GetInstance: TBaseNotificationCenter; begin Result := TBaseNotificationCenter(TNotificationCenterAndroid.NotificationCenter) end; end.
unit BCEditor.Editor.Scroll.Hint; interface uses Classes, Graphics; type TScrollHintFormat = (shfTopLineOnly, shfTopToBottom); TBCEditorScrollHint = class(TPersistent) strict private FFormat: TScrollHintFormat; public constructor Create; procedure Assign(Source: TPersistent); override; published property Format: TScrollHintFormat read FFormat write FFormat default shfTopLineOnly; end; implementation constructor TBCEditorScrollHint.Create; begin inherited; FFormat := shfTopLineOnly; end; procedure TBCEditorScrollHint.Assign(Source: TPersistent); begin if Source is TBCEditorScrollHint then with Source as TBCEditorScrollHint do Self.FFormat := FFormat else inherited Assign(Source); end; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Buttons, Vcl.StdCtrls, Vcl.Mask, Vcl.ComCtrls, Vcl.Samples.Spin, Vcl.Imaging.pngimage, Vcl.ExtCtrls; type TConverter = class(TForm) currencyField1: TComboBox; currencyField2: TComboBox; convert_button: TButton; numberField1: TSpinEdit; numberField2: TSpinEdit; Image1: TImage; Label1: TLabel; Button1: TButton; Image2: TImage; procedure FormCreate(Sender: TObject); procedure convert_buttonClick(Sender: TObject); procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; type TCurrency = class public ToKoruna: double; ToDollar: double; ToEuro: double; constructor Create(K,D,E: double); end; var Converter: TConverter; Koruna: TCurrency; Dollar: TCurrency; Euro: TCurrency; QuantityInput: TSpinEdit; QuantityOutput: TSpinEdit; currencyFrom: TComboBox; currencyTo: TComboBox; reverseDirection: boolean; implementation constructor TCurrency.Create(K,D,E: double); begin ToKoruna := K; ToDollar := D; ToEuro := E; end; {$R *.dfm} procedure TConverter.convert_buttonClick(Sender: TObject); function getCoefficient(): double; begin case currencyFrom.ItemIndex of 0: case currencyTo.ItemIndex of 0: exit(Koruna.ToKoruna); 1: exit(Koruna.ToDollar); 2: exit(Koruna.ToEuro); end; 1: case currencyTo.ItemIndex of 0: exit(Dollar.ToKoruna); 1: exit(Dollar.ToDollar); 2: exit(Dollar.ToEuro); end; 2: case currencyTo.ItemIndex of 0: exit(Euro.ToKoruna); 1: exit(Euro.ToDollar); 2: exit(Euro.ToEuro); end; end; end; begin QuantityOutput.Text := (StrToFloat(QuantityInput.Text) * getCoefficient).ToString; end; procedure defineSchema(reverseDirection: boolean); begin if reverseDirection then begin currencyFrom := Converter.currencyField2; currencyTo := Converter.currencyField1; QuantityInput := Converter.numberField2; QuantityOutput := Converter.numberField1; end else begin currencyFrom := Converter.currencyField1; currencyTo := Converter.currencyField2; QuantityInput := Converter.numberField1; QuantityOutput := Converter.numberField2; end; end; procedure TConverter.FormCreate(Sender: TObject); begin Koruna := TCurrency.Create(1, 0.042, 0.038); Dollar := TCurrency.Create(23.67 , 1, 0.89); Euro := TCurrency.Create(26.47, 1.12, 1); reverseDirection := false; defineSchema(reverseDirection); Image2.Visible := false; end; procedure TConverter.Button1Click(Sender: TObject); begin reverseDirection := not reverseDirection; defineSchema(reverseDirection); Image2.Visible := reverseDirection; Image1.Visible := Image1.Visible; end; end.
unit HomeU; interface uses Windows, Messages, SysUtils, Classes, HTTPApp, WebModu, HTTPProd, ReqMulti, WebAdapt, WebComp, WebSess, WebDisp; type THome = class(TWebAppDataModule) WebAppComponents: TWebAppComponents; ApplicationAdapter: TApplicationAdapter; PageDispatcher: TPageDispatcher; AdapterDispatcher: TAdapterDispatcher; SessionsService1: TSessionsService; UpdateSessionValue: TAdapterAction; AdaptTitle: TAdapterApplicationTitleField; SessionValue: TAdapterField; TerminateSession: TAdapterAction; Log: TStringsValuesList; LogString: TValuesListValueField; ClearLog: TAdapterAction; RedirectFlag: TAdapterBooleanField; procedure SessionValueGetValue(Sender: TObject; var Value: Variant); procedure UpdateSessionValueExecute(Sender: TObject; Params: TStrings); procedure SessionsService1StartSession(ASender: TObject; ASession: TAbstractWebSession); procedure SessionsService1EndSession(ASender: TObject; ASession: TAbstractWebSession; AReason: TEndSessionReason); procedure TerminateSessionExecute(Sender: TObject; Params: TStrings); procedure ClearLogExecute(Sender: TObject; Params: TStrings); procedure LogPrepareStrings(Sender: TObject); private procedure LogMessage(ASession: TAbstractWebSession; const AMessage: string); public end; function Home: THome; implementation {$R *.dfm} uses WebReq, WebCntxt, WebFact, Variants, AdaptReq; function Home: THome; begin Result := THome(WebContext.FindModuleClass(THome)); end; procedure THome.SessionValueGetValue(Sender: TObject; var Value: Variant); begin Value := WebContext.Session.Values['Foo']; if VarIsEmpty(Value) then Value := ''; end; procedure THome.UpdateSessionValueExecute(Sender: TObject; Params: TStrings); var V: Variant; begin if SessionValue.ActionValue.Values[0] <> '' then V := SessionValue.ActionValue.Values[0]; WebContext.Session.Values['Foo'] := V; end; procedure THome.SessionsService1StartSession(ASender: TObject; ASession: TAbstractWebSession); begin ASession.Values['StartTime'] := TimeToStr(Now); LogMessage(ASession, Format('Session %s started', [ASession.SessionID])); end; const sEndSessionReasons: array[TEndSessionReason] of string = ('esTimeout', 'esTerminate'); procedure THome.LogMessage(ASession: TAbstractWebSession; const AMessage: string); var V: Variant; begin V := ASession.Values['Log']; if VarIsEmpty(V) then V := '' else V := V + #13#10; V := V + AMessage; ASession.Values['Log'] := V; Log.Strings.Text := V; end; procedure THome.SessionsService1EndSession(ASender: TObject; ASession: TAbstractWebSession; AReason: TEndSessionReason); begin if AReason = esTerminate then // Copy log over to new session WebContext.Session.Values['Log'] := ASession.Values['Log']; LogMessage(WebContext.Session, Format('Session %s terminated reason: %s', [ASession.SessionID, sEndSessionReasons[AReason]])); end; procedure THome.TerminateSessionExecute(Sender: TObject; Params: TStrings); begin WebContext.Session.Terminate; if (RedirectFlag.ActionValue <> nil) and (RedirectFlag.ActionValue.Values[0] = True) then TerminateSession.RedirectOptions := roRedirect else TerminateSession.RedirectOptions := []; end; procedure THome.ClearLogExecute(Sender: TObject; Params: TStrings); begin Session.Values['Log'] := ''; Log.Strings.Text := Session.Values['Log']; end; procedure THome.LogPrepareStrings(Sender: TObject); var V: Variant; begin V := WebContext.Session.Values['Log']; if VarIsEmpty(V) then Log.Strings.Text := '' else Log.Strings.Text := V; end; initialization if WebRequestHandler <> nil then WebRequestHandler.AddWebModuleFactory(TWebAppDataModuleFactory.Create(THome, caCache)); end.
unit uPrincipal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TfrmDisco = class(TForm) cboBanda: TComboBox; lblTitle: TLabel; btnAdcBanda: TButton; btnRemvBanda: TButton; altBanda: TButton; lbxResultado: TListBox; btnListBanda: TButton; btnVerDisco: TButton; btnInfo: TButton; btnSair: TButton; procedure btnAdcBandaClick(Sender: TObject); procedure btnInfoClick(Sender: TObject); procedure btnRemoverClick(Sender: TObject); procedure btnSairClick(Sender: TObject); private type TTipoMensagem = (Informacao, Alerta, Erro); const cNOME_SISTEMA = 'Controle de Discos'; cVALOR_ZERO = 0; cVALOR_VAZIO = -1; var FQuantidadeRegistrosInseridos, FQuantidadeRegistrosExcluidos: integer; procedure ValidarInsercao; procedure ValidarExclusao; procedure ValidarLancamentoDuplicado; procedure AdicionarBanda; procedure RemoverBanda; procedure ExibirMensagem(pMensagem: string; pTipoMensagem: TTipoMensagem); public { Public declarations } end; var frmDisco: TfrmDisco; implementation {$R *.dfm} uses uCadastroBanda; procedure TfrmDisco.AdicionarBanda; begin lbxResultado.Items.Add(cboBanda.Text); cboBanda.ItemIndex := -1; end; procedure TfrmDisco.btnAdcBandaClick(Sender: TObject); begin ValidarInsercao; ValidarLancamentoDuplicado; AdicionarBanda; Inc(FQuantidadeRegistrosInseridos); end; procedure TfrmDisco.btnInfoClick(Sender: TObject); begin ExibirMensagem('Informações: ' + #13 + #13 + 'Total de Registros: ' + IntToStr(lbxResultado.Items.Count) + #13 + 'Total de Lançamentos: ' + IntToStr(FQuantidadeRegistrosInseridos) + #13 + 'Total de Exclusões: ' + IntToStr(FQuantidadeRegistrosExcluidos), Informacao); end; procedure TfrmDisco.btnRemoverClick(Sender: TObject); begin ValidarExclusao; RemoverBanda; Inc(FQuantidadeRegistrosExcluidos); end; procedure TfrmDisco.btnSairClick(Sender: TObject); begin Halt; end; // try // Application.CreateForm(TfrmCadBanda, frmDisco); // frmCadBanda.ShowModal; // finally // FreeAndNill(frmCadBanda); // end; // // end; procedure TfrmDisco.ExibirMensagem(pMensagem: string; pTipoMensagem: TTipoMensagem); begin case pTipoMensagem of Informacao: Application.MessageBox(PChar(pMensagem), PWideChar(cNOME_SISTEMA), MB_ICONINFORMATION); Alerta: Application.MessageBox(PChar(pMensagem), PWideChar(cNOME_SISTEMA), MB_ICONWARNING); Erro : Application.MessageBox(PChar(pMensagem), PWideChar(cNOME_SISTEMA), MB_ICONERROR); end; end; procedure TfrmDisco.RemoverBanda; begin lbxResultado.Items.Delete(lbxResultado.ItemIndex); end; procedure TfrmDisco.ValidarExclusao; begin if lbxResultado.Items.Count = cVALOR_ZERO then begin ExibirMensagem('Não há registros a serem excluídos.', Alerta); Abort; end; if lbxResultado.Items.Count = cVALOR_VAZIO then begin ExibirMensagem('Selecione a banda a ser removida.', Alerta); end; end; procedure TfrmDisco.ValidarInsercao; begin if cboBanda.ItemIndex = cVALOR_VAZIO then begin ExibirMensagem('Selecione a banda a ser adicionada.', Alerta); cboBanda.SetFocus; Abort; end; end; procedure TfrmDisco.ValidarLancamentoDuplicado; var i: integer; begin for i:= cVALOR_ZERO to Pred(lbxResultado.Items.Count) do if lbxResultado.Items[i] = cboBanda.Text then begin ExibirMensagem('A banda "' + cboBanda.Text + '" já foi adicionada.' + #13 + 'A operação será cancelada.', Alerta); Abort; end; end; end.
unit caCell; {$INCLUDE ca.inc} interface uses // Standard Delphi units  Windows, SysUtils, Classes, Math, TypInfo, Variants, // ca units  caUtils, caTypes; type //--------------------------------------------------------------------------- // TcaCell   //--------------------------------------------------------------------------- TcaCell = class(TObject) private // Private fields  FCellType: TcaCellType; FDependentCells: TList; FName: String; FSelected: Boolean; FShouldUpdate: Boolean; FTag: Integer; // Event property fields  FOnChange: TNotifyEvent; protected // Protected property methods  function GetAsString: String; virtual; procedure SetAsString(const Value: String); virtual; // Protected methods  procedure Changed; public // Create/Destroy  constructor Create; destructor Destroy; override; // Public class methods  class function StringToCellType(ACellTypeString: string): TcaCellType; class function VariantToCellType(AValue: Variant): TcaCellType; // Public methods  procedure AddDependentCell(ACell: TcaCell); // Properties  property AsString: String read GetAsString write SetAsString; property CellType: TcaCellType read FCellType write FCellType; property DependentCells: TList read FDependentCells; property Name: String read FName write FName; property Selected: Boolean read FSelected write FSelected; property ShouldUpdate: Boolean read FShouldUpdate write FShouldUpdate; property Tag: Integer read FTag write FTag; // Event properties  property OnChange: TNotifyEvent read FOnChange write FOnChange; end; TcaCellClass = class of TcaCell; //--------------------------------------------------------------------------- // TcaObjectCell   //--------------------------------------------------------------------------- TcaObjectCell = class(TcaCell) private // Property fields  FOwnsObject: Boolean; FValue: TObject; // Property methods  function GetOwnsObject: Boolean; function GetValue: TObject; procedure SetOwnsObject(const Value: Boolean); procedure SetValue(const Value: TObject); protected // Protected property methods  function GetAsString: String; override; procedure SetAsString(const Value: String); override; public // Create/Destroy  constructor Create; destructor Destroy; override; // Properties  property Value: TObject read GetValue write SetValue; property OwnsObject: Boolean read GetOwnsObject write SetOwnsObject; end; //---------------------------------------------------------------------------- // TcaIntegerCell   //---------------------------------------------------------------------------- TcaIntegerCell = class(TcaCell) private // Property fields  FValue: Integer; // Property methods  function GetValue: Integer; procedure SetValue(const Value: Integer); protected // Protected property methods  function GetAsString: String; override; procedure SetAsString(const Value: String); override; public // Create/Destroy  constructor Create; // Properties  property Value: Integer read GetValue write SetValue; end; //---------------------------------------------------------------------------- // TcaInt64Cell   //---------------------------------------------------------------------------- TcaInt64Cell = class(TcaCell) private // Property fields  FValue: Int64; // Property methods  function GetValue: Int64; procedure SetValue(const Value: Int64); protected // Protected property methods function GetAsString: String; override; procedure SetAsString(const Value: String); override; public // Create/Destroy  constructor Create; // Properties  property Value: Int64 read GetValue write SetValue; end; //---------------------------------------------------------------------------- // TcaSingleCell   //---------------------------------------------------------------------------- TcaSingleCell = class(TcaCell) private // Property fields  FValue: Single; // Property methods  function GetValue: Single; procedure SetValue(const Value: Single); protected // Protected property methods function GetAsString: String; override; procedure SetAsString(const Value: String); override; public // Create/Destroy  constructor Create; property Value: Single read GetValue write SetValue; end; //---------------------------------------------------------------------------- // TcaDoubleCell   //---------------------------------------------------------------------------- TcaDoubleCell = class(TcaCell) private // Property fields  FValue: Double; // Property methods  function GetValue: Double; procedure SetValue(const Value: Double); protected // Protected property methods function GetAsString: String; override; procedure SetAsString(const Value: String); override; public // Create/Destroy  constructor Create; // Properties  property Value: Double read GetValue write SetValue; end; //---------------------------------------------------------------------------- // TcaExtendedCell   //---------------------------------------------------------------------------- TcaExtendedCell = class(TcaCell) private // Property fields  FValue: Extended; // Property methods  function GetValue: Extended; procedure SetValue(const Value: Extended); protected // Protected property methods function GetAsString: String; override; procedure SetAsString(const Value: String); override; public // Create/Destroy  constructor Create; // Properties  property Value: Extended read GetValue write SetValue; end; //---------------------------------------------------------------------------- // TcaStringCell   //---------------------------------------------------------------------------- TcaStringCell = class(TcaCell) private // Property fields  FValue: String; FMemo: TStrings; // Property methods  function GetAsMemo: TStrings; function GetValue: String; procedure SetAsMemo(const Value: TStrings); procedure SetValue(const Value: String); protected // Protected property methods function GetAsString: String; override; procedure SetAsString(const Value: String); override; public // Create/Destroy  constructor Create; destructor Destroy; override; // Properties  property AsMemo: TStrings read GetAsMemo write SetAsMemo; property Value: String read GetValue write SetValue; end; //---------------------------------------------------------------------------- // TcaMemoCell   //---------------------------------------------------------------------------- TcaMemoCell = class(TcaCell) private // Property fields  FValue: TStrings; // Property methods  function GetValue: TStrings; procedure SetValue(const Value: TStrings); protected // Protected property methods function GetAsString: String; override; procedure SetAsString(const Value: String); override; public // Create/Destroy  constructor Create; destructor Destroy; override; // Properties  property Value: TStrings read GetValue write SetValue; end; //---------------------------------------------------------------------------- // TcaBooleanCell   //---------------------------------------------------------------------------- TcaBooleanCell = class(TcaCell) private // Property fields  FValue: Boolean; // Property methods  function GetValue: Boolean; procedure SetValue(const Value: Boolean); protected // Protected property methods function GetAsString: String; override; procedure SetAsString(const Value: String); override; public // Create/Destroy  constructor Create; // Properties  property Value: Boolean read GetValue write SetValue; end; //---------------------------------------------------------------------------- // TcaDateTimeCell   //---------------------------------------------------------------------------- TcaDateTimeCell = class(TcaCell) private // Property fields  FValue: TDateTime; // Property methods  function GetValue: TDateTime; procedure SetValue(const Value: TDateTime); protected // Protected property methods function GetAsString: String; override; procedure SetAsString(const Value: String); override; public // Create/Destroy  constructor Create; // Properties  property Value: TDateTime read GetValue write SetValue; end; //---------------------------------------------------------------------------- // TcaFormulaCell   //---------------------------------------------------------------------------- TcaFormulaCell = class(TcaCell) private // Property fields  FValue: String; // Property methods  function GetValue: String; procedure SetValue(const Value: String); protected // Protected property methods function GetAsString: String; override; procedure SetAsString(const Value: String); override; public // Create/Destroy  constructor Create; // Properties  property Value: String read GetValue write SetValue; end; implementation //--------------------------------------------------------------------------- // TcaCell   //--------------------------------------------------------------------------- constructor TcaCell.Create; begin inherited; FDependentCells := TList.Create; end; destructor TcaCell.Destroy; begin FDependentCells.Free; inherited; end; // Public class methods  class function TcaCell.StringToCellType(ACellTypeString: String): TcaCellType; var ACellType: TcaCellType; begin Result := Low(TcaCellType); for ACellType := Low(TcaCellType) to High(TcaCellType) do begin if GetEnumName(TypeInfo(TcaCellType), Ord(ACellType)) = ACellTypeString then begin Result := ACellType; Break; end; end; end; class function TcaCell.VariantToCellType(AValue: Variant): TcaCellType; var VType: TVarType; begin Result := ctNil; if not VarIsNull(AValue) then begin VType := VarType(AValue); case VType of varOleStr, varString: Result := ctString; varSmallint, varShortInt, varInteger, varByte, varWord, varLongWord: Result := ctInteger; varSingle: Result := ctSingle; varDouble, varCurrency: Result := ctDouble; varDate: Result := ctDateTime; varBoolean: Result := ctBoolean; varInt64: Result := ctInt64; end; end; end; // Public methods  procedure TcaCell.AddDependentCell(ACell: TcaCell); begin FDependentCells.Add(ACell); end; // Protected methods  procedure TcaCell.Changed; begin if Assigned(FOnChange) then FOnChange(Self); end; // Protected property methods  function TcaCell.GetAsString: String; begin Result := ''; end; procedure TcaCell.SetAsString(const Value: String); begin end; //--------------------------------------------------------------------------- // TcaObjectCell   //--------------------------------------------------------------------------- constructor TcaObjectCell.Create; begin inherited; CellType := ctObject; end; destructor TcaObjectCell.Destroy; begin if FOwnsObject then FValue.Free; inherited; end; // Protected property methods  function TcaObjectCell.GetAsString: String; begin Result := Utils.ObjectToString(FValue); end; procedure TcaObjectCell.SetAsString(const Value: String); begin SetValue(TObject(Utils.StringToInteger(Value))); end; // Property methods  function TcaObjectCell.GetOwnsObject: Boolean; begin Result := FOwnsObject; end; function TcaObjectCell.GetValue: TObject; begin Result := FValue; end; procedure TcaObjectCell.SetOwnsObject(const Value: Boolean); begin FOwnsObject := Value; end; procedure TcaObjectCell.SetValue(const Value: TObject); begin FValue := Value; Changed; end; //---------------------------------------------------------------------------- // TcaIntegerCell   //---------------------------------------------------------------------------- constructor TcaIntegerCell.Create; begin inherited; CellType := ctInteger; end; function TcaIntegerCell.GetAsString: String; begin Result := Utils.IntegerToString(FValue, ''); end; function TcaIntegerCell.GetValue: Integer; begin Result := FValue; end; procedure TcaIntegerCell.SetAsString(const Value: String); begin SetValue(Utils.StringToInteger(Value)); end; procedure TcaIntegerCell.SetValue(const Value: Integer); begin FValue := Value; Changed; end; //---------------------------------------------------------------------------- // TcaInt64Cell   //---------------------------------------------------------------------------- constructor TcaInt64Cell.Create; begin inherited; CellType := ctInt64; end; function TcaInt64Cell.GetAsString: String; begin Result := Utils.Int64ToString(FValue, ''); end; function TcaInt64Cell.GetValue: Int64; begin Result := FValue; end; procedure TcaInt64Cell.SetAsString(const Value: String); begin SetValue(Utils.StringToInt64(Value)); end; procedure TcaInt64Cell.SetValue(const Value: Int64); begin FValue := Value; Changed; end; //---------------------------------------------------------------------------- // TcaSingleCell   //---------------------------------------------------------------------------- constructor TcaSingleCell.Create; begin inherited; CellType := ctSingle; end; function TcaSingleCell.GetAsString: String; begin Result := Utils.SingleToString(FValue, ''); end; function TcaSingleCell.GetValue: Single; begin Result := FValue; end; procedure TcaSingleCell.SetAsString(const Value: String); begin SetValue(Utils.StringToSingle(Value)); end; procedure TcaSingleCell.SetValue(const Value: Single); begin FValue := Value; Changed; end; //---------------------------------------------------------------------------- // TcaDoubleCell   //---------------------------------------------------------------------------- constructor TcaDoubleCell.Create; begin inherited; CellType := ctDouble; end; function TcaDoubleCell.GetAsString: String; begin Result := Utils.DoubleToString(FValue, ''); end; function TcaDoubleCell.GetValue: Double; begin Result := FValue; end; procedure TcaDoubleCell.SetAsString(const Value: String); begin SetValue(Utils.StringToDouble(Value)); end; procedure TcaDoubleCell.SetValue(const Value: Double); begin FValue := Value; Changed; end; //---------------------------------------------------------------------------- // TcaExtendedCell   //---------------------------------------------------------------------------- constructor TcaExtendedCell.Create; begin inherited; CellType := ctExtended; end; function TcaExtendedCell.GetAsString: String; begin Result := Utils.ExtendedToString(FValue, ''); end; function TcaExtendedCell.GetValue: Extended; begin Result := FValue; end; procedure TcaExtendedCell.SetAsString(const Value: String); begin SetValue(Utils.StringToExtended(Value)); end; procedure TcaExtendedCell.SetValue(const Value: Extended); begin FValue := Value; Changed; end; //---------------------------------------------------------------------------- // TcaStringCell   //---------------------------------------------------------------------------- constructor TcaStringCell.Create; begin inherited; CellType := ctString; FMemo := TStringList.Create; end; destructor TcaStringCell.Destroy; begin FMemo.Free; inherited; end; // Property methods  function TcaStringCell.GetAsMemo: TStrings; begin FMemo.Text := FValue; Result := FMemo; end; function TcaStringCell.GetAsString: String; begin Result := FValue; end; function TcaStringCell.GetValue: String; begin Result := FValue; end; procedure TcaStringCell.SetAsMemo(const Value: TStrings); begin FMemo.Assign(Value); FValue := FMemo.Text; end; procedure TcaStringCell.SetAsString(const Value: String); begin SetValue(Value); end; procedure TcaStringCell.SetValue(const Value: String); begin FValue := Value; Changed; end; //---------------------------------------------------------------------------- // TcaMemoCell   //---------------------------------------------------------------------------- constructor TcaMemoCell.Create; begin inherited; CellType := ctMemo; FValue := TStringList.Create; end; destructor TcaMemoCell.Destroy; begin FValue.Free; inherited; end; function TcaMemoCell.GetAsString: String; begin Result := Utils.MemoToString(FValue); end; function TcaMemoCell.GetValue: TStrings; begin Result := FValue; end; procedure TcaMemoCell.SetAsString(const Value: String); begin Utils.StringToMemo(Value, FValue); Changed; end; procedure TcaMemoCell.SetValue(const Value: TStrings); begin FValue := Value; Changed; end; //---------------------------------------------------------------------------- // TcaBooleanCell   //---------------------------------------------------------------------------- constructor TcaBooleanCell.Create; begin inherited; CellType := ctBoolean; end; function TcaBooleanCell.GetAsString: String; begin Result := Utils.BooleanToString(FValue); end; function TcaBooleanCell.GetValue: Boolean; begin Result := FValue; end; procedure TcaBooleanCell.SetAsString(const Value: String); begin SetValue(Utils.StringToBoolean(Value)); end; procedure TcaBooleanCell.SetValue(const Value: Boolean); begin FValue := Value; Changed; end; //---------------------------------------------------------------------------- // TcaDateTimeCell   //---------------------------------------------------------------------------- constructor TcaDateTimeCell.Create; begin inherited; CellType := ctDateTime; end; function TcaDateTimeCell.GetAsString: String; begin Result := Utils.DateTimeToString(FValue, ''); end; function TcaDateTimeCell.GetValue: TDateTime; begin Result := FValue; end; procedure TcaDateTimeCell.SetAsString(const Value: String); begin SetValue(Utils.StringToDateTime(Value)); end; procedure TcaDateTimeCell.SetValue(const Value: TDateTime); begin FValue := Value; Changed; end; //---------------------------------------------------------------------------- // TcaFormulaCell   //---------------------------------------------------------------------------- constructor TcaFormulaCell.Create; begin inherited; CellType := ctFormula; end; function TcaFormulaCell.GetAsString: String; begin Result := FValue; end; function TcaFormulaCell.GetValue: String; begin Result := FValue; end; procedure TcaFormulaCell.SetAsString(const Value: String); begin SetValue(Value); end; procedure TcaFormulaCell.SetValue(const Value: String); begin FValue := Value; Changed; end; end.
unit ANovaFracaoFaccionista; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, Componentes1, ExtCtrls, PainelGradiente, Mask, numericos, ComCtrls, StdCtrls, Localizacao, Buttons, DBKeyViolation, Constantes, UnDadosProduto, UnOrdemProducao; type TRBTipoTela = (ttNovaFracao,ttRetornoFracao, ttDevolucao,ttRevisao); TFNovaFracaoFaccionista = class(TFormularioPermissao) PainelGradiente1: TPainelGradiente; PanelColor2: TPanelColor; Localiza: TConsultaPadrao; BGravar: TBitBtn; BCancelar: TBitBtn; ValidaGravacao1: TValidaGravacao; BCadastrar: TBitBtn; BFechar: TBitBtn; PanelColor3: TPanelColor; PanelColor1: TPanelColor; Label2: TLabel; SFilial: TSpeedButton; Label3: TLabel; Label1: TLabel; SOP: TSpeedButton; Label4: TLabel; Label5: TLabel; SFracao: TSpeedButton; Label6: TLabel; Label12: TLabel; SpeedButton6: TSpeedButton; Label13: TLabel; Label7: TLabel; SIdEstagio: TSpeedButton; Label8: TLabel; Label11: TLabel; LQtdEnviado: TLabel; LUMProducaoHora: TLabel; Label9: TLabel; SFaccionista: TSpeedButton; Label10: TLabel; Bevel1: TBevel; LValUnitario: TLabel; EFilial: TEditLocaliza; EOrdemProducao: TEditLocaliza; EFracao: TEditLocaliza; EUsuario: TEditLocaliza; EIDEstagio: TEditLocaliza; EQtdEnviado: Tnumerico; EFaccionista: TEditLocaliza; EData: TEditColor; EValUnitario: Tnumerico; PDevolucao: TPanelColor; CTipoMotivo: TRadioGroup; PFracaoFaccionista: TPanelColor; Label16: TLabel; Label14: TLabel; Label17: TLabel; Label18: TLabel; ETaxEntrega: Tnumerico; EDatRetorno: TCalendario; EUM: TComboBoxColor; EValUnitarioPosterior: Tnumerico; PRetornoFracao: TPanelColor; Bevel2: TBevel; Label19: TLabel; Label20: TLabel; Label21: TLabel; CFinalizar: TCheckBox; EDataNegociado: TCalendario; EValUniPosteriorRetorno: Tnumerico; EValUniREtorno: Tnumerico; EDesMotivo: TMemoColor; Label22: TLabel; CDefeito: TCheckBox; Label15: TLabel; EProduto: TEditLocaliza; SpeedButton1: TSpeedButton; LNomProduto: TLabel; BTerceiros: TBitBtn; EEstagio: TRBEditLocaliza; SEstagio: TSpeedButton; LSaldo: TLabel; ESaldo: Tnumerico; EQtdDevolucao: Tnumerico; LQtdDevolucao: TLabel; EDatEnvio: TCalendario; LDatEnvio: TLabel; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure EFilialChange(Sender: TObject); procedure BGravarClick(Sender: TObject); procedure EOrdemProducaoSelect(Sender: TObject); procedure EOrdemProducaoRetorno(Retorno1, Retorno2: String); procedure EFracaoSelect(Sender: TObject); procedure EIDEstagioSelect(Sender: TObject); procedure EFaccionistaCadastrar(Sender: TObject); procedure BCancelarClick(Sender: TObject); procedure BCadastrarClick(Sender: TObject); procedure EFaccionistaExit(Sender: TObject); procedure EQtdEnviadoExit(Sender: TObject); procedure BFecharClick(Sender: TObject); procedure EFaccionistaSelect(Sender: TObject); procedure EFracaoRetorno(Retorno1, Retorno2: String); procedure EFilialKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure BTerceirosClick(Sender: TObject); procedure EEstagioFimConsulta(Sender: TObject); private { Private declarations } VprAcao : Boolean; VprOperacao : TRBDOperacaoCadastro; VprDFracaoFaccionista : TRBDFracaoFaccionista; VprDRetornoFracao : TRBDRetornoFracaoFaccionista; VprDDevolucaoFracao : TRBDDevolucaoFracaoFaccionista; VprDRevisaoFracao : TRBDRevisaoFracaoFaccionista; VprDOrdemProducao : TRBDordemProducao; VprDFracaoOP : TRBDFracaoOrdemProducao; VprTipoTela : TRBTipoTela; FunOrdemProducao : TRBFuncoesOrdemProducao; VprDatEnvio : TDateTime; procedure InicializaTela; procedure InicializaTelaRetorno; procedure InicializaTelaDevolucao; procedure InicializaTelaREvisao; procedure CarDClasse; function CarDClasseRetorno : string; function CarDClasseDevolucao : String; function CarDClasseRevisao : String; function CarSeqItemFaccionista : String; procedure EstadoBotoes(VpaEstado : Boolean); procedure ConfiguraTelaRetornoFaccionista; procedure ConfiguraTamanhoTela; function GravaDFracaoFaccionista : String; function GravaDRetornoFaccionista : string; function GravaDDevolucaoFaccionista : string; function GravaDRevisaoFaccionista : String; procedure PreencheCodBarras; procedure ConfiguraTela; public { Public declarations } function NovaFracaoFaccionista : Boolean; function RetornoFracaoFaccionista : Boolean; function DevolucaoFracaoFaccionista : Boolean; function RevisaoFracaoFaccionista(VpaDRevisaoFracao : TRBDRevisaoFracaoFaccionista) : boolean; end; var FNovaFracaoFaccionista: TFNovaFracaoFaccionista; implementation uses APrincipal,FunData, FunObjeto, ConstMsg, UnProdutos, ATerceiroFaccionista, ANovaFaccionista; {$R *.DFM} { ****************** Na criação do Formulário ******************************** } procedure TFNovaFracaoFaccionista.FormCreate(Sender: TObject); begin { abre tabelas } { chamar a rotina de atualização de menus } FunOrdemProducao := TRBFuncoesOrdemProducao.cria(FPrincipal.BaseDados); VprDRetornoFracao := TRBDRetornoFracaoFaccionista.cria; VprAcao := false; VprDOrdemProducao := TRBDOrdemProducao.cria; VprDFracaoOP := TRBDFracaoOrdemProducao.cria; VprDFracaoFaccionista := TRBDFracaoFaccionista.cria; VprDDevolucaoFracao := TRBDDevolucaoFracaoFaccionista.cria; VprDatEnvio := now; ConfiguraTela; end; { ******************* Quando o formulario e fechado ************************** } procedure TFNovaFracaoFaccionista.FormClose(Sender: TObject; var Action: TCloseAction); begin { fecha tabelas } { chamar a rotina de atualização de menus } VprDFracaoOP.free; VprDOrdemProducao.free; VprDFracaoFaccionista.free; VprDRetornoFracao.free; VprDDevolucaoFracao.free; FunOrdemProducao.free; Action := CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações Diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} {******************************************************************************} procedure TFNovaFracaoFaccionista.EFilialChange(Sender: TObject); begin if VprOperacao in [ocInsercao] then ValidaGravacao1.execute; end; {******************************************************************************} procedure TFNovaFracaoFaccionista.InicializaTela; begin EstadoBotoes(true); VprOperacao :=ocInsercao; PanelColor1.Enabled := TRUE; VprDFracaoFaccionista.free; VprDFracaoFaccionista := TRBDFracaoFaccionista.Cria; VprDFracaoFaccionista.CodUsuario := varia.CodigoUsuario; VprDFracaoFaccionista.DatDigitacao := now; VprDFracaoFaccionista.DatRetorno := incdia(date,1); VprDFracaoFaccionista.ValEstagio := 0; LimpaComponentes(PanelColor3,0); EDatEnvio.Date := VprDatEnvio; EUsuario.AInteiro := VprDFracaoFaccionista.CodUsuario; EUsuario.Atualiza; EData.Text := FormatDateTime('DD/MM/YYYY HH:MM:SS',VprDFracaoFaccionista.DatDigitacao); EQtdEnviado.ReadOnly := false; EValUnitario.ReadOnly := false; EDatRetorno.DateTime := VprDFracaoFaccionista.DatRetorno; ActiveControl := EFilial; ConfiguraTamanhoTela; end; {******************************************************************************} procedure TFNovaFracaoFaccionista.InicializaTelaRetorno; begin VprOperacao :=ocConsulta; LimpaComponentes(PanelColor3,0); EstadoBotoes(true); VprOperacao :=ocInsercao; PanelColor1.Enabled := TRUE; VprDRetornoFracao.Free; VprDRetornoFracao := TRBDRetornoFracaoFaccionista.Cria; VprDRetornoFracao.CodUsuario := varia.CodigoUsuario; VprDRetornoFracao.DatDigitacao := now; EUsuario.AInteiro := VprDRetornoFracao.CodUsuario; EUsuario.Atualiza; EData.Text := FormatDateTime('DD/MM/YYYY HH:MM:SS',VprDRetornoFracao.DatDigitacao); EDataNegociado.DateTime := montadata(1,1,2000); EDatEnvio.Date := VprDatEnvio; ActiveControl := EFilial; end; {******************************************************************************} procedure TFNovaFracaoFaccionista.InicializaTelaDevolucao; begin VprOperacao :=ocConsulta; LimpaComponentes(PanelColor3,0); EstadoBotoes(true); VprOperacao :=ocInsercao; PanelColor1.Enabled := TRUE; VprDDevolucaoFracao.Free; VprDDevolucaoFracao := TRBDDevolucaoFracaoFaccionista.Cria; VprDDevolucaoFracao.CodUsuario := varia.CodigoUsuario; VprDDevolucaoFracao.DatCadastro := now; EUsuario.AInteiro := VprDDevolucaoFracao.CodUsuario; EUsuario.Atualiza; EData.Text := FormatDateTime('DD/MM/YYYY HH:MM:SS',VprDDevolucaoFracao.DatCadastro); CTipoMotivo.ItemIndex := 0; ActiveControl := EFilial; end; {******************************************************************************} procedure TFNovaFracaoFaccionista.InicializaTelaREvisao; begin VprOperacao := ocConsulta; LimpaComponentes(PanelColor3,0); EstadoBotoes(true); VprOperacao :=ocInsercao; PanelColor1.Enabled := TRUE; VprDRevisaoFracao.CodUsuario := varia.CodigoUsuario; VprDRevisaoFracao.DatRevisao := now; EUsuario.AInteiro := VprDRevisaoFracao.CodUsuario; EUsuario.Atualiza; EData.Text := FormatDateTime('DD/MM/YYYY HH:MM:SS',VprDRevisaoFracao.DatRevisao); EFilial.AInteiro := VprDRevisaoFracao.CodFilial; EFilial.Atualiza; EOrdemProducao.AInteiro := VprDRevisaoFracao.SeqOrdem; EOrdemProducao.Atualiza; EFracao.AInteiro := VprDRevisaoFracao.SeqFracao; EFracao.Atualiza; if config.EnviarFracaoFaccionistaPeloEstagio then begin EEstagio.AInteiro := VprDRevisaoFracao.SeqEstagio; EEstagio.Atualiza; end else begin EIDEstagio.AInteiro := VprDRevisaoFracao.SeqEstagio; EIDEstagio.Atualiza; end; EFaccionista.AInteiro := VprDRevisaoFracao.CodFaccionista; EFaccionista.Atualiza; EProduto.Text := VprDRevisaoFracao.CodProduto; LNomProduto.caption := VprDRevisaoFracao.NomProduto; AlterarEnabledDet([EFilial,EOrdemProducao,EFracao,EIDEstagio,EEstagio,EFaccionista,SFilial,SOP,SFracao,SIdEstagio,SFaccionista],false); ActiveControl := EQtdEnviado;; end; {******************************************************************************} function TFNovaFracaoFaccionista.NovaFracaoFaccionista : Boolean; begin PRetornoFracao.Visible := false; VprTipoTela := ttNovaFracao; InicializaTela; Showmodal; result := VprAcao; end; {******************************************************************************} function TFNovaFracaoFaccionista.RetornoFracaoFaccionista : Boolean; begin Caption := 'Retorno Fração Faccionista'; PainelGradiente1.Caption := ' Retorno Fração Faccionista '; LQtdEnviado.Caption := 'Qtd Produzido :'; VprTipoTela := ttRetornoFracao; InicializaTelaRetorno; ConfiguraTelaRetornoFaccionista; showmodal; Result := VprAcao; end; {******************************************************************************} function TFNovaFracaoFaccionista.DevolucaoFracaoFaccionista : Boolean; begin Caption := 'Devolução Fração Faccionista'; PainelGradiente1.Caption := ' Devolução Fração Faccionista '; LQtdEnviado.Caption := 'Qtd Devolvido :'; VprTipoTela := ttDevolucao; InicializaTelaDevolucao; ConfiguraTelaRetornoFaccionista; showmodal; Result := VprAcao; end; {******************************************************************************} function TFNovaFracaoFaccionista.RevisaoFracaoFaccionista(VpaDRevisaoFracao : TRBDRevisaoFracaoFaccionista) : boolean; begin Caption := 'Revisão Fração Faccionista'; PainelGradiente1.Caption := ' Revisão Fração Faccionista '; LQtdEnviado.Caption := 'Qtd Revisado : '; LValUnitario.Caption := 'Qtd Defeitos : '; VprTipoTela := ttRevisao; VprDRevisaoFracao := VpaDRevisaoFracao; InicializaTelaREvisao; ConfiguraTelaRetornoFaccionista; ShowModal; result := VprAcao; end; {******************************************************************************} procedure TFNovaFracaoFaccionista.CarDClasse; begin with VprDFracaoFaccionista do begin CodFilial := EFilial.AInteiro; SeqOrdem := EOrdemProducao.AInteiro; SeqFracao := EFracao.AInteiro; if config.EnviarFracaoFaccionistaPeloEstagio then SeqIDEstagio := EEstagio.AInteiro else SeqIDEstagio := EIDEstagio.AInteiro; CodUsuario := EUsuario.AInteiro; DatCadastro := EDatEnvio.DateTime; DatRetorno := EDatRetorno.DateTime; CodFaccionista := EFaccionista.AInteiro; QtdEnviado := EQtdEnviado.AValor; IndDefeito := CDefeito.Checked; DesUM := EUM.Text; ValUnitario := EValUnitario.AValor; ValUnitarioPosterior := EValUnitarioPosterior.AValor; ValTaxaEntrega := ETaxEntrega.AValor; end; end; {******************************************************************************} function TFNovaFracaoFaccionista.CarDClasseRetorno : String; begin result := CarSeqItemFaccionista; if result = '' then begin with VprDRetornoFracao do begin CodFilial := EFilial.AInteiro; SeqOrdem := EOrdemProducao.AInteiro; SeqFracao := EFracao.AInteiro; if config.EnviarFracaoFaccionistaPeloEstagio then SeqIDEstagio := EEstagio.AInteiro else SeqIDEstagio := EIDEstagio.AInteiro; CodFaccionista := EFaccionista.AInteiro; QtdRetorno := EQtdEnviado.AValor; ValUnitario := EValUnitario.AValor; DatCadastro := EDatEnvio.Date; IndFinalizar := CFinalizar.Checked; IndDefeito := CDefeito.Checked; IndValorMenor := false; if (MontaData(dia(VprDRetornoFracao.DatCadastro),mes(VprDRetornoFracao.DatCadastro),ano(VprDRetornoFracao.DatCadastro)) > VprDRetornoFracao.DatNegociado) and (VprDRetornoFracao.ValUnitario <> VprDRetornoFracao.ValUnitarioPosteriorEnviado) then IndValorMenor := true; end; end; end; {******************************************************************************} function TFNovaFracaoFaccionista.CarDClasseDevolucao : String; begin result := CarSeqItemFaccionista; if result = '' then begin with VprDDevolucaoFracao do begin CodUsuario := varia.CodigoUsuario; DatCadastro := now; CodFilial := EFilial.AInteiro; SeqOrdem := EOrdemProducao.AInteiro; SeqFracao := EFracao.AInteiro; CodFaccionista := EFaccionista.AInteiro; QtdDevolvido := EQtdEnviado.AValor; DesMotivo := EDesMotivo.Lines.Text; CodMotivo := CTipoMotivo.ItemIndex; if config.EnviarFracaoFaccionistaPeloEstagio then SeqIDEstagio := EEstagio.AInteiro else SeqIDEstagio := EIDEstagio.AInteiro; end; end; end; {******************************************************************************} function TFNovaFracaoFaccionista.CarDClasseRevisao : String; begin Result := ''; if EQtdEnviado.AValor = 0 then result := 'QUANTIDADE REVISADO INVÁLIDO!!!'#13'É necessário preencher a quantidade que foi revisado.'; if result = '' then begin VprDRevisaoFracao.QtdRevisado := EQtdEnviado.AValor; VprDRevisaoFracao.QtdDefeito := EValUnitario.AValor; end; end; {******************************************************************************} function TFNovaFracaoFaccionista.CarSeqItemFaccionista : String; var vpfEstagio : Integer; begin result := ''; if Config.EnviarFracaoFaccionistaPeloEstagio then vpfEstagio := EEstagio.AInteiro else vpfEstagio := EIDEstagio.AInteiro; FunOrdemProducao.CarValoreSeqItemFaccionista(EFilial.Ainteiro,EOrdemProducao.AInteiro,EFracao.AInteiro, vpfEstagio,EFaccionista.AInteiro,CDefeito.Checked,VprDRetornoFracao); ESaldo.AValor := VprDRetornoFracao.QtdFaltante; if VprDRetornoFracao.SeqItem = 0 then result := 'FRAÇÃO NÃO ENVIADA PARA ESSE FACCIONISTA!!!'#13'A fração digitada não foi enviada para esse faccionista'; if result = '' then begin if VprDRetornoFracao.DatFinalizacaoFracao > MontaData(1,1,1990) then begin if not confirmacao('FRAÇÃO JÁ SE ENCONTRA FINALIZADA NO DIA '+FormatDateTime('DD/MM/YYYY',VprDRetornoFracao.DatFinalizacaoFracao)+ '!!!'#13'Tem certeza que deseja continuar ?') then result := 'FRAÇÃO JÁ SE ENCONTRA FINALIZADA!!!'; end; EDataNegociado.DateTime := VprDRetornoFracao.DatNegociado; EValUniREtorno.AValor := VprDRetornoFracao.ValUnitarioEnviado; EValUniPosteriorRetorno.AValor := VprDRetornoFracao.ValUnitarioPosteriorEnviado; VprDDevolucaoFracao.SeqItem := VprDRetornoFracao.SeqItem; end; end; {******************************************************************************} procedure TFNovaFracaoFaccionista.EstadoBotoes(VpaEstado : Boolean); begin BGravar.Enabled := VpaEstado; BCancelar.Enabled:= VpaEstado; BCadastrar.Enabled := not VpaEstado; BFechar.Enabled := not VpaEstado; end; {******************************************************************************} procedure TFNovaFracaoFaccionista.ConfiguraTela; begin EEstagio.Visible := Config.EnviarFracaoFaccionistaPeloEstagio; SEstagio.Visible:= Config.EnviarFracaoFaccionistaPeloEstagio; EIDEstagio.Visible := not Config.EnviarFracaoFaccionistaPeloEstagio; SIdEstagio.Visible := not Config.EnviarFracaoFaccionistaPeloEstagio; end; {******************************************************************************} procedure TFNovaFracaoFaccionista.ConfiguraTelaRetornoFaccionista; begin if VprTipoTela = ttRetornoFracao then begin PFracaoFaccionista.Visible := false; FNovaFracaoFaccionista.Height := FNovaFracaoFaccionista.Height - PFracaoFaccionista.Height+PRetornoFracao.Height ; LDatEnvio.Caption := 'Data Retorno :'; end else if VprTipoTela = ttDevolucao then begin PFracaoFaccionista.Visible := false; PRetornoFracao.Visible := false; PDevolucao.Visible := true; EValUnitario.Visible := false; LValUnitario.Visible := false; end else if VprTipoTela = ttRevisao then begin PFracaoFaccionista.Visible := false; PRetornoFracao.Visible := false; PDevolucao.Visible := false; // PRevisao.visible := true; BCadastrar.Visible := false; BTerceiros.Visible := true; end; ConfiguraTamanhoTela; end; {******************************************************************************} procedure TFNovaFracaoFaccionista.ConfiguraTamanhoTela; var vpfLaco : Integer; VpfTamanho : Integer; begin AlterarVisibleDet([LSaldo,ESaldo,LQtdDevolucao,EQtdDevolucao],VprTipoTela = ttRetornoFracao); AlterarVisibleDet([LDatEnvio,EDatEnvio],VprTipoTela in[ttNovaFracao,ttRetornoFracao]); VpfTamanho :=0; if PanelColor1.Visible then VpfTamanho := VpfTamanho + PanelColor1.Height; if PFracaoFaccionista.Visible then VpfTamanho := VpfTamanho + PFracaoFaccionista.Height; if PRetornoFracao.Visible then VpfTamanho := VpfTamanho + PRetornoFracao.Height; if PDevolucao.Visible then VpfTamanho := VpfTamanho + PDevolucao.Height - 35; // if PRevisao.Visible then // VpfTamanho := VpfTamanho +PRevisao.Height; VpfTamanho := VpfTamanho + 35; Height := VpfTamanho +PainelGradiente1.Height +PanelColor2.Height; end; {******************************************************************************} function TFNovaFracaoFaccionista.GravaDFracaoFaccionista : String; begin CarDClasse; if not config.PermitirEnviarFracaoMaisde1VezparaoMesmoFaccionista then if not VprDFracaoFaccionista.IndDefeito then if FunOrdemProducao.ExisteFracaoFaccionista(VprDFracaoFaccionista) then result := 'FRAÇÃO FACCIONISTA DUPLICADO!!!'#13'Não é possível enviar a mesma fração mais de uma vez para o mesmo faccionista.'; if result = '' then result := FunOrdemProducao.GravaDFracaoFaccionista(VprDFracaoFaccionista); end; {******************************************************************************} function TFNovaFracaoFaccionista.GravaDRetornoFaccionista : string; begin result := CarDClasseRetorno; if result = '' then begin result := FunOrdemProducao.GravaDRetornoFracaoFaccionista(VprDRetornoFracao); if EQtdDevolucao.AValor > 0 then begin result := CarDClasseDevolucao; if result = '' then begin VprDDevolucaoFracao.QtdDevolvido := EQtdDevolucao.AValor; result := FunOrdemProducao.GravaDDevolucaoFracaoFaccionista(VprDDevolucaoFracao); end; end; end; end; {******************************************************************************} function TFNovaFracaoFaccionista.GravaDDevolucaoFaccionista : string; begin result := CarDClasseDevolucao; if result = '' then begin result := FunOrdemProducao.GravaDDevolucaoFracaoFaccionista(VprDDevolucaoFracao); end; end; {******************************************************************************} function TFNovaFracaoFaccionista.GravaDRevisaoFaccionista : String; begin result := CarDClasseRevisao; if result = '' then result := FunOrdemProducao.GravaDRevisaoFracaoFaccionista(VprDRevisaoFracao); end; {******************************************************************************} procedure TFNovaFracaoFaccionista.PreencheCodBarras; begin if Length(EFilial.Text) = 12 then begin EOrdemProducao.AInteiro := StrtoInt(copy(EFilial.Text,3,6)); EFracao.AInteiro := StrToInt(copy(EFilial.Text,9,4)); EFilial.AInteiro := StrToInt(copy(EFilial.Text,1,2)); EFilial.Atualiza; EOrdemProducao.Atualiza; EFracao.Atualiza; ActiveControl := EIDEstagio; end; end; {******************************************************************************} procedure TFNovaFracaoFaccionista.BGravarClick(Sender: TObject); var VpfResultado : String; begin VpfResultado := ''; if VprTipoTela = ttNovaFracao then VpfResultado := GravaDFracaoFaccionista else if VprTipoTela = ttRetornoFracao then VpfResultado := GravaDRetornoFaccionista else if VprTipoTela = ttDevolucao then VpfResultado := GravaDDevolucaoFaccionista else if VprTipoTela = ttRevisao then VpfResultado := GravaDRevisaoFaccionista; if VpfResultado = '' then begin VprDatEnvio := EDatEnvio.Date; VprAcao := true; EstadoBotoes(false); PanelColor1.Enabled := false; if VprTipoTela = ttRevisao then close else VprOperacao := ocConsulta; end else Aviso(VpfResultado); end; {******************************************************************************} procedure TFNovaFracaoFaccionista.EOrdemProducaoSelect(Sender: TObject); begin EOrdemProducao.ASelectLocaliza.Text := 'Select ORD.SEQORD, ORD.DATEMI, CLI.C_NOM_CLI from ORDEMPRODUCAOCORPO ORD, CADCLIENTES CLI '+ ' Where ORD.EMPFIL = '+ IntToStr(EFilial.AInteiro)+ ' and ORD.CODCLI = CLI.I_COD_CLI '+ ' AND CLI.C_NOM_CLI like ''@%'''; EOrdemProducao.ASelectValida.Text := 'Select ORD.SEQORD, ORD.DATEMI, CLI.C_NOM_CLI From ORDEMPRODUCAOCORPO ORD, CADCLIENTES CLI '+ ' Where ORD.EMPFIL = '+ IntToStr(EFilial.AInteiro)+ ' and ORD.CODCLI = CLI.I_COD_CLI '+ ' AND ORD.SEQORD = @'; end; {******************************************************************************} procedure TFNovaFracaoFaccionista.EOrdemProducaoRetorno(Retorno1, Retorno2: String); begin end; {******************************************************************************} procedure TFNovaFracaoFaccionista.EFracaoSelect(Sender: TObject); begin EFracao.ASelectLocaliza.Text := 'SELECT FRA.SEQFRACAO, FRA.DATENTREGA, FRA.QTDPRODUTO, FRA.CODESTAGIO from FRACAOOP FRA '+ ' Where FRA.SEQFRACAO LIKE ''@%'''+ ' AND FRA.CODFILIAL = '+IntToStr(EFilial.AInteiro)+ ' and FRA.SEQORDEM = '+IntToStr(EOrdemProducao.AInteiro); EFracao.ASelectValida.Text := 'SELECT FRA.SEQFRACAO, FRA.DATENTREGA, FRA.QTDPRODUTO, FRA.CODESTAGIO from FRACAOOP FRA '+ ' Where FRA.SEQFRACAO = @ '+ ' AND FRA.CODFILIAL = '+IntToStr(EFilial.AInteiro)+ ' and FRA.SEQORDEM = '+IntToStr(EOrdemProducao.AInteiro); end; {******************************************************************************} procedure TFNovaFracaoFaccionista.EIDEstagioSelect(Sender: TObject); begin EIDEstagio.ASelectValida.Text := 'Select FRA.SEQESTAGIO, PRO.DESESTAGIO, PRO.QTDPRODUCAOHORA, FRA.QTDPRODUZIDO '+ ' from FRACAOOPESTAGIO FRA, PRODUTOESTAGIO PRO '+ ' Where FRA.CODFILIAL = '+IntToStr(EFilial.AInteiro)+ ' and FRA.SEQORDEM = '+IntToStr(EOrdemProducao.AInteiro)+ ' AND FRA.SEQFRACAO = '+ IntToStr(EFracao.AInteiro)+ ' AND FRA.SEQESTAGIO = @'+ ' AND PRO.SEQPRODUTO = FRA.SEQPRODUTO '+ ' AND PRO.SEQESTAGIO = FRA.SEQESTAGIO'; EIDEstagio.ASelectLocaliza.Text := 'Select FRA.SEQESTAGIO, PRO.DESESTAGIO, PRO.QTDPRODUCAOHORA, FRA.QTDPRODUZIDO '+ ' from FRACAOOPESTAGIO FRA, PRODUTOESTAGIO PRO '+ ' Where FRA.CODFILIAL = '+IntToStr(EFilial.AInteiro)+ ' and FRA.SEQORDEM = '+IntToStr(EOrdemProducao.AInteiro)+ ' AND FRA.SEQFRACAO = '+ IntToStr(EFracao.AInteiro)+ ' AND PRO.DESESTAGIO LIKE ''@%'''+ ' AND PRO.SEQPRODUTO = FRA.SEQPRODUTO '+ ' AND PRO.SEQESTAGIO = FRA.SEQESTAGIO'; end; {******************************************************************************} procedure TFNovaFracaoFaccionista.EEstagioFimConsulta(Sender: TObject); begin if (VprTipoTela = ttNovaFracao) then begin VprDFracaoFaccionista.ValEstagio := FunOrdemProducao.RValorEstagio(EEstagio.AInteiro); if VprDFracaoFaccionista.ValEstagio <> 0 then begin EValUnitario.AValor := VprDFracaoFaccionista.ValEstagio; EValUnitarioPosterior.AValor := VprDFracaoFaccionista.ValEstagio; end; end; end; {******************************************************************************} procedure TFNovaFracaoFaccionista.EFaccionistaCadastrar(Sender: TObject); begin FNovaFaccionista := TFNovaFaccionista.CriarSDI(self,'',FPrincipal.VerificaPermisao('FNovaFaccionista')); FNovaFaccionista.Faccionistas.Insert; FNovaFaccionista.ShowModal; FNovaFaccionista.free; end; {******************************************************************************} procedure TFNovaFracaoFaccionista.BCancelarClick(Sender: TObject); begin close; end; {******************************************************************************} procedure TFNovaFracaoFaccionista.BCadastrarClick(Sender: TObject); begin if (VprTipoTela = ttNovaFracao) then InicializaTela else if VprTipoTela = ttRetornoFracao then InicializaTelaRetorno else if VprTipoTela = ttdevolucao then InicializaTelaDevolucao; end; {******************************************************************************} procedure TFNovaFracaoFaccionista.EFaccionistaExit(Sender: TObject); var VpfResultado : String; begin if (VprOperacao = ocInsercao) and (VprTipoTela in [ttRetornoFracao,ttDevolucao] ) then begin VpfResultado := CarSeqItemFaccionista; if VpfResultado <> '' then aviso(VpfREsultado) else EValUnitario.AValor := VprDRetornoFracao.ValUnitario; end; end; {******************************************************************************} procedure TFNovaFracaoFaccionista.EQtdEnviadoExit(Sender: TObject); begin if VprTipoTela = ttRetornoFracao then begin if (VprOperacao = ocInsercao) and (VprDRetornoFracao.SeqItem <> 0 ) then if not Config.PermitirEnviarFracaoMaisde1VezparaoMesmoFaccionista then CFinalizar.Checked := ((VprDRetornoFracao.QtdFaltante - EQtdEnviado.AValor) <=0); end; end; {******************************************************************************} procedure TFNovaFracaoFaccionista.BFecharClick(Sender: TObject); begin close; end; {******************************************************************************} procedure TFNovaFracaoFaccionista.EFaccionistaSelect(Sender: TObject); begin EFaccionista.ASelectValida.Text := 'Select * from FACCIONISTA ' + ' Where CODFACCIONISTA = @ '; EFaccionista.ASelectLocaliza.text := 'Select * from FACCIONISTA '+ ' Where NOMFACCIONISTA LIKE ''@%'''; if VprTipoTela = ttNovaFracao then begin EFaccionista.ASelectValida.Text := EFaccionista.ASelectValida.Text +' and INDATIVA = ''S'''; EFaccionista.ASelectLocaliza.text := EFaccionista.ASelectLocaliza.text + ' and INDATIVA = ''S'''; end; EFaccionista.ASelectLocaliza.text := EFaccionista.ASelectLocaliza.text + ' order by NOMFACCIONISTA '; end; {******************************************************************************} procedure TFNovaFracaoFaccionista.EFracaoRetorno(Retorno1, Retorno2: String); var VpfDProduto : TRBDProduto; begin if (EFilial.AInteiro <> 0) and (EOrdemProducao.AInteiro <> 0) then begin if ( ttRetornoFracao = VprTipoTela) or (ttNovaFracao = VprTipoTela) then begin VprDOrdemProducao.free; VprDOrdemProducao := TRBDOrdemProducao.cria; FunOrdemProducao.CarDOrdemProducaoBasica(EFilial.AInteiro,EOrdemProducao.AInteiro,VprDOrdemProducao); if (ttNovaFracao = VprTipoTela) then begin VpfDProduto := TRBDProduto.Cria; FunProdutos.CarDProduto(VpfDProduto,Varia.CodigoEmpresa,Varia.CodigoEmpFil,VprDOrdemProducao.SeqProduto); EValUnitario.AValor := VpfDProduto.ValPrecoFaccionista; EValUnitarioPosterior.AValor := VpfDProduto.ValPrecoFaccionista; VpfDProduto.Free; end; if varia.TipoOrdemProducao = toAgrupada then begin end else begin EUM.Items.Clear; EUM.Items.Assign(FunProdutos.RUnidadesParentes(VprDOrdemProducao.UMPedido)); EProduto.Text := VprDOrdemProducao.CodProduto; LNomProduto.Caption := VprDOrdemProducao.NomProduto; end; end; end; end; procedure TFNovaFracaoFaccionista.EFilialKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if key = 13 then PreencheCodBarras; end; procedure TFNovaFracaoFaccionista.BTerceirosClick(Sender: TObject); begin FTerceiroFaccionista := TFTerceiroFaccionista.criarSDI(Application,'',FPrincipal.VerificaPermisao('FTerceiroFaccionista')); if FTerceiroFaccionista.CadastraTerceiros(VprDRevisaoFracao) then begin EQtdEnviado.ReadOnly := true; EValUnitario.ReadOnly := true; EQtdEnviado.AValor := VprDRevisaoFracao.QtdRevisado; EValUnitario.AValor := VprDRevisaoFracao.QtdDefeito; end; FTerceiroFaccionista.free; end; Initialization { *************** Registra a classe para evitar duplicidade ****************** } RegisterClasses([TFNovaFracaoFaccionista]); end.
unit U.Person; interface uses System.Bindings.EvalProtocol; type TPerson = class private FBirthDate: TDate; FLastName: String; FFirstName: String; function GetIsAdult: Boolean; function GetAge: Integer; function GetFullName: String; public constructor Create(const AFirstName, ALastName, AStrBirthDate: String); property FirstName: String read FFirstName write FFirstName; property LastName: String read FLastName write FLastName; property FullName: String read GetFullName; property BirthDate: TDate read FBirthDate write FBirthDate; property Age: Integer read GetAge; property IsAdult: Boolean read GetIsAdult; end; function GetDictionaryScope: IScope; function GetPersonScopeSimple: IScope; implementation uses System.DateUtils, System.SysUtils, System.Bindings.EvalSys, System.Bindings.ObjEval; function GetDictionaryScope: IScope; var LPerson: TPerson; LPersonScope: IScope; LDictionaryScope: TDictionaryScope; begin LPerson := TPerson.Create('Maurizio', 'Del Magno', '22/10/1970'); LPersonScope := WrapObject(LPerson); LDictionaryScope := TDictionaryScope.Create; LDictionaryScope.Map.Add('Person', LPersonScope); Result := LDictionaryScope; // Compressed version // Result := TDictionaryScope.Create.Map.Add('Person', WrapObject(TPerson.Create('Maurizio', 'Del Magno', '22/10/1970'))); end; function GetPersonScopeSimple: IScope; begin Result := WrapObject(TPerson.Create('Marco', 'Mottadelli', '01/07/1980')); end; { TPerson } constructor TPerson.Create(const AFirstName, ALastName, AStrBirthDate: String); begin FFirstName := AFirstName; FLastName := ALastName; FBirthDate := StrToDate(AStrBirthDate); end; function TPerson.GetIsAdult: Boolean; begin Result := Age >= 18; end; function TPerson.GetAge: Integer; begin Result := YearsBetween(Now, FBirthDate); end; function TPerson.GetFullName: String; begin Result := FFirstName + ' ' + FLastName; end; end.
unit ADigitacaoProspect; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, Grids, CGrades, Componentes1, ExtCtrls, PainelGradiente, StdCtrls, Localizacao, Buttons, UnDados, UnDadosLocaliza, UnClientes, UnProspect, DBKeyViolation, FunObjeto; type TFDigitacaoProspect = class(TFormularioPermissao) PainelGradiente1: TPainelGradiente; PanelColor1: TPanelColor; Grade: TRBStringGridColor; PanelColor2: TPanelColor; ECodVendedor: TRBEditLocaliza; SpeedButton1: TSpeedButton; Label1: TLabel; Label2: TLabel; BGravar: TBitBtn; ECliente: TRBEditLocaliza; ERamoAtividade: TRBEditLocaliza; EUF: TRBEditLocaliza; ESuspect: TRBEditLocaliza; EHistoricoLigacao: TRBEditLocaliza; ECidade: TRBEditLocaliza; BAgendar: TBitBtn; BFechar: TBitBtn; BCancelar: TBitBtn; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure GradeCarregaItemGrade(Sender: TObject; VpaLinha: Integer); procedure GradeDadosValidos(Sender: TObject; var VpaValidos: Boolean); procedure GradeGetEditMask(Sender: TObject; ACol, ARow: Integer; var Value: String); procedure GradeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure GradeMudouLinha(Sender: TObject; VpaLinhaAtual, VpaLinhaAnterior: Integer); procedure ERamoAtividadeRetorno(VpaColunas: TRBColunasLocaliza); procedure EClienteRetorno(VpaColunas: TRBColunasLocaliza); procedure GradeNovaLinha(Sender: TObject); procedure GradeSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure BCancelarClick(Sender: TObject); procedure BGravarClick(Sender: TObject); procedure ECodVendedorChange(Sender: TObject); procedure EUFRetorno(VpaColunas: TRBColunasLocaliza); procedure GradeKeyPress(Sender: TObject; var Key: Char); procedure ESuspectRetorno(VpaColunas: TRBColunasLocaliza); procedure EHistoricoLigacaoRetorno(VpaColunas: TRBColunasLocaliza); procedure ECidadeRetorno(VpaColunas: TRBColunasLocaliza); procedure BAgendarClick(Sender: TObject); procedure BFecharClick(Sender: TObject); private { Private declarations } VprDDigiProspects : TRBDDigitacaoProspect; VprDProspect : TRBDDigitacaoProspectItem; VprDCliente : TRBDCliente; VprDSuspect : TRBDProspect; VprUltimaCidade, VprUltimoUF : string; VprUltimaData : TDateTime; procedure VerificaVariaveis; procedure CarTitulosGrade; procedure InicializaTela; procedure CarDGradeClasse; procedure ConfiguraPermissaoUsuario; procedure HabilitaBotoes(VpaEstado : Boolean); public { Public declarations } function CadastraProspect : Boolean; end; var FDigitacaoProspect: TFDigitacaoProspect; implementation uses APrincipal, Constantes, FunData, FunString, ConstMsg, ANovoAgendamento; {$R *.DFM} { ****************** Na criação do Formulário ******************************** } procedure TFDigitacaoProspect.FormCreate(Sender: TObject); begin { abre tabelas } { chamar a rotina de atualização de menus } VerificaVariaveis; VprDDigiProspects := TRBDDigitacaoProspect.cria; ConfiguraPermissaoUsuario; CarTitulosGrade; end; { ******************* Quando o formulario e fechado ************************** } procedure TFDigitacaoProspect.FormClose(Sender: TObject; var Action: TCloseAction); begin { fecha tabelas } { chamar a rotina de atualização de menus } VprDDigiProspects.free; Action := CaFree; end; {((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((( Ações Diversas )))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))} procedure TFDigitacaoProspect.VerificaVariaveis; begin if Varia.CodMeioDivulgacaoVisitaVendedor = 0 then aviso('MEIO DIVULGAÇÃO VISITA VENDEDOR NÃO PREENCHIDO!!!'#13'É necessário preencher nas configurações gerais do sistema, na página CRM o meio de divulgação da visita do vendedor.'); if varia.SeqCampanhaTelemarketing = 0 then aviso('CAMPANHA PADRÃO DE VENDAS NÃO PREENCHIDO!!!'#13'É necessário preencher nas configurações da empresa, na página TELEMARKETING a campanha padrão.'); if varia.CodHistoricoLigacaoVisitaVendedor = 0 then aviso('HISTORICO LIGAÇÃO VISITA VENDEDOR NÃO PREENCHIDO!!!'#13'É necessário preencher nas configurações gerais do sistema, na página CRM o histórigo ligação da visita do vendedor.'); end; {******************************************************************************} procedure TFDigitacaoProspect.CarTitulosGrade; begin Grade.Cells[1,0] := 'Data'; Grade.Cells[2,0] := 'Tipo'; Grade.Cells[3,0] := 'Prospect'; Grade.Cells[4,0] := 'Endereço'; Grade.Cells[5,0] := 'Bairro'; Grade.Cells[6,0] := 'Cidade'; Grade.Cells[7,0] := 'UF'; Grade.Cells[8,0] := 'Contato'; Grade.Cells[9,0] := 'e-mail'; Grade.Cells[10,0] := 'Ramo Atividade'; Grade.Cells[11,0] := 'Fone 1'; Grade.Cells[12,0] := 'Celular'; Grade.Cells[13,0] := 'Codigo'; Grade.Cells[14,0] := 'Histórico'; Grade.Cells[15,0] := 'Observações'; end; {******************************************************************************} procedure TFDigitacaoProspect.ConfiguraPermissaoUsuario; begin if (puCRNaoAlteraVendedorNaTelaDeDigitacaoRapida in varia.PermissoesUsuario) then begin ECodVendedor.Enabled:= false; SpeedButton1.Enabled:= false; end; end; {******************************************************************************} procedure TFDigitacaoProspect.InicializaTela; begin ECodVendedor.AInteiro := Varia.CodVendedor; ECodVendedor.Atualiza; if (ECodVendedor.AInteiro <> 0) or (ECodVendedor.Enabled=false) then ActiveControl := Grade else ActiveControl := ECodVendedor; Grade.ADados := VprDDigiProspects.Prospects; Grade.CarregaGrade; HabilitaBotoes(true); end; {******************************************************************************} procedure TFDigitacaoProspect.CarDGradeClasse; begin VprDProspect.DatVisita := StrToDate(Grade.Cells[1,Grade.ALinha]); VprDProspect.DesTipo := UpperCase(Grade.Cells[2,Grade.ALinha]); if VprDProspect.CodProspect = 0 then begin VprDProspect.NomProspect := UpperCase(RetiraAcentuacao(Grade.Cells[3,Grade.ALinha])); VprDProspect.DesEndereco := UpperCase(RetiraAcentuacao(Grade.Cells[4,Grade.ALinha])); VprDProspect.DesBairro := UpperCase(RetiraAcentuacao(Grade.Cells[5,Grade.ALinha])); VprDProspect.DesCidade := UpperCase(RetiraAcentuacao(Grade.Cells[6,Grade.ALinha])); VprDProspect.DesUF := UpperCase(RetiraAcentuacao(Grade.Cells[7,Grade.ALinha])); VprDProspect.DesEmail := UpperCase(RetiraAcentuacao(Grade.Cells[9,Grade.ALinha])); VprDProspect.DesFone := UpperCase(RetiraAcentuacao(Grade.Cells[11,Grade.ALinha])); VprDProspect.DesCelular := UpperCase(RetiraAcentuacao(Grade.Cells[12,Grade.ALinha])); end else begin VprDProspect.DesEndereco := UpperCase(RetiraAcentuacao(Grade.Cells[4,Grade.ALinha])); VprDProspect.DesBairro := UpperCase(RetiraAcentuacao(Grade.Cells[5,Grade.ALinha])); VprDProspect.DesEmail := UpperCase(RetiraAcentuacao(Grade.Cells[9,Grade.ALinha])); VprDProspect.DesFone := UpperCase(RetiraAcentuacao(Grade.Cells[11,Grade.ALinha])); VprDProspect.DesCelular := UpperCase(RetiraAcentuacao(Grade.Cells[12,Grade.ALinha])); end; VprDProspect.NomContato := UpperCase(RetiraAcentuacao(Grade.Cells[8,Grade.ALinha])); VprDProspect.DesObservacao := UpperCase(RetiraAcentuacao(Grade.Cells[15,Grade.ALinha])); VprUltimaCidade := UpperCase(RetiraAcentuacao(VprDProspect.DesCidade)); VprUltimaData := VprDProspect.DatVisita; VprUltimoUF := UpperCase(RetiraAcentuacao(VprDProspect.DesUF)); end; {******************************************************************************} function TFDigitacaoProspect.CadastraProspect : Boolean; begin InicializaTela; ShowModal; end; {******************************************************************************} procedure TFDigitacaoProspect.GradeCarregaItemGrade(Sender: TObject; VpaLinha: Integer); begin VprDProspect := TRBDDigitacaoProspectItem(VprDDigiProspects.Prospects.Items[VpaLinha-1]); if VprDProspect.DatVisita > montadata(1,1,1900) then Grade.Cells[1,VpaLinha] := FormatDateTime('DD/MM/YYYY',VprDProspect.DatVisita) else Grade.Cells[1,VpaLinha] := ''; Grade.Cells[2,VpaLinha] := VprDProspect.DesTipo; Grade.Cells[3,VpaLinha] := VprDProspect.NomProspect; Grade.Cells[4,VpaLinha] := VprDProspect.DesEndereco; Grade.Cells[5,VpaLinha] := VprDProspect.DesBairro; Grade.Cells[6,VpaLinha] := VprDProspect.DesCidade; Grade.Cells[7,VpaLinha] := VprDProspect.DesUF; Grade.Cells[8,VpaLinha] := VprDProspect.NomContato; Grade.Cells[9,VpaLinha] := VprDProspect.DesEmail; Grade.Cells[10,VpaLinha] := VprDProspect.NomRamoAtividade; Grade.Cells[11,VpaLinha] := VprDProspect.DesFone; Grade.Cells[12,VpaLinha] := VprDProspect.DesCelular; if VprDProspect.CodHistorico <> 0 then Grade.Cells[13,VpaLinha] := intToStr(VprDProspect.CodHistorico) else Grade.Cells[13,VpaLinha] := ''; Grade.Cells[14,VpaLinha] := VprDProspect.NomHistorico; Grade.Cells[15,VpaLinha] := VprDProspect.DesObservacao; end; {******************************************************************************} procedure TFDigitacaoProspect.GradeDadosValidos(Sender: TObject; var VpaValidos: Boolean); begin VpaValidos := true; if DeletaChars(DeletaChars(Grade.Cells[1,Grade.ALinha],'/'),' ') = '' then begin Grade.col := 1; aviso('DATA DA VISITA INVÁLIDA!!!'#13'É necessário digitar a data da visita.'); VpaValidos := false; end else if (Grade.Cells[2,Grade.ALinha] <> 'P')and (Grade.Cells[2,Grade.ALinha] <> 'S') then begin Grade.col := 2; aviso('TIPO CADASTRO INVÁLIDO!!!'#13'É necessário digitar o tipo do cadastro :'#13'P - PROSPECT'#13'S - SUSPECT'); VpaValidos := false; end else if DeletaChars(Grade.Cells[3,Grade.ALinha],' ') = '' then begin Grade.col := 3; aviso('PROSPECT INVÁLIDO!!!'#13'É necessário digitar o nome do prospect.'); VpaValidos := false; end else if not ECidade.AExisteCodigo(UpperCase(Grade.Cells[6,Grade.ALinha])) then begin Grade.col := 6; aviso('CIDADE INVÁLIDA!!!'#13'É necessário digitar uma Cidade válida.'); VpaValidos := false; end else if not EUF.AExisteCodigo(Grade.Cells[7,Grade.ALinha]) then begin Grade.col := 7; aviso('UF INVÁLIDA!!!'#13'É necessário digitar uma UF válida.'); VpaValidos := false; end else if not EHistoricoLigacao.AExisteCodigo(DeletaChars(Grade.Cells[13,Grade.ALinha],' ')) then begin Grade.col := 13; aviso('HISTORICO INVÁLIDO!!!'#13'É necessário digitar o histórico do prospect.'); VpaValidos := false; end else if DeletaChars(Grade.Cells[15,Grade.ALinha],' ') = '' then begin Grade.col := 15; aviso('OBSERVAÇÃO INVÁLIDO!!!'#13'É necessário digitar a observacao do prospect.'); VpaValidos := false; end else begin try StrToDate(Grade.Cells[1,Grade.ALinha]); except Grade.col := 1; VpaValidos := false; aviso('DATA DA VISITA INVÁLIDA!!!'#13'Foi preenchida um valor inválido para a data de visita.'); end; end; if VpaValidos then begin CarDGradeClasse; if (VprDProspect.DesEmail <> '') and (VprDProspect.CodProspect = 0) then begin if not(ExisteLetraString('@',VprDProspect.DesEmail)) then begin Grade.col := 9; VpaValidos := false; aviso('E-MAIL INVALIDO!!!!'#13'O e-mail digitado não é valido.'); end; end; end; end; {******************************************************************************} procedure TFDigitacaoProspect.GradeGetEditMask(Sender: TObject; ACol, ARow: Integer; var Value: String); begin case ACol of 1 : Value := '!99/00/0000;1;_'; 11,12 : Value := '!\(00\)>#000-0000;1; '; 13 : Value := '000000;0; '; end; end; {******************************************************************************} procedure TFDigitacaoProspect.GradeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case key of 114: case Grade.AColuna of 3 : begin if (Grade.Cells[2,Grade.ALinha] = 'P')then ECliente.AAbreLocalizacao else if (Grade.Cells[2,Grade.ALinha] = 'S')then ESuspect.AAbreLocalizacao; end; 6 : ECidade.AAbreLocalizacao; 9 : ERamoAtividade.AAbreLocalizacao; 13 : EHistoricoLigacao.AAbreLocalizacao; end; end; end; {******************************************************************************} procedure TFDigitacaoProspect.GradeMudouLinha(Sender: TObject; VpaLinhaAtual, VpaLinhaAnterior: Integer); begin if VprDDigiProspects.Prospects.Count > 0 then begin VprDProspect:= TRBDDigitacaoProspectItem(VprDDigiProspects.Prospects.Items[VpaLinhaAtual-1]); end; end; {******************************************************************************} procedure TFDigitacaoProspect.ERamoAtividadeRetorno( VpaColunas: TRBColunasLocaliza); begin Grade.cells[10,Grade.ALinha] := VpaColunas[1].AValorRetorno; IF VpaColunas[0].AValorRetorno <> '' then VprDProspect.CodRamoAtividade := StrToInt(VpaColunas[0].AValorRetorno) else VprDProspect.CodRamoAtividade := 0; end; {******************************************************************************} procedure TFDigitacaoProspect.ECidadeRetorno(VpaColunas: TRBColunasLocaliza); begin Grade.Cells[6,Grade.ALinha] := VpaColunas[0].AValorRetorno; if FunClientes.RQtdEstados(VpaColunas[0].AValorRetorno) = 1 then Grade.Cells[7,Grade.ALinha] := VpaColunas[1].AValorRetorno; end; {******************************************************************************} procedure TFDigitacaoProspect.EClienteRetorno( VpaColunas: TRBColunasLocaliza); var VpfNomRamoAtividade : String; begin if VpaColunas[0].AValorRetorno <> '' then begin VprDCliente.free; VprDCliente := TRBDCliente.cria; VprDCliente.CodCliente := StrToInt(VpaColunas[0].AValorRetorno); VprDProspect.CodProspect := VprDCliente.CodCliente; FunClientes.CarDCliente(VprDCliente); if VprDCliente.CodRamoAtividade <> 0 then VpfNomRamoAtividade := FunClientes.RNomRamoAtividade(VprDCliente.CodRamoAtividade); Grade.Cells[3,Grade.ALinha] := VprDCliente.NomFantasia; Grade.Cells[4,Grade.ALinha] := VprDCliente.DesEndereco; Grade.Cells[5,Grade.ALinha] := VprDCliente.DesBairro; Grade.Cells[6,Grade.ALinha] := VprDCliente.DesCidade; Grade.Cells[7,Grade.ALinha] := VprDCliente.DesUF; Grade.Cells[8,Grade.ALinha] := VprDCliente.NomContato; Grade.Cells[9,Grade.ALinha] := VprDCliente.DesEmail; Grade.Cells[10,Grade.ALinha] := VpfNomRamoAtividade; Grade.Cells[11,Grade.ALinha] := VprDCliente.DesFone1; Grade.Cells[12,Grade.ALinha] := VprDCliente.DesCelular; VprDProspect.NomProspect := VprDCliente.NomFantasia; VprDProspect.DesEndereco := VprDCliente.DesEndereco; VprDProspect.DesBairro := VprDCliente.DesBairro; VprDProspect.DesCidade := VprDCliente.DesCidade; VprDProspect.DesUF := VprDCliente.DesUF; VprDProspect.NomContato := VprDCliente.NomContato; VprDProspect.DesFone := VprDCliente.DesFone1; VprDProspect.DesCelular := VprDCliente.DesCelular; VprDProspect.DesEnderecoAnterior:= VprDProspect.DesEndereco; VprDProspect.DesBairroAnterior:= VprDProspect.DesBairro; VprDProspect.NomContatoAnterior:= VprDProspect.NomContato; VprDProspect.DesEmailAnterior:= VprDProspect.DesEmail; VprDProspect.DesFoneAnterior:= VprDProspect.DesFone; VprDProspect.DesCelularAnterior:= VprDProspect.DesCelular; end else begin if VprDProspect.CodProspect <> 0 then begin Grade.Cells[3,Grade.ALinha] := ''; Grade.Cells[4,Grade.ALinha] := ''; Grade.Cells[5,Grade.ALinha] := ''; Grade.Cells[6,Grade.ALinha] := ''; Grade.Cells[7,Grade.ALinha] := ''; Grade.Cells[8,Grade.ALinha] := ''; Grade.Cells[9,Grade.ALinha] := ''; Grade.Cells[11,Grade.ALinha] := ''; Grade.Cells[12,Grade.ALinha] := ''; VprDProspect.CodProspect := 0; end; end; end; {******************************************************************************} procedure TFDigitacaoProspect.GradeNovaLinha(Sender: TObject); begin VprDProspect := VprDDigiProspects.AddProspectItem; VprDProspect.DesTipo := 'P'; VprDProspect.DesCidade := VprUltimaCidade; VprDProspect.DesUF := VprUltimoUF; VprDProspect.DatVisita := VprUltimaData; EHistoricoLigacao.AInteiro := varia.CodHistoricoLigacaoVisitaVendedor; EHistoricoLigacao.Atualiza; end; {******************************************************************************} procedure TFDigitacaoProspect.GradeSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); var VpfCodCliente : Integer; begin if Grade.AEstadoGrade in [egEdicao, egInsercao] then begin if Grade.AColuna <> ACol then begin case Grade.Acoluna of 2: begin if (Grade.Cells[2,Grade.ALinha] <> 'P') AND (Grade.Cells[2,Grade.ALinha] <> 'S') then begin Grade.col := 2; aviso('TIPO CADASTRO INVÁLIDO!!!'#13'É necessário digitar o tipo do cadastro :'#13'P - PROSPECT'#13'S - SUSPECT'); abort; end end; 3: begin if (Grade.Cells[2,Grade.ALinha] = 'P') then begin if VprDProspect.CodProspect = 0 then begin VpfCodCliente := FunClientes.RCodCliente(UpperCase(Grade.Cells[3,Grade.ALinha])); if VpfCodCliente <> 0 then aviso('CLIENTE DUPLICADO!!!'#13'Já existe um cliente cadastrado com esse nome com o código '+ IntToStr(VpfCodCliente)); end; end; end; 6: begin if not ECidade.AExisteCodigo(Uppercase(Grade.Cells[6,Grade.ALinha])) then ECidade.AAbreLocalizacao; end; 7: begin if not EUF.AExisteCodigo(Grade.Cells[7,Grade.ALinha]) then EUF.AAbreLocalizacao; end; 11:begin if (Grade.Cells[2,Grade.ALinha] = 'P') then begin if VprDProspect.CodProspect = 0 then begin VpfCodCliente := FunClientes.RCodClientePeloTelefone(UpperCase(Grade.Cells[11,Grade.ALinha])); if VpfCodCliente <> 0 then aviso('CLIENTE DUPLICADO!!!'#13'Já existe um cliente cadastrado com esse telefone com o código '+ IntToStr(VpfCodCliente)); end; end; end; 13:begin if not EHistoricoLigacao.AExisteCodigo(Grade.Cells[13,Grade.ALinha]) then EHistoricoLigacao.AAbreLocalizacao; end; end; case Acol of 3: begin if (Grade.Cells[2,Grade.ALinha] = 'P')then ECliente.AAbreLocalizacao else if (Grade.Cells[2,Grade.ALinha] = 'S')then ESuspect.AAbreLocalizacao; end; 10: if VprDProspect.CodProspect = 0 then ERamoAtividade.AAbreLocalizacao; end; end; end; end; {******************************************************************************} procedure TFDigitacaoProspect.HabilitaBotoes(VpaEstado: Boolean); begin BGravar.Enabled := VpaEstado; BCancelar.Enabled := VpaEstado; BFechar.Enabled := not VpaEstado; end; {******************************************************************************} procedure TFDigitacaoProspect.BAgendarClick(Sender: TObject); begin FNovoAgedamento := TFNovoAgedamento.CriarSDI(self,'',FPrincipal.VerificaPermisao('FNovoAgedamento')); FNovoAgedamento.NovaAgendaCliente(VprDProspect.CodProspect); FNovoAgedamento.free; end; {******************************************************************************} procedure TFDigitacaoProspect.BCancelarClick(Sender: TObject); begin Close; end; {******************************************************************************} procedure TFDigitacaoProspect.BFecharClick(Sender: TObject); begin Close; end; {******************************************************************************} procedure TFDigitacaoProspect.BGravarClick(Sender: TObject); var VpfResultado : String; begin VprDDigiProspects.CodVendedor := ECodVendedor.AInteiro; VpfREsultado := FunClientes.GravaDDigitacaoProspect(VprDDigiProspects); if VpfResultado <> '' then aviso(VpfResultado); HabilitaBotoes(false); end; procedure TFDigitacaoProspect.ECodVendedorChange(Sender: TObject); begin end; {******************************************************************************} procedure TFDigitacaoProspect.EHistoricoLigacaoRetorno(VpaColunas: TRBColunasLocaliza); begin Grade.cells[13,Grade.ALinha] := VpaColunas[0].AValorRetorno; Grade.cells[14,Grade.ALinha] := VpaColunas[1].AValorRetorno; VprDProspect.NomHistorico := VpaColunas[1].AValorRetorno; IF VpaColunas[0].AValorRetorno <> '' then VprDProspect.CodHistorico := StrToInt(VpaColunas[0].AValorRetorno) else VprDProspect.CodHistorico := 0; end; {******************************************************************************} procedure TFDigitacaoProspect.EUFRetorno(VpaColunas: TRBColunasLocaliza); begin Grade.cells[7,Grade.ALinha] := VpaColunas[0].AValorRetorno; end; {******************************************************************************} procedure TFDigitacaoProspect.GradeKeyPress(Sender: TObject; var Key: Char); begin case Grade.AColuna of 2 : key := UpCase(key); end; if VprDProspect.CodProspect <> 0 then case Grade.AColuna of 3,6,7 : key := #0; end; end; {******************************************************************************} procedure TFDigitacaoProspect.ESuspectRetorno( VpaColunas: TRBColunasLocaliza); begin if VpaColunas[0].AValorRetorno <> '' then begin VprDSuspect.free; VprDSuspect := TRBDProspect.cria; FunProspect.CarDProspect(VprDSuspect,StrToInt(VpaColunas[0].AValorRetorno)); VprDProspect.CodProspect := VprDSuspect.CodProspect; Grade.Cells[3,Grade.ALinha] := VprDSuspect.NomFantasia; Grade.Cells[4,Grade.ALinha] := VprDSuspect.DesEndereco; Grade.Cells[5,Grade.ALinha] := VprDSuspect.DesBairro; Grade.Cells[6,Grade.ALinha] := VprDSuspect.DesCidade; Grade.Cells[7,Grade.ALinha] := VprDSuspect.DesUF; Grade.Cells[8,Grade.ALinha] := VprDSuspect.NomContato; Grade.Cells[9,Grade.ALinha] := VprDSuspect.DesEmail; Grade.Cells[11,Grade.ALinha] := VprDSuspect.DesFone1; Grade.Cells[12,Grade.ALinha] := VprDSuspect.DesFone2; VprDProspect.NomProspect := VprDSuspect.NomFantasia; VprDProspect.DesEndereco := VprDSuspect.DesEndereco; VprDProspect.DesBairro := VprDSuspect.DesBairro; VprDProspect.DesCidade := VprDSuspect.DesCidade; VprDProspect.DesUF := VprDSuspect.DesUF; VprDProspect.NomContato := VprDSuspect.NomContato; VprDProspect.DesFone := VprDSuspect.DesFone1; end else begin if VprDProspect.CodProspect <> 0 then begin Grade.Cells[3,Grade.ALinha] := ''; Grade.Cells[4,Grade.ALinha] := ''; Grade.Cells[5,Grade.ALinha] := ''; Grade.Cells[6,Grade.ALinha] := ''; Grade.Cells[7,Grade.ALinha] := ''; Grade.Cells[8,Grade.ALinha] := ''; Grade.Cells[9,Grade.ALinha] := ''; Grade.Cells[11,Grade.ALinha] := ''; Grade.Cells[12,Grade.ALinha] := ''; VprDProspect.CodProspect := 0; end; end; end; Initialization { *************** Registra a classe para evitar duplicidade ****************** } RegisterClasses([TFDigitacaoProspect]); end.
unit DelphiEx2; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TDelphiEx2Form = class(TForm) BoolBtn: TButton; BooleanLabel: TLabel; WordBtn: TButton; WordLabel: TLabel; DWordBtn: TButton; DWordLabel: TLabel; PtrBtn: TButton; PCharLabel: TLabel; FltBtn: TButton; RealLabel: TLabel; procedure BoolBtnClick(Sender: TObject); procedure WordBtnClick(Sender: TObject); procedure DWordBtnClick(Sender: TObject); procedure PtrBtnClick(Sender: TObject); procedure FltBtnClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var DelphiEx2Form: TDelphiEx2Form; implementation {$R *.DFM} // Here's the directive that tells Delphi to link in our // HLA code. {$L ReturnBoolean.obj } {$L ReturnWord.obj } {$L ReturnDWord.obj } {$L ReturnPtr.obj } {$L ReturnReal.obj } // Here are the external function declarations: function ReturnBoolean:boolean; external; function ReturnWord:smallint; external; function ReturnDWord:integer; external; function ReturnPtr:pchar; external; function ReturnReal:real; external; // Demonstration of calling an assembly language // procedure that returns a byte (boolean) result. procedure TDelphiEx2Form.BoolBtnClick(Sender: TObject); var b:boolean; begin // Call the assembly code and return its result: b := ReturnBoolean; // Display "true" or "false" depending on the return result. if( b ) then booleanLabel.caption := 'Boolean result = true ' else BooleanLabel.caption := 'Boolean result = false'; end; // Demonstrate calling an assembly language function that // returns a word result. procedure TDelphiEx2Form.WordBtnClick(Sender: TObject); var si:smallint; // Return result here. strVal:string; // Used to display return result. begin si := ReturnWord(); // Get result from assembly code. str( si, strVal ); // Convert result to a string. WordLabel.caption := 'Word Result = ' + strVal; end; // Demonstration of a call to an assembly language routine // that returns a 32-bit result in EAX: procedure TDelphiEx2Form.DWordBtnClick(Sender: TObject); var i:integer; // Return result goes here. strVal:string; // Used to display return result. begin i := ReturnDWord(); // Get result from assembly code. str( i, strVal ); // Convert that value to a string. DWordLabel.caption := 'Double Word Result = ' + strVal; end; // Demonstration of a routine that returns a pointer // as the function result. This demo is kind of lame // because we can't initialize anything inside the // assembly module, but it does demonstrate the mechanism // even if this example isn't very practical. procedure TDelphiEx2Form.PtrBtnClick(Sender: TObject); var p:pchar; // Put returned pointer here. begin // Get the pointer (to a zero byte) from the assembly code. p := ReturnPtr(); // Display the empty string that ReturnPtr returns. PCharLabel.caption := 'PChar Result = "' + p + '"'; end; // Quick demonstration of a function that returns a // floating point value as a function result. procedure TDelphiEx2Form.FltBtnClick(Sender: TObject); var r:real; strVal:string; begin // Call the assembly code that returns a real result. r := ReturnReal(); // Always returns 1.0 // Convert and display the result. str( r:13:10, strVal ); RealLabel.caption := 'Real Result = ' + strVal; end; end.
unit h_MainLib; interface uses inifiles,Windows, Sysutils, ExtCtrls, ADODB, ScktComp, Graphics ; Const LogFileName : String = '.\Log\Monitoring.Log'; INI_PATH : String = 'AwHouse.INI'; MenuCount = 6; START_SCNO = 1 ; // Start SC No End_SCNO = 4 ; // End SC No SPACE = #$20; BACKSPACE = #8 ; DEL = #48; STX = #2 ; ETX = #3 ; CR = #13; //D LF = #10; //A ACK = #6 ; NAK = #21; Enq = #5 ; SC_IN_BUFF : Array [1..3] of integer = (141, 151, 181); SC_OT_BUFF : Array [1..3] of integer = (130, 160, 170); AC_IN_BUFF : Array [1..3] of integer = (140, 150, 180); AC_OT_BUFF : Array [1..3] of integer = (131, 161, 171); AC_POS : Array [0..7] of integer = (433, 393, 309, 266, 182, 139, 55, 15); AC_BUFF : Array [1..8] of integer = (131, 124, 161, 171, 140, 150, 190, 180); BCR_LINE_BUFF : Array [1..3] of integer = (102, 112, 120); //================================== // 링롱 타이어 추가 2020.01.14 //================================== LANG_GUBUN : Array [1..3] of String = ('KOR', 'ENG', 'CHI'); GRADE_GUBUN : Array [0..3] of String = ('Supervisor','CCR','ASRS','ProductManager'); BUTTON_LIST : Array [0..6] of String = ('ORDER', 'REGIST', 'DELETE', 'UPDATE', 'EXCEL', 'PRINT', 'QUERY'); CELL_MAX_HOGI = 10; CELL_MAX_BANK = 2; CELL_MAX_BAY = 38; CELL_MAX_LEVEL = 12; TBM_MAX_COUNT = 20; // 성형기 설비수량(1,2 단계 합해서 20) CUR_MAX_COUNT = 68; // 가류기 설비수량 CUR_LINE_COUNT = 17; // 가류기 라인별 설비수량 CUR_LINE = 4; // 가류기 라인 수 MAN_IPGO_SCNO = 7; // 수동입고 크레인 No MAN_IPGO_F_SITE = 482; // 수동입고 Front Site MAN_IPGO_R_SITE = 484; // 수동입고 Rear Site MAN_IPGO_F_SITE_LIST : Array[1..11] of integer = (3011, 3021, 3031, 3041, 3051, 0, 3071, 3081, 3091, 3111, 3121); // 호기별 수동입고 Front Site MAN_IPGO_R_SITE_LIST : Array[1..11] of integer = (3012, 3022, 3032, 3042, 3052, 0, 3072, 3082, 3092, 3112, 3122); // 호기별 수동입고 Rear Site CONN_STATUS_COLOR : Array [0..1] of TColor = ($008484FF, $0068FF68); //======================================================================== // 메인폼 툴바 버튼 Tag값 //======================================================================== MSG_MDI_WIN_ORDER = 11 ; // 지시 MSG_MDI_WIN_ADD = 12 ; // 신규 MSG_MDI_WIN_DELETE = 13 ; // 삭제 MSG_MDI_WIN_UPDATE = 14 ; // 수정 MSG_MDI_WIN_EXCEL = 15 ; // 엑셀 MSG_MDI_WIN_PRINT = 16 ; // 인쇄 MSG_MDI_WIN_QUERY = 17 ; // 조회 MSG_MDI_WIN_CLOSE = 20 ; // 닫기 MSG_MDI_WIN_LANG = 21 ; // 언어 type TStatus = (START, STANDBY, READY, ORDER, RETURN, CLEAR, RESET, ERR) ; TPopupData = Record DATA01, DATA02, DATA03, DATA04, DATA05, DATA06, DATA07, DATA08, DATA09, DATA10 : String; WEIGHT, QTY : integer; ResultCd : String; PopupType, PopupMsg,PopupRc : String; tmOn : Boolean; end; TPGM_HIST_INFO = Record MENU_ID : String; HIST_TYPE : String; EVENT_NAME : String; COMMAND_TYPE : String; COMMAND_TEXT : String; PARAM : String; ERROR_MSG : String; o_ERR_CD : String; o_ERR_MSG : String; end; TDATA_INFO = Record FrmNo : String; DATA1 : String; DATA2 : String; DATA3 : String; DATA4 : String; DATA5 : String; DATA6 : String; DATA7 : String; DATA8 : String; DATA9 : String; DATA10 : String; CompareStr : String; end; TMENU_GRADE = Record FrmNo : String; Grade : String; end; TMachUsed = Record In_Used : Boolean; Ot_Used : Boolean; end; TTORDER = Record ID_DATE : String; ID_TIME : String; ID_TYPE : String; ID_INDEX : integer; ID_SUBIDX : integer; ID_EMG : integer; ID_SC : String; ID_CODE : String; LOAD_BANK : String; LOAD_BAY : String; LOAD_LEVEL : String; UNLOAD_BANK : String; UNLOAD_BAY : String; UNLOAD_LEVEL : String; KIND_1 : String; KIND_2 : String; KIND_3 : String; KIND_4 : String; KIND_5 : String; NOW_SITE : String; NOW_MACH : String; IN_SITE : String; IN_DATE : String; OT_SITE : String; OT_DATE : String; BCR_CHK : integer; STATUS : String; PROCESS : String; ITEM_LOT : String; ITEM_TYPE : String; ITEM_WEIGHT : String; ITEM_QTY : String; ITEM_INFO_01 : String; ITEM_INFO_02 : String; ITEM_INFO_03 : String; ITEM_INFO_04 : String; ITEM_INFO_05 : String; ITEM_INFO_06 : String; ITEM_INFO_07 : String; ITEM_INFO_08 : String; ITEM_INFO_09 : String; ITEM_INFO_10 : String; ITEM_INFO_11 : String; ITEM_INFO_12 : String; ITEM_INFO_13 : String; ITEM_INFO_14 : String; ITEM_INFO_15 : String; ITEM_INFO_16 : String; ITEM_INFO_17 : String; ITEM_INFO_18 : String; ITEM_INFO_19 : String; ITEM_INFO_20 : String; PLT_CODE : String; WRAP_YN : String; MEMO_1 : String; MEMO_2 : String; MEMO_3 : String; MEMO_4 : String; MEMO_5 : String; ID_USER : String; END_YN : String; SEND_YN : String; OR_DT : String; UP_DT : String; CR_DT : String; end; TTRACKInfo = Record ID_DATE : String; ID_TIME : String; ID_TYPE : String; ID_INDEX : integer; ID_SUBIDX : integer; ID_EMG : integer; ID_SC : String; ID_CODE : String; ID_BANK : String; ID_BAY : String; ID_LEVEL : String; KIND_1 : String; KIND_2 : String; KIND_3 : String; KIND_4 : String; KIND_5 : String; IN_SITE : String; IN_DATE : String; OT_SITE : String; OT_DATE : String; BCR_CHK : integer; STATUS : String; PROCESS : String; ITEM_LOT : String; ITEM_TYPE : String; ITEM_WEIGHT : String; ITEM_QTY : String; ITEM_INFO_01 : String; ITEM_INFO_02 : String; ITEM_INFO_03 : String; ITEM_INFO_04 : String; ITEM_INFO_05 : String; ITEM_INFO_06 : String; ITEM_INFO_07 : String; ITEM_INFO_08 : String; ITEM_INFO_09 : String; ITEM_INFO_10 : String; ITEM_INFO_11 : String; ITEM_INFO_12 : String; ITEM_INFO_13 : String; ITEM_INFO_14 : String; ITEM_INFO_15 : String; ITEM_INFO_16 : String; ITEM_INFO_17 : String; ITEM_INFO_18 : String; ITEM_INFO_19 : String; ITEM_INFO_20 : String; PLT_CODE : String; WRAP_YN : String; MEMO_1 : String; MEMO_2 : String; MEMO_3 : String; MEMO_4 : String; MEMO_5 : String; ID_USER : String; UP_DT : String; CR_DT : String; End; TITEMInfo = Record ITEM_TYPE : String; ITEM_WEIGHT : String; ITEM_QTY : String; ITEM_INFO_01 : String; ITEM_INFO_02 : String; ITEM_INFO_03 : String; ITEM_INFO_04 : String; ITEM_INFO_05 : String; ITEM_INFO_06 : String; ITEM_INFO_07 : String; ITEM_INFO_08 : String; ITEM_INFO_09 : String; ITEM_INFO_10 : String; ITEM_INFO_11 : String; ITEM_INFO_12 : String; ITEM_INFO_13 : String; ITEM_INFO_14 : String; ITEM_INFO_15 : String; ITEM_INFO_16 : String; ITEM_INFO_17 : String; ITEM_INFO_18 : String; ITEM_INFO_19 : String; ITEM_INFO_20 : String; End; TSCRC = Record ForkCenter : String; ForkTrayExist : String; ReturnFinish : String; WorkReady : String; MachineAction : String; MachineTrouble : String; WorkMode : String; MachinePower : String; Bay : integer; Level : integer; Error : integer; End; TSCIO = Record ID_DATE : String; ID_TIME : String; ID_INDEX : integer; ID_SUBIDX : integer; IO_TYPE : String; ID_SC : String; LOAD_BANK : String; LOAD_BAY : String; LOAD_LEVEL : String; UNLOAD_BANK : String; UNLOAD_BAY : String; UNLOAD_LEVEL : String; SC_STATUS : String; CR_DT : String; End; TLANG_DESC = Record FORMID : String; FIELD_NAME : String; FIELD_TYPE : String; DESC : Array [1..3] of String; end; TLANG_PGM = Record // Form Name Description LANG : Array [0..49] of TLANG_DESC ; // [Form개수] end; TLANG_INFO = Record // Form Field Description LANG : Array [0..66,0..99] of TLANG_DESC ; // [Form번호,단어개수] end; Main_Info = Record MainHd : Hwnd; IdPass : Boolean; ConChk : Boolean ; MenuName, MenuNumber, MenuTitle : String ; UserCode, UserName, UserPwd, UserGrade, UserAdmin, UserETC1, UserETC2 : String; DbOle, DbType, DbUser, DbPswd, DbAlais, DbFile : String; WMS_NO : String; Popup_ItemInfo : TPopupData; WRHS : String; LANG_TYPE : integer; LANG_STR : String; LANG_PGM : TLANG_PGM; LANG_FORM : TLANG_INFO; PCPosition : integer; ReLogin : Boolean; ActiveFormID, ActiveFormName : String; HistInfo : TPGM_HIST_INFO; ActivePCName, ActivePCAddr : String; end; Mach_Info = Record ID : String; USED : String; end; Form_Info = Record Mainhd : HWND ; ConnectionType : String; Menu_Name, Menu_Number, Menu_Title : String ; End; TCVR = Record Case Integer of 1 : (All : Array [1..6] of AnsiChar); 2 : ( CargoExist : AnsiChar; StraightFinish : AnsiChar; LeftFinish : AnsiChar; // Fork RightFinish : AnsiChar; // Join ByPassFinish : AnsiChar; PosCenter : AnsiChar; // 정위치 ) End; TOP = Record Case Integer of 1 : (All : Array [1..7] of AnsiChar); 2 : ( Auto : AnsiChar; Semi : AnsiChar; Manu : AnsiChar; Erro : AnsiChar; Emer : AnsiChar; RRun1 : AnsiChar; RRun2 : AnsiChar; ) End; TSC = Record Case Integer of 1 : (All : Array [1..2] of AnsiChar); 2 : ( InReady : AnsiChar; OutReady : AnsiChar; ) End; TAC = Record Case Integer of 1 : (All : Array [1..27] of AnsiChar); 2 : ( Ready : Array [1..8] of AnsiChar; // 작업대 Ready OtSensor : Array [1..8] of AnsiChar; // 작업대 돌출감지 AC_Auto : AnsiChar; // 자동 AC_Manu : AnsiChar; // 수동 AC_Emer : AnsiChar; // 비상정지 AC_Ready : AnsiChar; // 오토카 Ready AC_Run : AnsiChar; // 작업중 AC_Error : AnsiChar; // 에러 AC_Cargo : AnsiChar; // 화물유 AC_LCPL : AnsiChar; // 로딩완료 AC_UCPL : AnsiChar; // 언로딩완료 DoorOpen1 : AnsiChar; // 안전 펜스 DOOR OPEN (H.P) DoorOpen2 : AnsiChar; // 안전 펜스 DOOR OPEN (O.P) ) End; TRM = Record Case Integer of 1 : (All : Array [1..7] of AnsiChar); 2 : ( RM1_RUN_CMD : AnsiChar; // 포장룸1 출고 RUN CMD RM1_FEED_BK : AnsiChar; // 포장룸1 입고 RUN FEED BANK RM1_DOOR : AnsiChar; // 포장룸1 DOOR OPEN RM2_RUN_CMD : AnsiChar; // 포장룸2 출고 RUN CMD RM2_FEED_BK : AnsiChar; // 포장룸2 입고 RUN FEED BANK RM2_DOOR : AnsiChar; // 포장룸2 DOOR OPEN RM_EMER : AnsiChar; // 포장룸 비상정지 ) End; TDR = Record Case Integer of 1 : (All : Array [1..9] of AnsiChar); 2 : ( IN_DR_RDY : AnsiChar; // 입고라인 DOOR READY IN_DR_RUN : AnsiChar; // 입고라인 DOOR RUNNING IN_DR_UPL : AnsiChar; // 입고라인 DOOR FULL UP LIMIT IN_DR_DWL : AnsiChar; // 입고라인 DOOR FULL DOWN LIMIT OT_DR_RDY : AnsiChar; // 출고라인 DOOR READY OT_DR_RUN : AnsiChar; // 출고라인 DOOR RUNNING OT_DR_UPL : AnsiChar; // 출고라인 DOOR FULL UP LIMIT OT_DR_DWL : AnsiChar; // 출고라인 DOOR FULL DOWN LIMIT AGV_LOCK : AnsiChar; // AGV CV120 LOCK 요청상태 ) End; TSDR = Record Case Integer of 1 : (All : Array [1..2] of AnsiChar); 2 : ( SDoor1 : AnsiChar; SDoor2 : AnsiChar; ) End; TWP = Record Case Integer of 1 : (All : Array [1..4] of AnsiChar); 2 : ( WP_MANUAL_CENTER : AnsiChar; // WRAPPING MACHINE 수동 정위치 상태 WP_READY : AnsiChar; // WRAPPING MACHINE 자동 준비 상태 WP_JOB_COMPLETE : AnsiChar; // WRAPPING MACHINE 랩핑완료 WP_EMER : AnsiChar; // WRAPPING MACHINE 비상정지 ) End; TCVCR = Record case Integer of 1 : (All : Array [0..1268] of AnsiChar); 2 : ( OP : Array [ 1.. 2 ] of TOP; // 2 * 7 = 14 Byte 2019.04.10 Update BUFF : Array [ 0..199 ] of TCVR; // 200 * 6 = 1200 Byte 2019.04.19 Update SC : Array [ 1.. 3 ] of TSC; // 3 * 2 = 6 Byte 2019.04.10 Update AC : TAC; // 1 * 27 = 27 Byte 2019.04.19 Update ROOM : TRM; // 1 * 7 = 7 Byte 2019.05.16 Update DOOR : TDR; // 1 * 9 = 9 Byte 2019.05.16 Update WRAP : TWP; // 1 * 4 = 4 Byte 2019.04.19 Update SDoor : TSDR; // 1* 2 = 2 Byte 2019.09.27 Update ) end; TCVW = Record Case Integer of 1 : (All : Array [1..4] of AnsiChar); 2 : ( StraightOrder : AnsiChar; LeftOrder : AnsiChar; // Fork RightOrder : AnsiChar; // Join ByPass : Ansichar; ) End; TACW = Record Case Integer of 1 : (All : Array [1..13] of AnsiChar); 2 : ( AC_JobPos : Array [1..8] of AnsiChar; AC_Order : AnsiChar; AC_Cancel : AnsiChar; AC_Retry : AnsiChar; AC_Reset : AnsiChar; AC_Home : AnsiChar; ) End; TCVCW = Record Case Integer of 1 : (All : Array [1..817] of AnsiChar); 2 : ( BUFF : Array [0..199] of TCVW; // 200 * 4 = 800 AC : TACW; // 13 * 1 = 13 E_STOP : AnsiChar; // 1 F_RESET : AnsiChar; // 1 RM1_READ_CONF : AnsiChar; // 1 RM2_READ_CONF : AnsiChar; // 1 ) End; TCV = Record Case Integer of 1 : (All : Array[1..2086] of AnsiChar); 2 : ( Read : TCVCR; // 1269 Write : TCVCW; // 817 ) end; implementation end.
{*******************************************************} { } { Delphi LiveBindings Framework } { } { Copyright(c) 2011-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit System.Bindings.ManagerDefaults; interface uses System.SysUtils, System.Classes, System.Rtti, System.Generics.Collections, System.Bindings.EvalProtocol, System.Bindings.NotifierContracts, System.Bindings.Manager, System.Bindings.Factories; type /// <summary> /// Manager that supports incoming change notifications from bindable objects /// or other binding managers that might have further dispatched the notification.</summary> /// <remarks>Implements the default behaviour for the binding managers.</remarks> TBindingManagerDefault = class(TBindingManager, IBindingNotification) private FNotifHandler: IBindingNotification; protected /// <summary>Handles the incoming notifications from bindable objects.</summary> property NotifHandler: IBindingNotification read FNotifHandler implements IBindingNotification; public constructor Create(Owner: TBindingManager = nil); destructor Destroy; override; end; implementation uses System.Bindings.NotifierDefaults, System.Bindings.Expression, System.Bindings.Search, System.Bindings.Graph; type { TBindingManagerNotification Notification interceptor for binding managers that handles: * the dispatching of the message to submanagers * the changes inside a manager when it is notified } TBindingManagerNotification = class(TBindingNotification) private FCounter: Integer; protected procedure NotifyExpressions(Notifier: IBindingNotifier; const PropertyName: String); virtual; // dispatches further the notification to the submanagers procedure NotifyManagers(Notifier: IBindingNotifier; const PropertyName: String); virtual; // entry point for receiving notifications procedure Notification(Notifier: IBindingNotifier; const PropertyName: String); override; end; { TBindingManagerDefault } constructor TBindingManagerDefault.Create(Owner: TBindingManager); begin inherited; FNotifHandler := TBindingManagerNotification.Create(Self); end; destructor TBindingManagerDefault.Destroy; begin FNotifHandler := nil; inherited; end; { TBindingManagerNotification } procedure TBindingManagerNotification.Notification(Notifier: IBindingNotifier; const PropertyName: String); var LFurtherNotif: Boolean; // True - the notification is further sent to the depenendent expressions LExpr: TBindingExpression; // a binding expression LExprScope: IScope; // scope of the expression LExprWrprs: TWrapperDictionary; // input wrappres of a binding expression LWrpr: IInterface; // input wrapper LWrprChild: IChild; // child support for the input wrapper LWrprPlaceholder: IPlaceholder; // placeholder support for the input wrapper LCanEvaluate: Boolean; // indicates if an expression can be evaluated begin if Assigned(Notifier) then begin Inc(FCounter); try LFurtherNotif := True; case Notifier.Reserved of bnrtExternal: begin // scan the subgraph to mark the object properties and expressions // where the notification must later be propagated TBindingGraph.ClearTopology; TBindingGraph.ScanTopology(Notifier.Owner, PropertyName, Owner as TBindingManager); // jump to the next iteration TBindingGraph.ClearIteration; TBindingGraph.IncIteration; // iteration mark the object member that changed TBindingGraph.MarkIteration(Notifier.Owner, PropertyName); end; bnrtInternal: begin // can notify further if the object property is not iteration marked LFurtherNotif := not TBindingGraph.IsIterationMarked(Notifier.Owner, PropertyName); if LFurtherNotif then TBindingGraph.MarkIteration(Notifier.Owner, PropertyName); end; end; // notify to expressions and submanagers that the value of this object property // has changed only if it hasn't been marked already if LFurtherNotif then begin NotifyExpressions(Notifier, PropertyName); NotifyManagers(Notifier, PropertyName); end; // it's the start point of the notification wave; // handle the expressions that are on the wait queue if Notifier.Reserved = bnrtExternal then while not TBindingGraph.IsWaitQueueEmpty do begin // get the first expression from the wait queue LExprWrprs := nil; LExpr := TBindingGraph.DequeueWait; if Supports(LExpr, IScope, LExprScope) then try // get all the input wrappers of the expression and mark the // input object properties from the input wrappers only if all // the wrappers are attached to objects LCanEvaluate := True; LExprWrprs := TBindingSearch.DepthGetWrappers(LExprScope); for LWrpr in LExprWrprs.Keys do if Supports(LWrpr, IChild, LWrprChild) then begin LCanEvaluate := Supports(LWrpr, IPlaceholder, LWrprPlaceholder) and (LWrprPlaceholder.Attached or LWrprPlaceholder.EvalTimeOnly); // of object types so that the expression would also need a recompilation or better said a reattachment of // those wrappers. It needs a reattachment of the wrappers becaue some of the wrappers that are already // marked may have been marked in previous phases of the notification process. That means the objects // have new values and the wrappers need to reattach to those objects again. // Take a look at the reattachment done in the NotifyExpressions(). // if at most one wrapper is not attached, we cannot evaluate the expression if LCanEvaluate then TBindingGraph.MarkIteration(LWrprChild.Parent, LWrprChild.MemberName) else Break; end; // iteration-mark the expression and execute it to continue the notification wave if LCanEvaluate then begin TBindingGraph.MarkIteration(LExpr); LExpr.EvaluateOutputs; end; finally LExprWrprs.Free; end; end; finally Dec(FCounter); if FCounter = 0 then TBindingGraph.ClearIteration; end; end; end; procedure TBindingManagerNotification.NotifyExpressions( Notifier: IBindingNotifier; const PropertyName: String); var LExprsWrprs: TBindingGraph.TExprWrappersDict; // relates expressions with all their input wrappers LExprWrprsPair: TBindingGraph.TExprWrappersPair; // single relation between expression and its input wrappers LWrpr: IInterface; // input wrapper LWrprChild: IChild; // wrapper child support LWrprPlaceholder: IPlaceholder; // wrapper placeholder support LWrprScopeEnum: IScopeEnumerable; // wrapper enumerable support LWrprDups: TWrapperDictionary; // stores wrappers that point to the same object member LWrprGroup: IGroup; // wrapper group support LPermitsObjWrpr: Boolean; LObjectOnly: Boolean; // the whole object is signaled to be changed (meaning PropertyName = '') LFound: Boolean; begin LWrprDups := nil; LExprsWrprs := nil; // the group is iterated first, before its instances. Using a structure similar // to the dictionary for lookups, but which assures us that the group is enumerated // before the instances will improve speed, considering the conditions in the // loops below try LWrprDups := TWrapperDictionary.Create; // determine whether the changed object property is of an object type and // thus accepts an object wrapper around it LObjectOnly := PropertyName = ''; LPermitsObjWrpr := LObjectOnly or TBindingSearch.PermitsObjectWrapper(Notifier.Owner, PropertyName); // the main purpose of the these loops is to iteration-mark the independent inputs; // they are not topologically scanned because there is no way to get to them; // for properties that are of object types, it reattaches the wrappers to the new value; // it also generates the list of wrappers that wrap around the triggering object property LExprsWrprs := TBindingGraph.GetDependentExprsWrappers(Notifier.Owner, PropertyName, Owner as TBindingManager); for LExprWrprsPair in LExprsWrprs do begin // attach the wrappers for the triggering object property to Notifier.Owner; despite // they are already attached to that, it triggers a chain reaction to their subwrappers; // among the rest of the expression wrappers may be subwrappers of the wrappers for // Owner.Property and this way they will be attached to the new value of Owner.Property if LPermitsObjWrpr then begin // preallocate space in the duplicates list LWrprDups.Clear; for LWrpr in LExprWrprsPair.Value.Keys do begin // determine if the current wrapper is wrapping the changed object or object member case LObjectOnly of True: // it is an object wrapper LFound := TBindingSearch.IsObjectWrapper(LWrpr, Notifier.Owner); False: // it is an object member wrapper LFound := TBindingSearch.IsMemberWrapper(LWrpr, Notifier.Owner, PropertyName); else LFound := False; end; // wrapper group instances are added to the duplicates wrapper list to avoid the // same reattachment multiple times; reattaching the group is sufficient because // it reattaches the instances, too if LFound and (not LWrprDups.ContainsKey(LWrpr)) and Supports(LWrpr, IPlaceholder, LWrprPlaceholder) and // it must be able to reattach Supports(LWrpr, IScopeEnumerable, LWrprScopeEnum) then // and cycle through its subwrappers begin // groups contain wrapper instances that point to the same object // member and they are considered duplicates; if Supports(LWrpr, IGroup, LWrprGroup) then TBindingSearch.CollectGroupInstWrprs(LWrprGroup, LWrprDups); // reset the arguments of the subwrappers of this wrapper and // reattach the wrapper to the new parent TBindingSearch.ResetWrappersArguments(LWrprScopeEnum); LWrprPlaceholder.Attach(Notifier.Owner); end; end; end; // iteration-mark all the input objects and object properties that haven't // been topologically scanned LWrprDups.Clear; for LWrpr in LExprWrprsPair.Value.Keys do begin if Supports(LWrpr, IChild, LWrprChild) and Supports(LWrpr, IPlaceholder, LWrprPlaceholder) and not LWrprDups.ContainsKey(LWrpr) then begin if Supports(LWrpr, IGroup, LWrprGroup) then TBindingSearch.CollectGroupInstWrprs(LWrprGroup, LWrprDups); // we can iteration-mark the wrapper if the notification is done by the user at this stage (external) // or if the wrapper is attached (which is clear that the wrapper can be queried for a valid value) // or if the wrapper can have its value determined only at evaluation time // and the object member wrapped hasn't been iteration-marked yet if (Notifier.Reserved = bnrtExternal) or ((LWrprPlaceholder.Attached or LWrprPlaceholder.EvalTimeOnly) and not TBindingGraph.IsTopologicMarked(LWrprChild.Parent, LWrprChild.MemberName)) then TBindingGraph.MarkIteration(LWrprChild.Parent, LWrprChild.MemberName); end; end; end; // evalute all the expressions dependent on the current object property // that <have all their inputs iteration-marked> and <the expressions are // not iteration-marked> for LExprWrprsPair in LExprsWrprs do begin if not TBindingGraph.IsIterationMarked(LExprWrprsPair.Key) then // all the inputs of the expression are iteration-marked; evaluate it if TBindingGraph.AreAllIterationMarked(LExprWrprsPair.Value) then begin // an expression that is iteration-marked is ready for evaluation because // all its inputs are iteration-marked; so if the expression is in the wait // queue, it must not be there anymore TBindingGraph.MarkIteration(LExprWrprsPair.Key); TBindingGraph.DequeueWait(LExprWrprsPair.Key); // because the property is an object actually and it might add to the subgraph another subgraph that must be // scanned before execution if LPermitsObjWrpr then begin end; // evaluate the expression; wrappers are attached to objects as soon as they can // in the process of evaluation LExprWrprsPair.Key.EvaluateOutputs; end // there are inputs that must be marked in some later steps of the notification else TBindingGraph.EnqueueWait(LExprWrprsPair.Key); end; finally LExprsWrprs.Free; LWrprDups.Free; end; end; procedure TBindingManagerNotification.NotifyManagers(Notifier: IBindingNotifier; const PropertyName: String); var LManager: TBindingManager; LBindingNotif: IBindingNotification; i: Integer; begin LManager := Owner as TBindingManager; // dispatch the notification information further to the submanagers for i := 0 to LManager.ManagerCount - 1 do if Supports(LManager.Managers[i], IBindingNotification, LBindingNotif) then LBindingNotif.Notification(Notifier, PropertyName) end; end.
{**********************************************************************} {* Иллюстрация к книге "OpenGL в проектах Delphi" *} {* Краснов М.В. softgl@chat.ru *} {**********************************************************************} unit frmMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, OpenGL; type TfrmGL = class(TForm) Timer1: TTimer; procedure FormCreate(Sender: TObject); procedure FormResize(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure Timer1Timer(Sender: TObject); private DC: HDC; hrc: HGLRC; qobj : GLUquadricObj ; procedure SetDCPixelFormat; protected procedure WMPaint(var Msg: TWMPaint); message WM_PAINT; end; var frmGL: TfrmGL; Angle : GLint = 0; implementation {$R *.DFM} {======================================================================= Рисование картинки} procedure TfrmGL.WMPaint(var Msg: TWMPaint); var ps : TPaintStruct; begin BeginPaint(Handle, ps); glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); glPushMatrix; glRotatef (Angle, 1.0, 1.0, 0.0); {красная сфера внутри} glColor4f (1.0, 1.0, 0.0, 1.0); gluSphere(qobj, 0.5, 20, 20); {наружняя сфера} glPushMatrix; glTranslatef(0, -0.3, 0); glRotatef(angle, 0, 1, 0); glTranslatef(0, 0, 0.6); glColor4f (1.0, 0.0, 0.5, 0.5); gluSphere(qobj, 0.3, 20, 20); glPopMatrix; glPopMatrix; SwapBuffers(DC); EndPaint(Handle, ps); end; {======================================================================= Создание окна} procedure TfrmGL.FormCreate(Sender: TObject); const mat_specular : Array [0..3] of GLFloat = (1.0, 1.0, 1.0, 1.0); mat_shininess : GLFloat = 50.0; begin DC := GetDC(Handle); SetDCPixelFormat; hrc := wglCreateContext(DC); wglMakeCurrent(DC, hrc); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, @mat_specular); glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, @mat_shininess); glEnable(GL_LIGHT0); glEnable(GL_LIGHTING); glEnable(GL_BLEND); glEnable(GL_DEPTH_TEST); glEnable(GL_COLOR_MATERIAL); qObj := gluNewQuadric; glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); end; {======================================================================= Обработка нажатия клавиши} procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin If Key = VK_ESCAPE then Close; end; {======================================================================= Устанавливаем формат пикселей} procedure TfrmGL.SetDCPixelFormat; var nPixelFormat: Integer; pfd: TPixelFormatDescriptor; begin FillChar(pfd, SizeOf(pfd), 0); pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; nPixelFormat := ChoosePixelFormat(DC, @pfd); SetPixelFormat(DC, nPixelFormat, @pfd); end; {======================================================================= Изменение размеров окна} procedure TfrmGL.FormResize(Sender: TObject); begin glMatrixMode(GL_PROJECTION); glLoadIdentity; gluPerspective(2.0, ClientWidth / ClientHeight, 80.0, 150.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity; glTranslatef(0.0, 0.0, -100.0); glRotatef (90.0, 0.0, 1.0, 0.0); InvalidateRect(Handle, nil, False); end; {======================================================================= Конец работы программы} procedure TfrmGL.FormDestroy(Sender: TObject); begin gluDeleteQuadric (qObj); wglMakeCurrent(0, 0); wglDeleteContext(hrc); ReleaseDC(Handle, DC); DeleteDC (DC); end; procedure TfrmGL.Timer1Timer(Sender: TObject); begin Angle := (Angle + 2) mod 360; InvalidateRect(Handle, nil, False); end; end.
unit frmTestPersistence1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, ExtCtrls, TestModel1, tiModelMediator, agTIOPFUtills; type { TForm1 } TForm1 = class(TForm) btnShowModelInfo: TButton; btnShowPersistenceInfo: TButton; btnSetupPersistence: TButton; Button1: TButton; btnReadList: TButton; btnSaveList: TButton; btnCreate5: TButton; lePhoneNumber: TLabeledEdit; leName: TLabeledEdit; Memo1: TMemo; Memo2: TMemo; Memo3: TMemo; Panel1: TPanel; Panel2: TPanel; Splitter1: TSplitter; Splitter2: TSplitter; Splitter3: TSplitter; procedure btnReadListClick(Sender: TObject); procedure btnSaveListClick(Sender: TObject); procedure btnShowModelInfoClick(Sender: TObject); procedure btnShowPersistenceInfoClick(Sender: TObject); procedure btnSetupPersistenceClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure FormShow(Sender: TObject); private { private declarations } FFilename: String; FPersistenceLayer: String; FDatabaseName: String; FTableName: String; FDBParams: String; FUserName: String; FPassword: String; FMediator: TtiModelMediator; FModel: TTestModel1; FModelList: TTestModel1List; FModelList_Create: TTestModel1List_Create; procedure SetupMediators; procedure SetupPersistence; procedure Log(aString: String); public { public declarations } end; var Form1: TForm1; implementation Uses tiOPFManager, tiQuery, tiQueryXMLlight, tiQueryCSV, tiobject, tiPersistenceLayers; {$R *.lfm} { TForm1 } procedure TForm1.FormCreate(Sender: TObject); begin FModel := TTestModel1.Create; FModelList := TTestModel1List.Create; FModelList_Create := TTestModel1List_Create.Create; FFilename := 'TestXMLLight.xmllight'; FPersistenceLayer := 'xmlLight'; FTableName := 'TestModel1'; FUserName := 'Al'; FPassword := '011572'; end; procedure TForm1.btnShowModelInfoClick(Sender: TObject); begin Memo1.Lines.Clear; Memo1.Lines.Add(FModel.AsDebugString); Memo1.Lines.Add('**************************'); Memo1.Lines.Add(FModelList.AsDebugString); Memo1.Lines.Add('**************************'); end; procedure TForm1.btnReadListClick(Sender: TObject); begin try FModelList.Read; log('FModelList has been read.'); except log('FModelList could not be read!'); end; end; procedure TForm1.btnSaveListClick(Sender: TObject); begin try FModelList.Save; log('FModelList has been Saved.'); Except log('FModelList could not be Saved!'); end; end; procedure TForm1.btnShowPersistenceInfoClick(Sender: TObject); begin Memo2.Clear; with Memo2.Lines do begin Add('Persistence Layer Name = ' +gagtiopfutills.PersistenceLayerName); add('Persistence layer Names : '); AddStrings(gagtiopfutills.PersistenceLayerNames); Add('DefaultPersistenceLayerName : ' + gagtiopfutills.DefaultPersistenceLayerName); Add('Connected Databases : '); AddStrings(gagtiopfutills.ConnecetedDatabases); end; end; procedure TForm1.btnSetupPersistenceClick(Sender: TObject); begin SetupPersistence; end; procedure TForm1.FormDestroy(Sender: TObject); begin FModel.Free; FModelList.Free; FModelList_Create.Free;//: TTestModel1List_Create; end; procedure TForm1.FormShow(Sender: TObject); begin SetupMediators; //SetupPersistence; end; procedure TForm1.SetupMediators; begin end; procedure TForm1.SetupPersistence; var PerLayer: TtiPersistenceLayer; procedure CreateDB; begin {Does Database file Exist, if not create it.} if Not(FileExists(FFilename)) then begin try PerLayer.CreateDatabase(FFilename, FUserName, FPassword, FPersistenceLayer); log('Create Database: ' + FFilename + ' as ' + FPersistenceLayer + ' Success.'); except log('Create Database: ' + FFilename + ' as ' + FPersistenceLayer + ' Failed.'); end; end else begin {Database File Exists, check if DatabaseExists} if PerLayer.DatabaseExists(FFilename, FUserName, FPassword) then begin log('Database: ' + FFilename + ' Exists.') end else begin try PerLayer.CreateDatabase(FFilename, FUserName, FPassword, FPersistenceLayer); log('Create Database: ' + FFilename + ' as ' + FPersistenceLayer + ' Success.'); except log('Create Database: ' + FFilename + ' as ' + FPersistenceLayer + ' Failed.'); end; end; end; end; procedure CreateTable; var aTableMetaData: TtiDBMetaDataTable; begin aTableMetaData := TtiDBMetaDataTable.create; try aTableMetaData.Name:=FTablename; aTableMetaData.AddInstance('Name', qfkString, 200); aTableMetaData.AddInstance('PhoneNumber', qfkString, 200); gTIOPFManager.CreateTable(aTableMetaData, FDatabaseName, FPersistenceLayer); Log('Table ' + FTablename + ' Created.'); finally end; end; begin {Set Persistence Layer} try gTIOPFManager.LoadPersistenceLayer(FPersistenceLayer); log('Load PersistenceLayer: ' + FPersistenceLayer + ' Success.'); PerLayer := gTIOPFManager.PersistenceLayers.FindByPersistenceLayerName(FPersistenceLayer); Except log('Load PersistenceLayer: ' + FPersistenceLayer + ' Failed!'); end; Assert(PerLayer <> nil, 'Persistence Layer Name not regisatered, BREAK'); CreateDB; {Try to connect to database} try gTIOPFManager.ConnectDatabase(FTableName, FFilename, FUserName, FPassword, FDBParams, FPersistenceLayer); log('ConnectDatabase(' + FTableName + ', ' + FFilename + ', ' + FUserName + ', ' + FPassword + ', ' + FDBParams + ', ' + FPersistenceLayer + ') Success.'); gTIOPFManager.DefaultDBConnectionName:=FFilename; log('DefaultDatabaseConnectionName Set as : ' + FFilename); except log('ConnectDatabase(' + FTableName + ', ' + FFilename + ', ' + FUserName + ', ' + FPassword + ', ' + FDBParams + ', ' + FPersistenceLayer + ') Failed!'); end; {Does Table Exist} if gagTIOPFUtills.TableExists(FTableName) then Log('Table ' + FTableName + ' exists.') else begin Log('Table ' + FTablename + ' Does not Exist!'); try CreateTable; log('Table: ' + FTablename + ' Created.'); except log('Table: ' + FTablename + ' Could Not Be Created!'); end; end; end; procedure TForm1.Log(aString: String); begin Memo3.Lines.Add(aString); end; end.
unit ProgressBarForm3; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, RootForm, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, dxSkinsCore, dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis, dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray, dxSkinOffice2013White, dxSkinOffice2016Colorful, dxSkinOffice2016Dark, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine, dxSkinVisualStudio2013Blue, dxSkinVisualStudio2013Dark, dxSkinVisualStudio2013Light, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue, cxLabel, cxProgressBar, ProgressInfo; type TfrmProgressBar3 = class(TfrmRoot) pbRead: TcxProgressBar; lRead: TcxLabel; lWrite: TcxLabel; pbWrite: TcxProgressBar; lWrite0: TcxLabel; pbWrite0: TcxProgressBar; lAnalize: TcxLabel; bpAnalize: TcxProgressBar; private FReadLabel: string; FAnalizeLabel: string; FWriteLabel0: string; FWriteLabel: string; { Private declarations } protected property ReadLabel: string read FReadLabel write FReadLabel; property AnalizeLabel: string read FAnalizeLabel write FAnalizeLabel; property WriteLabel0: string read FWriteLabel0 write FWriteLabel0; property WriteLabel: string read FWriteLabel write FWriteLabel; public constructor Create(AOwner: TComponent); override; procedure UpdateReadStatistic(AProgressInfo: TProgressInfo); procedure UpdateWriteStatistic(AProgressInfo: TProgressInfo); procedure UpdateWriteStatistic0(AProgressInfo: TProgressInfo); procedure UpdateAnalizeStatistic(AProgressInfo: TProgressInfo); { Public declarations } end; var frmProgressBar3: TfrmProgressBar3; implementation {$R *.dfm} constructor TfrmProgressBar3.Create(AOwner: TComponent); begin inherited; FReadLabel := 'Прочитано строк'; FWriteLabel0 := 'Добавлено/обновлено параметров'; FWriteLabel := 'Сохранено записей'; FAnalizeLabel := 'Проанализировано записей'; end; procedure TfrmProgressBar3.UpdateReadStatistic(AProgressInfo: TProgressInfo); begin Assert(AProgressInfo <> nil); lRead.Caption := Format('%s: %d из %d', [FReadLabel, AProgressInfo.ProcessRecords, AProgressInfo.TotalRecords]); pbRead.Position := AProgressInfo.Position; Application.ProcessMessages; end; procedure TfrmProgressBar3.UpdateWriteStatistic(AProgressInfo: TProgressInfo); begin lWrite.Caption := Format('%s: %d из %d', [FWriteLabel, AProgressInfo.ProcessRecords, AProgressInfo.TotalRecords]); pbWrite.Position := AProgressInfo.Position; Application.ProcessMessages; end; procedure TfrmProgressBar3.UpdateWriteStatistic0(AProgressInfo: TProgressInfo); begin lWrite0.Caption := Format('%s: %d из %d', [FWriteLabel0, AProgressInfo.ProcessRecords, AProgressInfo.TotalRecords]); pbWrite0.Position := AProgressInfo.Position; Application.ProcessMessages; end; procedure TfrmProgressBar3.UpdateAnalizeStatistic(AProgressInfo: TProgressInfo); begin lAnalize.Caption := Format('%s: %d из %d', [FAnalizeLabel, AProgressInfo.ProcessRecords, AProgressInfo.TotalRecords]); bpAnalize.Position := AProgressInfo.Position; Application.ProcessMessages; end; end.
{ CTU Open Contest 2002 ===================== Sample solution for the problem: symmetry Martin Kacer, Oct 2002 } Program Symetry; Const MAXPTS = 100000; Type TPoint = Record X, Y: Integer; End; Var Pts : Array [1..MAXPTS] of TPoint; NumPts : Integer; {compare two points - we have to sort them for faster searching; return true iff (A <= B)} Function Compare (A, B: TPoint) : Boolean; Begin If (A.X < B.X) then Compare := True else If (A.X > B.X) then Compare := False else Compare := (A.Y <= B.Y); End; Function Middle (A, B, C: TPoint) : TPoint; Begin If Compare (A, B) and Compare (B, C) then Middle := B else If Compare (C, B) and Compare (B, A) then Middle := B else If Compare (A, C) and Compare (C, B) then Middle := C else If Compare (B, C) and Compare (C, A) then Middle := C else Middle := A; End; { Middle } {sorting function - not the best implementation but should be ok for us} Procedure QuickSort (L, R: Integer); Var LX, RX: Integer; Med, X: TPoint; Begin LX := L; RX := R; If (L < R) then Begin Med := Pts[(L+R) div 2]; If not Compare (Med, Pts[R]) then Med := Pts[R]; If (R-L > 15) then Med := Middle (Pts[L+3], Pts[R-3], Pts[(L+R) div 2 + 2]); While (L < R) do Begin While (L < R) and Compare (Pts[L], Med) do Inc (L); While (L < R) and not Compare (Pts[R], Med) do Dec (R); If (L < R) then Begin X := Pts[L]; Pts[L] := Pts[R]; Pts[R] := X; End; End; if Compare (Pts[L], Med) and (L < RX) then Inc (L) else Dec (R); QuickSort (LX, R); QuickSort (L, RX); End; End; {find the specified point in a sorted array; return its index or 0 if not found} Function BinSearch (X: TPoint) : Integer; Var L, R, I: Integer; Begin L := 1; R := NumPts; While (L < R) do Begin I := (L+R) div 2; If Compare (X, Pts[I]) then R := I else L := I+1; End; If (X.X = Pts[L].X) and (X.Y = Pts[L].Y) then BinSearch := L else BinSearch := 0; End; {solve one situation - find the "center of gravity" and check whether every point has its counterpart} Function Solve (Var TwiceX, TwiceY: Integer) : Boolean; Var SX, SY: Integer; I: Integer; X: TPoint; Begin Solve := false; QuickSort (1, NumPts); SX := 0; SY := 0; For I := 1 to NumPts do Begin SX := SX + Pts[I].X; SY := SY + Pts[I].Y; End; If ((SX*2) mod NumPts = 0) and ((SY*2) mod NumPts = 0) then Begin SX := (SX*2) div NumPts; SY := (SY*2) div NumPts; Solve := true; For I := 1 to NumPts do Begin X := Pts[I]; X.X := SX - X.X; X.Y := SY - X.Y; If (BinSearch (X) = 0) then Solve := false; End; End; TwiceX := SX; TwiceY := SY; End; Var I: Integer; X, Y: Integer; Begin Repeat ReadLn (NumPts); If (NumPts > 0) then Begin For I := 1 to NumPts do ReadLn (Pts[I].X, Pts[I].Y); If Solve (X, Y) then WriteLn ('V.I.P. should stay at (', X div 2, '.', (X mod 2) * 5, ',', Y div 2, '.', (Y mod 2) * 5, ').') else WriteLn ('This is a dangerous situation!'); End; until (NumPts = 0); End.
Program DiskTest; {$M 8192, 131072, 131072} {$N+ enable FPU, for scaling of output on pattern tests} {$E+ enable FPU emulation if FPU not present} {IOMeter type performance tests for XT/AT PCs with MS-DOS. Used for the development of the Dangerous Prototype XT-IDE board, and subsequently the lo-tech XT-CF board. Includes pattern tests for testing 8-bit interface reliability and to generate patterns to check with a scope attached. Performance Testing =================== By default, creates a 4MB file in the current working directory using 32K IOs. Then reads it back also using 32K IOs. Next performs two random workload tests on it: - 70% read, using 8K IOs (8K aligned) - 100% read, using 512-byte IOs (sector aligned) Finally displays the results, with speed calculated based on the system clock. Note therefore that any hardware causing clock-skew via extended disabling of interupts (causing loss of timer ticks) will cause results to be overstated. Pattern Testing =============== For media testing, 'mediatest' command line option runs a 10-pass pattern test. Default file size is 4MB; this can be extended to all available free space by also specifying 'maxsize'. As with the performance test, test size will be automatically truncated to available disk space. Tests are potentially time consuming - can skip on (to the next part) by pressing any key. Progress is shown onscreen though. For interface testing, special patterns can be tested using the command line option 'signaltest'. This option runs patterns that enable assessment of signal quality with an osciloscope: Test 1 - For testing at DD7. Flips the bit continually, all others will be low. Line DD7 has a 10k pull-down at the interface. Test 2 - For testing at DD11. Holds the bit low and flips all other bits continually. Enables measurement of cross-talk as the line serving this bit is in the middle of the data lines on the 40-pin connector. Test 3 - For testing on the ISA Bus at data bit 4 (ISA slot pin A5). To enable assessment of signal quality on the ISA bus. Flips this bit repeatedly. By James Pearce, lo-tech.co.uk Modified by Foone Turing, foone.org v1.0 - 06-May-10 - Initial build 32K read and write and 8k random v1.1 - 15-Apr-11 - Fixed transfer sizes (were 512-bytes too large) v1.2 - 26-Apr-11: - Added 512-byte random read test - note random r-w at sector level would be misleading due to variable DOS cluster sizes. Writes less than a cluster must be performed as read-update-write. - Added automatic reduction of test file size depending on free space available. - Added command line options (any order): - 'maxsize', to test with maximum free space of drive - 'maxseeks', to test random with 4096 seeks (default is 256) - 'highseeks', to test random with 1024 seeks - 'lowseeks', to test random with 128 seeks - 'minseeks', to test random with 32 seeks (for floppys) - '-h' or '/h' or '/?' to display a command line reference v1.3 - 08-Sep-11: - Added 'testintegrity' option, which performs extended pattern testing and reports on any errors encountered (instead of the performance tests). v1.4 - 10-Sep-11: - Revised checking method to detect errors for integrity test - Added run-time and error notification to end of test - Increased to 10 patterns - Added progress indicators and some formating to ensure entire test info will always show on one screen, regardless of test file size. - Made pattern tests 'two dimensional', to test interface integrity too (i.e. individual bits in consecutive words transferred will change) - Added 'crosstalktest' option (for XT-IDE prototype scoping, see below) v1.5 - 14-Sep-11: - Renamed and extended pattern tests - Revised most parts for efficiency - Set memory limits to ensure will run on 256K XT - consolidated pattern test code - added option 'cycle' to shift bits for every word on media-test v1.6 - 19-Sep-11: - Changed pattern test procedure to a function (returns no. of errors) - Revised display scaling code in pattern test - Added operational indication to performance tests - Added ability to completely terminate pattern tests (press 'Q') v1.7 - 14-Feb-12: - Added "size=" parameter to enable test size to be directly set. Specified size can include K or M for KB or MB respecitively. Specified size must be >64KB, and will be truncated to avaulable disk space. E.g: size=8M will define an 8MB test file, if that much space is available. v1.8 - 16-Feb-12: - Added 'powertest' to signal test function and refined pattern writing utility to support looping operation (to support it). The powertest mode continually reads or writes 0x55AA 0xAA55 pairs as fast as possible (without verifying), simply wrapping at the end of the test file size allocated repeatedly until the test is terminated by the user. By flipping all 16-bits on every word, and all 8-bits on every byte, power consumption of the card should be maximised, hence allowing measurement of power drawn of the card in this worst-case test pattern. - Re-designed help screens as too much for one 80x25 page v1.9 - 10-Apr-12 - Changed pattern definitions to consider the two seperate 8-bit transfers more closely. Patterns are now: 0,$FFFF,$F0F0,$CCCC,$AAAA,$AA55,$A5A5,$FF00,$18E7,$E718 v2.0 - 29-Apr-12 - Added readonly test option. v2.1 - 30-Apr-12 - Re-coded block comparison function in pattern tests; testing now runs *much* faster on XT class hardware (5x). v2.2 - 01-May-12 - Changed pattern testing to include both static patterns and walking-ones / walking-zeros tests. Basic patterns are now: 0,$FFFF,$FF00,$F00F,$AA55,$A55A,$18E7,$E718, then walking-1s and walking-0s. Cycle option has been removed. v2.3 - 04-May-12 - Added RAM test to the pattern test routine. - Added 'noprogress' switch to surpress screen progress marks on performance tests. v2.4 - 04-Oct-17 - Delete test file at end of test } Uses Dos, Crt; TYPE Sector = array[0..255] of word; {512 bytes} T32kArray = array[0..16383] of word; {32KB} P32kArray = ^T32kArray; T8kArray = array[0..8191] of word; {8k} P8kArray = ^T8kArray; CONST TestSize : LongInt = 4194304; {4MB} FName : String = 'TEST$$$.FIL'; Seeks : Word = 256; PatternTests : Byte = 10; Patterns : Array[1..10] of Word = (0,$FFFF,$FF00,$F00F,$AA55,$A55A,$18E7,$E718,$0001,$FFFE); PatternCycle : Array[1..10] of Byte = (0, 0, 0, 0, 0, 0, 0, 0, 1, 1); PatternNames : Array[1..10] of String[10] = ('','','','','','','','','Walking 1s','Walking 0s'); PowerPatterns : Array[1..2] of Word = ($55AA,$AA55); VERSION : String = '2.4'; DisplayCodesCount : Byte = 4; DisplayCodes : Array[1..4] of Char = ('-','\','|','/'); {Pattern test writer modes} PatRead : Byte = 1; PatReadContinuous : Byte = 2; PatWrite : Byte = 4; PatWriteContinuous : Byte = 8; PatVerify : Byte = 16; PatPrompt : Byte = 32; VAR Time : Real; QUIT : Boolean; noprogress : Boolean; procedure StartClock; var hr, min, sec, sec100 : word; begin GetTime(hr,min,sec,sec100); Time := (hr * 3600) + (min * 60) + sec + (sec100 / 100); end;{StartClock} function StopClock : Real; var hr, min, sec, sec100 : word; Time2 : real; begin GetTime(hr,min,sec,sec100); Time2 := (hr * 3600) + (min * 60) + sec + (sec100 / 100); If Time2 = Time then StopClock := 0.01 {prevent div by 0} else StopClock := (Time2 - Time); end;{StopClock} function CreateFile : Real; {creates the file and returns the rate in KB/s} var f : file of T32kArray; buffer : P32kArray; i : word; max : word; res : word; Mark, X, Y : Byte; begin Assign(f,FName); Rewrite(f); new(buffer); max := TestSize div SizeOf(T32kArray); X := WhereX; Y := WhereY; Mark := 1; StartClock; {now do the write test} if noprogress then begin for i := 1 to max do write(f,buffer^); end else begin for i := 1 to max do begin Inc(Mark); If Mark > DisplayCodesCount then Mark := 1; write(DisplayCodes[Mark]); GotoXY(X,Y); write(f,buffer^); end;{for} end;{if/else} close(f); CreateFile := TestSize / 1024 / StopClock; Dispose(buffer); end;{createfile} function ReadFile : Real; {reads the file and returns the rate in KB/s} var f : file of T32kArray; buffer : P32kArray; i : word; max : word; res : word; Mark, X, Y : Byte; begin Assign(f,FName); Filemode := 0; {open read-only} Reset(f); new(buffer); max := TestSize div SizeOf(T32kArray); X := WhereX; Y := WhereY; Mark := 1; StartClock; {now do the read test} if noprogress then begin for i := 1 to max do read(f,buffer^); end else begin for i := 1 to max do begin Inc(Mark); If Mark > DisplayCodesCount then Mark := 1; write(DisplayCodes[Mark]); GotoXY(X,Y); read(f,buffer^); end;{for i} end;{if/else} close(f); ReadFile := TestSize / 1024 / StopClock; dispose(buffer); end;{createfile} function RandomTest( transfersize : word; readpercent : byte ) : Real; {Random IOPS test, returns the rate in IOPS Tests IOs of up to 32K each - transfersize is the size in bytes readpercent is percentage that should be reads (50 = 50%)} type PositionArray = array[1..4096] of LongInt; var f : file; buffer : P32kArray; i, n : word; max : LongInt; p1, p2 : word; max1, max2 : word; res : word; p : LongInt; Positions : ^PositionArray; limit : byte; Mark, X, Y : Byte; TimeInSeeks, TimeInTransfers : Real; begin Randomize; Assign(f,FName); if readpercent = 100 then Filemode := 0 {open read-only} else Filemode := 2; {open read/write} Reset(f,1); max := TestSize - transfersize; {take off the transfer size to allow for the last block} max1 := max SHR 16; max2 := max AND 65535; p1 := 0; new(Positions); new(buffer); for i := 1 to Seeks do begin {create an array of seek positions (in bytes)} if max1 > 0 then p1 := Random(max1); p2 := Random(max2); p := (longint(p1) SHL 16) + (p2 AND $FE00); {sector align} Positions^[i] := p; end;{for} n := 1; X := WhereX; Y := WhereY; Mark := 1; limit := readpercent div 10; StartClock; TimeInSeeks := 0; TimeInTransfers := 0; {do the random IO test} for i := 1 to Seeks do begin if not noprogress then begin Inc(Mark); If Mark > DisplayCodesCount then Mark := 1; write(DisplayCodes[Mark]); GotoXY(X,Y); end;{if not noprogress} seek(f,Positions^[i]); {n keeps track of reads and writes} if n <= limit then blockread(f,buffer^,transfersize) else blockwrite(f,buffer^, transfersize,res); inc(n); if n > 10 then n := 1; end;{for} close(f); RandomTest := i / StopClock; Dispose(buffer); Dispose(Positions); end;{RandomTest} procedure PurgeTestFile; {purges the contents of the test file, if it's present} var f : file; begin Assign(f,FName); Rewrite(f); Truncate(f); Close(f); end;{procedure PurgeTestFile} procedure DeleteTestFile; {deletes the test file} var f : file; begin WriteLn('Deleting ', FName, '.'); Assign(f,FName); Erase(f); end;{procedure DeleteTestFile} function CheckTestFile : LongInt; {returns the size of the test file, if it can be found} var f : file; begin Assign(f,FName); Filemode := 0; {open readonly} {$I-} Reset(f,1); {$I+} If IOResult <> 0 then CheckTestFile := 0 else begin CheckTestFile := FileSize(f); Close(f); end;{if IOResult} end;{function} Function COMPSW( source, destination : pointer; words : word) : Word; {implements COMPSW function, comparing source with destination on a word-by-word basis, returning zero if they were OK} var rDS, rSI, rES, rDI : Word; BlockBad : Word; begin rDS := Seg(source^); rSI := Ofs(source^); rES := Seg(destination^); rDI := Ofs(destination^); asm push ds push si push es push di mov ax, rDS mov ds, ax mov ax, rSI mov si, ax mov ax, rES mov es, ax mov ax, rDI mov di, rDI mov cx, words cld rep cmpsw jz @NoDiffs inc cx @NoDiffs: mov BlockBad, cx pop di pop es pop si pop ds end;{asm} COMPSW := BlockBad; end;{function COMPSW} Function PatternTest( WriteBlock, Rd : P32kArray; DisplayStr : string; Mode : Byte ) : LongInt; {writer for pattern testing. Returns the number of errors encountered. See constants at the top for the mode options (which can be combined). Also checks the two transfer buffers with the pattern in question first, to avoid showing a RAM problem as a controller problem.} var f : file of T32kArray; ErrCount, TotalErrors : LongInt; IO, j, i : Word; max, readmax : LongInt; Dots, Mark, Next, CurrentDot : Byte; CurrentPosition : Single; X, Y, XBreak, X1, X2, Y1 : Byte; Ch : Char; PromptStr : String; begin Assign(f,FName); Filemode := 2;{read/write} max := TestSize div SizeOf(T32KArray); {number of IOs for test} readmax := max; {size of read test - will reduce if write phase is skipped} TotalErrors := 0; ErrCount := 0; DisplayStr := DisplayStr + ' - Writing: '; Dots := (78 - Length(DisplayStr) - Length(' Comparing: ')) div 2; {Dots will be the number of dots to displayed during the test each way} {write out info + get cursor position} Write(DisplayStr); X := WhereX; Y := WhereY; X1 := X; Y1 := Y; Ch := CHAR(0); {now write out file - will always do this part} repeat GoToXY(X1,Y1); for i := 1 to dots do write(' '); GoToXY(X1,Y1); X := X1; Reset(f); CurrentDot := 0; Mark := 1; for IO := 1 to max do begin {calculate when to write a dot on screen.} CurrentPosition := IO * Dots / max; {debug line follows - introduces an error on one 32K block written} {if IO = 4 then write(f,Rd^) else} write(f,WriteBlock^); {now update screen} Next := trunc(CurrentPosition); if (Next > CurrentDot) then begin {time to advance dot(s) on screen} repeat Write('.'); Inc(X); Inc(CurrentDot); until CurrentDot = Next; end else begin Inc(Mark); If Mark > DisplayCodesCount then Mark := 1; write(DisplayCodes[Mark]); GotoXY(X,Y); end; if KeyPressed then begin while KeyPressed do Ch := ReadKey; {clear keyboard buffer} if (Ch = ' ') and ((Mode AND PatWriteContinuous) = PatWriteContinuous) then {space finishes the current write block, then skips} Mode := Mode AND NOT PatWriteContinuous else begin readmax := IO; {record how many blocks were written} IO := max; {end write loop} if (readmax < max) then begin if X > (80 - Dots - Length(' Comparing: ') - Length('Skipped ')) then GotoXY((80 - Dots - Length(' Comparing: ') - Length('Skipped ')),Y); Write('Skipped '); end;{if (readmax<max)} If UpCase(Ch) = 'S' then readmax := 0 else if UpCase(Ch) = 'Q' then begin QUIT := true; readmax := 0; end;{if/else} end;{if Ch=' '} end;{if keypressed} end; until (Ch<>CHAR(0)) OR ((Mode AND PatWriteContinuous) <> PatWriteContinuous); If ((Mode AND PatPrompt) = PatPrompt) then begin if ((Mode AND PatVerify) = PatVerify) then PromptStr := 'Verify ' else PromptStr := 'Read '; if ((Mode AND PatReadContinuous) = PatReadContinuous) then PromptStr := PromptStr + '(C)ontinuous/'; PromptStr := PromptStr + '(O)nce/(N)o: '; X2 := 78 - Dots - Length(PromptStr); GotoXY( X2, Y ); Write(PromptStr); If ((Mode AND PatReadContinuous) = PatReadContinuous) then repeat Ch := Upcase(ReadKey); until Ch in ['C', 'O', 'N'] else repeat Ch := Upcase(ReadKey); until Ch in ['O', 'N']; case Ch of 'O' : mode := mode AND NOT PatReadContinuous; {user selected not continuous} 'N' : mode := 0; {nothing to do} end;{case} GotoXY( X2, Y ); for i := 1 to length(PromptStr) do Write(' '); end;{read and verify behaviour required check} while keypressed do Ch := ReadKey; {clear keyboard buffer} Ch := CHAR(0); {clear input} while (Ch = CHAR(0)) AND (readmax > 0) AND ((mode AND PatRead) = PatRead) do begin {now read back and compare if verify was specified} GotoXY( (78 - Dots - Length('Comparing: ')), Y ); if ((mode and PatVerify) = PatVerify) then Write(' Comparing: ') else Write(' Reading: '); reset(f); CurrentDot := 0; X := WhereX; for IO := 1 to readmax do begin {calculate when to write a dot on screen} CurrentPosition := IO * Dots / readmax; {read the block} read(f,Rd^); {find which dot we're on now} Next := trunc(CurrentPosition); {compare what was read with what was written, if we need to} if ((mode AND PatVerify) = PatVerify) then ErrCount := ErrCount + COMPSW(WriteBlock,Rd,16384); {now update screen} if (Next > CurrentDot) then begin {time to advance mark(s) on screen} repeat if ErrCount = 0 then Write('û') else write('!'); Inc(X); Inc(CurrentDot); until CurrentDot = Next; if ErrCount <> 0 then begin Inc(TotalErrors); ErrCount := 0; end; end else begin Inc(Mark); If Mark > DisplayCodesCount then Mark := 1; write(DisplayCodes[Mark]); GotoXY(X,Y); end; {check if user has interupted} if KeyPressed then begin while KeyPressed do Ch := ReadKey; {clear keyboard buffer} IO := readmax; {end read loop} if X > (79 - Length('Skipped')) then GotoXY((79 - Length('Skipped')),Y); Write('Skipped'); if UpCase(Ch) = 'Q' then QUIT := true; end;{if} end; If ((mode AND PatReadContinuous) <> PatReadContinuous) then mode := mode XOR PatRead; {end while loop as only one pass was required} end;{while...} {clear up} WriteLn(' '); close(f); PatternTest := TotalErrors; end;{procedure PatternTest} function InHex(value : word) : string; var i, num : byte; Ch : char; begin InHex := '0x'; InHex[0] := char(6); {set length to 6 chars} for i := 1 to 4 do begin num := value AND 15; {lower 4 bits} value := value SHR 4; {strip off lower for, for the next iteration} if num < 10 then ch := char(num+48) {'0' is ASCII 48} else ch := char(num+55); {'A' is ASCII 65} InHex[(7-i)] := ch; end;{for} end;{fucntion} function TwoDigit(var number : byte) : String; var TempStr : String; begin Str(number,TempStr); if number < 10 then TwoDigit := '0' + TempStr else TwoDigit := TempStr; end;{function} procedure MediaTest; var Wr, Rd : P32kArray; {we allocation both memory blocks here,} Test : byte; {so that we can test the pattern in RAM first} DisplayStr : String; H, M, S : Byte; TestTime : Real; i : Word; Errors : LongInt; Res : LongInt; WrDS, WrSI : Word; begin Write('Pattern testing with ',PatternTests,' patterns over '); if (TestSize > 1048576) then {file is MB size} write( (TestSize / 1048576):1:1,' MB.') else {file is KB size} write( (TestSize div 1024),' KB.'); WriteLn; Write('Press any key to skip on, S to skip test completely, Q to quit.'); WriteLn; WriteLn; new(Wr); new(Rd); Errors := 0; QUIT := false; StartClock; for Test := 1 to PatternTests do begin {fill array with pattern} if (PatternCycle[Test]=1) then begin {this is a cyclic test, i.e. walking 1's or walking 0's etc} {build the pattern array shifting every BYTE, since it's an 8-bit interface} {we're testing} WrDS := Seg(Wr^); WrSI := Ofs(Wr^); Wr^[0] := Patterns[Test]; asm push ds push si push ax push cx mov ds, WrDS mov si, WrSI mov ax, ds:[si] mov cx, 32768 @comploop: mov ds:[si], al rol al, 1 inc si loop @comploop pop cx pop ax pop si pop ds end;{asm} end else for i := 0 to 16383 do Wr^[i] := Patterns[Test]; {fill array with pattern} {now check the allocated RAM is free from apparent errors} Rd^ := Wr^; {copy between the buffers} {get test name} If (PatternCycle[Test]=1) then DisplayStr := PatternNames[Test] else DisplayStr := 'Pattern ' + InHex(Patterns[Test]); {check the allocated RAM blocks for errors} if COMPSW(Wr,Rd,16384) <> 0 then begin {RAM apparently is bad} WriteLn('RAM Error detected with ', DisplayStr, '.'); WriteLn(' Block A is at: ', InHex(Seg(Wr^)), ':', InHex(Ofs(Wr^)), 'h'); WriteLn(' Block B is at: ', InHex(Seg(Rd^)), ':', InHex(Ofs(Rd^)), 'h'); WriteLn(' Source is at : ', InHex(Seg(Patterns)), ':', InHex(Ofs(Patterns)+Test), 'h'); WriteLn; Write('Checking: '); for i := 0 to 16383 do begin if Wr^[i] <> Rd^[i] then begin WriteLn('Difference encountered at offset ', InHex((i*2))); i := 16383; {drop out of loop} end; end;{for} dispose(Rd); dispose(Wr); Exit; end;{if COMPSW} {Otherwise, run the pattern test} Errors := Errors + PatternTest(Wr,Rd,DisplayStr,(PatRead+PatWrite+PatVerify)); if Quit then Test := PatternTests; end;{for} TestTime := StopClock; Dispose(Rd); Dispose(Wr); H := Trunc(TestTime) div 3600; M := (Trunc(TestTime) mod 3600) div 60; S := Trunc(TestTime) mod 60; WriteLn; Write('Test ran for ',TwoDigit(H),':',TwoDigit(M),':',TwoDigit(S),'. '); If Errors = 0 then Write('No') else write(Abs(Errors),' 32K'); write(' blocks had errors.'); end;{procedure MediaTest} procedure SignalTest; {optional pattern tests specifically targetted at 8-bit XT/IDE adapter development. See info in narrative at top of file.} var Test : Byte; Wr, Rd : P32kArray; EndOfTest : Boolean; Ch : Char; i : Word; DisplayStr : String; Errors : LongInt; TestMode : Byte; begin WriteLn('XT/IDE Development Pattern Tests - using ',(TestSize div 1048576),'MB test file.'); New(Wr); New(Rd); EndOfTest := False; Errors := 0; repeat WriteLn; WriteLn('Test 1 - For testing at DD7. Flips the bit continually, all others'); WriteLn(' will be low. Line DD7 has a 10k pull-down at the interface.'); WriteLn; WriteLn('Test 2 - For testing at DD11. Holds the bit low and flips all other bits'); WriteLn(' continually. Enables measurement of cross-talk as the line serving'); WriteLn(' this bit is in the middle of the data lines on the 40-pin connector.'); WriteLn; WriteLn('Test 3 - For testing on the ISA Bus at data bit 4 (ISA slot pin A5). To enable'); WriteLn(' assessment of ISA bus signal quality, flips this bit repeatedly.'); WriteLn; WriteLn('Test 4 - For measuring peak power consumption of the interface under read and'); WriteLn(' write workloads. Total power consumption will be affected by the'); WriteLn(' system (and bus) speed, since faster switching will use more power.'); WriteLn(' Test patterns are', InHex(PowerPatterns[1]), ' and ', InHex(PowerPatterns[2]), '.' ); WriteLn; WriteLn('Test 5 - As test 4, except that the read part of the test is a one-pass verify'); WriteLn(' This will run much slower, but will confirm, after a heavy write test'); WriteLn(' that the signals were intact.'); WriteLn; Write('Enter Test (1-5) or E to end: '); repeat ch := UpCase(readkey); until ch in ['1', '2', '3', '4', '5', 'E', 'Q']; WriteLn(ch); if (Ch = 'E') or (Ch = 'Q') then EndOfTest := True else begin {Fill buffer depending on choice} if ch = '1' then begin for i := 0 to 16383 do begin Wr^[i] := $80; inc(i); Wr^[i] := 0; end; {for} end else if ch = '2' then begin for i := 0 to 16383 do begin Wr^[i] := $F7FF; inc(i); Wr^[i] := 0; end; {for} end else if ch = '3' then begin for i := 0 to 16383 do Wr^[i] := $1000 end else if ch in ['4','5'] then begin for i := 0 to 16383 do begin Wr^[i] := PowerPatterns[1]; inc(i); Wr^[i] := PowerPatterns[2]; end; {for} end;{if/else} {perform the test} WriteLn; Write('Will perform WRITE test first, then the READ. Data read back will '); If Ch <> '5' then write('not '); WriteLn; WriteLn('be verified. Press SPACE to move on to read test once current write'); WriteLn('test has finished, N to skip on immediately, or S to skip it.'); DisplayStr := 'Test ' + Ch; TestMode := PatRead + PatWrite + PatWriteContinuous; If Ch = '5' then TestMode := TestMode + PatVerify else TestMode := TestMode + PatReadContinuous; Errors := Errors + PatternTest(Wr,Rd,DisplayStr,TestMode); end;{if/else} until EndOfTest; Dispose(Rd); Dispose(Wr); If Errors = 0 then Write('No') else write(Errors); write(' errors were encountered.'); end;{procedure SignalTest} function ParamSpecified(s : string) : boolean; {checks all command line arguments for s, returning true if found} var i : word; found : boolean; begin found := false; for i := 1 to ParamCount do if Copy(ParamStr(i),1,Length(s)) = s then found := true; ParamSpecified := found; end;{function ParamSpecified} function GetParam(s : string) : string; {returns the value specified by a paramter, e.g. for 'size=8M' it would return '8M'} var i : word; returnstr : string; begin returnstr := ''; for i := 1 to ParamCount do if Copy(ParamStr(i),1,Length(s)) = s then {this is the parameter we're looking for} ReturnStr := Copy(ParamStr(i),succ(Length(s)), (Length(ParamStr(i))-Length(s)) ); GetParam := ReturnStr; end;{function GetParam} function StringToValue(s : string) : LongInt; {returns the value specified in the string as a LongInt, taking account of K and M suffixes (Kilobytes and Megabytes)} var IsMega : Boolean; IsKilo : Boolean; n : LongInt; Cd : Integer; begin IsKilo := False; IsMega := False; Case UpCase(s[length(s)]) of 'K' : IsKilo := True; 'M' : IsMega := True; end;{case} If IsKilo or IsMega then BYTE(s[0]) := Pred(BYTE(s[0])); {chop off suffix, if present} val(s,n,cd); if cd = 0 then begin {converted OK so apply multiplier} if IsKilo then n := n SHL 10; if IsMega then n := n SHL 20; end; If (n < 65536) or (cd <> 0) then begin {didn't understand size= input or < 64KB was specified; set to default} writeln('Didn''t understand size parameter. Must be 64K or more.'); n := TestSize; end; StringToValue := n; end;{function StringToValue} {=========================================================================} {Program main block follows. {=========================================================================} VAR ReadSpeed, WriteSpeed, IOPS : Real; Ch : Char; Readonly : Boolean; TestDone : Boolean; BEGIN WriteLn('DiskTest, by James Pearce & Foone Turing. Version ', VERSION); If ParamSpecified('/h') or ParamSpecified('-h') or ParamSpecified('/?') or ParamSpecified('-?') then begin WriteLn('Disk and interface performance and reliability testing.'); WriteLn; WriteLn('With no command line parameters, the utility will perform a file-system based'); WriteLn('performance test with a test file size of 4MB and 256 seeks, with file size'); WriteLn('truncated to available free space if it is less.'); WriteLn; WriteLn('Performance test specific command line options:'); WriteLn; WriteLn(' * maxseeks - 4096 seeks (default is 256)'); WriteLn(' * highseeks - 1024 seeks'); WriteLn(' * lowseeks - 128 seeks'); WriteLn(' * minseeks - 32 seeks (use for floppy drives)'); WriteLn(' * size=x - specify the test file size, which will be truncated to'); WriteLn(' available free space. To use all free space use ''maxsize'' '); WriteLn(' instead. Value is in bytes, specify K or M as required.'); WriteLn(' examples: size=4M (default), size=16M, size=300K'); WriteLn; WriteLn('Example: disktest size=8M maxseeks'); WriteLn; WriteLn('Note: XT class hardware with stepper-motor drives will process random IO at'); WriteLn(' about 5 - 10 IOPS only, hence 256 seeks is enough for measurement on'); WriteLn(' such systems.'); WriteLn; Write('Press (c) for reliability testing usage, any other key to quit: '); Ch := UpCase(ReadKey); If Ch = 'C' then begin {display reliability testing usage notes} WriteLn(Ch); WriteLn; WriteLn('Reliability Testing Options:'); WriteLn; WriteLn(' * mediatest - performs pattern testing instead of performance testing,'); Writeln(' reporting errors as it runs. 10 tests.'); WriteLn; WriteLn(' * signaltest - performs pattern tests for checking signal quality and'); WriteLn(' measuring power consumption. These operate interactively,'); WriteLn(' hence more help with this option is provided when specified.'); WriteLn; WriteLn('Note: size=xM can also be specified for these tests.'); end;{if Ch} end {help screen} else begin WriteLn; TestDone := False; {check if we're running a read-only test on an existing test file} if ParamSpecified('readonly') then readonly := true else readonly := false; if ParamSpecified('noprogress') then noprogress := true else noprogress := false; {controls whether progress marks are displayed in performance tests} if Not Readonly then begin TestDone := True; {First truncate the test file to 0 bytes, if it's present} Write('Preparing drive...'); PurgeTestFile; {check to see if specific test size was specified with size=} if ParamSpecified('size=') then TestSize := StringToValue( GetParam('size=') ); {Then check disk space on the current drive, and reduce TestSize accordingly} If (DiskFree(0) < TestSize) or (ParamSpecified('maxsize')) then begin TestSize := (DiskFree(0) SHR 15) SHL 15; {truncate to 32K boundary} end;{if DiskFree} WriteLn; If ParamSpecified('mediatest') then MediaTest else if ParamSpecified('signaltest') then SignalTest else TestDone := False; end; If Not TestDone then begin {Next check for seek command line options} If ParamSpecified('maxseeks') then Seeks := 4096; If ParamSpecified('highseeks') then Seeks := 1024; If ParamSpecified('lowseeks') then Seeks := 128; If ParamSpecified('minseeks') then Seeks := 32; If ReadOnly then begin {check for the test file and how big it is} Write('Read-only test mode; checking for existing test file...'); TestSize := CheckTestFile; if TestSize = 0 then begin WriteLn(' file not found.'); Halt(0); end else writeLn(' OK'); end;{if ReadOnly} {print test summary} Write('Configuration: ',(TestSize div 1024),' KB test file, '); WriteLn(Seeks,' IOs in random tests.'); WriteLn; If Not Readonly then begin Write('Write Speed : '); WriteSpeed := CreateFile; WriteLn(WriteSpeed:3:2,' KB/s'); end;{if not Readonly} Write('Read Speed : '); ReadSpeed := ReadFile; WriteLn(ReadSpeed:3:2,' KB/s'); If ReadOnly then begin Write('8K random read : '); IOPS := RandomTest(8192,100); end else begin Write('8K random, 70% read : '); IOPS := RandomTest(8192,70); end;{if ReadOnly} WriteLn(IOPS:3:1,' IOPS'); Write('Sector random read : '); IOPS := RandomTest(512,100); WriteLn(IOPS:3:1,' IOPS'); WriteLn; Write('Average access time (includes latency and file system'); WriteLn(' overhead), is ',(1000/IOPS):2:0,' ms.'); WriteLn; end;{if not TestDone} if Not ReadOnly then begin DeleteTestFile end;{if not ReadOnly} end;{if/else} END.{PROGRAM}
{**********************************************} { TeeChart GIF Export format } { Copyright (c) 2000-2004 by David Berneda } {**********************************************} unit TeeGIF; {$I TeeDefs.inc} interface Uses {$IFNDEF LINUX} Windows, {$ENDIF} Classes, {$IFDEF CLX} QGraphics, QForms, QStdCtrls, QExtCtrls, QControls, {$ELSE} Graphics, Forms, Controls, StdCtrls, ExtCtrls, {$ENDIF} {$IFNDEF CLX} {$IFNDEF CLR} GIFImage, {$ENDIF} {$ENDIF} TeeProcs, TeeExport, TeCanvas; type {$IFDEF CLX} TGIFImage=TBitmap; TDitherMode=Integer; {$ENDIF} TTeeGIFOptions = class(TForm) RGCompression: TRadioGroup; Label1: TLabel; CBDither: TComboFlat; Label2: TLabel; CBReduction: TComboFlat; procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); Procedure RGCompressionClick(Sender: TObject); private { Private declarations } public { Public declarations } end; {$IFDEF CLR} TGIFCompression=Integer; TDitherMode=Integer; TColorReduction=(rmNone); TGIFImage=class(TBitmap) private FCompression:TGIFCompression; FDitherMode:TDitherMode; FColorReduction:TColorReduction; public property Compression:TGIFCompression read FCompression write FCompression; property DitherMode:TDitherMode read FDitherMode write FDitherMode; property ColorReduction:TColorReduction read FColorReduction write FColorReduction; end; {$ENDIF} TGIFExportFormat=class(TTeeExportFormat) private Procedure CheckProperties; protected FProperties : TTeeGIFOptions; Procedure DoCopyToClipboard; override; public function Description:String; override; function FileExtension:String; override; function FileFilter:String; override; Function GIF:TGIFImage; Function Options(Check:Boolean=True):TForm; override; Procedure SaveToStream(Stream:TStream); override; end; implementation {$IFNDEF CLX} {$R *.DFM} {$ELSE} {$R *.xfm} {$ENDIF} Uses {$IFDEF CLX} QClipbrd, {$ELSE} Clipbrd, {$ENDIF} SysUtils, TeeConst; const GIFImageDefaultDitherMode:TDitherMode=TDitherMode(0); function TGIFExportFormat.Description:String; begin result:=TeeMsg_AsGIF; end; function TGIFExportFormat.FileFilter:String; begin result:=TeeMsg_GIFFilter; end; function TGIFExportFormat.FileExtension:String; begin result:='gif'; end; Function TGIFExportFormat.GIF:TGIFImage; var tmpBitmap : TBitmap; IGIFImage : TGIFImage; begin CheckProperties; CheckSize; IGIFImage:=TGIFImage.Create; With IGIFImage do begin {$IFNDEF CLX} //MM Pending Unisys decision // See: http://www.unisys.com/about__unisys/lzw // Compression:=TGIFCompression(1); { 5.02 } Removed in 6.02, patent expired. Compression:=TGIFCompression(FProperties.RGCompression.ItemIndex); // 6.02 DitherMode:=TDitherMode(FProperties.CBDither.ItemIndex); ColorReduction:=TColorReduction(FProperties.CBReduction.ItemIndex); {$ENDIF} tmpBitmap:=Panel.TeeCreateBitmap(Panel.Color,TeeRect(0,0,Self.Width,Self.Height)); try Assign(tmpBitmap); { 5.01 } finally tmpBitmap.Free; end; end; result:=IGIFImage; end; Procedure TGIFExportFormat.CheckProperties; begin if not Assigned(FProperties) then begin FProperties:=TTeeGIFOptions.Create(nil); FProperties.FormShow(Self); end; end; Function TGIFExportFormat.Options(Check:Boolean=True):TForm; begin if Check then CheckProperties; result:=FProperties; end; procedure TGIFExportFormat.DoCopyToClipboard; var tmp : TGIFImage; begin tmp:=GIF; try Clipboard.Assign(tmp); finally tmp.Free; end; end; procedure TGIFExportFormat.SaveToStream(Stream:TStream); begin With GIF do try SaveToStream(Stream); finally Free; end; end; procedure TTeeGIFOptions.FormShow(Sender: TObject); begin {$IFDEF CLX} CBDither.ItemIndex:=0; CBReduction.ItemIndex:=0; {$ELSE} CBDither.ItemIndex:=Ord(GIFImageDefaultDitherMode); CBReduction.ItemIndex:=Ord(rmNone); {$ENDIF} //RGCompression.ItemIndex:=Ord(GIFImageDefaultCompression); //MM Pending Unisys decision, see above. //RGCompression.ItemIndex:=1; // 6.02 end; Procedure TTeeGIFOptions.RGCompressionClick(Sender: TObject); begin // {$IFNDEF TEEGIFCOMPRESSION} // RGCompression.ItemIndex:=1; { 5.02 } Removed in 6.02 // {$ENDIF} end; procedure TTeeGIFOptions.FormCreate(Sender: TObject); begin Align:=alClient; end; initialization RegisterTeeExportFormat(TGIFExportFormat); finalization UnRegisterTeeExportFormat(TGIFExportFormat); end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls; type { TForm1 } TForm1 = class(TForm) Button1: TButton; Memo1: TMemo; procedure Button1Click(Sender: TObject); private { private declarations } public { public declarations } end; var Form1: TForm1; implementation {$R *.lfm} const size = 10; type pole =array[1..size] of integer; var i :integer; function fillArrayAndReturn(var p:pole; rand:integer):pole; begin Randomize; for i:= 1 to size do begin p[i]:= random(rand) + 1; end; Result:=p; end; function returnMinMaxInArray(p:pole):string; var min, max, indexMin, indexMax :integer; begin min :=p[1]; max :=p[1]; indexMin:= 1; indexMax:= 1; for i:=1 to size do begin if (min > p[i]) then begin min :=p[i]; indexMin:=i; end; if (max < p[i]) then begin max :=p[i]; indexMax:=i; end; end; Result:= 'max: ' + IntToStr(max) + ' indexMax: ' +IntToStr(indexMax) + ' min: ' +IntToStr(min) + ' indexMin: ' +IntToStr(indexMin); end; procedure memoizuj(str:string); begin Form1.Memo1.Lines.Add(str); end; procedure writeArray(var p:pole); var all:string; begin for i:= 0 to size do begin all += IntToStr(p[i]) + ', '; end; memoizuj(all); end; { TForm1 } procedure TForm1.Button1Click(Sender: TObject); var ar :pole; rand:integer; begin rand:= 50; memoizuj(returnMinMaxInArray(fillArrayAndReturn(ar, rand))); writeArray(ar); end; end.
{ ID:asiapea1 PROG:fence8 LANG:PASCAL } program fence8; const maxn=50; maxr=1023; var a:array[0..maxn+1] of longint; b,sum:array[0..maxr+1] of longint; n,i,r,ans,tot,waste:longint; procedure opf; begin assign(input,'fence8.in'); reset(input); assign(output,'fence8.out'); rewrite(output); end; procedure clf; begin close(input); close(output); end; function qpass(s,t:integer; var x:array of longint):integer; var i,j,r:integer; begin i:=s; j:=t; r:=x[s]; while i<j do begin while (i<j) and (x[j]>=r) do dec(j); x[i]:=x[j]; while (i<j) and (x[i]<=r) do inc(i); x[j]:=x[i]; end; x[i]:=r; qpass:=i; end; procedure qsort(s,t:integer; var x:array of longint); var k,r:longint; begin if s<t then begin k:=random(t-s)+s; r:=x[s]; x[s]:=x[k]; x[k]:=r; k:=qpass(s,t,x); qsort(s,k-1,x); qsort(k+1,t,x); end; end; procedure init; begin randomize; tot:=0; readln(n); for i:=1 to n do begin readln(a[i]); inc(tot,a[i]); end; readln(r); sum[0]:=0; for i:=1 to r do readln(b[i]); qsort(1,n,a); qsort(1,r,b); for i:=1 to r do sum[i]:=sum[i-1]+b[i]; end; function can(x:integer):boolean; var p:array[0..maxn+1] of longint; function dfs(now,lp,x:integer):boolean; var i,j:integer; change:boolean; begin if now=0 then exit(true); if waste+sum[x]>tot then exit(false); if (now<>x) and (b[now]=b[now+1]) then j:=lp else j:=1; for i:=j to n do if p[i]>=b[now] then begin dec(p[i],b[now]); change:=false; if p[i]<b[1] then begin change:=true; inc(waste,p[i]); end; if dfs(now-1,i,x) then exit(true); if change then dec(waste,p[i]); inc(p[i],b[now]); end; exit(false); end; begin waste:=0; p:=a; if dfs(x,0,x) then exit(true) else exit(false); end; procedure main; var s,t,m:integer; begin s:=1; t:=r; ans:=0; while s<=t do begin m:=(s+t+1) div 2; if can(m) then begin ans:=m; s:=m+1; end else t:=m-1; end; end; procedure outit; begin writeln(ans); end; begin opf; init; main; outit; clf; end.
unit TestLocalTypes; { AFS 9 March 2K test local types This code compiles, but is not semantically meaningfull. It is test cases for the code-formating utility procedure-local types are an obscure piece of legacy syntax that I would not reccomend to anyone } interface implementation uses Dialogs; procedure Fred; type TFred = integer; const FRED = 'hello wold'; var li: TFred; begin ShowMessage ('Fred was here'); end; procedure Jim; type TGoon = (NedSeagoon, Eccles, Bluebottle, HenryCrun, Bloodnok); TGoons = set of TGoon; pTGoon = ^TGoon; pGoonProc = function: TGoon of object; const Protagonist: TGoon = NedSeagoon; begin ShowMessage ('Allo Jiim'); end; procedure ClasslessSociety; type //TThing = class; { this does not compile - it gives "error 62. Local class or object types not allowed The solution is to move out the declaration of the class or object type to the global scope." Thanks for *some* sanity. One could apply that comment to all procedure-local types } Tbub = Boolean; TFredsNumbers = 42..122; var liWhatFredHas: TFredsNumbers; begin end; procedure HasRecords; type TFoo = record liBar: integer; liBaz: string; end; TFoo2 = record Bar: integer; case Spon: Boolean of True: (Baz: pChar); False: (Fred: integer); end; begin end; end.
unit xProtocolPacksDl645; interface uses System.Types, xProtocolPacks, System.Classes, system.SysUtils, xDL645Type, xFunction, xMeterDataRect; type /// <summary> /// 数据包发送事件 TDL645_DATA /// </summary> TGet645Data = procedure( A645data : TStringList ) of object; type /// <summary> /// DL645命令包 /// </summary> TDL645_DATA = class private FOrderType: Integer; FDataSign: Int64; FDataFormat: string; FDataReply: string; FDataSend: string; FDataLen: Integer; FAddress: string; FDateTimeValue: TDateTime; FBlockNum: Integer; FDataPackSN: Integer; FRePlyError: TDL645_07_ERR; FFreezeType: TDL645_07_FREEZE_TYPE; FClearEventTYPE: TDL645_07_CLEAREVENT_TYPE; FMeterDataGroupName: string; FBytesDataValue: TBytes; FDataNote: string; FMeterProtocolType : TDL645_PROTOCOL_TYPE; FReadLoadRecord: Integer; // function GetBytesDataValue: TBytes; procedure SetBytesDataValue(const Value: TBytes); procedure SetMeterDataGroupName(const Value: string); procedure SetMeterProtocolType(const Value: TDL645_PROTOCOL_TYPE); public constructor Create; procedure Assign(Source: TObject); procedure AssignMeterItem(Source: TObject); /// <summary> /// 命令类型 /// </summary> property OrderType : Integer read FOrderType write FOrderType; /// <summary> /// 通信地址 /// </summary> property Address : string read FAddress write FAddress; /// <summary> /// 数据标识 /// </summary> property DataSign : Int64 read FDataSign write FDataSign; /// <summary> /// 块数 /// </summary> property BlockNum : Integer read FBlockNum write FBlockNum; /// <summary> /// 时间(冻结时间,负荷记录块时间) /// </summary> property DateTimeValue : TDateTime read FDateTimeValue write FDateTimeValue; /// <summary> /// 读取负荷记录 (0 非读取负荷记录,1读取负荷记录块数,2读取给定时间的负荷记录块) /// </summary> property ReadLoadRecord: Integer read FReadLoadRecord write FReadLoadRecord; /// <summary> /// 冻结类型 /// </summary> property FreezeType : TDL645_07_FREEZE_TYPE read FFreezeType write FFreezeType; /// <summary> /// 后续帧序号 /// </summary> property DataPackSN : Integer read FDataPackSN write FDataPackSN; /// <summary> /// 数据格式 /// </summary> property DataFormat : string read FDataFormat write FDataFormat; /// <summary> /// 数据长度 /// </summary> property DataLen : Integer read FDataLen write FDataLen; /// <summary> /// 数据描述 /// </summary> property DataNote : string read FDataNote write FDataNote; /// <summary> /// 发送的数据(通讯地址、通讯速率,密码权限,多功能口输出类型) /// </summary> property DataSend : string read FDataSend write FDataSend; /// <summary> /// 数据包格式的值 /// </summary> property BytesDataValue : TBytes read FBytesDataValue write SetBytesDataValue; /// <summary> /// 接收到的数据(通讯地址、各种表格) /// </summary> property DataReply : string read FDataReply write FDataReply; /// <summary> /// 清除事件类型 /// </summary> property ClearEventTYPE : TDL645_07_CLEAREVENT_TYPE read FClearEventTYPE write FClearEventTYPE; /// <summary> /// 返回错误 /// </summary> property RePlyError : TDL645_07_ERR read FRePlyError write FRePlyError; /// <summary> /// 表组名称 /// </summary> property MeterDataGroupName:string read FMeterDataGroupName write SetMeterDataGroupName; /// <summary> /// 协议类型 /// </summary> property MeterProtocolType : TDL645_PROTOCOL_TYPE read FMeterProtocolType write SetMeterProtocolType; end; type TProtocolPacksDl645 = class(TProtocolPacks) private FAddrWildcard: Byte; FUserCode: Integer; FIsUseWildcard: Boolean; FUnifyAddSign: Byte; FLongPWD: Integer; FAddrFillSign: Byte; FOnRev645Data: TGet645Data; function GetPWDLevel: Byte; function GetShortPWD: Integer; procedure SetPWDLevel(const Value: Byte); procedure SetShortPWD(const Value: Integer); protected FDevice : TDL645_DATA; // 电表数据项 FRevList : TStringList; FRev645Data : TBytes; // 接收临时数据包 FIsStartRev : Boolean; // 是否开始接收 nLength : Integer; // 数据包的数据长度 /// <summary> /// 获取波特率标识 /// </summary> function GetBaudRateCode( sBaudRate : string ) : Integer; virtual; abstract; /// <summary> /// 获取发送命令包长度 /// </summary> function GetSendCodeLen : Integer; virtual; /// <summary> /// 获取地址 /// </summary> function GetAddrCode(ADL645Data : TDL645_DATA) : TBytes; virtual; /// <summary> /// 获取控制码 /// </summary> function GetControlCode(ADL645Data : TDL645_DATA) : Integer; virtual;abstract; /// <summary> /// 获取标识 /// </summary> function GetSignCode( nDataSign : Int64) : TBytes; virtual;abstract; /// <summary> /// 提取电表返回数据包中的数据 /// </summary> procedure GetRvdPackData; /// <summary> /// 处理接收数据包 /// </summary> procedure ProcRvdData(RvdPack : TBytes); virtual; /// <summary> /// 解析接收到的数据包 /// </summary> procedure ParseRevPack( APack : TBytes ); virtual; /// <summary> /// 生成数据包 /// </summary> procedure CreatePacks(var aDatas: TBytes; nCmdType: Integer; ADevice: TObject);override; public constructor Create; override; destructor Destroy; override; /// <summary> /// 解析接收的数据包 /// </summary> function RevPacks(nCmdType: Integer; ADevice: TObject; APack: TBytes): Integer;override; /// <summary> /// 接收数据事件 /// </summary> property OnRev645Data : TGet645Data read FOnRev645Data write FOnRev645Data; public /// <summary> /// 地址填充字符($00,$99,$AA) /// </summary> property AddrFillSign : Byte read FAddrFillSign write FAddrFillSign; /// <summary> /// 通配符($AA) /// </summary> property AddrWildcard : Byte read FAddrWildcard write FAddrWildcard; /// <summary> /// 广播地址标识 $99,$AA) /// </summary> property UnifyAddSign : Byte read FUnifyAddSign write FUnifyAddSign; /// <summary> /// 长密码(包括权限和密码) /// </summary> property LongPWD : Integer read FLongPWD write FLongPWD; /// <summary> /// 短密码 /// </summary> property ShortPWD : Integer read GetShortPWD write SetShortPWD; /// <summary> /// 权限 /// </summary> property PWDLevel : Byte read GetPWDLevel write SetPWDLevel; /// <summary> /// 操作者代码 /// </summary> property UserCode : Integer read FUserCode write FUserCode; /// <summary> /// 是否用通配符 true 用通配符 地址为AA或99 /// </summary> property IsUseWildcard : Boolean read FIsUseWildcard write FIsUseWildcard; end; implementation { TProtocolPacksDl645 } constructor TProtocolPacksDl645.Create; begin inherited; FRevList := TStringList.Create; FIsUseWildcard := False; FIsStartRev := False; FAddrFillSign := $00; FAddrWildcard := $AA; FUnifyAddSign := $99; FLongPWD := $02000000; FUserCode := $12345678; end; procedure TProtocolPacksDl645.CreatePacks(var aDatas: TBytes; nCmdType: Integer; ADevice: TObject); var nLen : Integer; ABytes : TBytes; i: Integer; ADL645Data : TDL645_DATA; begin if not Assigned(ADevice) then Exit; SetLength(FRev645Data, 0); if ADevice is TDL645_DATA then begin FDevice := TDL645_DATA(ADevice); ADL645Data := TDL645_DATA(ADevice); case ADL645Data.OrderType of C_645_RESET_TIME: aDatas := CreatePackRsetTime; C_645_READ_DATA: aDatas := CreatePackReadData; C_645_READ_NEXTDATA: aDatas := CreatePackReadNextData; C_645_READ_ADDR: aDatas := CreatePackReadAddr; C_645_WRITE_DATA: aDatas := CreatePackWriteData; C_645_WRITE_ADDR: aDatas := CreatePackWriteAddr; C_645_FREEZE: aDatas := CreatePackFreeze; C_645_CHANGE_BAUD_RATE: aDatas := CreatePackChangeBaudRate; C_645_CHANGE_PWD: aDatas := CreatePackChangePWD; C_645_CLEAR_MAX_DEMAND: aDatas := CreatePackClearMaxDemand; C_645_CLEAR_RDATA: aDatas := CreatePackClearData; C_645_CLEAR_REVENT: aDatas := CreatePackClearEvent; C_SET_WOUT_TYPE: aDatas := CreatePackSetWOutType; C_645_IDENTITY: aDatas := CreatePackIdentity; C_645_ONOFF_CONTROL: aDatas := CreatePackOnOffControl; else aDatas := nil; end; if aDatas <> nil then begin nLen := High( aDatas ); // 包头$68 aDatas[0] := $68; // 地址 ABytes := GetAddrCode(ADL645Data); for i := 0 to Length(ABytes) - 1 do aDatas[i + 1] := ABytes[i]; // 包头$68 aDatas[7] := $68; // 控制码 aDatas[8] := GetControlCode(ADL645Data); // 长度 aDatas[9] := Length(aDatas) - 12; // 校验码 aDatas[ nLen - 1 ] := CalCS( aDatas, 0, nLen - 2 ); // 包尾 $16 aDatas[ nLen ] := $16; SetLength(aDatas, Length(aDatas) + 4); for i := Length(aDatas) - 1 downto 4 do begin aDatas[i] := aDatas[i-4]; end; aDatas[0] := $FE; aDatas[1] := $FE; aDatas[2] := $FE; aDatas[3] := $FE; end; end; end; destructor TProtocolPacksDl645.Destroy; begin ClearStringList(FRevList); FRevList.Free; inherited; end; function TProtocolPacksDl645.GetAddrCode(ADL645Data : TDL645_DATA): TBytes; var i: Integer; begin SetLength(Result, 6); case ADL645Data.OrderType of C_645_RESET_TIME: begin for i := 0 to Length(Result) - 1 do Result[i] := UnifyAddSign; end; C_645_READ_ADDR, C_645_WRITE_ADDR: begin if ADL645Data.FMeterProtocolType = dl645pt2007 then begin for i := 0 to Length(Result) - 1 do Result[i] := AddrWildcard; end else begin for i := 0 to Length(Result) - 1 do Result[i] := UnifyAddSign; end; end; else begin if FIsUseWildcard then begin if ADL645Data.MeterProtocolType = dl645pt2007 then begin for i := 0 to Length(Result) - 1 do Result[i] := AddrWildcard; end else begin for i := 0 to Length(Result) - 1 do Result[i] := UnifyAddSign; end; end else begin for i := 0 to Length(Result) - 1 do begin if Length(ADL645Data.Address) >= i * 2 + 2 then begin Result[5-i] := StrToInt('$' + Copy(ADL645Data.Address,i*2+1, 2)); end else begin Result[5-i] := $00; end; end; end; end; end; end; function TProtocolPacksDl645.GetPWDLevel: Byte; begin Result := FLongPWD shr 24; end; procedure TProtocolPacksDl645.GetRvdPackData; procedure ChangeStrSize( var s : string; nLen : Integer ); var i : Integer; begin if Length( s ) < nLen then begin for i := 1 to nLen - Length( s ) do s := s + '0'; end else if Length( s ) > nLen then begin // 多个时段信息 时 下面错误 s := Copy( s, 1, nLen ); end; end; var i: Integer; sDataReplay : string; sDataReplayFinal : string; nFormatLen , nFormatCount, nRvdDataLen: Integer; j: Integer; bFu : Boolean; begin sDataReplay := ''; sDataReplayFinal := ''; bFu := False; with FDevice do begin if (FOrderType = C_645_READ_DATA) or (FOrderType = C_645_READ_NEXTDATA) then begin if Length(FBytesDataValue) > 0 then begin nRvdDataLen := Length(FBytesDataValue); if Length( FDataFormat ) = 0 then nFormatLen := FDataLen else nFormatLen := Round(Length( FDataFormat )/2); nFormatCount := Round(nRvdDataLen/ nFormatLen ); for i := 0 to nRvdDataLen - 1 do begin if (i = nRvdDataLen -1)and (BytesDataValue[i] and $80 = $80) then begin bFu := True; sDataReplay := IntToHex(BytesDataValue[i]-$80, 2) + sDataReplay; end else begin sDataReplay := IntToHex(BytesDataValue[i], 2) + sDataReplay; end; end; if nFormatLen <> 0 then begin for j := 0 to nFormatCount -1 do begin sDataReplayFinal := Copy(sDataReplay, j * nFormatLen * 2 +1, nFormatLen * 2) + sDataReplayFinal end; end; ChangeStrSize(sDataReplayFinal,DataLen * 2); FDataReply := VerifiedStr(sDataReplayFinal, FDataFormat,DataLen); if bFu then FDataReply := '-'+FDataReply; end; end; end; end; function TProtocolPacksDl645.GetSendCodeLen: Integer; begin case FDevice.OrderType of C_645_RESET_TIME: Result := 18; C_645_READ_NEXTDATA: Result := 14; C_645_READ_ADDR: Result := 14; C_645_WRITE_DATA: Result := 14 + FDevice.DataLen; C_645_WRITE_ADDR: Result := 18; C_645_CHANGE_BAUD_RATE: Result := 13; C_645_CHANGE_PWD: Result := 20; C_645_CLEAR_MAX_DEMAND: Result := 12; else Result := 14; end; end; function TProtocolPacksDl645.GetShortPWD: Integer; begin Result := FLongPWD and $00FFFFFF; end; procedure TProtocolPacksDl645.ParseRevPack(APack: TBytes); begin end; procedure TProtocolPacksDl645.ProcRvdData(RvdPack: TBytes); begin // 检查停止位 if RvdPack[ High( RvdPack ) ] <> $16 then begin // FReplySate := C_REPLY_PACK_ERROR; Exit; end; // 检查校验码 if CalCS( RvdPack, 0, High( RvdPack ) - 2 ) <> RvdPack[ High( RvdPack ) - 1 ] then begin // FReplySate := C_REPLY_PACK_ERROR; Exit; end; // 解析数据包 ParseRevPack(RvdPack); // FReplySate := C_REPLY_CORRECT; end; function TProtocolPacksDl645.RevPacks(nCmdType: Integer; ADevice: TObject; APack: TBytes): Integer; procedure AddRevData( nByte : Byte ); begin if Length(FRev645Data) = 9 then nLength := nByte; SetLength(FRev645Data, Length(FRev645Data) + 1); FRev645Data[Length(FRev645Data)-1] := nByte; end; var i: Integer; nValue : Byte; begin Result := 0; // 68 01 00 00 00 00 00 68 81 06 43 C3 A8 99 33 33 05 16 for i := 0 to Length(APack) - 1 do begin nValue := APack[i]; if nValue = $68 then begin if (Length(FRev645Data)>6)and(FRev645Data[Length(FRev645Data)-7]=$68) and (nLength = 0)then begin nLength := 0; AddRevData(nValue); end else begin if not FIsStartRev then begin AddRevData(nValue); end else begin SetLength(FRev645Data, 0); AddRevData(nValue); FIsStartRev := false; end; end; end else if (nValue = $16) then begin if (Length(FRev645Data)=nLength+11) then begin AddRevData(nValue); ProcRvdData(FRev645Data); FIsStartRev := true; SetLength(FRev645Data, 0); end else begin AddRevData(nValue); end; end else begin if (nValue = $FE) and (Length(FRev645Data) = 0) then begin Continue; end else begin AddRevData(nValue); end; end; end; end; procedure TProtocolPacksDl645.SetPWDLevel(const Value: Byte); begin FLongPWD := (FLongPWD and $00FFFFFF) + (Value shl 24); end; procedure TProtocolPacksDl645.SetShortPWD(const Value: Integer); var nValue : Integer; begin nValue := FLongPWD and $FF000000; FLongPWD := nValue + (Value and $00FFFFFF); end; procedure TDL645_DATA.Assign(Source: TObject); begin Assert( Source is TDL645_DATA ); FOrderType := TDL645_DATA( Source ).OrderType; FDataSign := TDL645_DATA( Source ).DataSign; FDataFormat := TDL645_DATA( Source ).DataFormat; FDataReply := TDL645_DATA( Source ).DataReply; FDataSend := TDL645_DATA( Source ).DataSend; FDataLen := TDL645_DATA( Source ).DataLen; FAddress := TDL645_DATA( Source ).Address; FRePlyError := TDL645_DATA( Source ).RePlyError; FDateTimeValue:= TDL645_DATA( Source ).DateTimeValue; FDataPackSN:= TDL645_DATA( Source ).DataPackSN; FBlockNum := TDL645_DATA( Source ).BlockNum; FMeterDataGroupName:= TDL645_DATA(Source).MeterDataGroupName; FBytesDataValue := TDL645_DATA( Source ).BytesDataValue; FMeterProtocolType := TDL645_DATA( Source ).MeterProtocolType; FClearEventTYPE := TDL645_DATA( Source ).ClearEventTYPE; FFreezeType:= TDL645_DATA(Source).FreezeType; FReadLoadRecord:= TDL645_DATA(Source).ReadLoadRecord; end; procedure TDL645_DATA.AssignMeterItem(Source: TObject); begin Assert( Source is TMeterDataItem ); // FOrderType := TMeterDataItem( Source ).OrderType; FDataSign := TMeterDataItem( Source ).Sign; FDataFormat := TMeterDataItem( Source ).Format; // FDataReply := TMeterDataItem( Source ).DataReply; FDataSend := TMeterDataItem( Source ).Value; FDataLen := TMeterDataItem( Source ).Length; // FAddress := TMeterDataItem( Source ).Address; // FDateTimeValue:= TMeterDataItem( Source ).DateTimeValue; // FBlockNum := TMeterDataItem( Source ).BlockNum; end; constructor TDL645_DATA.Create; begin inherited; FOrderType := 0; FDataSign := 0; FDataFormat := ''; FDataReply := ''; FDataSend := ''; FDataLen := 0; FAddress := ''; FDateTimeValue:= 0; FBlockNum := 0; FMeterDataGroupName:= ''; FReadLoadRecord := 0; FMeterProtocolType := dl645pt2007; end; procedure TDL645_DATA.SetBytesDataValue(const Value: TBytes); begin // 数据 FBytesDataValue := Value; // FDataReply := FixDataForShow(Value,FDataFormat, FDataLen); end; procedure TDL645_DATA.SetMeterDataGroupName(const Value: string); begin FMeterDataGroupName := Value; end; procedure TDL645_DATA.SetMeterProtocolType(const Value: TDL645_PROTOCOL_TYPE); begin FMeterProtocolType := Value; end; end.
(** This module contains a class which represents a form for editing the lists of external applications which need to be run before and after the compilation of the currently active project. @Version 1.0 @Author David Hoyle @Date 05 Jan 2018 **) Unit ITHelper.ConfigurationForm; Interface Uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ComCtrls, ToolsAPI, ImgList, ExtCtrls, System.ImageList, ITHelper.ExternalProcessInfo, ITHelper.Interfaces; Type (** An enumerate to define which set of data the dialogue is to work with. **) TITHDlgType = (dtBefore, dtAfter); (** A class to represent the editing interface. **) TfrmITHConfigureDlg = Class(TForm) lblCompile: TLabel; btnAdd: TBitBtn; btnEdit: TBitBtn; btnDelete: TBitBtn; btnOK: TBitBtn; btnCancel: TBitBtn; lvCompile: TListView; btnUp: TBitBtn; btnDown: TBitBtn; ilStatus: TImageList; btnCopy: TBitBtn; chkWarn: TCheckBox; btnHelp: TBitBtn; Procedure btnAddClick(Sender: TObject); Procedure lvResize(Sender: TObject); Procedure btnDeleteClick(Sender: TObject); Procedure btnEditClick(Sender: TObject); Procedure btnUpClick(Sender: TObject); Procedure btnDownClick(Sender: TObject); Procedure lvCompileDblClick(Sender: TObject); Procedure lvFileListCustomDrawItem(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; Var DefaultDraw: Boolean); Procedure btnCopyClick(Sender: TObject); Procedure lvCompileSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure btnHelpClick(Sender: TObject); Strict Private { Private declarations } FGlobalOps: IITHGlobalOptions; FProject : IOTAProject; FDlgType : TITHDlgType; Strict Protected Procedure SwapItems(Const Item1, Item2: TListItem); Procedure AddListItem(Const Item: TListItem; Const Process: TITHProcessInfo); Procedure AddProcesses(Const Processes: TITHProcessCollection; Const strSection: String; Const ListView: TListView; Const Project: IOTAProject); Procedure SaveProcesses(Const Processes: TITHProcessCollection; Const ListView: TListView; Const strSection: String; Const Project: IOTAProject); Procedure InitialiseOptions(Const Project: IOTAProject); Procedure SaveOptions(Const Project: IOTAProject); Public { Public declarations } Class Function Execute(Const Project: IOTAProject; Const GlobalOps: IITHGlobalOptions; Const DlgType : TITHDlgType): Boolean; End; Implementation {$R *.dfm} Uses IniFiles, FileCtrl, ITHelper.ProgrammeInfoForm, ITHelper.TestingHelperUtils; Type (** An enumerate to define the columns of the dialogue listview. @nohints **) TITHColumn = (coTitle, coEXE, coParams, coDir); (** A record helper for the above enumerate to translate the enumerate to a subimte or column reference index. @nohints **) TITHColumnHelper = Record Helper For TITHColumn Function ColumnIndex : Integer; Function SubItemIndex : Integer; End; Const (** A constant array of string representing the data type the dialogue is to work with. **) DlgTypes : Array[Low(TITHDlgType)..High(TITHDlgType)] of String = ('Before', 'After'); (** An INI Section Suffix for the dialogue settings. **) strDlg = ' Dlg'; (** An INI Key name for the top position of the dialogue. **) strTopKey = 'Top'; (** An INI Key name for the left position of the dialogue. **) strLeftKey = 'Left'; (** An INI Key name for the height of the dialogue. **) strHeightKey = 'Height'; (** An INI Key name for the width of the dialogue. **) strWidthKey = 'Width'; { TITHColumnHelper } (** This method returns the enumerate as a column index. @precon None. @postcon Returns the enumerate as a column index. @return an Integer **) Function TITHColumnHelper.ColumnIndex: Integer; Begin Result := Ord(Self); End; (** This method returns the enumerate as a subitem index. @precon None. @postcon Returns the enumerate as a subitem index. @return an Integer **) Function TITHColumnHelper.SubItemIndex: Integer; Begin Result := Pred(Ord(Self)); End; (** This procedure configures the item in the list view. @precon Item must be a valid. @postcon Configures the item in the list view. @param Item as a TListItem as a constant @param Process as a TITHProcessInfo as a constant **) Procedure TfrmITHConfigureDlg.AddListItem(Const Item: TListItem; Const Process: TITHProcessInfo); Begin Item.Checked := Process.FEnabled; Item.Caption := Process.FTitle; Item.SubItems.Add(Process.FEXE); Item.SubItems.Add(Process.FParams); Item.SubItems.Add(Process.FDir); End; (** This procedure adds processes to the passed list view. @precon Processes and ListView must be valid instances. @postcon Adds processes to the passed list view. @param Processes as a TITHProcessCollection as a constant @param strSection as a String as a constant @param ListView as a TListView as a constant @param Project as an IOTAProject as a constant **) Procedure TfrmITHConfigureDlg.AddProcesses(Const Processes: TITHProcessCollection; Const strSection: String; Const ListView: TListView; Const Project: IOTAProject); Var i : Integer; Item : TListItem; ProjectOps: IITHProjectOptions; Begin ProjectOps := FGlobalOps.ProjectOptions(Project); Try Processes.LoadFromINI(ProjectOps.INIFile, strSection); For i := 0 To Processes.Count - 1 Do Begin Item := ListView.Items.Add; AddListItem(Item, Processes[i]); End; Finally ProjectOps := Nil; End; End; (** This is an on click event handler for the Add Before button. @precon None. @postcon Adds an external programme to the Before Compile list view. @param Sender as a TObject **) Procedure TfrmITHConfigureDlg.btnAddClick(Sender: TObject); Var strTitle, strProgramme, strParameters, strWorkingDirectory: String; Item: TListItem; Begin If TfrmITHProgrammeInfo.Execute(strTitle, strProgramme, strParameters, strWorkingDirectory, FGlobalOps.INIFileName) Then Begin Item := lvCompile.Items.Add; Item.Caption := strTitle; Item.SubItems.Add(strProgramme); Item.SubItems.Add(strParameters); Item.SubItems.Add(strWorkingDirectory); Item.Checked := True; End; End; (** This is an on click event handler for the Copy Before button. @precon None. @postcon Copies to selected item to a new entry. @param Sender as a TObject **) Procedure TfrmITHConfigureDlg.btnCopyClick(Sender: TObject); Var iIndex: Integer; Item : TListItem; P : TITHProcessInfo; Begin iIndex := lvCompile.ItemIndex; If iIndex > -1 Then Begin Item := lvCompile.Items[iIndex]; P.FTitle := Item.Caption; P.FEXE := Item.SubItems[coEXE.SubItemIndex]; P.FParams := Item.SubItems[coParams.SubItemIndex]; P.FDir := Item.SubItems[coDir.SubItemIndex]; P.FEnabled := Item.Checked; Item := lvCompile.Items.Add; Item.Caption := P.FTitle; Item.SubItems.Add(P.FEXE); Item.SubItems.Add(P.FParams); Item.SubItems.Add(P.FDir); Item.Checked := P.FEnabled; End; End; (** This is an on click event handler for the Delete Before button. @precon None. @postcon Deletes the selected item from the Before Compile List View. @param Sender as a TObject **) Procedure TfrmITHConfigureDlg.btnDeleteClick(Sender: TObject); Var iIndex: Integer; Begin iIndex := lvCompile.ItemIndex; If iIndex > -1 Then lvCompile.Items.Delete(iIndex); End; (** This is an on click event handler for the Down Before button. @precon None. @postcon Moves the selected item down the Before Compile list view. @param Sender as a TObject **) Procedure TfrmITHConfigureDlg.btnDownClick(Sender: TObject); Var iIndex: Integer; Begin iIndex := lvCompile.ItemIndex; If (iIndex > -1) And (iIndex < lvCompile.Items.Count - 1) Then Begin SwapItems(lvCompile.Items[iIndex], lvCompile.Items[iIndex + 1]); lvCompile.ItemIndex := iIndex + 1; End; End; (** This is an on click event handler for the Edit Before button. @precon None. @postcon Allows the user to edit the selected Before Compile List View Item. @param Sender as a TObject **) Procedure TfrmITHConfigureDlg.btnEditClick(Sender: TObject); Var iIndex: Integer; strTitle, strProgramme, strParameters, strWorkingDirectory: String; Item : TListItem; Begin iIndex := lvCompile.ItemIndex; If iIndex > -1 Then Begin Item := lvCompile.Items[iIndex]; strTitle := Item.Caption; strProgramme := Item.SubItems[coEXE.SubItemIndex]; strParameters := Item.SubItems[coParams.SubItemIndex]; strWorkingDirectory := Item.SubItems[coDir.SubItemIndex]; If TfrmITHProgrammeInfo.Execute(strTitle, strProgramme, strParameters, strWorkingDirectory, FGlobalOps.INIFileName) Then Begin Item.Caption := strTitle; Item.SubItems[coEXE.SubItemIndex] := strProgramme; Item.SubItems[coParams.SubItemIndex] := strParameters; Item.SubItems[coDir.SubItemIndex] := strWorkingDirectory; End; End; End; (** This is an on click event handler for the Help button. @precon None. @postcon Display the Compilation Tools help page. @param Sender as a TObject **) Procedure TfrmITHConfigureDlg.btnHelpClick(Sender: TObject); Const strCompilationTools = 'CompilationTools'; Begin HTMLHelp(0, PChar(ITHHTMLHelpFile(strCompilationTools)), HH_DISPLAY_TOPIC, 0); End; (** This is an on click event handler for the Up Before button. @precon None. @postcon Moves the selected item up the Before Compile List View. @param Sender as a TObject **) Procedure TfrmITHConfigureDlg.btnUpClick(Sender: TObject); Var iIndex: Integer; Begin iIndex := lvCompile.ItemIndex; If iIndex > 0 Then Begin SwapItems(lvCompile.Items[iIndex], lvCompile.Items[iIndex - 1]); lvCompile.ItemIndex := iIndex - 1; End; End; (** This is the classes main interface method for invoking the dialogue. @precon None. @postcon The classes main interface method for invoking the dialogue. @param Project as an IOTAProject as a constant @param GlobalOps as an IITHGlobalOptions as a constant @param DlgType as a TITHDlgType as a constant @return a Boolean **) Class Function TfrmITHConfigureDlg.Execute(Const Project: IOTAProject; Const GlobalOps: IITHGlobalOptions; Const DlgType : TITHDlgType): Boolean; Const strSection : Array[Low(TITHDlgType)..High(TITHDlgType)] Of String = ( 'Pre-Compilation', 'Post-Compilation'); ResourceString strProgrammesToExecuteCompilation = 'Programmes to execute %s compilation: %s'; Var Processes: TITHProcessCollection; frm: TfrmITHConfigureDlg; Begin Result := False; frm := TfrmITHConfigureDlg.Create(Nil); Try frm.FProject := Project; frm.FGlobalOps := GlobalOps; frm.FDlgType := DlgType; frm.Caption := Format(strProgrammesToExecuteCompilation, [DlgTypes[DlgType], GetProjectName(Project)]); frm.lblCompile.Caption := Format(frm.lblCompile.Caption, [DlgTypes[DlgType]]); frm.chkWarn.Caption := Format(frm.chkWarn.Caption, [DlgTypes[DlgType]]); frm.InitialiseOptions(Project); Processes := TITHProcessCollection.Create; Try frm.AddProcesses(Processes, strSection[DlgType], frm.lvCompile, Project); Finally Processes.Free; End; frm.lvCompileSelectItem(Nil, Nil, False); If frm.ShowModal = mrOK Then Begin frm.SaveOptions(Project); Processes := TITHProcessCollection.Create; Try frm.SaveProcesses(Processes, frm.lvCompile, strSection[DlgType], Project); Finally Processes.Free; End; Result := True; End; Finally frm.Free; End; End; (** This method initialises the project options in the dialogue. @precon None. @postcon Initialises the project options in the dialogue. @param Project as an IOTAProject as a constant **) Procedure TfrmITHConfigureDlg.InitialiseOptions(Const Project: IOTAProject); Var iniFile: TMemIniFile; ProjectOps: IITHProjectOptions; Begin iniFile :=TMemIniFile.Create(FGlobalOps.INIFileName); Try Top := iniFile.ReadInteger(DlgTypes[FDlgType] + strDlg, strTopKey, (Screen.Height - Height) Div 2); Left := iniFile.ReadInteger(DlgTypes[FDlgType] + strDlg, strLeftKey, (Screen.Width - Width) Div 2); Height := iniFile.ReadInteger(DlgTypes[FDlgType] + strDlg, strHeightKey, Height); Width := iniFile.ReadInteger(DlgTypes[FDlgType] + strDlg, strWidthKey, Width); Finally iniFile.Free; End; ProjectOps := FGlobalOps.ProjectOptions(Project); Try If FDlgType = dtBefore Then chkWarn.Checked := ProjectOps.WarnBefore Else chkWarn.Checked := ProjectOps.WarnAfter; Finally ProjectOps := Nil; End; End; (** This is an on double click event handler for the Before Compile List View. @precon None. @postcon Edits the selected item. @param Sender as a TObject **) Procedure TfrmITHConfigureDlg.lvCompileDblClick(Sender: TObject); Begin btnEditClick(Sender); End; (** This method updates the buttons assoviated with the before compile programmes and enables and disables them depending upon the selection of items in the list. @precon None. @postcon Updates the buttons assoviated with the before compile programmes and enables and disables them depending upon the selection of items in the list. @param Sender as a TObject @param Item as a TListItem @param Selected as a Boolean **) Procedure TfrmITHConfigureDlg.lvCompileSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); Begin btnAdd.Enabled := True; btnEdit.Enabled := lvCompile.Selected <> Nil; btnDelete.Enabled := lvCompile.Selected <> Nil; btnUp.Enabled := (lvCompile.Selected <> Nil) And (lvCompile.ItemIndex > 0); btnDown.Enabled := (lvCompile.Selected <> Nil) And (lvCompile.ItemIndex < lvCompile.Items.Count - 1); btnCopy.Enabled := lvCompile.Selected <> Nil; End; (** This is an CustomDrawItem event for the list view. @precon None. @postcon Draw readonly items in the list with a light red background. @param Sender as a TCustomListView @param Item as a TListItem @param State as a TCustomDrawState @param DefaultDraw as a Boolean as a reference **) Procedure TfrmITHConfigureDlg.lvFileListCustomDrawItem(Sender: TCustomListView; Item: TListItem; State: TCustomDrawState; Var DefaultDraw: Boolean); Const iSmallPadding = 2; iLargePadding = 6; Var cstrBuffer : Array[0..MAX_PATH] Of Char; (** This function returns display rectangle for the given indexed sub item. @precon iIndex must be a valid SubItem index.. @postcon Returns display rectangle for the given indexed sub item. @param iIndex as an Integer as a constant @return a TRect **) Function GetSubItemRect(Const iIndex: Integer): TRect; Var j: Integer; Begin Result := Item.DisplayRect(drBounds); For j := 0 To iIndex Do Begin Inc(Result.Left, Sender.Column[j].Width); Result.Right := Result.Left + Sender.Column[j + 1].Width; End; Inc(Result.Top, iSmallPadding); Inc(Result.Bottom, iSmallPadding); Inc(Result.Left, iLargePadding); Dec(Result.Right, iLargePadding); End; (** This method draws the sub items in the listview. @precon None. @postcon The subitem is drawn in the listview. **) Procedure DrawSubItems; Var i : Integer; R: TRect; Ops : Integer; Begin For i := Pred(Integer(coEXE)) To Pred(Integer(coDir)) Do Begin Case i Of Pred(Integer(coEXE)), Pred(Integer(coDir)): Ops := DT_LEFT Or DT_MODIFYSTRING Or DT_PATH_ELLIPSIS Or DT_NOPREFIX; Pred(Integer(coParams)): Ops := DT_LEFT Or DT_MODIFYSTRING Or DT_END_ELLIPSIS Or DT_NOPREFIX; Else Ops := DT_LEFT; End; R := GetSubItemRect(i); Sender.Canvas.Brush.Color := clWindow; If Item.Selected Then Sender.Canvas.Brush.Color := clHighlight; Sender.Canvas.Refresh; StrPCopy(cstrBuffer, Item.SubItems[i]); DrawText(Sender.Canvas.Handle, cstrBuffer, Length(Item.SubItems[i]), R, Ops); R.Left := R.Right; End; End; Var R, ItemR: TRect; Ops : Integer; Begin DefaultDraw := False; // Set Left Background Sender.Canvas.Brush.Color := clWindow; If Item.Selected Then Begin Sender.Canvas.Brush.Color := clHighlight; Sender.Canvas.Font.Color := clHighlightText; End; ItemR := Item.DisplayRect(drBounds); Sender.Canvas.FillRect(ItemR); // Draw Status Icon R := Item.DisplayRect(drBounds); Sender.Canvas.FillRect(R); ilStatus.Draw(Sender.Canvas, R.Left, R.Top, Integer(Item.Checked), True); // Draw Caption R := Item.DisplayRect(drLabel); Inc(R.Top, iSmallPadding); Inc(R.Bottom, iSmallPadding); Inc(R.Left, iSmallPadding); Dec(R.Right, iSmallPadding); Ops := DT_LEFT Or DT_MODIFYSTRING Or DT_END_ELLIPSIS Or DT_NOPREFIX; StrPCopy(cstrBuffer, Item.Caption); DrawText(Sender.Canvas.Handle, cstrBuffer, Length(Item.Caption), R, Ops); DrawSubItems; End; (** This is an on resize event handler for both list view controls. @precon None. @postcon Ensures the columns of the list views are wide enough to display in the dialogue. @param Sender as a TObject **) Procedure TfrmITHConfigureDlg.lvResize(Sender: TObject); Const dblTitlePctWidth = 0.15; dblEXEPctWidth = 0.35; dblParamsPctWidth = 0.20; dblDirPctWidth = 0.30; Var i: Integer; LV: TListView; Begin LV := Sender As TListView; i := LV.ClientWidth; LV.Columns[coTitle.ColumnIndex].Width := Trunc(i * dblTitlePctWidth); LV.Columns[coExe.ColumnIndex].Width := Trunc(i * dblEXEPctWidth); LV.Columns[coParams.ColumnIndex].Width := Trunc(i * dblParamsPctWidth); LV.Columns[coDir.ColumnIndex].Width := Trunc(i * dblDirPctWidth); End; (** This method saves the project options to the ini file. @precon None. @postcon Saves the project options to the ini file. @param Project as an IOTAProject as a constant **) Procedure TfrmITHConfigureDlg.SaveOptions(Const Project: IOTAProject); Var iniFile: TMemIniFile; ProjectOps: IITHProjectOptions; Begin iniFile := TMemIniFile.Create(FGlobalOps.INIFileName); Try iniFile.WriteInteger(DlgTypes[FDlgType] + strDlg, strTopKey, Top); iniFile.WriteInteger(DlgTypes[FDlgType] + strDlg, strLeftKey, Left); iniFile.WriteInteger(DlgTypes[FDlgType] + strDlg, strHeightKey, Height); iniFile.WriteInteger(DlgTypes[FDlgType] + strDlg, strWidthKey, Width); iniFile.UpdateFile; Finally iniFile.Free; End; ProjectOps := FGlobalOps.ProjectOptions(Project); Try If FDlgType = dtBefore Then ProjectOps.WarnBefore := chkWarn.Checked Else ProjectOps.WarnAfter := chkWarn.Checked; Finally ProjectOps := Nil; End; End; (** This procedure saves the list view items to an INI file. @precon Processes and ListView must be valid instances. @postcon Saves the list view items to an INI file. @param Processes as a TITHProcessCollection as a constant @param ListView as a TListView as a constant @param strSection as a String as a constant @param Project as an IOTAProject as a constant **) Procedure TfrmITHConfigureDlg.SaveProcesses(Const Processes: TITHProcessCollection; Const ListView: TListView; Const strSection: String; Const Project: IOTAProject); Var i: Integer; Begin For i := 0 To ListView.Items.Count - 1 Do Processes.AddProcessInfo( ListView.Items[i].Checked, ListView.Items[i].SubItems[coEXE.SubItemIndex], ListView.Items[i].SubItems[coParams.SubItemIndex], ListView.Items[i].SubItems[coDir.SubItemIndex], ListView.Items[i].Caption); Processes.SaveToINI(FGlobalOps.ProjectOptions(Project).INIFile, strSection); End; (** This method swaps the information in the 2 list view items. @precon None. @postcon Swaps the information in the 2 list view items. @param Item1 as a TListItem as a constant @param Item2 as a TListItem as a constant **) Procedure TfrmITHConfigureDlg.SwapItems(Const Item1, Item2: TListItem); Var strTitle, strEXE, strParam, strDir: String; boolEnabled: Boolean; Begin strTitle := Item1.Caption; strEXE := Item1.SubItems[coEXE.SubItemIndex]; strParam := Item1.SubItems[coParams.SubItemIndex]; strDir := Item1.SubItems[coDir.SubItemIndex]; boolEnabled := Item1.Checked; Item1.Caption := Item2.Caption; Item1.SubItems[coEXE.SubItemIndex] := Item2.SubItems[coEXE.SubItemIndex]; Item1.SubItems[coParams.SubItemIndex] := Item2.SubItems[coParams.SubItemIndex]; Item1.SubItems[coDir.SubItemIndex] := Item2.SubItems[coDir.SubItemIndex]; Item1.Checked := Item2.Checked; Item2.Caption := strTitle; Item2.SubItems[coEXE.SubItemIndex] := strEXE; Item2.SubItems[coParams.SubItemIndex] := strParam; Item2.SubItems[coDir.SubItemIndex] := strDir; Item2.Checked := boolEnabled; End; End.
unit fOrdersDC; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, fBase508Form, fAutoSz, StdCtrls, ORFn, ORCtrls, ExtCtrls, ORNet, VA508AccessibilityManager, rMisc; type TfrmDCOrders = class(TfrmBase508Form) Label1: TLabel; Panel1: TPanel; lstOrders: TCaptionListBox; Panel2: TPanel; lblReason: TLabel; lstReason: TORListBox; cmdOK: TButton; cmdCancel: TButton; procedure FormCreate(Sender: TObject); procedure cmdOKClick(Sender: TObject); procedure cmdCancelClick(Sender: TObject); procedure lstOrdersDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); procedure lstOrdersMeasureItem(Control: TWinControl; Index: Integer; var AHeight: Integer); procedure FormDestroy(Sender: TObject); procedure unMarkedOrignalOrderDC(OrderArr: TStringList); private OKPressed: Boolean; DCReason: Integer; function MeasureColumnHeight(TheOrderText: string; Index: Integer):integer; public OrderIDArr: TStringList; end; function ExecuteDCOrders(SelectedList: TList; var DelEvt: boolean): Boolean; implementation {$R *.DFM} uses rOrders, uCore, uConst, fOrders; function ExecuteDCOrders(SelectedList: TList; var DelEvt: boolean): Boolean; const DCT_NEWORDER = 1; DCT_DELETION = 2; DCT_NEWSTATUS = 3; var frmDCOrders: TfrmDCOrders; AnOrder: TOrder; i, j, CanSign, DCType: Integer; NeedReason,NeedRefresh,OnCurrent, DCNewOrder: Boolean; OriginalID,APtEvtID,APtEvtName,AnEvtInfo,tmpPtEvt: string; PtEvtList: TStringList; DCChangeItem: TChangeItem; begin Result := False; DelEvt := False; OnCurrent := False; NeedRefresh := False; DCNewOrder := false; PtEvtList := TStringList.Create; if SelectedList.Count = 0 then Exit; frmDCOrders := TfrmDCOrders.Create(Application); try SetFormPosition(frmDCOrders); ResizeFormToFont(TForm(frmDCOrders)); NeedReason := False; with SelectedList do for i := 0 to Count - 1 do begin AnOrder := TOrder(Items[i]); frmDCOrders.lstOrders.Items.Add(AnOrder.Text); frmDCOrders.OrderIDArr.Add(AnOrder.ID); if not ((AnOrder.Status = 11) and (AnOrder.Signature = 2)) then NeedReason := True; if (NeedReason = True) and (AnOrder.Status = 10) and (AnOrder.Signature = 2) then NeedReason := False; end; if NeedReason then begin frmDCOrders.lblReason.Visible := True; frmDCOrders.lstReason.Visible := True; frmDCOrders.lstReason.ScrollWidth := 10; end else begin frmDCOrders.lblReason.Visible := False; frmDCOrders.lstReason.Visible := False; end; frmDCOrders.ShowModal; if frmDCOrders.OKPressed then begin if (Encounter.Provider = User.DUZ) and User.CanSignOrders then CanSign := CH_SIGN_YES else CanSign := CH_SIGN_NA; with SelectedList do for i := 0 to Count - 1 do begin AnOrder := TOrder(Items[i]); OriginalID := AnOrder.ID; PtEvtList.Add(AnOrder.EventPtr + '^' + AnOrder.EventName); if Changes.Orders.Count = 0 then DCNewOrder := false else begin for j := 0 to Changes.Orders.Count - 1 do begin DCChangeItem := TChangeItem(Changes.Orders.Items[j]); if DCChangeItem.ID = AnOrder.ID then begin if (Pos('DC', AnOrder.ActionOn) = 0) then DCNewOrder := True else DCNewOrder := False; end; end; end; DCOrder(AnOrder, frmDCOrders.DCReason, DCNewOrder, DCType); case DCType of DCT_NEWORDER: begin Changes.Add(CH_ORD, AnOrder.ID, AnOrder.Text, '', CanSign, AnOrder.ParentID, user.DUZ, AnOrder.DGroupName, True); AnOrder.ActionOn := OriginalID + '=DC'; end; DCT_DELETION: begin Changes.Remove(CH_ORD, OriginalID); if (AnOrder.ID = '0') or (AnOrder.ID = '') then AnOrder.ActionOn := OriginalID + '=DL' // delete order else AnOrder.ActionOn := OriginalID + '=CA'; // cancel action {else AnOrder.ActionOn := AnOrder.ID + '=CA'; - caused cancel from meds to not update orders} UnlockOrder(OriginalID); // for deletion of unsigned DC end; DCT_NEWSTATUS: begin AnOrder.ActionOn := OriginalID + '=DC'; UnlockOrder(OriginalID); end; else UnlockOrder(OriginalID); end; SendMessage(Application.MainForm.Handle, UM_NEWORDER, ORDER_ACT, Integer(AnOrder)); end; if frmOrders.lstSheets.ItemIndex > -1 then if CharAt(frmOrders.lstSheets.Items[frmOrders.lstSheets.ItemIndex],1)='C' then OnCurrent := True; if not OnCurrent then begin for i := 0 to PtEvtList.Count - 1 do begin if Length(PtEvtList[i])>1 then begin APtEvtID := Piece(PtEvtList[i],'^',1); APtEvtName := Piece(PtEvtList[i],'^',2); AnEvtInfo := EventInfo(APtEvtID); if isExistedEvent(Patient.DFN,Piece(AnEvtInfo,'^',2),tmpPtEvt) and (DeleteEmptyEvt(APtEvtID,APtEvtName,False)) then begin NeedRefresh := True; frmOrders.ChangesUpdate(APtEvtID); end; end; end; if NeedRefresh then begin frmOrders.InitOrderSheetsForEvtDelay; frmOrders.lstSheets.ItemIndex := 0; frmOrders.lstSheetsClick(nil); DelEvt := True; end; end; Result := True; end else with SelectedList do for i := 0 to Count - 1 do UnlockOrder(TOrder(Items[i]).ID); SaveUserBounds(frmDCOrders); finally frmDCOrders.Release; end; end; procedure TfrmDCOrders.FormCreate(Sender: TObject); var DefaultIEN: Integer; begin inherited; OKPressed := False; OrderIDArr := TStringList.Create; ListDCReasons(lstReason.Items, DefaultIEN); lstReason.SelectByIEN(DefaultIEN); { the following commented out so that providers can enter DC reasons } // if Encounter.Provider = User.DUZ then // begin // lblReason.Visible := False; // lstReason.Visible := False; // end; end; procedure TfrmDCOrders.cmdOKClick(Sender: TObject); const TX_REASON_REQ = 'A reason for discontinue must be selected.'; TC_REASON_REQ = 'Missing Discontinue Reason'; begin inherited; if (lstReason.Visible) and (not (lstReason.ItemIEN > 0)) then begin InfoBox(TX_REASON_REQ, TC_REASON_REQ, MB_OK); Exit; end; OKPressed := True; DCReason := lstReason.ItemIEN; Close; end; procedure TfrmDCOrders.cmdCancelClick(Sender: TObject); begin inherited; unMarkedOrignalOrderDC(Self.OrderIDArr); Close; end; procedure TfrmDCOrders.lstOrdersDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); var x: string; ARect: TRect; begin inherited; x := ''; ARect := Rect; with lstOrders do begin Canvas.FillRect(ARect); Canvas.Pen.Color := Get508CompliantColor(clSilver); Canvas.MoveTo(0, ARect.Bottom - 1); Canvas.LineTo(ARect.Right, ARect.Bottom - 1); if Index < Items.Count then begin x := Items[Index]; DrawText(Canvas.handle, PChar(x), Length(x), ARect, DT_LEFT or DT_NOPREFIX or DT_WORDBREAK); end; end; end; procedure TfrmDCOrders.lstOrdersMeasureItem(Control: TWinControl; Index: Integer; var AHeight: Integer); var x:string; begin inherited; with lstOrders do if Index < Items.Count then begin x := Items[index]; AHeight := MeasureColumnHeight(x, Index); end; end; function TfrmDCOrders.MeasureColumnHeight(TheOrderText: string; Index: Integer): integer; var ARect: TRect; begin ARect.Left := 0; ARect.Top := 0; ARect.Bottom := 0; ARect.Right := lstOrders.Width - 6; Result := WrappedTextHeightByFont(lstOrders.Canvas,lstOrders.Font,TheOrderText,ARect); end; procedure TfrmDCOrders.FormDestroy(Sender: TObject); begin inherited; if self.OrderIDArr <> nil then self.OrderIDArr.Free; end; procedure TfrmDCOrders.unMarkedOrignalOrderDC(OrderArr: TStringList); begin CallVistA('ORWDX1 UNDCORIG', [OrderArr]); end; end.
unit record_properties_5; interface implementation type TRec = record private FCnt: Int32; function GetCount: Int32; public property Count: Int32 read GetCount; procedure Run; end; var G: Int32; function TRec.GetCount: Int32; begin Result := FCnt; end; procedure TRec.Run; begin G := Count; end; procedure Test; var R: TRec; begin R.FCnt := 12; R.Run(); end; initialization Test(); finalization Assert(G = 12); end.
unit ClassFrmBase; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, dxGDIPlusClasses, Vcl.ExtCtrls, CommonTypes, CommonVars, Data.DB; const AppCaption = 'Первая фумигационная компания'; type TBooleanFunc = function(Sender: TObject): boolean; type TBaseForm = class(TForm) img1: TImage; procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); private procedure SetCaption(AValue: string); protected fCloseOnCancelCall: boolean; //закрывать при отмене звонка fCanClose: Boolean; fHideOnClose: boolean; //скрывать при закрытии fOnCalcHideOnClose: TBooleanFunc; //событие fTitle: string; fFrmParam: TFrmCreateParam; fNonValidateList: TStringList; fValidateList: TStringList; //процедуры возвращают поля без признака Required procedure SetNonValidate(Alist: string); function Validate(ADataSource: TDataSource): Boolean; procedure WmStartCall(var Msg: TMessage); message WM_STARTCALL; procedure WmFinishCall(var Msg: TMessage); message WM_FINISHCALL; procedure WmAcceptCall(var Msg: TMessage); message WM_ACCEPTCALL; procedure DoStartCall; virtual; procedure DoFinishCall; virtual; procedure DoAcceptCall; virtual; function CalcHideOnClose: boolean; virtual; public property OnCalcHideOnClose: TBooleanFunc read fOnCalcHideOnClose write fOnCalcHideOnClose; constructor Create(AOwner: TComponent; ATitle: string=''; AParam: PFrmCreateParam=nil); overload; virtual; class function ValidateData(ADataSource: TDataSource; AComponent: TComponent = nil; ANonValidList: TStringList=nil; AValidList: TStringList=nil): Boolean; //проверка заполненности необходимых полей destructor Destroy; overload; procedure SetValidateList(Alist: string); procedure CloseAbsolute; //закрыть, не смотря CanClose procedure HideAbsolute; //скрыть procedure PostMessageToAll(AMsg: TMessage); published property Title: string read fTitle write SetCaption; property CanClose: Boolean read fCanClose write fCanClose; property CloseOnCancelCall: Boolean read fCloseOnCancelCall write fCloseOnCancelCall; property HideOnClose: boolean read CalcHideOnClose; end; implementation {$R *.dfm} uses System.TypInfo, IBX.IBQuery, cxDBEdit, cxDBLookupComboBox, frameBase; function TBaseForm.CalcHideOnClose: boolean; begin if Assigned(fOnCalcHideOnClose)then Result := fOnCalcHideOnClose(self) else Result := fHideOnClose; end; procedure TBaseForm.CloseAbsolute; begin CanClose := True; if fsModal in FormState then ModalResult := mrCancel else Close; end; constructor TBaseForm.Create(AOwner: TComponent; ATitle: string=''; AParam: PFrmCreateParam=nil); begin inherited Create(AOwner); if ATitle = '' then ATitle := Caption; if Aparam <> nil then fFrmParam := AParam^; Title := ATitle; fNonValidateList := TStringList.Create; fValidateList := TStringList.Create; fCanClose := True; end; destructor TBaseForm.Destroy; begin fNonValidateList.Free; fValidateList.Free; end; procedure TBaseForm.DoAcceptCall; begin end; procedure TBaseForm.DoFinishCall; begin if fCloseOnCancelCall and CallObj.Cancelled then Self.CloseAbsolute; end; procedure TBaseForm.DoStartCall; begin end; procedure TBaseForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CanClose := fCanClose; if not CanClose then Exit; CanClose := not HideOnClose; if HideOnClose then Hide; end; procedure TBaseForm.HideAbsolute; begin Hide; if fsModal in FormState then ModalResult := mrCancel; end; procedure TBaseForm.PostMessageToAll(AMsg: TMessage); var i: Integer; begin for I := 0 to Screen.FormCount - 1 do PostMessage(Screen.Forms[i].Handle, AMsg.Msg, 0, 0); end; procedure TBaseForm.SetCaption(AValue: string); begin fTitle := AValue; Caption := AppCaption + '. ' + AValue; end; procedure TBaseForm.SetNonValidate(Alist: string); begin fNonValidateList.DelimitedText := Alist; end; procedure TBaseForm.SetValidateList(Alist: string); begin fValidateList.DelimitedText := Alist; end; function TBaseForm.Validate(ADataSource: TDataSource): Boolean; begin Result := ValidateData(ADataSource, self, fNonValidateList, fValidateList); fCanClose := Result; end; class function TBaseForm.ValidateData(ADataSource: TDataSource; AComponent: TComponent = nil; ANonValidList: TStringList=nil; AValidList: TStringList=nil): Boolean; function SetRequiredBorder(AComponent: TComponent; AField: TField): boolean; var c: TComponent; i: integer; res: Boolean; begin Result := not AField.IsNull; res := True; for i := 0 to AComponent.ComponentCount - 1 do begin c := AComponent.Components[i]; if c.ComponentCount > 0 then begin SetRequiredBorder(C, AField); if (C is TDbFrameBase) and not TDbFrameBase(C).ReadOnly then if not TDbFrameBase(C).ValidateData then res := False; end; if ((C is TcxDBTextEdit) or (C is TcxDBLookupComboBox)) and (TcxDBTextEdit(C).DataBinding.Field = AField) then if AField.IsNull then begin TcxDBTextEdit(C).Style.Color := clSkyBlue; TcxDBTextEdit(C).Style.TransparentBorder := False; end else begin TcxDBTextEdit(C).Style.Color := clWindow; TcxDBTextEdit(C).Style.TransparentBorder := true; end; end; Result := Result and res; end; var i: Integer; res, resAll: Boolean; fld: TField; begin if AComponent = nil then AComponent := ADataSource.Owner; resAll := True; if Assigned(ADataSource.DataSet) and ADataSource.DataSet.Modified then for i := 0 to ADataSource.DataSet.FieldCount - 1 do begin fld := ADataSource.DataSet.Fields[i]; if (fld.Required or (Assigned(AValidList) and (AValidList.IndexOf(fld.FieldName) > -1))) and (TIBQuery(ADataSource.DataSet).GeneratorField.Field <> fld.FieldName) and not(Assigned(ANonValidList) and (ANonValidList.IndexOf(ADataSource.DataSet.Fields[i].FieldName)> -1)) then //поля генератора исключаем из проверки begin res := SetRequiredBorder(AComponent, ADataSource.DataSet.Fields[i]); if not res then resAll := False; end; end; Result := resAll; end; procedure TBaseForm.WmAcceptCall(var Msg: TMessage); begin DoAcceptCall; end; procedure TBaseForm.WmFinishCall(var Msg: TMessage); begin DoFinishCall; end; procedure TBaseForm.WmStartCall(var Msg: TMessage); begin DoStartCall; end; end.
unit AndroidManifestEditor; {$mode objfpc}{$H+} interface uses Classes, SysUtils, LazFileUtils, laz2_XMLRead, Laz2_DOM, AvgLvlTree, IDEOptionsIntf, ProjectIntf, Forms, Controls, Dialogs, Grids, StdCtrls, LResources, ExtCtrls, Spin; type { TLamwAndroidManifestOptions } TLamwAndroidManifestOptions = class private xml: TXMLDocument; // AndroidManifest.xml FFileName: string; FPermissions: TStringList; FPermNames: TStringToStringTree; FUsesSDKNode: TDOMElement; FMinSdkVersion, FTargetSdkVersion: Integer; FVersionCode: Integer; FVersionName: string; procedure Clear; public constructor Create; destructor Destroy; override; procedure Load(AFileName: string); procedure Save; property Permissions: TStringList read FPermissions; property PermNames: TStringToStringTree read FPermNames; property MinSDKVersion: Integer read FMinSdkVersion write FMinSdkVersion; property TargetSDKVersion: Integer read FTargetSdkVersion write FTargetSdkVersion; property VersionCode: Integer read FVersionCode write FVersionCode; property VersionName: string read FVersionName write FVersionName; end; { TLamwAndroidManifestEditor } TLamwAndroidManifestEditor = class(TAbstractIDEOptionsEditor) edVersionName: TEdit; gbVersion: TGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; lblErrorMessage: TLabel; ErrorPanel: TPanel; seMinSdkVersion: TSpinEdit; seTargetSdkVersion: TSpinEdit; PermissonGrid: TStringGrid; seVersionCode: TSpinEdit; private { private declarations } FOptions: TLamwAndroidManifestOptions; procedure ErrorMessage(const msg: string); procedure FillPermissionGrid(Permissions: TStringList; PermNames: TStringToStringTree); procedure SetControlsEnabled(en: Boolean); public { public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; class function SupportedOptionsClass: TAbstractIDEOptionsClass; override; function GetTitle: String; override; procedure Setup({%H-}ADialog: TAbstractOptionsEditorDialog); override; procedure ReadSettings({%H-}AOptions: TAbstractIDEOptions); override; procedure WriteSettings({%H-}AOptions: TAbstractIDEOptions); override; end; implementation uses LazIDEIntf, laz2_XMLWrite, Graphics, strutils; {$R *.lfm} { TLamwAndroidManifestOptions } procedure TLamwAndroidManifestOptions.Clear; begin xml.Free; FUsesSDKNode := nil; FMinSdkVersion := 11; FTargetSdkVersion := 19; FPermissions.Clear; end; constructor TLamwAndroidManifestOptions.Create; procedure AddPerm(PermVisibleName: string; android_name: string = ''); begin if android_name = '' then android_name := 'android.permission.' + StringReplace(UpperCase(PermVisibleName), ' ', '_', [rfReplaceAll]); FPermNames[android_name] := PermVisibleName; end; begin FPermissions := TStringList.Create; FPermNames := TStringToStringTree.Create(True); AddPerm('Bluetooth'); AddPerm('Access bluetooth share'); AddPerm('Access coarse location'); AddPerm('Access fine location'); AddPerm('Access network state'); AddPerm('Access wifi state'); AddPerm('Bluetooth admin'); AddPerm('Call phone'); AddPerm('Camera'); AddPerm('Change wifi state'); AddPerm('Internet'); AddPerm('NFC'); AddPerm('Read contacts'); AddPerm('Read external storage'); AddPerm('Read owner data'); AddPerm('Read phone state'); AddPerm('Receive SMS'); AddPerm('Restart packages'); AddPerm('Send SMS'); AddPerm('Vibrate'); AddPerm('Write contacts'); AddPerm('Write external storage'); AddPerm('Write owner data'); AddPerm('Write user dictionary'); { todo: Access location extra commands Access mock location Add voicemail Authenticate accounts Battery stats Bind accessibility service Bind device admin Bind input method Bind remoteviews Bind text service Bind vpn service Bind wallpaper Broadcast sticky Change configuration Change network state Change wifi multicast state Clear app cache Disable keyguard Expand status bar Flashlight Get accounts Get package size Get tasks Global search Kill background processes Manage accounts Modify audio settings Process outgoing calls Read calendar Read call log Read history bookmarks Read profile Read SMS Read social stream Read sync settings Read sync stats Read user dictionary Receive boot completed Receive MMS Receive WAP push Record audio Reorder tasks Set alarm Set time zone Set wallpaper Subscribed feeds read Subscribed feeds write System alert window Use credentials Use SIP Vending billing (In-app Billing) Wake lock Write calendar Write call log Write history bookmarks Write profile Write settings Write SMS Write social stream Write sync settings Write user dictionary + Advanced... } FPermissions.Sorted := True; end; destructor TLamwAndroidManifestOptions.Destroy; begin FPermNames.Free; FPermissions.Free; xml.Free; inherited Destroy; end; procedure TLamwAndroidManifestOptions.Load(AFileName: string); var i, j: Integer; s, v: string; n: TDOMNode; begin Clear; ReadXMLFile(xml, AFileName); FFileName := AFileName; if (xml = nil) or (xml.DocumentElement = nil) then Exit; with xml.DocumentElement do begin FVersionCode := StrToIntDef(AttribStrings['android:versionCode'], 1); FVersionName := AttribStrings['android:versionName']; end; with xml.DocumentElement.ChildNodes do begin FPermNames.GetNames(FPermissions); for i := Count - 1 downto 0 do if Item[i].NodeName = 'uses-permission' then begin s := Item[i].Attributes.GetNamedItem('android:name').TextContent; j := FPermissions.IndexOf(s); if j >= 0 then FPermissions.Objects[j] := TObject(PtrUInt(1)) else begin v := Copy(s, RPos('.', s) + 1, MaxInt); FPermNames[s] := v; FPermissions.AddObject(s, TObject(PtrUInt(1))); end; xml.ChildNodes[0].DetachChild(Item[i]).Free; end else if Item[i].NodeName = 'uses-sdk' then begin FUsesSDKNode := Item[i] as TDOMElement; n := FUsesSDKNode.Attributes.GetNamedItem('android:minSdkVersion'); if Assigned(n) then FMinSdkVersion := StrToIntDef(n.TextContent, FMinSdkVersion); n := FUsesSDKNode.Attributes.GetNamedItem('android:targetSdkVersion'); if Assigned(n) then FTargetSdkVersion := StrToIntDef(n.TextContent, FTargetSdkVersion); end; end; end; procedure TLamwAndroidManifestOptions.Save; var i: Integer; r: TDOMNode; n: TDOMElement; begin // writing manifest if not Assigned(xml) then Exit; xml.DocumentElement.AttribStrings['android:versionCode'] := IntToStr(FVersionCode); xml.DocumentElement.AttribStrings['android:versionName'] := FVersionName; if not Assigned(FUsesSDKNode) then begin FUsesSDKNode := xml.CreateElement('uses-sdk'); with xml.DocumentElement do if ChildNodes.Count = 0 then AppendChild(FUsesSDKNode) else InsertBefore(FUsesSDKNode, ChildNodes[0]); end; with FUsesSDKNode do begin AttribStrings['android:minSdkVersion'] := IntToStr(FMinSdkVersion); AttribStrings['android:targetSdkVersion'] := IntToStr(FTargetSdkVersion); end; // permissions r := FUsesSDKNode.NextSibling; for i := 0 to FPermissions.Count - 1 do begin n := xml.CreateElement('uses-permission'); n.AttribStrings['android:name'] := FPermissions[i]; if Assigned(r) then xml.ChildNodes[0].InsertBefore(n, r) else xml.ChildNodes[0].AppendChild(n); end; WriteXMLFile(xml, FFileName); end; { TLamwAndroidManifestEditor } procedure TLamwAndroidManifestEditor.SetControlsEnabled(en: Boolean); var i: Integer; begin for i := 0 to ControlCount - 1 do Controls[i].Enabled := en; end; constructor TLamwAndroidManifestEditor.Create(AOwner: TComponent); begin inherited Create(AOwner); FOptions := TLamwAndroidManifestOptions.Create; end; destructor TLamwAndroidManifestEditor.Destroy; begin FOptions.Free; inherited Destroy; end; procedure TLamwAndroidManifestEditor.ErrorMessage(const msg: string); begin lblErrorMessage.Caption := msg; ErrorPanel.Visible := True; ErrorPanel.Enabled := True; end; procedure TLamwAndroidManifestEditor.FillPermissionGrid(Permissions: TStringList; PermNames: TStringToStringTree); var i: Integer; n: string; begin PermissonGrid.BeginUpdate; try PermissonGrid.RowCount := Permissions.Count + 1; with PermissonGrid do for i := 0 to Permissions.Count - 1 do begin n := PermNames[Permissions[i]]; if n = '' then n := Permissions[i]; Cells[0, i + 1] := n; if Permissions.Objects[i] = nil then Cells[1, i + 1] := '0' else Cells[1, i + 1] := '1' end; finally PermissonGrid.EndUpdate; end; end; class function TLamwAndroidManifestEditor.SupportedOptionsClass: TAbstractIDEOptionsClass; begin Result := nil; end; function TLamwAndroidManifestEditor.GetTitle: string; begin Result := '[Lamw] Android Manifest'; end; procedure TLamwAndroidManifestEditor.Setup(ADialog: TAbstractOptionsEditorDialog); begin // localization end; procedure TLamwAndroidManifestEditor.ReadSettings(AOptions: TAbstractIDEOptions); var proj: TLazProject; fn: string; begin // reading manifest SetControlsEnabled(False); proj := LazarusIDE.ActiveProject; if (proj = nil) or (proj.IsVirtual) then Exit; fn := proj.MainFile.Filename; fn := Copy(fn, 1, Pos(PathDelim + 'jni' + PathDelim, fn)); fn := fn + 'AndroidManifest.xml'; if not FileExistsUTF8(fn) then begin ErrorMessage('"' + fn + '" not found!'); Exit; end; try with FOptions do begin Load(fn); FillPermissionGrid(Permissions, PermNames); seMinSdkVersion.Value := MinSDKVersion; seTargetSdkVersion.Value := TargetSDKVersion; seVersionCode.Value := VersionCode; edVersionName.Text := VersionName; end; except on e: Exception do begin ErrorMessage(e.Message); Exit; end end; SetControlsEnabled(True); end; procedure TLamwAndroidManifestEditor.WriteSettings(AOptions: TAbstractIDEOptions); var i: Integer; begin with FOptions do begin for i := PermissonGrid.RowCount - 1 downto 1 do if PermissonGrid.Cells[1, i] <> '1' then Permissions.Delete(i - 1); MinSDKVersion := seMinSdkVersion.Value; TargetSDKVersion := seTargetSdkVersion.Value; VersionCode := seVersionCode.Value; VersionName := edVersionName.Text; Save; end; end; initialization RegisterIDEOptionsEditor(GroupProject, TLamwAndroidManifestEditor, 1000); end.
unit U_Dico; interface uses U_FichierTexte, U_Liste, SysUtils, U_Pile; type (* exception si il y en a ??exception = class(SysUtils.Exception); *) (*============================================DICO===============================================*) // Pointeur de Cellule (pointeur de noeud de l'arbre) P_CELLULE = ^CELLULE; // type DICTIONNAIRE (un dictionnaire est un arbre) DICTIONNAIRE = P_CELLULE; // Une cellule est un enregistrement qui possede deux champs CELLULE = record // le premier indique la fin de mot * isMot : BOOLEAN; (* par default, en pascal, un booleen est initialisé à false*) // le second represente les 26 lettres de l'alphabet Contenu : ARRAY['a'..'z'] of P_CELLULE; (* par default, en pascal, un pointeur est initialisé à nil.*) end{CELLULE}; (*============================================MOT===============================================*) // type MOT = une chaine de caractere MOT = STRING; (*============================================LISTE de P_CELLULE ===============================================*) ELEMENT = P_CELLULE; LISTE_P_CELLULE = ^NOEUD; NOEUD = record tete : ELEMENT; reste : LISTE_P_CELLULE; end {NOEUD}; ListePCelluleVide = class(SysUtils.Exception); const LISTE_VIDE_PC : LISTE_P_CELLULE = NIL; (*============================================Primitive Liste===============================================*) function ajouterEnTetePC(const l : LISTE_P_CELLULE; const x : ELEMENT): LISTE_P_CELLULE; function tetePC(l : LISTE_P_CELLULE) : ELEMENT; function restePC(l : LISTE_P_CELLULE) : LISTE_P_CELLULE; procedure modifierTetePC(var l : LISTE_P_CELLULE; x : ELEMENT); function estListeVidePC(l : LISTE_P_CELLULE): BOOLEAN; // Ajout d'un mot dans le dictionnaire procedure ajouter (mot : MOT); // Construction du dictionnaire à partir d'un fichier procedure construire(fichier : STRING); // Construction d'une liste contenant tous les mots du dico.txt //function tousLesMots : LISTE; //(* function tousLesMots : LISTE; procedure RechercheDesMots(noeud : P_CELLULE; out L : LISTE; var chaine : STRING; var profondeur : INTEGER; L_PC : LISTE_P_CELLULE); //*) implementation var monDico : DICTIONNAIRE; i : integer; procedure ajouter (mot : MOT); var i : integer; p,racine : P_CELLULE; begin //writeln('appel de ajouter(',mot,')'); racine := monDico; //writeln('adresse racine =',cardinal(racine)); //writeln('isMot du noeud courant = ',monDico^.isMot); //writeln; for i:=1 to length(mot) do begin //writeln('For i = ',i); //writeln('length(',mot,') = ',length(mot)); // Si il n'existe pas de fils pour la lettre mot[i] : if (monDico^.contenu[mot[i]]=NIL) then begin // On cree une nouvelle cellule : new(p); // On passe la valeur par default de true à false du champ isMot p^.isMot := false; //writeln('la valeur par default de isMot du noeud cree :',p^.isMot); //writeln('adresse de la nouvelle cellule creer : ',cardinal(p)); // On fait le chainage vers la cellule crée : //writeln('procedure ajouter : ',mot[i]); monDico^.contenu[mot[i]]:= p; //writeln('adresse de monDico^.contenu[mot[i]] : ',cardinal(monDico^.contenu[mot[i]]) ); // On passe au fils suivant : //writeln('ajouter / 1.on passe au fils suivant'); monDico := p ; //writeln('On se retrouve à l''adresse de monDico : ',cardinal(monDico));writeln; //writeln('isMot du noeud courant = ',monDico^.isMot); // Si on se trouve en fin de mot if( i = length(mot))then begin monDico^.isMot := true; //writeln('isMot du noeud courant = ',monDico^.isMot); //writeln('On se retrouve à l''adresse de monDico : ',cardinal(monDico));writeln; monDico := racine; end; end else begin //Sinon le fils existe et on passe au fils suivant : //writeln('ajouter / 2.on passe au fils suivant'); monDico:= monDico^.contenu[mot[i]]; //writeln('On se retrouve à l''adresse de monDico : ',cardinal(monDico));writeln; //writeln('isMot du noeud courant = ',monDico^.isMot); //writeln('i = ',i); //writeln('length(',mot,') = ',length(mot)); if( i = length(mot))then monDico^.isMot := true; //writeln('if / isMot du noeud courant = ',monDico^.isMot); end;//if end;//for //writeln('fin de l''appel de ajouter(',mot,')'); monDico := racine; //writeln('adresse de monDico final =',cardinal(monDico)); end{ajouter}; procedure construire(fichier : STRING); begin ouvrir(fichier); while (not(lectureTerminee)) do begin ajouter(lireMotSuivant); end;//while fermer; end{construire}; (* function tousLesMots : LISTE; var L : LISTE; begin L:= LISTE_VIDE; L:=ajouterEnTete(L,'babar'); L:=ajouterEnTete(L,'ane'); L:=ajouterEnTete(L,'barbe'); L:=ajouterEnTete(L,'bar'); L:=ajouterEnTete(L,'zut'); L:=ajouterEnTete(L,'presque'); L:=ajouterEnTete(L,'pittoresque'); L:=ajouterEnTete(L,'une'); tousLesMots:= L; end{tousLesMots}; *) function tousLesMots : LISTE; var L : LISTE; mot : STRING; prof : INTEGER; L_PC : LISTE_P_CELLULE; begin L := LISTE_VIDE; L_PC := LISTE_VIDE_PC; mot := ''; prof := 0; writeln('adresse de monDico avant fonction tousLesMots : ',cardinal(monDico)); RechercheDesMots(monDico,L,mot,prof,L_PC); writeln('adresse de monDico apres fonction tousLesMots : ',cardinal(monDico)); tousLesMots := L; end{tousLesMots}; procedure RechercheDesMots(noeud : P_CELLULE; out L : LISTE; var chaine : STRING; var profondeur : INTEGER; L_PC : LISTE_P_CELLULE); var i,j : INTEGER; begin writeln('debut procedure adresse de monDico : ',cardinal(monDico)); for j:= ord('a') to ord('z') do begin writeln('on est ds for de j '); writeln(char(j),' : ', cardinal(monDico^.contenu[char(j)]) ); end; writeln('on sort du for de j '); writeln('on rentre dans for de i'); for i:= ord('a') to ord('z') do begin writeln('on est ds for de i '); writeln(char(i)); writeln('profondeur actuelle : ',profondeur); writeln('avant IF monDico^.contenu[char(i)] <> NIL = ',monDico^.contenu[char(i)] <> NIL); if (monDico^.contenu[char(i)] <> NIL) then begin writeln('aprés IF monDico^.contenu[char(i)] <> NIL = ',monDico^.contenu[char(i)] <> NIL); writeln('chaine avant modif :',chaine); chaine := chaine + char(i); writeln('chaine aprés modif :',chaine); L_PC := ajouterEnTetePC(L_PC,monDico); monDico := monDico^.contenu[char(i)]; profondeur:= profondeur + 1; writeln('on descend dans l''arbre'); writeln('adresse de monDico : ',cardinal(monDico)); writeln('profondeur actuelle : ',profondeur); if (monDico^.isMot) then begin L := ajouterEnTete(L,chaine); chaine := copy(chaine,profondeur,0); writeln('la tete de L vaut : ',tete(L)); AfficherListe(L);writeln; end; writeln('avant appel recursif adresse de monDico : ',cardinal(monDico)); RechercheDesMots(monDico,L,chaine,profondeur,L_PC); monDico := tetePC(L_PC); L_PC := restePC(L_PC); writeln('aprés appel recursif adresse de monDico : ',cardinal(monDico)); profondeur:= profondeur - 1; writeln('on remonte dans l''arbre'); writeln('adresse de monDico : ',cardinal(monDico)); end;//if end;//for writeln('on sort du for de i '); (* racine := monDico; while (monDico^.isMot = false) do begin // Si il n'existe pas de fils pour la lettre mot[i] : if (monDico^.contenu[mot[i]]=NIL) then begin // On cree une nouvelle cellule : //new(p); // On passe la valeur par default de true à false du champ isMot //p^.isMot := false; // On fait le chainage vers la cellule crée : //monDico^.contenu[mot[i]]:= p; // On passe au fils suivant : monDico := p ; // Si on se trouve en fin de mot if( i = length(mot))then begin monDico^.isMot := true; monDico := racine; end; end else begin //Sinon le fils existe et on passe au fils suivant : monDico:= monDico^.contenu[mot[i]]; if( i = length(mot))then monDico^.isMot := true; end;//if end;//while monDico := racine; *) end{RechercheDesMots}; function ajouterEnTetePC(const l : LISTE_P_CELLULE; const x : ELEMENT): LISTE_P_CELLULE; var res : LISTE_P_CELLULE = NIL; begin new(res); res.tete := x; res.reste := l; ajouterEnTetePC := res; end {ajouterEnTete}; function tetePC(l : LISTE_P_CELLULE) : ELEMENT; begin if l = LISTE_VIDE_PC then raise ListePCelluleVide.create('Impossible d acceder a la tete'); tetePC := l.tete; end {tete}; function restePC(l : LISTE_P_CELLULE) : LISTE_P_CELLULE; begin if l = LISTE_VIDE_PC then raise ListePCelluleVide.create('Impossible d acceder a la tete'); restePC := l.reste; end {reste}; function estListeVidePC(l : LISTE_P_CELLULE): BOOLEAN; begin estListeVidePC := l = LISTE_VIDE_PC; end {estListeVide}; procedure modifierTetePC(var l : LISTE_P_CELLULE; x : ELEMENT); begin if l = LISTE_VIDE_PC then raise ListePCelluleVide.create('Impossible d acceder a la tete'); l.tete := x; end {modifierTete}; initialization // Creation d'un dictionnaire Vide. new(monDico); monDico^.isMot := FALSE; for i:= ord('a') to ord('z') do begin monDico^.Contenu[char(i)] := NIL; end;//for construire('dicotest.txt'); end {U_Dico}.
unit Financas.View.Cliente; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo, FMX.Edit, System.Rtti, FMX.Grid.Style, Data.Bind.Controls, Data.Bind.Components, Data.Bind.DBScope, FMX.Layouts, FMX.Bind.Navigator, FMX.Grid, Data.DB, Data.Bind.EngExt, FMX.Bind.DBEngExt, FMX.Bind.Grid, System.Bindings.Outputs, FMX.Bind.Editors, Data.Bind.Grid, Financas.Controller.Entity.Interfaces; type TViewCliente = class(TForm) ToolBar: TToolBar; LabelTitle: TLabel; DataSource: TDataSource; StringGrid: TStringGrid; BindNavigator: TBindNavigator; BindSourceDB: TBindSourceDB; BindingsList: TBindingsList; LinkGridToDataSourceBindSourceDB: TLinkGridToDataSource; procedure FormCreate(Sender: TObject); private { Private declarations } FEntity: iControllerEntity; public { Public declarations } end; var ViewCliente: TViewCliente; implementation uses Financas.Controller.Entity.Factory; {$R *.fmx} procedure TViewCliente.FormCreate(Sender: TObject); begin FEntity := TControllerEntityFactory.New.Cliente; FEntity.Lista(DataSource); end; initialization RegisterFmxClasses([TViewCliente]); end.
{*******************************************************} { } { Delphi FireDAC Framework } { FireDAC Advantage Database Server driver } { } { Copyright(c) 2004-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} {$I FireDAC.inc} {$IF DEFINED(IOS) OR DEFINED(ANDROID)} {$HPPEMIT LINKUNIT} {$ELSE} {$IFDEF WIN32} {$HPPEMIT '#pragma link "FireDAC.Phys.ADS.obj"'} {$ELSE} {$HPPEMIT '#pragma link "FireDAC.Phys.ADS.o"'} {$ENDIF} {$ENDIF} unit FireDAC.Phys.ADS; interface uses System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.Phys, FireDAC.Phys.ADSWrapper; type TFDPhysADSDriverLink = class; TFDADSService = class; TFDADSBackupRestore = class; TFDADSBackup = class; TFDADSRestore = class; TFDADSUtility = class; [ComponentPlatformsAttribute(pfidWindows or pfidLinux)] TFDPhysADSDriverLink = class(TFDPhysDriverLink) private FDateFormat: String; FDecimals: Integer; FDefaultPath: String; FSearchPath: String; FShowDeleted: Boolean; FEpoch: Word; FExact: Boolean; function GetDateFormat: String; function GetDecimals: Word; function GetDefaultPath: String; function GetEpoch: Word; function GetExact: Boolean; function GetSearchPath: String; function GetShowDeleted: Boolean; procedure SetDateFormat(const AValue: String); procedure SetDecimals(const AValue: Word); procedure SetDefaultPath(const AValue: String); procedure SetEpoch(const AValue: Word); procedure SetExact(const AValue: Boolean); procedure SetSearchPath(const AValue: String); procedure SetShowDeleted(const AValue: Boolean); function IsDFS: Boolean; function IsDS: Boolean; function IsDPS: Boolean; function IsEpS: Boolean; function IsExS: Boolean; function IsSDS: Boolean; function IsSPS: Boolean; protected function GetBaseDriverID: String; override; function IsConfigured: Boolean; override; procedure ApplyTo(const AParams: IFDStanDefinition); override; public constructor Create(AOwner: TComponent); override; published property DateFormat: String read GetDateFormat write SetDateFormat stored IsDFS; property Decimals: Word read GetDecimals write SetDecimals stored IsDS; property DefaultPath: String read GetDefaultPath write SetDefaultPath stored IsDPS; property SearchPath: String read GetSearchPath write SetSearchPath stored IsSPS; property ShowDeleted: Boolean read GetShowDeleted write SetShowDeleted stored IsSDS; property Epoch: Word read GetEpoch write SetEpoch stored IsEpS; property Exact: Boolean read GetExact write SetExact stored IsExS; end; TFDADSService = class (TFDPhysDriverService) private FPassword: String; FUserName: String; FDatabase: String; function GetDriverLink: TFDPhysADSDriverLink; procedure SetDriverLink(const AValue: TFDPhysADSDriverLink); procedure GetConnection(out AConn: IFDPhysConnection; out ACmd: IFDPhysCommand); protected function GetConnectionString: String; virtual; published property DriverLink: TFDPhysADSDriverLink read GetDriverLink write SetDriverLink; property Database: String read FDatabase write FDatabase; property UserName: String read FUserName write FUserName; property Password: String read FPassword write FPassword; end; TFDADSBackupRestore = class(TFDADSService) private FInclude: TStrings; FExclude: TStrings; FTableTypeMap: TStrings; FResults: TFDDatSTable; FArchiveFile: String; procedure SetInclude(const AValue: TStrings); procedure SetExclude(const AValue: TStrings); procedure SetTableTypeMap(const AValue: TStrings); class procedure AddOption(var AStr: String; const AName, AValue: String); static; protected function GetOptions: String; virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Results: TFDDatSTable read FResults; published property Include: TStrings read FInclude write SetInclude; property Exclude: TStrings read FExclude write SetExclude; property TableTypeMap: TStrings read FTableTypeMap write SetTableTypeMap; property ArchiveFile: String read FArchiveFile write FArchiveFile; end; TFDADSBackupOptions = set of (boMetaOnly, boPrepareDiff, boDiff, boCompressArchive); [ComponentPlatformsAttribute(pfidWindows or pfidLinux)] TFDADSBackup = class(TFDADSBackupRestore) private FBackupPath: String; FOptions: TFDADSBackupOptions; protected procedure InternalExecute; override; function GetOptions: String; override; public procedure Backup; published property BackupPath: String read FBackupPath write FBackupPath; property Options: TFDADSBackupOptions read FOptions write FOptions default []; end; TFDADSRestoreOptions = set of (roDontOverwrite, roMetaOnly, roNoWarnings, roCompressedArchive, roForceArchiveExtract); [ComponentPlatformsAttribute(pfidWindows or pfidLinux)] TFDADSRestore = class(TFDADSBackupRestore) private FSourcePath: String; FSourcePassword: String; FDestinationPath: String; FDDPassword: String; FOptions: TFDADSRestoreOptions; protected procedure InternalExecute; override; function GetOptions: String; override; public procedure Restore; published property SourcePath: String read FSourcePath write FSourcePath; property SourcePassword: String read FSourcePassword write FSourcePassword; property DestinationPath: String read FDestinationPath write FDestinationPath; property DDPassword: String read FDDPassword write FDDPassword; property Options: TFDADSRestoreOptions read FOptions write FOptions default []; end; [ComponentPlatformsAttribute(pfidWindows or pfidLinux)] TFDADSUtility = class(TFDADSService) private type TMode = (umEncrypt, umDecrypt, umPack, umZap, umReindex, umRecall); private FTables: TStrings; FMode: TMode; FOnProgress: TFDPhysServiceProgressEvent; FTableType: TADSTableType; FTablePassword: String; procedure SetTables(const AValue: TStrings); protected function GetConnectionString: String; override; procedure InternalExecute; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Encrypt; procedure Decrypt; procedure Pack; procedure Zap; procedure Reindex; procedure Recall; published property Tables: TStrings read FTables write SetTables; property TableType: TADSTableType read FTableType write FTableType default ttDefault; property TablePassword: String read FTablePassword write FTablePassword; property OnProgress: TFDPhysServiceProgressEvent read FOnProgress write FOnProgress; end; {-------------------------------------------------------------------------------} implementation uses System.Variants, System.Generics.Collections, Data.DB, FireDAC.Stan.Consts, FireDAC.Stan.Error, FireDAC.Stan.Util, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Factory, FireDAC.Stan.ResStrs, FireDAC.Phys.SQLGenerator, FireDAC.Phys.ADSCli, FireDAC.Phys.ADSMeta, FireDAC.Phys.ADSDef; type TFDPhysADSDriver = class; TFDPhysADSConnection = class; TFDPhysADSTransaction = class; TFDPhysADSEventAlerter = class; TFDPhysADSCommand = class; TFDPhysADSCliHandles = array [0..0] of NativeUInt; PFDPhysADSCliHandles = ^TFDPhysADSCliHandles; TFDPhysADSDriver = class(TFDPhysDriver) private FLib: TADSLib; protected class function GetBaseDriverID: String; override; class function GetBaseDriverDesc: String; override; class function GetRDBMSKind: TFDRDBMSKind; override; class function GetConnectionDefParamsClass: TFDConnectionDefParamsClass; override; procedure InternalLoad; override; procedure InternalUnload; override; function InternalCreateConnection(AConnHost: TFDPhysConnectionHost): TFDPhysConnection; override; function GetCliObj: Pointer; override; function GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable; override; public constructor Create(AManager: TFDPhysManager; const ADriverDef: IFDStanDefinition); override; destructor Destroy; override; end; TFDPhysADSConnection = class (TFDPhysConnection) private FConnection: TADSConnection; FDictionary: TADSDictionary; FServerVersion: TFDVersion; FCliHandles: TFDPhysADSCliHandles; FAliasPath: String; FAliasTableType: String; FTablePasswords: TStrings; function BuildServerTypes(const AConnDef: IFDStanConnectionDef): Integer; function BuildConnectionPath(const AConnDef: IFDStanConnectionDef): String; function Build60Options(const AConnDef: IFDStanConnectionDef): Integer; function BuildADS101ConnectString(const AConnDef: IFDStanConnectionDef): String; procedure BaseConnect(AConn: TADSConnection; const AConnDef: IFDStanConnectionDef); procedure LoadPasswords; protected procedure InternalConnect; override; procedure InternalSetMeta; override; procedure InternalDisconnect; override; procedure InternalPing; override; procedure InternalChangePassword(const AUserName, AOldPassword, ANewPassword: String); override; function InternalCreateTransaction: TFDPhysTransaction; override; function InternalCreateEvent(const AEventKind: String): TFDPhysEventAlerter; override; function InternalCreateCommand: TFDPhysCommand; override; function InternalCreateMetadata: TObject; override; function InternalCreateCommandGenerator(const ACommand: IFDPhysCommand): TFDPhysCommandGenerator; override; {$IFDEF FireDAC_MONITOR} procedure InternalTracingChanged; override; {$ENDIF} procedure InternalExecuteDirect(const ASQL: String; ATransaction: TFDPhysTransaction); override; procedure GetItem(AIndex: Integer; out AName: String; out AValue: Variant; out AKind: TFDMoniAdapterItemKind); override; function GetItemCount: Integer; override; function GetMessages: EFDDBEngineException; override; function GetCliObj: Pointer; override; function InternalGetCliHandle: Pointer; override; function GetLastAutoGenValue(const AName: String): Variant; override; procedure InternalAnalyzeSession(AMessages: TStrings); override; public constructor Create(ADriverObj: TFDPhysDriver; AConnHost: TFDPhysConnectionHost); override; destructor Destroy; override; end; TFDPhysADSTransaction = class(TFDPhysTransaction) protected procedure InternalStartTransaction(ATxID: LongWord); override; procedure InternalCommit(ATxID: LongWord); override; procedure InternalRollback(ATxID: LongWord); override; procedure InternalChanged; override; procedure InternalCheckState(ACommandObj: TFDPhysCommand; ASuccess: Boolean); override; procedure InternalNotify(ANotification: TFDPhysTxNotification; ACommandObj: TFDPhysCommand); override; end; TFDPhysADSEventAlerter = class(TFDPhysEventAlerter) private FWaitThread: TThread; FWaitConnection: IFDPhysConnection; FWaitCommand: IFDPhysCommand; FTab: TFDDatSTable; procedure DoFired; protected // TFDPhysEventAlerter procedure InternalAllocHandle; override; procedure InternalRegister; override; procedure InternalHandle(AEventMessage: TFDPhysEventMessage); override; procedure InternalAbortJob; override; procedure InternalUnregister; override; procedure InternalReleaseHandle; override; procedure InternalSignal(const AEvent: String; const AArgument: Variant); override; end; PFDAdsParInfoRec = ^TFDAdsParInfoRec; PFDAdsColInfoRec = ^TFDAdsColInfoRec; TFDAdsParInfoRec = record FAdsParamIndex: Integer; FParamIndex: Integer; FOutSQLDataType: Word; FDestDataType: TFDDataType; FSrcDataType: TFDDataType; FOutDataType: TFDDataType; FSrcFieldType: TFieldType; FSrcSize: LongWord; FSrcPrec: Integer; FSrcScale: Integer; FParamType: TParamType; end; TFDAdsColInfoRec = record FName: String; FPos: Integer; FLen: LongWord; FPrec, FScale: Integer; FSrcSQLDataType, FSrcSQLMemoType: Word; FSrcDataType, FDestDataType: TFDDataType; FAttrs: TFDDataAttributes; FVar: TADSVariable; FADLen: LongWord; FInPK: WordBool; end; TFDPhysADSCommand = class(TFDPhysCommand) private FStmt: TADSStatement; FCursor: TADSCursor; FParInfos: array of TFDAdsParInfoRec; FColInfos: array of TFDAdsColInfoRec; FColIndex: Integer; FMetainfoAddonView: TFDDatSView; FMetaEncoder: TFDEncoder; FPasswordsSet: Boolean; FHasIntStreams: Boolean; function GetConnection: TFDPhysADSConnection; function UseExecDirect: Boolean; procedure SetupStatementBeforePrepare(AStmt: TADSStatement); procedure SetupStatementBeforeExecute(AStmt: TADSStatement); procedure SetupCursor(ACrs: TADSCursor); function FDType2SQL(AType: TFDDataType; AFixedLen: Boolean): Word; procedure SQL2ADColInfo(ASQLType, ASQLMemoType: Word; ASQLLen: LongWord; ASQLPrec, ASQLScale: Word; out AType: TFDDataType; var AAttrs: TFDDataAttributes; out ALen: LongWord; out APrec, AScale: Integer; AFmtOpts: TFDFormatOptions); procedure CreateParamInfos; procedure DestroyParamInfos; procedure CreateColInfos; procedure DestroyColInfos; procedure DoExecute(ATimes, AOffset: Integer; var ACount: TFDCounter; AFlush: Boolean); procedure SetParamValue(AFmtOpts: TFDFormatOptions; AParam: TFDParam; AAdsParam: TADSVariable; ApInfo: PFDAdsParInfoRec; AParIndex: Integer); procedure SetParamValues(AParIndex: Integer = 0); procedure FetchRow(ATable: TFDDatSTable; AParentRow: TFDDatSRow); function FetchMetaRow(ATable: TFDDatSTable; AParentRow: TFDDatSRow; ARowNo: Integer): Boolean; procedure GetParamValues(AParIndex: Integer = 0); procedure SetupStatementDataAccess(AStmt: TADSStatement); procedure SetupStatementPasswords(AStmt: TADSStatement); protected procedure InternalAbort; override; procedure InternalClose; override; procedure InternalExecute(ATimes, AOffset: Integer; var ACount: TFDCounter); override; procedure InternalCloseStreams; override; function InternalFetchRowSet(ATable: TFDDatSTable; AParentRow: TFDDatSRow; ARowsetSize: LongWord): LongWord; override; function InternalOpen(var ACount: TFDCounter): Boolean; override; function InternalNextRecordSet: Boolean; override; procedure InternalPrepare; override; function InternalUseStandardMetadata: Boolean; override; function InternalColInfoStart(var ATabInfo: TFDPhysDataTableInfo): Boolean; override; function InternalColInfoGet(var AColInfo: TFDPhysDataColumnInfo): Boolean; override; procedure InternalUnprepare; override; function GetCliObj: Pointer; override; public constructor Create(AConnection: TFDPhysConnection); destructor Destroy; override; property ADSConnection: TFDPhysADSConnection read GetConnection; property ADSStatement: TADSStatement read FStmt; end; const S_FD_UDP = 'UDP'; S_FD_IPX = 'IPX'; S_FD_TCPIP = 'TCPIP'; S_FD_TLS = 'TLS'; S_FD_Remote = 'Remote'; S_FD_Local = 'Local'; S_FD_Internet = 'Internet'; // S_FD_Internet S_FD_Always = 'Always'; S_FD_Never = 'Never'; S_FD_Default = 'Default'; S_FD_CDX = 'CDX'; S_FD_VFP = 'VFP'; S_FD_ADT = 'ADT'; S_FD_NTX = 'NTX'; S_FD_Proprietary = 'Proprietary'; S_FD_Compatible = 'Compatible'; C_AdsCharTypeMap = 'ANSI;OEM'; {-------------------------------------------------------------------------------} { TFDPhysADSDriverLink } {-------------------------------------------------------------------------------} const C_DefDateFormat = 'MM/DD/YYYY'; C_DefDecimals = 2; C_DefShowDeleted = True; C_DefEpoch = 1900; C_DefExact = False; constructor TFDPhysADSDriverLink.Create(AOwner: TComponent); begin inherited Create(AOwner); FDateFormat := C_DefDateFormat; FDecimals := C_DefDecimals; FShowDeleted := C_DefShowDeleted; FEpoch := C_DefEpoch; FExact := C_DefExact; end; {-------------------------------------------------------------------------------} function TFDPhysADSDriverLink.GetBaseDriverID: String; begin Result := S_FD_ADSId; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSDriverLink.ApplyTo(const AParams: IFDStanDefinition); begin inherited ApplyTo(AParams); if IsDFS then AParams.AsString[S_FD_ConnParam_ADS_DateFormat] := DateFormat; if IsDS then AParams.AsInteger[S_FD_ConnParam_ADS_Decimals] := Decimals; if IsDPS then AParams.AsString[S_FD_ConnParam_ADS_DefaultPath] := DefaultPath; if IsSPS then AParams.AsString[S_FD_ConnParam_ADS_SearchPath] := SearchPath; if IsSDS then AParams.AsString[S_FD_ConnParam_ADS_ShowDeleted] := S_FD_Bools[ShowDeleted]; if IsEpS then AParams.AsInteger[S_FD_ConnParam_ADS_Epoch] := Epoch; if IsExS then AParams.AsString[S_FD_ConnParam_ADS_Exact] := S_FD_Bools[Exact]; end; {-------------------------------------------------------------------------------} function TFDPhysADSDriverLink.IsConfigured: Boolean; begin Result := inherited IsConfigured or IsDFS or IsDS or IsDPS or IsSPS or IsSDS or IsEpS or IsExS; end; {-------------------------------------------------------------------------------} function TFDPhysADSDriverLink.GetDateFormat: String; begin if DriverState in [drsLoaded, drsActive] then Result := TADSLib(DriverIntf.CliObj).DateFormat else Result := FDateFormat; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSDriverLink.SetDateFormat(const AValue: String); begin FDateFormat := AValue; if DriverState in [drsLoaded, drsActive] then TADSLib(DriverIntf.CliObj).DateFormat := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysADSDriverLink.IsDFS: Boolean; begin Result := (FDateFormat <> '') and (FDateFormat <> C_DefDateFormat); end; {-------------------------------------------------------------------------------} function TFDPhysADSDriverLink.GetDecimals: Word; begin if DriverState in [drsLoaded, drsActive] then Result := TADSLib(DriverIntf.CliObj).Decimals else Result := FDecimals; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSDriverLink.SetDecimals(const AValue: Word); begin FDecimals := AValue; if DriverState in [drsLoaded, drsActive] then TADSLib(DriverIntf.CliObj).Decimals := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysADSDriverLink.IsDS: Boolean; begin Result := (FDecimals <> C_DefDecimals) and (FDecimals <= 30); end; {-------------------------------------------------------------------------------} function TFDPhysADSDriverLink.GetDefaultPath: String; begin if DriverState in [drsLoaded, drsActive] then Result := TADSLib(DriverIntf.CliObj).DefaultPath else Result := FDefaultPath; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSDriverLink.SetDefaultPath(const AValue: String); begin FDefaultPath := AValue; if DriverState in [drsLoaded, drsActive] then TADSLib(DriverIntf.CliObj).DefaultPath := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysADSDriverLink.IsDPS: Boolean; begin Result := (FDefaultPath <> '') and (CompareText(FDefaultPath, GetCurrentDir) <> 0); end; {-------------------------------------------------------------------------------} function TFDPhysADSDriverLink.GetSearchPath: String; begin if DriverState in [drsLoaded, drsActive] then Result := TADSLib(DriverIntf.CliObj).SearchPath else Result := FSearchPath; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSDriverLink.SetSearchPath(const AValue: String); begin FSearchPath := AValue; if DriverState in [drsLoaded, drsActive] then TADSLib(DriverIntf.CliObj).SearchPath := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysADSDriverLink.IsSPS: Boolean; begin Result := (FSearchPath <> '') and (CompareText(FSearchPath, DefaultPath) <> 0); end; {-------------------------------------------------------------------------------} function TFDPhysADSDriverLink.GetShowDeleted: Boolean; begin if DriverState in [drsLoaded, drsActive] then Result := TADSLib(DriverIntf.CliObj).ShowDeleted else Result := FShowDeleted; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSDriverLink.SetShowDeleted(const AValue: Boolean); begin FShowDeleted := AValue; if DriverState in [drsLoaded, drsActive] then TADSLib(DriverIntf.CliObj).ShowDeleted := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysADSDriverLink.IsSDS: Boolean; begin Result := FShowDeleted <> C_DefShowDeleted; end; {-------------------------------------------------------------------------------} function TFDPhysADSDriverLink.GetEpoch: Word; begin if DriverState in [drsLoaded, drsActive] then Result := TADSLib(DriverIntf.CliObj).Epoch else Result := FEpoch; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSDriverLink.SetEpoch(const AValue: Word); begin FEpoch := AValue; if DriverState in [drsLoaded, drsActive] then TADSLib(DriverIntf.CliObj).Epoch := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysADSDriverLink.IsEpS: Boolean; begin Result := FEpoch <> C_DefEpoch; end; {-------------------------------------------------------------------------------} function TFDPhysADSDriverLink.GetExact: Boolean; begin if DriverState in [drsLoaded, drsActive] then Result := TADSLib(DriverIntf.CliObj).Exact else Result := FExact; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSDriverLink.SetExact(const AValue: Boolean); begin FExact := AValue; if DriverState in [drsLoaded, drsActive] then TADSLib(DriverIntf.CliObj).Exact := AValue; end; {-------------------------------------------------------------------------------} function TFDPhysADSDriverLink.IsExS: Boolean; begin Result := FExact <> C_DefExact; end; {-------------------------------------------------------------------------------} { TFDADSService } {-------------------------------------------------------------------------------} function TFDADSService.GetDriverLink: TFDPhysADSDriverLink; begin Result := inherited DriverLink as TFDPhysADSDriverLink; end; {-------------------------------------------------------------------------------} procedure TFDADSService.SetDriverLink(const AValue: TFDPhysADSDriverLink); begin inherited DriverLink := AValue; end; {-------------------------------------------------------------------------------} function TFDADSService.GetConnectionString: String; begin Result := 'DriverID=' + DriverLink.ActualDriverID + ';Database=' + Database + ';ServerTypes=Local|Remote'; if UserName <> '' then Result := Result + ';User_Name=' + UserName; if Password <> '' then Result := Result + ';Password=' + Password; end; {-------------------------------------------------------------------------------} procedure TFDADSService.GetConnection(out AConn: IFDPhysConnection; out ACmd: IFDPhysCommand); begin FDPhysManager().CreateConnection(GetConnectionString(), AConn); AConn.ErrorHandler := Self as IFDStanErrorHandler; AConn.Open; AConn.CreateCommand(ACmd); ACmd.Options.ResourceOptions.CmdExecMode := amBlocking; end; {-------------------------------------------------------------------------------} { TFDADSBackupRestore } {-------------------------------------------------------------------------------} constructor TFDADSBackupRestore.Create(AOwner: TComponent); begin inherited Create(AOwner); FInclude := TFDStringList.Create; FExclude := TFDStringList.Create; FTableTypeMap := TFDStringList.Create; FResults := TFDDatSTable.Create; FResults.CountRef; end; {-------------------------------------------------------------------------------} destructor TFDADSBackupRestore.Destroy; begin FResults.RemRef; FResults := nil; FDFreeAndNil(FInclude); FDFreeAndNil(FExclude); FDFreeAndNil(FTableTypeMap); inherited Destroy; end; {-------------------------------------------------------------------------------} procedure TFDADSBackupRestore.SetInclude(const AValue: TStrings); begin FInclude.SetStrings(AValue); end; {-------------------------------------------------------------------------------} procedure TFDADSBackupRestore.SetExclude(const AValue: TStrings); begin FExclude.SetStrings(AValue); end; {-------------------------------------------------------------------------------} procedure TFDADSBackupRestore.SetTableTypeMap(const AValue: TStrings); begin FTableTypeMap.SetStrings(AValue); end; {-------------------------------------------------------------------------------} class procedure TFDADSBackupRestore.AddOption(var AStr: String; const AName, AValue: String); begin if AStr <> '' then AStr := AStr + ';'; AStr := AStr + AName; if AValue <> '' then AStr := AStr + '=' + AValue; end; {-------------------------------------------------------------------------------} function TFDADSBackupRestore.GetOptions: String; var i: Integer; s: String; begin if Include.Count > 0 then begin s := ''; for i := 0 to Include.Count - 1 do if Trim(Include[i]) <> '' then begin if s <> '' then s := s + ', '; s := s + Include[i]; end; AddOption(Result, 'include', s); end; if Exclude.Count > 0 then begin s := ''; for i := 0 to Exclude.Count - 1 do if Trim(Exclude[i]) <> '' then begin if s <> '' then s := s + ', '; s := s + Exclude[i]; end; AddOption(Result, 'exclude', s); end; if TableTypeMap.Count > 0 then begin s := ''; for i := 0 to TableTypeMap.Count - 1 do if Trim(Exclude[i]) <> '' then begin if s <> '' then s := s + ', '; s := s + TableTypeMap[i]; end; AddOption(Result, 'TABLETYPEMAP', s); end; end; {-------------------------------------------------------------------------------} { TFDADSBackup } {-------------------------------------------------------------------------------} function TFDADSBackup.GetOptions: String; begin Result := inherited GetOptions; if boMetaOnly in Options then AddOption(Result, 'MetaOnly', ''); if boPrepareDiff in Options then AddOption(Result, 'PrepareDiff', ''); if boDiff in Options then AddOption(Result, 'Diff', ''); if ArchiveFile <> '' then if boCompressArchive in Options then AddOption(Result, 'ArchiveFileCompressed', ArchiveFile) else AddOption(Result, 'ArchiveFile', ArchiveFile); end; {-------------------------------------------------------------------------------} procedure TFDADSBackup.InternalExecute; var oConn: IFDPhysConnection; oCmd: IFDPhysCommand; begin GetConnection(oConn, oCmd); oCmd.CommandText := 'EXECUTE PROCEDURE sp_BackupDatabase(:p1, :p2)'; oCmd.Params[0].AsString := BackupPath; oCmd.Params[1].DataType := ftMemo; oCmd.Params[1].Value := GetOptions; oCmd.Prepare(); oCmd.Define(FResults); oCmd.Fetch(FResults, True, True); end; {-------------------------------------------------------------------------------} procedure TFDADSBackup.Backup; begin Execute; end; {-------------------------------------------------------------------------------} { TFDADSRestore } {-------------------------------------------------------------------------------} function TFDADSRestore.GetOptions: String; begin Result := inherited GetOptions; if roDontOverwrite in Options then AddOption(Result, 'DontOverwrite', ''); if roMetaOnly in Options then AddOption(Result, 'MetaOnly', ''); if roNoWarnings in Options then AddOption(Result, 'NoWarnings', ''); if DDPassword <> '' then AddOption(Result, 'DDPassword', DDPassword); if ArchiveFile <> '' then if roCompressedArchive in Options then AddOption(Result, 'ArchiveFileCompressed', ArchiveFile) else AddOption(Result, 'ArchiveFile', ArchiveFile); if roForceArchiveExtract in Options then AddOption(Result, 'ForceArchiveExtract', ''); end; {-------------------------------------------------------------------------------} procedure TFDADSRestore.InternalExecute; var oConn: IFDPhysConnection; oCmd: IFDPhysCommand; begin GetConnection(oConn, oCmd); oCmd.CommandText := 'EXECUTE PROCEDURE sp_RestoreDatabase(:p1, :p2, :p3, :p4)'; oCmd.Params[0].AsString := SourcePath; oCmd.Params[1].AsString := SourcePassword; oCmd.Params[2].AsString := DestinationPath; oCmd.Params[3].DataType := ftMemo; oCmd.Params[3].Value := GetOptions; oCmd.Prepare(); oCmd.Define(FResults); oCmd.Fetch(FResults, True, True); end; {-------------------------------------------------------------------------------} procedure TFDADSRestore.Restore; begin Execute; end; {-------------------------------------------------------------------------------} { TFDADSUtility } {-------------------------------------------------------------------------------} constructor TFDADSUtility.Create(AOwner: TComponent); begin inherited Create(AOwner); FTables := TFDStringList.Create; end; {-------------------------------------------------------------------------------} destructor TFDADSUtility.Destroy; begin FDFreeAndNil(FTables); inherited Destroy; end; {-------------------------------------------------------------------------------} function TFDADSUtility.GetConnectionString: String; var s: String; begin Result := inherited GetConnectionString; case TableType of ttCDX: s := S_FD_CDX; ttVFP: s := S_FD_VFP; ttADT: s := S_FD_ADT; ttNTX: s := S_FD_NTX; end; if s <> '' then Result := Result + ';TableType=' + s; end; {-------------------------------------------------------------------------------} procedure TFDADSUtility.SetTables(const AValue: TStrings); begin FTables.SetStrings(AValue); end; {-------------------------------------------------------------------------------} procedure TFDADSUtility.Encrypt; begin FMode := umEncrypt; Execute; end; {-------------------------------------------------------------------------------} procedure TFDADSUtility.Decrypt; begin FMode := umDecrypt; Execute; end; {-------------------------------------------------------------------------------} procedure TFDADSUtility.Pack; begin FMode := umPack; Execute; end; {-------------------------------------------------------------------------------} procedure TFDADSUtility.Zap; begin FMode := umZap; Execute; end; {-------------------------------------------------------------------------------} procedure TFDADSUtility.Recall; begin FMode := umRecall; Execute; end; {-------------------------------------------------------------------------------} procedure TFDADSUtility.Reindex; begin FMode := umReindex; Execute; end; {-------------------------------------------------------------------------------} procedure TFDADSUtility.InternalExecute; var oConn: IFDPhysConnection; oCmd: IFDPhysCommand; oMetaCmd: IFDPhysMetaInfoCommand; oTab: TADSTable; oNames: TStrings; i: Integer; oSTab: TFDDatSTable; oDict: TADSDictionary; sPath: String; begin GetConnection(oConn, oCmd); oNames := Tables; try oDict := TADSDictionary.Create(TADSConnection(oConn.CliObj)); try if not oDict.HasDictionary then sPath := TADSConnection(oConn.CliObj).ConnectionPath else sPath := ''; finally FDFree(oDict); end; if oNames.Count = 0 then begin oNames := TFDStringList.Create; oSTab := TFDDatSTable.Create; try oConn.CreateMetaInfoCommand(oMetaCmd); oMetaCmd.MetaInfoKind := mkTables; if sPath <> '' then oMetaCmd.CatalogName := sPath; oMetaCmd.TableKinds := [tkTable]; oMetaCmd.ObjectScopes := [osMy, osOther]; oMetaCmd.Open(True); oMetaCmd.Define(oSTab); oMetaCmd.Fetch(oSTab, True); for i := 0 to oSTab.Rows.Count - 1 do oNames.Add(oSTab.Rows[i].AsString['TABLE_NAME']); finally FDFree(oSTab); end; end; oTab := TADSTable.Create(TADSConnection(oConn.CliObj), Self); try for i := 0 to oNames.Count - 1 do begin oTab.Close; oTab.Options := ADS_EXCLUSIVE; oTab.TableName := FDNormPath(sPath) + oNames[i]; oTab.TableType := TableType; oTab.Open; if TablePassword <> '' then oTab.EnableEncryption(TablePassword); case FMode of umEncrypt: if not oTab.IsEncrypted then oTab.Encrypt; umDecrypt: if oTab.IsEncrypted then oTab.Decrypt; umPack: oTab.Pack; umZap: oTab.Zap; umReindex: oTab.Reindex; umRecall: oTab.RecallAll; end; if Assigned(OnProgress) then OnProgress(Self, oTab.TableName); end; finally FDFree(oTab); end; finally if oNames <> Tables then FDFree(oNames); end; end; {-------------------------------------------------------------------------------} { TFDPhysADSDriver } {-------------------------------------------------------------------------------} constructor TFDPhysADSDriver.Create(AManager: TFDPhysManager; const ADriverDef: IFDStanDefinition); begin inherited Create(AManager, ADriverDef); FLib := TADSLib.Create(FDPhysManagerObj); end; {-------------------------------------------------------------------------------} destructor TFDPhysADSDriver.Destroy; begin inherited Destroy; FDFreeAndNil(FLib); end; {-------------------------------------------------------------------------------} class function TFDPhysADSDriver.GetBaseDriverID: String; begin Result := S_FD_ADSId; end; {-------------------------------------------------------------------------------} class function TFDPhysADSDriver.GetBaseDriverDesc: String; begin Result := 'Advantage Database Server'; end; {-------------------------------------------------------------------------------} class function TFDPhysADSDriver.GetRDBMSKind: TFDRDBMSKind; begin Result := TFDRDBMSKinds.Advantage; end; {-------------------------------------------------------------------------------} class function TFDPhysADSDriver.GetConnectionDefParamsClass: TFDConnectionDefParamsClass; begin Result := TFDPhysADSConnectionDefParams; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSDriver.InternalLoad; var sHome, sLib: String; begin sHome := ''; sLib := ''; GetVendorParams(sHome, sLib); FLib.Load(sHome, sLib); if Params <> nil then begin if Params.OwnValue(S_FD_ConnParam_ADS_DateFormat) then FLib.DateFormat := Params.AsString[S_FD_ConnParam_ADS_DateFormat]; if Params.OwnValue(S_FD_ConnParam_ADS_Decimals) then FLib.Decimals := Params.AsInteger[S_FD_ConnParam_ADS_Decimals]; if Params.OwnValue(S_FD_ConnParam_ADS_DefaultPath) then FLib.DefaultPath := Params.AsString[S_FD_ConnParam_ADS_DefaultPath]; if Params.OwnValue(S_FD_ConnParam_ADS_SearchPath) then FLib.SearchPath := Params.AsString[S_FD_ConnParam_ADS_SearchPath]; if Params.OwnValue(S_FD_ConnParam_ADS_ShowDeleted) then FLib.ShowDeleted := Params.AsBoolean[S_FD_ConnParam_ADS_ShowDeleted]; if Params.OwnValue(S_FD_ConnParam_ADS_Epoch) then FLib.Epoch := Params.AsInteger[S_FD_ConnParam_ADS_Epoch]; if Params.OwnValue(S_FD_ConnParam_ADS_Exact) then FLib.Exact := Params.AsBoolean[S_FD_ConnParam_ADS_Exact]; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSDriver.InternalUnload; begin FLib.Unload; end; {-------------------------------------------------------------------------------} function TFDPhysADSDriver.InternalCreateConnection( AConnHost: TFDPhysConnectionHost): TFDPhysConnection; begin Result := TFDPhysADSConnection.Create(Self, AConnHost); end; {-------------------------------------------------------------------------------} function TFDPhysADSDriver.GetCliObj: Pointer; begin Result := FLib; end; {-------------------------------------------------------------------------------} function TFDPhysADSDriver.GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable; var oView: TFDDatSView; oList: TFDStringList; begin Result := inherited GetConnParams(AKeys, AParams); oView := Result.Select('Name=''' + S_FD_ConnParam_Common_Database + ''''); if oView.Rows.Count = 1 then begin oView.Rows[0].BeginEdit; oView.Rows[0].SetValues('Type', '@F:Advantage Dictionary|*.add'); oView.Rows[0].SetValues('LoginIndex', 2); oView.Rows[0].EndEdit; end; Employ; try oList := TFDStringList.Create(#0, ';'); try FLib.ListAliases(oList); Result.Rows.Add([Unassigned, S_FD_ConnParam_ADS_Alias, oList.DelimitedText, '', S_FD_ConnParam_ADS_Alias, -1]); Result.Rows.Add([Unassigned, S_FD_ConnParam_ADS_ServerTypes, S_FD_Remote + ';' + S_FD_Local + ';' + S_FD_Internet, '', S_FD_ConnParam_ADS_ServerTypes, -1]); Result.Rows.Add([Unassigned, S_FD_ConnParam_ADS_Protocol, S_FD_UDP + ';' + S_FD_IPX + ';' + S_FD_TCPIP + ';' + S_FD_TLS, '', S_FD_ConnParam_ADS_Protocol, -1]); FLib.ListServers(oList); Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_Server, oList.DelimitedText, '', S_FD_ConnParam_Common_Server, -1]); Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_Port, '@I', '', S_FD_ConnParam_Common_Port, -1]); Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_CharacterSet, C_AdsCharTypeMap, 'ANSI', S_FD_ConnParam_Common_CharacterSet, -1]); Result.Rows.Add([Unassigned, S_FD_ConnParam_ADS_Compress, S_FD_Internet + ';' + S_FD_Always + ';' + S_FD_Never, '', S_FD_ConnParam_ADS_Compress, -1]); Result.Rows.Add([Unassigned, S_FD_ConnParam_ADS_TableType, S_FD_Default + ';' + S_FD_CDX + ';' + S_FD_VFP + ';' + S_FD_ADT + ';' + S_FD_NTX, S_FD_Default, S_FD_ConnParam_ADS_TableType, -1]); Result.Rows.Add([Unassigned, S_FD_ConnParam_ADS_TablePassword, '@S', '', S_FD_ConnParam_ADS_TablePassword, -1]); Result.Rows.Add([Unassigned, S_FD_ConnParam_ADS_Locking, S_FD_Proprietary + ';' + S_FD_Compatible, '', S_FD_ConnParam_ADS_Locking, -1]); Result.Rows.Add([Unassigned, S_FD_ConnParam_ADS_ADSAdvanced, '@S', '', S_FD_ConnParam_ADS_ADSAdvanced, -1]); Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaDefCatalog, '@S', '', S_FD_ConnParam_Common_MetaDefCatalog, -1]); Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaCurCatalog, '@S', '', S_FD_ConnParam_Common_MetaCurCatalog, -1]); finally FDFree(oList); end; finally Vacate; end; end; {-------------------------------------------------------------------------------} { TFDPhysADSConnection } {-------------------------------------------------------------------------------} constructor TFDPhysADSConnection.Create(ADriverObj: TFDPhysDriver; AConnHost: TFDPhysConnectionHost); begin inherited Create(ADriverObj, AConnHost); FTablePasswords := TFDStringList.Create(#0, ';'); end; {-------------------------------------------------------------------------------} destructor TFDPhysADSConnection.Destroy; begin FDFreeAndNil(FTablePasswords); inherited Destroy; end; {-------------------------------------------------------------------------------} function TFDPhysADSConnection.InternalCreateTransaction: TFDPhysTransaction; begin Result := TFDPhysADSTransaction.Create(Self); end; {-------------------------------------------------------------------------------} function TFDPhysADSConnection.InternalCreateEvent(const AEventKind: String): TFDPhysEventAlerter; var oConnMeta: IFDPhysConnectionMetadata; begin CreateMetadata(oConnMeta); if (oConnMeta.ServerVersion >= caADS10) and (CompareText(AEventKind, S_FD_EventKind_ADS_Events) = 0) then Result := TFDPhysADSEventAlerter.Create(Self, AEventKind) else Result := nil; end; {-------------------------------------------------------------------------------} function TFDPhysADSConnection.InternalCreateCommand: TFDPhysCommand; begin Result := TFDPhysADSCommand.Create(Self); end; {-------------------------------------------------------------------------------} function TFDPhysADSConnection.InternalCreateCommandGenerator( const ACommand: IFDPhysCommand): TFDPhysCommandGenerator; begin if ACommand <> nil then Result := TFDPhysADSCommandGenerator.Create(ACommand) else Result := TFDPhysADSCommandGenerator.Create(Self); end; {-------------------------------------------------------------------------------} function TFDPhysADSConnection.InternalCreateMetadata: TObject; begin Result := TFDPhysADSMetadata.Create(Self, FServerVersion, TFDPhysADSDriver(DriverObj).FLib.Version, not FDictionary.HasDictionary); end; {-------------------------------------------------------------------------------} {$IFDEF FireDAC_Monitor} procedure TFDPhysADSConnection.InternalTracingChanged; begin if FConnection <> nil then begin FConnection.Monitor := FMonitor; FConnection.Tracing := FTracing; end; end; {$ENDIF} {-------------------------------------------------------------------------------} function TFDPhysADSConnection.BuildServerTypes(const AConnDef: IFDStanConnectionDef): Integer; const C_PS: TFDParseFmtSettings = (FDelimiter: '|'; FQuote: #0; FQuote1: #0; FQuote2: #0); var s, sType: String; i, iCode: Integer; begin Result := 0; if AConnDef.HasValue(S_FD_ConnParam_ADS_ServerTypes) then begin s := Trim(AConnDef.AsString[S_FD_ConnParam_ADS_ServerTypes]); Val(s, Result, iCode); if iCode <> 0 then begin i := 1; while i <= Length(s) do begin sType := Trim(FDExtractFieldName(s, i, C_PS)); if CompareText(sType, S_FD_Remote) = 0 then Result := Result or ADS_REMOTE_SERVER else if CompareText(sType, S_FD_Local) = 0 then Result := Result or ADS_LOCAL_SERVER else if CompareText(sType, S_FD_Internet) = 0 then Result := Result or ADS_AIS_SERVER; end; end; end; end; {-------------------------------------------------------------------------------} function TFDPhysADSConnection.Build60Options(const AConnDef: IFDStanConnectionDef): Integer; var s: String; begin Result := 0; if AConnDef.HasValue(S_FD_ConnParam_ADS_Protocol) then begin s := AConnDef.AsString[S_FD_ConnParam_ADS_Protocol]; if CompareText(s, S_FD_UDP) = 0 then Result := Result or ADS_UDP_IP_CONNECTION else if CompareText(s, S_FD_IPX) = 0 then Result := Result or ADS_IPX_CONNECTION else if CompareText(s, S_FD_TCPIP) = 0 then Result := Result or ADS_TCP_IP_CONNECTION else if CompareText(s, S_FD_TLS) = 0 then Result := Result or ADS_TLS_CONNECTION; end; if AConnDef.HasValue(S_FD_ConnParam_ADS_Compress) then begin s := AConnDef.AsString[S_FD_ConnParam_ADS_Compress]; if CompareText(s, S_FD_Internet) = 0 then Result := Result or ADS_COMPRESS_INTERNET else if CompareText(s, S_FD_Always) = 0 then Result := Result or ADS_COMPRESS_ALWAYS else if CompareText(s, S_FD_Never) = 0 then Result := Result or ADS_COMPRESS_NEVER; end; end; {-------------------------------------------------------------------------------} function TFDPhysADSConnection.BuildConnectionPath(const AConnDef: IFDStanConnectionDef): String; var i: Integer; oParams: TFDPhysADSConnectionDefParams; begin Result := ''; oParams := TFDPhysADSConnectionDefParams(AConnDef.Params); if AConnDef.HasValue(S_FD_ConnParam_Common_Server) then begin Result := oParams.Server; if (Result <> '') and (Copy(Result, 1, 2) <> '//') and (Copy(Result, 1, 2) <> '\\') then Result := '//' + Result; if AConnDef.HasValue(S_FD_ConnParam_Common_Port) then begin i := Pos(':', Result); if i <> 0 then Result := Copy(Result, 1, i - 1); if oParams.Port <> 0 then Result := Result + ':' + IntToStr(oParams.Port); end; end; if AConnDef.HasValue(S_FD_ConnParam_Common_Database) or (FAliasPath <> '') then begin if (Result <> '') and (Copy(Result, Length(Result), 1) <> '/') and (Copy(Result, Length(Result), 1) <> '\') then Result := Result + '/'; if oParams.Database <> '' then Result := Result + oParams.Database else if FAliasPath <> '' then Result := Result + FAliasPath; end; end; {-------------------------------------------------------------------------------} function TFDPhysADSConnection.BuildADS101ConnectString(const AConnDef: IFDStanConnectionDef): String; procedure Add(const AParam, AValue: String); begin if Result <> '' then Result := Result + ';'; Result := Result + AParam + '=' + AValue; end; var oParams: TFDPhysADSConnectionDefParams; s: String; begin Result := ''; oParams := TFDPhysADSConnectionDefParams(AConnDef.Params); s := IntToStr(BuildServerTypes(AConnDef)); if s <> '0' then Add('ServerType', s); s := ''; if AConnDef.HasValue(S_FD_ConnParam_ADS_Protocol) then case oParams.Protocol of prUDP: s := 'UDP_IP'; prIPX: s := 'IPX'; prTCPIP: s := 'TCP_IP'; prTLS: s := 'TLS'; end; if s <> '' then Add('CommType', s); s := BuildConnectionPath(AConnDef); if s <> '' then Add('Data Source', s); if AConnDef.HasValue(S_FD_ConnParam_Common_UserName) then Add('User ID', oParams.UserName); if AConnDef.HasValue(S_FD_ConnParam_Common_Password) then Add('Password', oParams.Password); if AConnDef.HasValue(S_FD_ConnParam_Common_CharacterSet) then Add('CharType', AConnDef.AsString[S_FD_ConnParam_Common_CharacterSet]); if AConnDef.HasValue(S_FD_ConnParam_ADS_Compress) then Add('Compression', AConnDef.AsString[S_FD_ConnParam_ADS_Compress]); if AConnDef.HasValue(S_FD_ConnParam_ADS_TableType) then Add('TableType', AConnDef.AsString[S_FD_ConnParam_ADS_TableType]) else if FAliasTableType <> '' then Add('TableType', FAliasTableType); if AConnDef.HasValue(S_FD_ConnParam_ADS_Locking) then Add('LockMode', AConnDef.AsString[S_FD_ConnParam_ADS_Locking]); if AConnDef.HasValue(S_FD_ConnParam_ADS_ADSAdvanced) then Result := Result + ';' + oParams.ADSAdvanced; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSConnection.BaseConnect(AConn: TADSConnection; const AConnDef: IFDStanConnectionDef); var oParams: TFDPhysADSConnectionDefParams; begin oParams := TFDPhysADSConnectionDefParams(AConnDef.Params); if AConnDef.HasValue(S_FD_ConnParam_ADS_Alias) then AConn.Lib.ResolveAlias(oParams.Alias, FAliasPath, FAliasTableType) else begin FAliasPath := ''; FAliasTableType := ''; end; if Assigned(AConn.Lib.FAdsConnect101) then AConn.Connect101(BuildADS101ConnectString(AConnDef)) else begin AConn.Connect60(BuildConnectionPath(AConnDef), BuildServerTypes(AConnDef), oParams.UserName, oParams.Password, Build60Options(AConnDef)); if AConnDef.HasValue(S_FD_ConnParam_Common_CharacterSet) then AConn.Collation := AConnDef.AsString[S_FD_ConnParam_Common_CharacterSet]; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSConnection.LoadPasswords; var oMetaCmd: IFDPhysMetaInfoCommand; oSTab: TFDDatSTable; i: Integer; sPwd: String; ePrevState: TFDPhysConnectionState; begin FTablePasswords.DelimitedText := ConnectionDef.AsString[S_FD_ConnParam_ADS_TablePassword]; if (FTablePasswords.Count = 1) and (FTablePasswords.ValueFromIndex[0] = '') then begin oSTab := TFDDatSTable.Create; ePrevState := FState; try FState := csConnected; CreateMetaInfoCommand(oMetaCmd); oMetaCmd.MetaInfoKind := mkTables; if not FDictionary.HasDictionary then oMetaCmd.CatalogName := FConnection.ConnectionPath; oMetaCmd.TableKinds := [tkTable]; oMetaCmd.ObjectScopes := [osMy, osOther]; oMetaCmd.Open(True); oMetaCmd.Define(oSTab); oMetaCmd.Fetch(oSTab, True); sPwd := FTablePasswords[0]; FTablePasswords.Clear; for i := 0 to oSTab.Rows.Count - 1 do FTablePasswords.AddPair(FDExtractFileNameNoPath(oSTab.Rows[i].AsString['TABLE_NAME']), sPwd); finally FState := ePrevState; FDFree(oSTab); end; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSConnection.InternalConnect; var pCliHandles: PFDPhysADSCliHandles; oParams: TFDPhysADSConnectionDefParams; begin oParams := ConnectionDef.Params as TFDPhysADSConnectionDefParams; if InternalGetSharedCliHandle() <> nil then begin pCliHandles := PFDPhysADSCliHandles(InternalGetSharedCliHandle()); FConnection := TADSConnection.CreateUsingHandle(TFDPhysADSDriver(DriverObj).FLib, pCliHandles^[0], Self); end else FConnection := TADSConnection.Create(TFDPhysADSDriver(DriverObj).FLib, Self); {$IFDEF FireDAC_MONITOR} InternalTracingChanged; {$ENDIF} if InternalGetSharedCliHandle() = nil then begin BaseConnect(FConnection, ConnectionDef); if oParams.NewPassword <> '' then InternalExecuteDirect('EXECUTE PROCEDURE sp_ModifyUserProperty(''' + oParams.UserName + ''', ''USER_PASSWORD'', ''' + oParams.NewPassword + '''', nil); end; FDictionary := TADSDictionary.Create(FConnection); FServerVersion := FConnection.ServerVersion; LoadPasswords; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSConnection.InternalSetMeta; var sName: String; begin inherited InternalSetMeta; sName := FConnection.ConnectionPath; if FCurrentCatalog = '' then FCurrentCatalog := sName; if FDefaultCatalog = '' then FDefaultCatalog := sName; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSConnection.InternalDisconnect; begin FDFreeAndNil(FDictionary); FDFreeAndNil(FConnection); end; {-------------------------------------------------------------------------------} procedure TFDPhysADSConnection.InternalPing; begin FConnection.Ping; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSConnection.InternalChangePassword(const AUserName, AOldPassword, ANewPassword: String); var oConnDef: IFDStanConnectionDef; oConn: TADSConnection; oStmt: TADSStatement; begin FDCreateInterface(IFDStanConnectionDef, oConnDef); oConnDef.ParentDefinition := ConnectionDef; oConnDef.Params.UserName := AUserName; oConnDef.Params.Password := AOldPassword; oConn := TADSConnection.Create(TFDPhysADSDriver(DriverObj).FLib, Self); oStmt := TADSStatement.Create(oConn, Self); try BaseConnect(oConn, oConnDef); oStmt.ExecuteDirect('EXECUTE PROCEDURE sp_ModifyUserProperty(''' + AUserName + ''', ''USER_PASSWORD'', ''' + ANewPassword + ''''); finally FDFree(oStmt); FDFree(oConn); end; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSConnection.InternalExecuteDirect(const ASQL: String; ATransaction: TFDPhysTransaction); var oStmt: TADSStatement; begin oStmt := TADSStatement.Create(FConnection, Self); try oStmt.ExecuteDirect(ASQL); finally FDFree(oStmt); end; end; {-------------------------------------------------------------------------------} function TFDPhysADSConnection.GetLastAutoGenValue(const AName: String): Variant; var iLastAutoInc: Cardinal; begin if (FConnection <> nil) and (AName = '') then begin iLastAutoInc := FConnection.LastAutoInc; if iLastAutoInc = 0 then Result := FLastAutoGenValue else Result := iLastAutoInc end else Result := inherited GetLastAutoGenValue(AName); end; {-------------------------------------------------------------------------------} function TFDPhysADSConnection.GetItemCount: Integer; begin Result := inherited GetItemCount; if DriverObj.State in [drsLoaded, drsActive] then begin Inc(Result, 2); if FConnection <> nil then Inc(Result, 3); end; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSConnection.GetItem(AIndex: Integer; out AName: String; out AValue: Variant; out AKind: TFDMoniAdapterItemKind); begin if AIndex < inherited GetItemCount then inherited GetItem(AIndex, AName, AValue, AKind) else case AIndex - inherited GetItemCount of 0: begin AName := 'Client version'; AValue := Integer(TFDPhysADSDriver(DriverObj).FLib.Version); AKind := ikClientInfo; end; 1: begin AName := 'Client DLL name'; AValue := TFDPhysADSDriver(DriverObj).FLib.DLLName; AKind := ikClientInfo; end; 2: begin AName := 'Server version'; AValue := FConnection.ServerVersionStr; AKind := ikSessionInfo; end; 3: begin AName := 'Server collation'; AValue := FConnection.Collation; AKind := ikSessionInfo; end; 4: begin AName := 'Connection path'; AValue := FConnection.ConnectionPath; AKind := ikSessionInfo; end; end; end; {-------------------------------------------------------------------------------} function TFDPhysADSConnection.GetMessages: EFDDBEngineException; begin Result := nil; end; {-------------------------------------------------------------------------------} function TFDPhysADSConnection.GetCliObj: Pointer; begin Result := FConnection; end; {-------------------------------------------------------------------------------} function TFDPhysADSConnection.InternalGetCliHandle: Pointer; begin if FConnection <> nil then begin FCliHandles[0] := FConnection.Handle; Result := @FCliHandles; end else Result := nil; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSConnection.InternalAnalyzeSession(AMessages: TStrings); var oConnMeta: IFDPhysConnectionMetadata; begin inherited InternalAnalyzeSession(AMessages); CreateMetadata(oConnMeta); // 2. The minimal Advantage server version is 10.0 if (oConnMeta.ServerVersion > 0) and (oConnMeta.ServerVersion < caADS10) then AMessages.Add(Format(S_FD_ADSWarnMinAdvantageVer, [FDVerInt2Str(oConnMeta.ServerVersion)])); // 3. The minimal ACE version is 10.0 if (oConnMeta.ClientVersion > 0) and (oConnMeta.ClientVersion < caADS10) then AMessages.Add(Format(S_FD_ADSWarnMinACEVer, [FDVerInt2Str(oConnMeta.ClientVersion)])); end; {-------------------------------------------------------------------------------} { TFDPhysADSTransaction } {-------------------------------------------------------------------------------} procedure TFDPhysADSTransaction.InternalStartTransaction(ATxID: LongWord); begin TFDPhysADSConnection(ConnectionObj).InternalExecuteDirect( 'BEGIN TRANSACTION; SAVEPOINT ' + 't_' + IntToStr(ATxID), Self); end; {-------------------------------------------------------------------------------} procedure TFDPhysADSTransaction.InternalCommit(ATxID: LongWord); begin TFDPhysADSConnection(ConnectionObj).InternalExecuteDirect( 'COMMIT', Self); end; {-------------------------------------------------------------------------------} procedure TFDPhysADSTransaction.InternalRollback(ATxID: LongWord); begin if GetNestingLevel = 1 then TFDPhysADSConnection(ConnectionObj).InternalExecuteDirect( 'ROLLBACK', Self) else TFDPhysADSConnection(ConnectionObj).InternalExecuteDirect( 'ROLLBACK TO SAVEPOINT ' + 't_' + IntToStr(ATxID), Self); end; {-------------------------------------------------------------------------------} procedure TFDPhysADSTransaction.InternalChanged; var s: String; begin // ADS does not support transaction modes, only autocommit on/off if xoAutoCommit in GetOptions.Changed then begin if GetOptions.AutoCommit then s := 'ON' else s := 'OFF'; TFDPhysADSConnection(ConnectionObj).InternalExecuteDirect( 'SET TRANSACTION AUTOCOMMIT_' + s, nil); end; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSTransaction.InternalCheckState(ACommandObj: TFDPhysCommand; ASuccess: Boolean); var oStmt: TADSStatement; oCrs: TADSCursor; iTrans, iSize: Integer; lActive: Boolean; begin if ASuccess and (TFDPhysADSCommand(ACommandObj).GetCommandKind in [skStartTransaction, skCommit, skRollback]) then begin oStmt := TADSStatement.Create(TFDPhysADSConnection(ConnectionObj).FConnection, Self); oCrs := nil; try // Local server ignores transaction control commands. // So, the ::conn.TransactionCount is always zero. oStmt.ExecuteDirect('SELECT ::conn.TransactionCount FROM system.iota'); oCrs := oStmt.GetCursor; oCrs.AddColumns; oCrs.Columns[0].GetData(@iTrans, iSize); lActive := (iTrans > 0); if GetActive <> lActive then if lActive then TransactionStarted else TransactionFinished; finally FDFree(oCrs); FDFree(oStmt); end; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSTransaction.InternalNotify( ANotification: TFDPhysTxNotification; ACommandObj: TFDPhysCommand); begin // ADS does not invalidate open cursors after explicit // transaction control commands inherited InternalNotify(ANotification, ACommandObj); end; {-------------------------------------------------------------------------------} { TFDPhysADSEventThread } {-------------------------------------------------------------------------------} type TFDPhysADSEventThread = class(TThread) private [weak] FAlerter: TFDPhysADSEventAlerter; protected procedure Execute; override; public constructor Create(AAlerter: TFDPhysADSEventAlerter); destructor Destroy; override; end; {-------------------------------------------------------------------------------} constructor TFDPhysADSEventThread.Create(AAlerter: TFDPhysADSEventAlerter); begin inherited Create(False); FAlerter := AAlerter; FreeOnTerminate := True; end; {-------------------------------------------------------------------------------} destructor TFDPhysADSEventThread.Destroy; begin FAlerter.FWaitThread := nil; inherited Destroy; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSEventThread.Execute; begin while not Terminated and FAlerter.IsRunning do try FAlerter.FWaitCommand.Open; if not Terminated then FAlerter.DoFired; except on E: EFDDBEngineException do if E.Kind <> ekCmdAborted then begin Terminate; FAlerter.AbortJob; end; end; end; {-------------------------------------------------------------------------------} { TFDPhysADSEventMessage } {-------------------------------------------------------------------------------} type TFDPhysADSEventMessage = class(TFDPhysEventMessage) private FName: String; FCount: Integer; FMessage: String; public constructor Create(const AName: String; ACount: Integer; const AMessage: String); end; {-------------------------------------------------------------------------------} constructor TFDPhysADSEventMessage.Create(const AName: String; ACount: Integer; const AMessage: String); begin inherited Create; FName := AName; FCount := ACount; FMessage := AMessage; end; {-------------------------------------------------------------------------------} { TFDPhysADSEventAlerter } {-------------------------------------------------------------------------------} const C_WakeUpEvent = C_FD_SysNamePrefix + 'WAKEUP'; C_SignalEventProc = C_FD_SysNamePrefix + '_SIGNALEVENT'; procedure TFDPhysADSEventAlerter.InternalAllocHandle; begin FWaitConnection := GetConnection.Clone; if FWaitConnection.State = csDisconnected then FWaitConnection.Open; FWaitConnection.CreateCommand(FWaitCommand); SetupCommand(FWaitCommand); FTab := TFDDatSTable.Create; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSEventAlerter.DoFired; var i: Integer; oRow: TFDDatSRow; begin try if FTab.Columns.Count = 0 then FWaitCommand.Define(FTab); FWaitCommand.Fetch(FTab); for i := 0 to FTab.Rows.Count - 1 do begin oRow := FTab.Rows[i]; if (oRow.GetData(1) <> 0) and (CompareText(oRow.GetData(0), C_WakeUpEvent) <> 0) then FMsgThread.EnqueueMsg(TFDPhysADSEventMessage.Create( oRow.GetData(0), oRow.GetData(1), VarToStr(oRow.GetData(2)))); end; finally FTab.Clear; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSEventAlerter.InternalHandle( AEventMessage: TFDPhysEventMessage); var oEventMsg: TFDPhysADSEventMessage; begin oEventMsg := TFDPhysADSEventMessage(AEventMessage); InternalHandleEvent(oEventMsg.FName, oEventMsg.FMessage); end; {-------------------------------------------------------------------------------} procedure TFDPhysADSEventAlerter.InternalAbortJob; begin if FWaitThread <> nil then begin FWaitThread.Terminate; InternalSignal(C_WakeUpEvent, Null); FWaitCommand.AbortJob(True); while (FWaitThread <> nil) and (FWaitThread.ThreadID <> TThread.Current.ThreadID) do Sleep(1); end; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSEventAlerter.InternalRegister; var i: Integer; begin FWaitCommand.CommandText := 'SELECT 1 FROM system.storedprocedures WHERE UPPER(Name) = ''' + C_SignalEventProc + ''''; FWaitCommand.Open; FWaitCommand.Define(FTab); FWaitCommand.Fetch(FTab); if FTab.Rows.Count = 0 then begin FWaitCommand.Prepare('CREATE PROCEDURE ' + C_SignalEventProc + ' (AEvNm CHAR(200), AWFC LOGICAL, AEvDt MEMO)' + ' BEGIN' + ' DECLARE @AEvNm CHAR(200), @AWFC LOGICAL, @AEvDt MEMO;' + ' @AEvNm = (SELECT A.AEvNm FROM __INPUT A);' + ' @AWFC = (SELECT A.AWFC FROM __INPUT A);' + ' @AEvDt = (SELECT A.AEvDt FROM __INPUT A);' + ' EXECUTE PROCEDURE sp_SignalEvent(@AEvNm, @AWFC, 0, @AEvDt);' + ' END;'); FWaitCommand.Execute(); end; FTab.Reset; FWaitCommand.CommandText := 'EXECUTE PROCEDURE sp_CreateEvent(:EventName, 2)'; FWaitCommand.Params[0].DataType := ftString; FWaitCommand.Prepare; FWaitCommand.Params[0].AsString := C_WakeUpEvent; FWaitCommand.Execute(); for i := 0 to GetNames.Count - 1 do begin FWaitCommand.Params[0].AsString := GetNames()[i]; FWaitCommand.Execute(); end; FWaitCommand.CommandText := 'SELECT * FROM (EXECUTE PROCEDURE sp_WaitForAnyEvent(-1, 0, 0)) A'; FWaitCommand.Prepare; FWaitThread := TFDPhysADSEventThread.Create(Self); end; {-------------------------------------------------------------------------------} procedure TFDPhysADSEventAlerter.InternalUnregister; begin FWaitThread := nil; if FWaitCommand <> nil then try FWaitCommand.Prepare('EXECUTE PROCEDURE sp_DropAllEvents(0)'); FWaitCommand.Execute(); except // hide exception end; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSEventAlerter.InternalReleaseHandle; begin FDFreeAndNil(FTab); FWaitCommand := nil; FWaitConnection := nil; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSEventAlerter.InternalSignal(const AEvent: String; const AArgument: Variant); var oCmd: IFDPhysCommand; sCmd: String; begin sCmd := 'EXECUTE PROCEDURE ' + C_SignalEventProc + '(' + QuotedStr(AEvent) + ', true'; if VarIsNull(AArgument) or VarIsEmpty(AArgument) then sCmd := sCmd + ', NULL' else sCmd := sCmd + ', ' + QuotedStr(VarToStr(AArgument)); sCmd := sCmd + ')'; GetConnection.CreateCommand(oCmd); SetupCommand(oCmd); oCmd.Prepare(sCmd); oCmd.Execute(); end; {-------------------------------------------------------------------------------} { TFDPhysADSCommand } {-------------------------------------------------------------------------------} constructor TFDPhysADSCommand.Create(AConnection: TFDPhysConnection); begin inherited Create(AConnection); FMetaEncoder := TFDEncoder.Create(nil); FMetaEncoder.Encoding := ecANSI; end; {-------------------------------------------------------------------------------} destructor TFDPhysADSCommand.Destroy; begin FDFreeAndNil(FMetaEncoder); inherited Destroy; end; {-------------------------------------------------------------------------------} function TFDPhysADSCommand.GetConnection: TFDPhysADSConnection; begin Result := TFDPhysADSConnection(FConnectionObj); end; {-------------------------------------------------------------------------------} function TFDPhysADSCommand.GetCliObj: Pointer; begin Result := FStmt; end; {-------------------------------------------------------------------------------} function TFDPhysADSCommand.UseExecDirect: Boolean; begin Result := (FOptions.ResourceOptions.DirectExecute or (GetCommandKind in [skSet, skSetSchema, skCreate, skDrop, skAlter, skOther, skStartTransaction, skCommit, skRollback])) and (GetParams.Count = 0); end; {-------------------------------------------------------------------------------} procedure TFDPhysADSCommand.SetupStatementDataAccess(AStmt: TADSStatement); var s: String; begin if ADSConnection.ConnectionDef.HasValue(S_FD_ConnParam_ADS_TableType) or (ADSConnection.FAliasTableType <> '') then begin s := ADSConnection.ConnectionDef.AsString[S_FD_ConnParam_ADS_TableType]; if s = '' then s := ADSConnection.FAliasTableType; if CompareText(s, S_FD_ADT) = 0 then AStmt.TableType := ttADT else if CompareText(s, S_FD_VFP) = 0 then AStmt.TableType := ttVFP else if CompareText(s, S_FD_CDX) = 0 then AStmt.TableType := ttCDX else if CompareText(s, S_FD_NTX) = 0 then AStmt.TableType := ttNTX; end; if ADSConnection.ConnectionDef.HasValue(S_FD_ConnParam_ADS_Locking) then begin s := ADSConnection.ConnectionDef.AsString[S_FD_ConnParam_ADS_Locking]; if CompareText(s, S_FD_Proprietary) = 0 then AStmt.LockType := ltProprietary else if CompareText(s, S_FD_Compatible) = 0 then AStmt.LockType := ltCompatible; end; if ADSConnection.ConnectionDef.HasValue(S_FD_ConnParam_Common_CharacterSet) then AStmt.Collation := ADSConnection.ConnectionDef.AsString[S_FD_ConnParam_Common_CharacterSet]; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSCommand.SetupStatementPasswords(AStmt: TADSStatement); var oPwds: TStrings; i: Integer; begin oPwds := ADSConnection.FTablePasswords; if (oPwds.Count = 1) and (oPwds.ValueFromIndex[0] = '') then begin if GetSourceObjectName <> '' then AStmt.SetTablePassword(GetSourceObjectName, oPwds[0]) else if GetSourceRecordSetName <> '' then AStmt.SetTablePassword(GetSourceRecordSetName, oPwds[0]); end else for i := 0 to oPwds.Count - 1 do AStmt.SetTablePassword(oPwds.KeyNames[i], oPwds.ValueFromIndex[i]); end; {-------------------------------------------------------------------------------} procedure TFDPhysADSCommand.SetupStatementBeforePrepare(AStmt: TADSStatement); var oFmtOpts: TFDFormatOptions; begin oFmtOpts := FOptions.FormatOptions; if GetMetaInfoKind <> mkNone then begin AStmt.StrsTrim := True; AStmt.StrsEmpty2Null := True; end else begin AStmt.StrsTrim := oFmtOpts.StrsTrim; AStmt.StrsEmpty2Null := oFmtOpts.StrsEmpty2Null; end; AStmt.ReadOnly := True; if not Assigned(AStmt.Lib.FAdsConnect101) then SetupStatementDataAccess(AStmt); end; {-------------------------------------------------------------------------------} procedure TFDPhysADSCommand.SetupStatementBeforeExecute(AStmt: TADSStatement); var oResOpts: TFDResourceOptions; iTimeout: Cardinal; begin oResOpts := FOptions.ResourceOptions; iTimeout := oResOpts.CmdExecTimeout; if (oResOpts.CmdExecMode = amBlocking) and (iTimeout <> $FFFFFFFF) then AStmt.Timeout := (iTimeout + 999) div 1000 else AStmt.Timeout := ADS_DEFAULT_SQL_TIMEOUT; if (ADSConnection.FTablePasswords.Count > 0) and not FPasswordsSet then begin FPasswordsSet := True; SetupStatementPasswords(AStmt); end; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSCommand.SetupCursor(ACrs: TADSCursor); var oFetchOpts: TFDFetchOptions; begin oFetchOpts := FOptions.FetchOptions; ACrs.CacheRecords := oFetchOpts.RowsetSize; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSCommand.InternalPrepare; var rName: TFDPhysParsedName; oConnMeta: IFDPhysConnectionMetadata; begin // generate metadata SQL command if GetMetaInfoKind <> mkNone then begin GetSelectMetaInfoParams(rName); // ADS returns error for mkIndexes query to the SYSTEM catalog tables if (CompareText(rName.FCatalog, 'SYSTEM') = 0) and (GetMetaInfoKind in [mkIndexes, mkIndexFields]) then Exit; // ADS returns error for SP query to a non-dictionary connection if not ADSConnection.FDictionary.HasDictionary and (GetMetaInfoKind in [mkPackages, mkProcs, mkProcArgs, mkGenerators]) then Exit; if GetMetaInfoKind = mkIndexes then begin GetConnection.CreateMetadata(oConnMeta); FMetainfoAddonView := oConnMeta.GetTablePrimaryKey(rName.FCatalog, rName.FSchema, Trim(GetCommandText())); end; GenerateSelectMetaInfo(rName); if FDbCommandText = '' then Exit; end // generate stored proc call SQL command else if GetCommandKind in [skStoredProc, skStoredProcWithCrs, skStoredProcNoCrs] then begin GetConnection.CreateMetadata(oConnMeta); oConnMeta.DecodeObjName(Trim(GetCommandText()), rName, Self, []); FDbCommandText := ''; if fiMeta in FOptions.FetchOptions.Items then GenerateStoredProcParams(rName); // ADS does not support <catalog>.<name> as a stored procedure name rName.FCatalog := ''; GenerateStoredProcCall(rName, GetCommandKind); end; // adjust SQL command GenerateLimitSelect(); GenerateParamMarkers(); FStmt := TADSStatement.Create(ADSConnection.FConnection, Self); SetupStatementBeforePrepare(FStmt); if GetParams.Count > 0 then CreateParamInfos; if not UseExecDirect then FStmt.Prepare(FDbCommandText); end; {-------------------------------------------------------------------------------} function TFDPhysADSCommand.FDType2SQL(AType: TFDDataType; AFixedLen: Boolean): Word; begin case AType of dtSByte, dtByte, dtInt16, dtUInt16: Result := ADS_SHORTINT; dtInt32, dtUInt32: Result := ADS_INTEGER; dtInt64, dtUInt64: Result := ADS_LONGLONG; dtDouble, dtSingle, dtExtended: Result := ADS_DOUBLE; dtCurrency: Result := ADS_MONEY; dtBCD, dtFmtBcd: Result := ADS_NUMERIC; dtAnsiString: if AFixedLen then Result := ADS_STRING else Result := ADS_VARCHAR; dtWideString: if AFixedLen then Result := ADS_NCHAR else Result := ADS_NVARCHAR; dtMemo, dtHMemo: Result := ADS_MEMO; dtWideMemo, dtWideHMemo, dtXML: Result := ADS_NMEMO; dtByteString: Result := ADS_RAW; dtBlob, dtHBFile, dtHBlob: Result := ADS_BINARY; dtDate: Result := ADS_DATE; dtTime: Result := ADS_TIME; dtDateTime, dtDateTimeStamp: Result := ADS_TIMESTAMP; dtBoolean: Result := ADS_LOGICAL; dtGUID: if ADSConnection.FConnection.Lib.Version >= caADS12 then Result := ADS_GUID else Result := ADS_STRING; else // dtTimeIntervalFull, dtTimeIntervalYM, dtTimeIntervalDS, // dtCursorRef, dtRowSetRef, dtRowRef, dtArrayRef, dtParentRowRef, dtObject Result := ADS_TYPE_UNKNOWN; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSCommand.SQL2ADColInfo(ASQLType, ASQLMemoType: Word; ASQLLen: LongWord; ASQLPrec, ASQLScale: Word; out AType: TFDDataType; var AAttrs: TFDDataAttributes; out ALen: LongWord; out APrec, AScale: Integer; AFmtOpts: TFDFormatOptions); begin AType := dtUnknown; ALen := 0; APrec := 0; AScale := 0; Exclude(AAttrs, caFixedLen); Exclude(AAttrs, caBlobData); Include(AAttrs, caSearchable); case ASQLType of ADS_SHORTINT: AType := dtInt16; ADS_INTEGER: AType := dtInt32; ADS_LONGLONG: AType := dtInt64; ADS_AUTOINC: begin AType := dtInt32; Include(AAttrs, caAutoInc); Include(AAttrs, caReadOnly); end; ADS_ROWVERSION: begin AType := dtInt64; Include(AAttrs, caRowVersion); Include(AAttrs, caReadOnly); end; ADS_DOUBLE: AType := dtDouble; ADS_CURDOUBLE, ADS_MONEY: begin APrec := 19; AScale := 4; AType := dtCurrency; end; ADS_NUMERIC: begin APrec := ASQLPrec; AScale := ASQLScale; if AFmtOpts.IsFmtBcd(APrec, AScale) then AType := dtFmtBCD else AType := dtBCD end; ADS_STRING, ADS_CISTRING, ADS_VARCHAR, ADS_VARCHAR_FOX: if ASQLLen <= AFmtOpts.MaxStringSize then begin ALen := ASQLLen; AType := dtAnsiString; if ASQLType in [ADS_STRING, ADS_CISTRING] then Include(AAttrs, caFixedLen); end else begin AType := dtMemo; Include(AAttrs, caBlobData); end; ADS_MEMO: begin AType := dtMemo; Include(AAttrs, caBlobData); Exclude(AAttrs, caSearchable); end; ADS_NCHAR, ADS_NVARCHAR: if ASQLLen <= AFmtOpts.MaxStringSize then begin ALen := ASQLLen; AType := dtWideString; if ASQLType = ADS_NCHAR then Include(AAttrs, caFixedLen); end else begin AType := dtWideMemo; Include(AAttrs, caBlobData); end; ADS_NMEMO: begin AType := dtWideMemo; Include(AAttrs, caBlobData); Exclude(AAttrs, caSearchable); end; ADS_RAW, ADS_VARBINARY_FOX, ADS_SYSTEM_FIELD: begin AType := dtByteString; ALen := ASQLLen; if ASQLType in [ADS_RAW, ADS_SYSTEM_FIELD] then Include(AAttrs, caFixedLen); end; ADS_BINARY, ADS_IMAGE, ADS_FOXGENERAL, ADS_FOXPICTURE: begin AType := dtBlob; Include(AAttrs, caBlobData); Exclude(AAttrs, caSearchable); end; ADS_DATE, ADS_COMPACTDATE: AType := dtDate; ADS_TIME: begin AType := dtTime; AScale := 1; end; ADS_TIMESTAMP, ADS_MODTIME: begin AType := dtDateTimeStamp; AScale := 1; end; ADS_LOGICAL: AType := dtBoolean; ADS_GUID: AType := dtGUID; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSCommand.CreateParamInfos; var i: Integer; oFmtOpts: TFDFormatOptions; oParams: TFDParams; oParam: TFDParam; iAdsParIndex, iAdsParRef: Integer; oAdsParam: TADSVariable; eDestFldType: TFieldType; eAttrs: TFDDataAttributes; iPrec, iScale: Integer; iLen: LongWord; pPar: PFDAdsParInfoRec; lFixedLen: Boolean; begin oFmtOpts := FOptions.FormatOptions; oParams := GetParams; iAdsParIndex := 0; for i := 0 to oParams.Count - 1 do if oParams[i].ParamType in [ptUnknown, ptInput, ptInputOutput] then Inc(iAdsParIndex); FStmt.Params.Count := iAdsParIndex; SetLength(FParInfos, iAdsParIndex); iAdsParIndex := 0; for i := 0 to oParams.Count - 1 do begin oParam := oParams[i]; if oParam.ParamType in [ptUnknown, ptInput, ptInputOutput] then begin pPar := @FParInfos[iAdsParIndex]; case GetParams.BindMode of pbByName: iAdsParRef := iAdsParIndex; pbByNumber: iAdsParRef := oParam.Position - 1; else iAdsParRef := -1; end; if (iAdsParRef >= 0) and (iAdsParRef < FStmt.Params.Count) then begin oAdsParam := FStmt.Params[iAdsParRef]; pPar^.FAdsParamIndex := iAdsParRef; pPar^.FParamIndex := i; pPar^.FParamType := oParam.ParamType; if oParam.DataType = ftUnknown then ParTypeUnknownError(oParam); pPar^.FSrcFieldType := oParam.DataType; oFmtOpts.ResolveFieldType('', oParam.DataTypeName, oParam.DataType, oParam.FDDataType, oParam.Size, oParam.Precision, oParam.NumericScale, eDestFldType, pPar^.FSrcSize, pPar^.FSrcPrec, pPar^.FSrcScale, pPar^.FSrcDataType, pPar^.FDestDataType, False); lFixedLen := pPar^.FSrcFieldType in [ftFixedChar, ftBytes, ftFixedWideChar]; pPar^.FOutSQLDataType := FDType2SQL(pPar^.FDestDataType, lFixedLen); eAttrs := []; SQL2ADColInfo(pPar^.FOutSQLDataType, ADS_MEMO, pPar^.FSrcSize, pPar^.FSrcPrec, pPar^.FSrcScale, pPar^.FOutDataType, eAttrs, iLen, iPrec, iScale, oFmtOpts); case GetParams.BindMode of pbByName: oAdsParam.Name := oParam.Name; pbByNumber: oAdsParam.Position := oParam.Position; end; oAdsParam.ValueType := pPar^.FOutSQLDataType; end; Inc(iAdsParIndex); end; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSCommand.DestroyParamInfos; begin SetLength(FParInfos, 0); end; {-------------------------------------------------------------------------------} procedure TFDPhysADSCommand.CreateColInfos; var i: Integer; oDef: TADSColumnDef; oFmtOpts: TFDFormatOptions; iPrec, iScale: Integer; sKeyColumns: String; pCol: PFDAdsColInfoRec; oVar: TADSVariable; begin oFmtOpts := FOptions.FormatOptions; SetLength(FColInfos, FCursor.ColumnDefsCount); FCursor.Columns.Count := FCursor.ColumnDefsCount; sKeyColumns := ''; if (GetMetaInfoKind = mkNone) and (fiMeta in FOptions.FetchOptions.Items) then begin sKeyColumns := FCursor.KeyColumns; if sKeyColumns <> '' then sKeyColumns := ';' + AnsiUpperCase(sKeyColumns) + ';'; end; for i := 0 to Length(FColInfos) - 1 do begin oDef := FCursor.ColumnDefs[i]; try pCol := @FColInfos[i]; pCol^.FName := oDef.Name; pCol^.FPos := i + 1; pCol^.FLen := oDef.Length; pCol^.FPrec := oDef.Precision; pCol^.FScale := oDef.Scale; pCol^.FSrcSQLDataType := oDef.FieldType; pCol^.FSrcSQLMemoType := oDef.MemoType; // ACE API does not provide more information about result set columns pCol^.FAttrs := [caAllowNull]; if sKeyColumns <> '' then pCol^.FInPK := Pos(';' + AnsiUpperCase(pCol^.FName) + ';', sKeyColumns) > 0; if CompareText(pCol^.FName, 'ROWID') = 0 then begin Include(pCol^.FAttrs, caROWID); Include(pCol^.FAttrs, caAllowNull); end; SQL2ADColInfo(pCol^.FSrcSQLDataType, pCol^.FSrcSQLMemoType, pCol^.FLen, pCol^.FPrec, pCol^.FScale, pCol^.FSrcDataType, pCol^.FAttrs, pCol^.FADLen, iPrec, iScale, oFmtOpts); pCol^.FPrec := iPrec; pCol^.FScale := iScale; if GetMetaInfoKind = mkNone then oFmtOpts.ResolveDataType(pCol^.FName, '', pCol^.FSrcDataType, pCol^.FADLen, pCol^.FPrec, pCol^.FScale, pCol^.FDestDataType, pCol^.FADLen, True) else pCol^.FDestDataType := pCol^.FSrcDataType; if CheckFetchColumn(pCol^.FSrcDataType, pCol^.FAttrs) then begin oVar := FCursor.Columns[i]; oVar.Position := pCol^.FPos; oVar.Name := oDef.Name; oVar.ValueType := oDef.FieldType; oVar.IsImage := oDef.MemoType = ADS_IMAGE; pCol^.FVar := oVar; end else pCol^.FVar := nil; finally FDFree(oDef); end; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSCommand.DestroyColInfos; begin SetLength(FColInfos, 0); end; {-------------------------------------------------------------------------------} procedure TFDPhysADSCommand.SetParamValue(AFmtOpts: TFDFormatOptions; AParam: TFDParam; AAdsParam: TADSVariable; ApInfo: PFDAdsParInfoRec; AParIndex: Integer); var pData: PByte; iSize, iSrcSize: LongWord; oIntStr, oExtStr: TStream; lExtStream: Boolean; begin pData := nil; iSize := 0; // null if (AParam.DataType <> ftStream) and AParam.IsNulls[AParIndex] then AAdsParam.SetData(nil, 0) // assign BLOB stream else if AParam.IsStreams[AParIndex] then begin oExtStr := AParam.AsStreams[AParIndex]; lExtStream := (oExtStr <> nil) and not ((oExtStr is TADSBLOBStream) and (TADSBLOBStream(oExtStr).Obj = FStmt)); if (AParam.DataType <> ftStream) and not lExtStream or (oExtStr <> nil) and (oExtStr.Size < 0) or not (ApInfo^.FOutDataType in C_FD_VarLenTypes) then UnsupParamObjError(AParam); oIntStr := AAdsParam.CreateBlobStream(smOpenWrite); try if lExtStream then begin if oExtStr.Size <> -1 then oIntStr.Size := oExtStr.Size; oIntStr.CopyFrom(oExtStr, -1); end else begin FHasIntStreams := True; AParam.AsStreams[AParIndex] := oIntStr; end; finally if lExtStream then FDFree(oIntStr); end; end // conversion is not required else if ApInfo^.FSrcDataType = ApInfo^.FOutDataType then begin // byte string data, then optimizing - get data directly if ApInfo^.FOutDataType in C_FD_VarLenTypes then begin AParam.GetBlobRawData(iSize, pData, AParIndex); AAdsParam.SetData(pData, iSize); end else begin iSize := AParam.GetDataLength(AParIndex); FBuffer.Check(iSize); AParam.GetData(FBuffer.Ptr, AParIndex); AAdsParam.SetData(FBuffer.Ptr, iSize); end; end // conversion is required else begin // calculate buffer size to move param values iSrcSize := AParam.GetDataLength(AParIndex); FBuffer.Extend(iSrcSize, iSize, ApInfo^.FSrcDataType, ApInfo^.FOutDataType); // get, convert and set parameter value AParam.GetData(FBuffer.Ptr, AParIndex); AFmtOpts.ConvertRawData(ApInfo^.FSrcDataType, ApInfo^.FOutDataType, FBuffer.Ptr, iSrcSize, FBuffer.FBuffer, FBuffer.Size, iSize, ADSConnection.FConnection.Encoder); AAdsParam.SetData(FBuffer.Ptr, iSize); end; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSCommand.SetParamValues(AParIndex: Integer = 0); var oFmtOpts: TFDFormatOptions; oParams: TFDParams; oParam: TFDParam; oAdsParam: TADSVariable; i: Integer; pParInfo: PFDAdsParInfoRec; begin FHasIntStreams := False; oParams := GetParams; if oParams.Count = 0 then Exit; oFmtOpts := GetOptions.FormatOptions; for i := 0 to Length(FParInfos) - 1 do begin pParInfo := @FParInfos[i]; oParam := oParams[pParInfo^.FParamIndex]; if (pParInfo^.FAdsParamIndex <> -1) and (oParam.DataType <> ftCursor) and (oParam.ParamType in [ptInput, ptInputOutput, ptUnknown]) then begin oAdsParam := FStmt.Params[pParInfo^.FAdsParamIndex]; CheckParamMatching(oParam, pParInfo^.FSrcFieldType, pParInfo^.FParamType, 0); SetParamValue(oFmtOpts, oParam, oAdsParam, pParInfo, AParIndex); end; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSCommand.GetParamValues(AParIndex: Integer = 0); var oTab: TFDDatSTable; i: Integer; oParams: TFDParams; oPar: TFDParam; ePrevState: TFDPhysCommandState; begin oParams := GetParams; if (FCursor = nil) or (oParams.Count = 0) then Exit; SetupCursor(FCursor); FCursor.AddColumns; if FCursor.Columns.Count = 0 then Exit; CreateColInfos; oTab := TFDDatSTable.Create; oTab.Setup(FOptions); ePrevState := GetState; SetState(csOpen); try Define(oTab); if oTab.Columns.Count > 0 then begin FetchRow(oTab, nil); // SP parameters are binded by name for i := 0 to oTab.Columns.Count - 1 do begin oPar := oParams.FindParam(oTab.Columns[i].Name); if (oPar <> nil) and (oPar.ParamType in [ptOutput, ptInputOutput, ptResult]) then oPar.Values[AParIndex] := oTab.Rows[0].GetData(i); end; end; finally SetState(ePrevState); FDFree(oTab); DestroyColInfos; end; end; {-------------------------------------------------------------------------------} function TFDPhysADSCommand.InternalUseStandardMetadata: Boolean; begin Result := False; end; {-------------------------------------------------------------------------------} function TFDPhysADSCommand.InternalColInfoStart(var ATabInfo: TFDPhysDataTableInfo): Boolean; begin Result := OpenBlocked; if ATabInfo.FSourceID = -1 then begin ATabInfo.FSourceName := GetCommandText; ATabInfo.FSourceID := 1; FColIndex := 0; end; end; {-------------------------------------------------------------------------------} function TFDPhysADSCommand.InternalColInfoGet(var AColInfo: TFDPhysDataColumnInfo): Boolean; var pColInfo: PFDAdsColInfoRec; begin if FColIndex < Length(FColInfos) then begin pColInfo := @FColInfos[FColIndex]; AColInfo.FSourceName := pColInfo^.FName; AColInfo.FSourceID := pColInfo^.FPos; AColInfo.FSourceType := pColInfo^.FSrcDataType; AColInfo.FOriginTabName.FSchema := ''; AColInfo.FOriginTabName.FObject := ''; AColInfo.FOriginColName := ''; AColInfo.FType := pColInfo^.FDestDataType; AColInfo.FLen := pColInfo^.FADLen; AColInfo.FPrec := pColInfo^.FPrec; AColInfo.FScale := pColInfo^.FScale; AColInfo.FAttrs := pColInfo^.FAttrs; AColInfo.FForceAddOpts := []; if pColInfo^.FInPK then Include(AColInfo.FForceAddOpts, coInKey); Inc(FColIndex); Result := True; end else Result := False; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSCommand.DoExecute(ATimes, AOffset: Integer; var ACount: TFDCounter; AFlush: Boolean); var i, iArraySize: Integer; iTimes: Integer; iCount: TFDCounter; begin SetupStatementBeforeExecute(FStmt); if ATimes - AOffset > 1 then begin iArraySize := GetParams.ArraySize; if ATimes > iArraySize then iTimes := iArraySize else iTimes := ATimes; for i := AOffset to iTimes - 1 do begin iCount := 0; DoExecute(i + 1, i, iCount, False); Inc(ACount, iCount); end; end else begin if not AFlush then SetParamValues(AOffset); if FHasIntStreams xor AFlush then begin ACount := -1; Exit; end; ADSConnection.FConnection.EnableProgress; try try if UseExecDirect then FStmt.ExecuteDirect(FDbCommandText) else FStmt.Execute; except on E: EAdsNativeException do begin E.Errors[0].RowIndex := AOffset; raise; end; end; finally ADSConnection.FConnection.DisableProgress; Inc(ACount, FStmt.RecordCount); end; FCursor := FStmt.GetCursor; if FCursor <> nil then try GetParamValues; finally InternalClose; end; end; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSCommand.InternalExecute(ATimes, AOffset: Integer; var ACount: TFDCounter); begin DoExecute(ATimes, AOffset, ACount, False); end; {-------------------------------------------------------------------------------} procedure TFDPhysADSCommand.InternalCloseStreams; var i, j: Integer; oPar: TFDParam; oStr: Tstream; iTmp: TFDCounter; begin if (FStmt <> nil) and FHasIntStreams then begin for i := 0 to GetParams().Count - 1 do begin oPar := GetParams()[i]; for j := 0 to oPar.ArraySize - 1 do if oPar.IsStreams[j] then begin oStr := oPar.AsStreams[j]; if (oStr is TADSBLOBStream) and (TADSBLOBStream(oStr).Obj.OwningObj = Self) then TADSBLOBStream(oStr).Flush; end; end; GetParams.Close; DoExecute(1, 0, iTmp, True); end; end; {-------------------------------------------------------------------------------} function TFDPhysADSCommand.InternalOpen(var ACount: TFDCounter): Boolean; begin ACount := 0; Result := False; if (GetMetaInfoKind <> mkNone) and (FDbCommandText = '') then Exit; SetupStatementBeforeExecute(FStmt); ADSConnection.FConnection.EnableProgress; try SetParamValues; try if UseExecDirect then FStmt.ExecuteDirect(FDbCommandText) else FStmt.Execute; FCursor := FStmt.GetCursor; if FCursor <> nil then begin SetupCursor(FCursor); CreateColInfos; Result := Length(FColInfos) > 0; end; except on E: Exception do begin InternalClose; if not ((GetMetaInfoKind <> mkNone) and (E is EADSNativeException) and (EADSNativeException(E).Kind = ekObjNotExists)) then raise; end; end; finally ADSConnection.FConnection.DisableProgress; ACount := TFDCounter(FStmt.RecordCount); end; end; {-------------------------------------------------------------------------------} function TFDPhysADSCommand.InternalNextRecordSet: Boolean; begin Result := False; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSCommand.FetchRow(ATable: TFDDatSTable; AParentRow: TFDDatSRow); var oRow: TFDDatSRow; oFmtOpts: TFDFormatOptions; pColInfo: PFDAdsColInfoRec; j: Integer; lMetadata: Boolean; [unsafe] oCol: TFDDatSColumn; procedure ProcessColumn(AColIndex: Integer; ARow: TFDDatSRow; ApInfo: PFDAdsColInfoRec); var iSize: Integer; iDestSize: LongWord; lIsVal: Boolean; oVar: TADSVariable; begin iSize := 0; oVar := ApInfo^.FVar; if (oVar = nil) or not CheckFetchColumn(ApInfo^.FSrcDataType, ApInfo^.FAttrs) then Exit // null else if oVar.IsNull then lIsVal := False // conversion is not required else if ApInfo^.FSrcDataType = ApInfo^.FDestDataType then begin if ApInfo^.FSrcDataType in C_FD_BlobTypes then iSize := oVar.GetDataLength else iSize := ApInfo^.FLen; FBuffer.Check((iSize + 1) * SizeOf(WideChar)); lIsVal := oVar.GetData(FBuffer.FBuffer, iSize); if lIsVal then ARow.SetData(AColIndex, FBuffer.Ptr, iSize); end // conversion is required else begin if ApInfo^.FSrcDataType in C_FD_BlobTypes then iSize := oVar.GetDataLength else iSize := ApInfo^.FLen; FBuffer.Check((iSize + 1) * SizeOf(WideChar)); lIsVal := oVar.GetData(FBuffer.FBuffer, iSize); if lIsVal then begin iDestSize := 0; oFmtOpts.ConvertRawData(ApInfo^.FSrcDataType, ApInfo^.FDestDataType, FBuffer.Ptr, iSize, FBuffer.FBuffer, FBuffer.Size, iDestSize, ADSConnection.FConnection.Encoder); ARow.SetData(AColIndex, FBuffer.Ptr, iDestSize); end; end; if not lIsVal then ARow.SetData(AColIndex, nil, 0); end; procedure ProcessMetaColumn(AColIndex: Integer; ARow: TFDDatSRow; ApInfo: PFDAdsColInfoRec); var iSize: Integer; iDestSize: Longword; lIsVal: Boolean; oVar: TADSVariable; begin iSize := 0; oVar := ApInfo^.FVar; if oVar = nil then Exit else if AColIndex = 0 then begin lIsVal := True; ARow.SetData(0, ATable.Rows.Count + 1); end else if oVar.IsNull then lIsVal := False else begin FBuffer.Check((ApInfo^.FLen + 1) * SizeOf(WideChar)); lIsVal := oVar.GetData(FBuffer.FBuffer, iSize); if lIsVal then begin iDestSize := 0; if (ApInfo^.FDestDataType in C_FD_AnsiTypes) or (ApInfo^.FDestDataType in [dtInt16, dtInt32, dtDouble, dtBCD, dtFmtBCD]) then oFmtOpts.ConvertRawData(ApInfo^.FDestDataType, ATable.Columns[AColIndex].DataType, FBuffer.Ptr, iSize, FBuffer.FBuffer, FBuffer.Size, iDestSize, ADSConnection.FConnection.Encoder) else iDestSize := iSize; ARow.SetData(AColIndex, FBuffer.Ptr, iDestSize); end; end; if not lIsVal then ARow.SetData(AColIndex, nil, 0) end; begin oFmtOpts := FOptions.FormatOptions; oRow := ATable.NewRow(False); lMetadata := GetMetaInfoKind <> mkNone; try for j := 0 to ATable.Columns.Count - 1 do begin oCol := ATable.Columns[j]; if oCol.SourceID > 0 then begin pColInfo := @FColInfos[oCol.SourceID - 1]; if lMetadata then ProcessMetaColumn(j, oRow, pColInfo) else ProcessColumn(j, oRow, pColInfo); end; end; if AParentRow <> nil then begin oRow.ParentRow := AParentRow; AParentRow.Fetched[ATable.Columns.ParentCol] := True; end; ATable.Rows.Add(oRow); except FDFree(oRow); raise; end; end; {-------------------------------------------------------------------------------} function TFDPhysADSCommand.FetchMetaRow(ATable: TFDDatSTable; AParentRow: TFDDatSRow; ARowNo: Integer): Boolean; var oRow: TFDDatSRow; iRecNo: Integer; lDeleteRow: Boolean; pData: Pointer; i, iSize: Integer; eTableKind: TFDPhysTableKind; eScope: TFDPhysObjectScope; eAttrs: TFDDataAttributes; {iAdsType,} iAdsSize, iAdsDec: Integer; iLen: LongWord; iPrec, iScale: Integer; eType: TFDDataType; eIndKind: TFDPhysIndexKind; oConnMeta: IFDPhysConnectionMetadata; rName: TFDPhysParsedName; eCascade: TFDPhysCascadeRuleKind; eProcKind: TFDPhysProcedureKind; eParType: TParamType; s: String; procedure DecodeColInfo(ASQLDataType: String; ASQLLen, ASQLScale: Integer; out AType: TFDDataType; var AAttrs: TFDDataAttributes; out ALen: LongWord; out APrec, AScale: Integer); begin AType := dtUnknown; ALen := 0; APrec := 0; AScale := 0; Exclude(AAttrs, caFixedLen); Exclude(AAttrs, caBlobData); Include(AAttrs, caSearchable); if (ASQLDataType = 'SHORT') or (ASQLDataType = 'SHORTINT') then AType := dtInt16 else if (ASQLDataType = 'INTEGER') or (ASQLDataType = 'Integer') then AType := dtInt32 else if ASQLDataType = 'LONG' then AType := dtInt64 else if ASQLDataType = 'AUTOINC' then begin AType := dtInt32; AAttrs := AAttrs + [caAutoInc]; end else if ASQLDataType = 'ROWVERSION' then begin AType := dtInt64; AAttrs := AAttrs + [caRowVersion, caReadOnly]; end else if ASQLDataType = 'DOUBLE' then begin AType := dtDouble; end else if ASQLDataType = 'CURDOUBLE' then begin AType := dtCurrency; APrec := 15; AScale := 4; end else if (ASQLDataType = 'MONEY') or (ASQLDataType = 'Money') then begin AType := dtCurrency; APrec := 19; AScale := 4; end else if (ASQLDataType = 'NUMERIC') or (ASQLDataType = 'Numeric') then begin if (ASQLLen - 2 > 18) or (ASQLScale > 4) then AType := dtBCD else AType := dtFmtBCD; APrec := ASQLLen - 2; AScale := ASQLScale; end else if (ASQLDataType = 'CHAR') or (ASQLDataType = 'CHARACTER') or (ASQLDataType = 'CICHAR') or (ASQLDataType = 'CICHARACTER') then begin AType := dtAnsiString; AAttrs := AAttrs + [caFixedLen]; ALen := ASQLLen; end else if (ASQLDataType = 'VARCHAR') or (ASQLDataType = 'VARCHARFOX') then begin AType := dtAnsiString; ALen := ASQLLen; end else if ASQLDataType = 'NCHAR' then begin AType := dtWideString; AAttrs := AAttrs + [caFixedLen]; ALen := ASQLLen; end else if ASQLDataType = 'NVARCHAR' then begin AType := dtWideString; ALen := ASQLLen; end else if (ASQLDataType = 'MEMO') or (ASQLDataType = 'Memo') then begin AType := dtMemo; AAttrs := AAttrs + [caBlobData] - [caSearchable]; end else if ASQLDataType = 'NMEMO' then begin AType := dtWideMemo; AAttrs := AAttrs + [caBlobData] - [caSearchable]; end else if ASQLDataType = 'RAW' then begin AType := dtByteString; AAttrs := AAttrs + [caFixedLen]; ALen := ASQLLen; end else if (ASQLDataType = 'VARBINARY') or (ASQLDataType = 'VARBINARYFOX') then begin AType := dtByteString; ALen := ASQLLen; end else if (ASQLDataType = 'BINARY') or (ASQLDataType = 'BLOB') or (ASQLDataType = 'IMAGE') then begin AType := dtBlob; AAttrs := AAttrs + [caBlobData] - [caSearchable]; end else if (ASQLDataType = 'DATE') or (ASQLDataType = 'SHORTDATE') then AType := dtDate else if ASQLDataType = 'TIME' then AType := dtTime else if (ASQLDataType = 'TIMESTAMP') or (ASQLDataType = 'MODTIME') then AType := dtDateTimeStamp else if ASQLDataType = 'LOGICAL' then AType := dtBoolean else if ASQLDataType = 'GUID' then AType := dtGUID; end; function GetCrsData(ACrsIndex, ARowIndex: Integer): Boolean; var pOut: Pointer; begin iSize := 0; Result := FCursor.Columns[ACrsIndex].GetData(pData, iSize); if not Result then begin pOut := nil; iSize := 0; end else if ATable.Columns[ARowIndex].DataType in C_FD_WideTypes then begin pOut := nil; iSize := FMetaEncoder.Decode(pData, iSize, pOut, ecUTF16); end else pOut := pData; oRow.SetData(ARowIndex, pOut, iSize); end; begin lDeleteRow := False; iRecNo := ATable.Rows.Count + 1; oRow := ATable.NewRow(False); pData := FBuffer.Check(1024); try FConnection.CreateMetadata(oConnMeta); case GetMetaInfoKind of mkCatalogs: begin oRow.SetData(0, iRecNo); GetCrsData(0, 1); if (GetWildcard <> '') and not FDStrLike(VarToStr(oRow.GetData(1, rvDefault)), GetWildcard, True) then lDeleteRow := True; end; mkTables: begin oRow.SetData(0, iRecNo); GetCrsData(0, 1); GetCrsData(1, 2); GetCrsData(2, 3); iSize := 0; eTableKind := tkTable; eScope := osOther; if FCursor.Columns[3].GetData(pData, iSize) then begin eScope := osMy; s := FMetaEncoder.Decode(pData, iSize); if StrLIComp(PChar(s), 'TABLE', iSize) = 0 then eTableKind := tkTable else if StrLIComp(PChar(s), 'VIEW', iSize) = 0 then eTableKind := tkView else if StrLIComp(PChar(s), 'SYSTEM TABLE', iSize) = 0 then begin eTableKind := tkTable; eScope := osSystem; end else if StrLIComp(PChar(s), 'LOCAL TEMPORARY', iSize) = 0 then eTableKind := tkLocalTable end; oRow.SetData(4, Smallint(eTableKind)); oRow.SetData(5, Smallint(eScope)); lDeleteRow := not (eTableKind in GetTableKinds) or not (eScope in GetObjectScopes); end; mkTableFields: begin oRow.SetData(0, iRecNo); GetCrsData(0, 1); GetCrsData(1, 2); GetCrsData(2, 3); GetCrsData(3, 4); iSize := 0; if FCursor.Columns.Count >= 17 then begin if FCursor.Columns[16].GetData(pData, iSize) then oRow.SetData(5, PInteger(pData)^); end else oRow.SetData(5, iRecNo); eAttrs := [caBase]; iSize := 0; if FCursor.Columns[5].GetData(pData, iSize) then begin s := FMetaEncoder.Decode(pData, iSize); if StrLIComp(PChar(s), 'AUTOINC', iSize) = 0 then begin Include(eAttrs, caAutoInc); Include(eAttrs, caReadOnly); end else if StrLIComp(PChar(s), 'ROWVERSION', iSize) = 0 then begin Include(eAttrs, caRowVersion); Include(eAttrs, caReadOnly); end; oRow.SetData(7, pData, iSize); end; iSize := 0; if FCursor.Columns.Count >= 13 then if FCursor.Columns[12].GetData(pData, iSize) and (iSize > 0) then begin s := FMetaEncoder.Decode(pData, iSize); if StrLIComp(PChar(s), 'NULL', iSize) <> 0 then Include(eAttrs, caDefault); end; iSize := 0; if not FCursor.Columns[10].GetData(pData, iSize) or (PSIGNED16(pData)^ <> 0) then Include(eAttrs, caAllowNull); iSize := 0; { if FCursor.Columns[4].GetData(pData, iSize) then iAdsType := PSIGNED16(pData)^ else iAdsType := 0; } iSize := 0; if FCursor.Columns[6].GetData(pData, iSize) then iAdsSize := PSIGNED32(pData)^ else iAdsSize := 0; iSize := 0; if FCursor.Columns[8].GetData(pData, iSize) then iAdsDec := PSIGNED16(pData)^ else iAdsDec := 0; DecodeColInfo(oRow.GetData(7), iAdsSize, iAdsDec, eType, eAttrs, iLen, iPrec, iScale); oRow.SetData(6, Smallint(eType)); oRow.SetData(8, PWord(@eAttrs)^); oRow.SetData(9, iPrec); oRow.SetData(10, iScale); oRow.SetData(11, iLen); end; mkIndexes: begin iSize := 0; if FCursor.Columns[6].GetData(pData, iSize) and (PSIGNED16(pData)^ = 0) then lDeleteRow := True else begin oRow.SetData(0, iRecNo); GetCrsData(0, 1); GetCrsData(1, 2); GetCrsData(2, 3); GetCrsData(5, 4); iSize := 0; if FCursor.Columns[3].GetData(pData, iSize) and (PWordBool(pData)^ = False) then eIndKind := ikUnique else eIndKind := ikNonUnique; FMetainfoAddonView.RowFilter := 'INDEX_NAME = ''' + VarToStr(oRow.GetData(4)) + ''''; if FMetainfoAddonView.Rows.Count > 0 then begin eIndKind := ikPrimaryKey; oRow.SetData(5, FMetainfoAddonView.Rows[0].GetData(5)); end; oRow.SetData(6, Smallint(eIndKind)); FMetainfoAddonView.RowFilter := ''; for i := 0 to ATable.Rows.Count - 1 do if (VarToStr(ATable.Rows[i].GetData(1, rvDefault)) = VarToStr(oRow.GetData(1, rvDefault))) and (VarToStr(ATable.Rows[i].GetData(2, rvDefault)) = VarToStr(oRow.GetData(2, rvDefault))) and (VarToStr(ATable.Rows[i].GetData(3, rvDefault)) = VarToStr(oRow.GetData(3, rvDefault))) and (VarToStr(ATable.Rows[i].GetData(4, rvDefault)) = VarToStr(oRow.GetData(4, rvDefault))) then begin lDeleteRow := True; Break; end; if not lDeleteRow and (GetWildcard <> '') and not FDStrLike(VarToStr(oRow.GetData(4, rvDefault)), GetWildcard, True) then lDeleteRow := True; end; end; mkIndexFields: begin iSize := 0; if FCursor.Columns[6].GetData(pData, iSize) and (PSIGNED16(pData)^ = 0) then lDeleteRow := True else begin oRow.SetData(0, iRecNo); GetCrsData(0, 1); GetCrsData(1, 2); GetCrsData(2, 3); GetCrsData(5, 4); GetCrsData(8, 5); iSize := 0; if FCursor.Columns[7].GetData(pData, iSize) then oRow.SetData(6, PSIGNED16(pData)^); GetCrsData(9, 7); GetCrsData(12, 8); oConnMeta.DecodeObjName(Trim(GetCommandText), rName, Self, [doNormalize, doUnquote]); lDeleteRow := (AnsiCompareText(rName.FObject, Trim(VarToStr(oRow.GetData(4, rvDefault)))) <> 0); if not lDeleteRow and (GetWildcard <> '') and not FDStrLike(VarToStr(oRow.GetData(5, rvDefault)), GetWildcard, True) then lDeleteRow := True; end; end; mkPrimaryKey: begin oRow.SetData(0, iRecNo); GetCrsData(0, 1); GetCrsData(1, 2); GetCrsData(2, 3); iSize := 0; if FCursor.Columns.Count >= 6 then begin GetCrsData(5, 4); GetCrsData(5, 5); end; oRow.SetData(6, Smallint(ikPrimaryKey)); for i := 0 to ATable.Rows.Count - 1 do if (VarToStr(ATable.Rows[i].GetData(1, rvDefault)) = VarToStr(oRow.GetData(1, rvDefault))) and (VarToStr(ATable.Rows[i].GetData(2, rvDefault)) = VarToStr(oRow.GetData(2, rvDefault))) and (VarToStr(ATable.Rows[i].GetData(3, rvDefault)) = VarToStr(oRow.GetData(3, rvDefault))) and (VarToStr(ATable.Rows[i].GetData(5, rvDefault)) = VarToStr(oRow.GetData(5, rvDefault))) then begin lDeleteRow := True; Break; end; if not lDeleteRow and (GetWildcard <> '') and not FDStrLike(VarToStr(oRow.GetData(4, rvDefault)), GetWildcard, True) then lDeleteRow := True; end; mkPrimaryKeyFields: begin oRow.SetData(0, iRecNo); GetCrsData(0, 1); GetCrsData(1, 2); GetCrsData(2, 3); if FCursor.Columns.Count >= 6 then GetCrsData(5, 4); GetCrsData(3, 5); iSize := 0; if FCursor.Columns[4].GetData(pData, iSize) then oRow.SetData(6, PSIGNED16(pData)^); oRow.SetData(7, 'A'); if not lDeleteRow and (GetWildcard <> '') and not FDStrLike(VarToStr(oRow.GetData(5, rvDefault)), GetWildcard, True) then lDeleteRow := True; end; mkForeignKeys: begin oRow.SetData(0, iRecNo); GetCrsData(4, 1); GetCrsData(5, 2); GetCrsData(6, 3); GetCrsData(11, 4); GetCrsData(0, 5); GetCrsData(1, 6); GetCrsData(2, 7); iSize := 0; if FCursor.Columns[10].GetData(pData, iSize) then begin eCascade := ckNone; case PSIGNED16(pData)^ of 0: eCascade := ckCascade; 2: eCascade := ckSetNull; 3: eCascade := ckRestrict; 4: eCascade := ckSetDefault; end; oRow.SetData(8, SmallInt(eCascade)); end; iSize := 0; if FCursor.Columns[9].GetData(pData, iSize) then begin eCascade := ckNone; case PSIGNED16(pData)^ of 0: eCascade := ckCascade; 2: eCascade := ckSetNull; 3: eCascade := ckRestrict; 4: eCascade := ckSetDefault; end; oRow.SetData(9, SmallInt(eCascade)); end; for i := 0 to ATable.Rows.Count - 1 do if (VarToStr(ATable.Rows[i].GetData(1, rvDefault)) = VarToStr(oRow.GetData(1, rvDefault))) and (VarToStr(ATable.Rows[i].GetData(2, rvDefault)) = VarToStr(oRow.GetData(2, rvDefault))) and (VarToStr(ATable.Rows[i].GetData(3, rvDefault)) = VarToStr(oRow.GetData(3, rvDefault))) and (VarToStr(ATable.Rows[i].GetData(4, rvDefault)) = VarToStr(oRow.GetData(4, rvDefault))) then begin lDeleteRow := True; Break; end; if not lDeleteRow and (GetWildcard <> '') and not FDStrLike(VarToStr(oRow.GetData(4, rvDefault)), GetWildcard, True) then lDeleteRow := True; end; mkForeignKeyFields: begin oRow.SetData(0, iRecNo); GetCrsData(4, 1); GetCrsData(5, 2); GetCrsData(6, 3); GetCrsData(11, 4); GetCrsData(7, 5); GetCrsData(3, 6); GetCrsData(8, 7); oConnMeta.DecodeObjName(Trim(GetCommandText), rName, Self, [doNormalize, doUnquote]); lDeleteRow := (AnsiCompareText(rName.FObject, Trim(VarToStr(oRow.GetData(4, rvDefault)))) <> 0); if not lDeleteRow and (GetWildcard <> '') and not FDStrLike(VarToStr(oRow.GetData(5, rvDefault)), GetWildcard, True) then lDeleteRow := True; end; mkProcs: begin oRow.SetData(0, iRecNo); GetCrsData(0, 1); GetCrsData(1, 2); GetCrsData(2, 4); iSize := 0; if FCursor.Columns[7].GetData(pData, iSize) and (PSIGNED16(pData)^ = 2) then eProcKind := pkFunction else eProcKind := pkProcedure; oRow.SetData(6, Smallint(eProcKind)); eScope := osMy; oRow.SetData(7, Smallint(eScope)); iSize := 0; if FCursor.Columns[3].GetData(pData, iSize) then if PInteger(pData)^ = -1 then oRow.SetData(8, 0) else oRow.SetData(8, PInteger(pData)^); iSize := 0; if FCursor.Columns[4].GetData(pData, iSize) then if PInteger(pData)^ = -1 then oRow.SetData(9, 0) else oRow.SetData(9, PInteger(pData)^); lDeleteRow := not (eScope in GetObjectScopes); if not lDeleteRow and (GetWildcard <> '') and not FDStrLike(VarToStr(oRow.GetData(4, rvDefault)), GetWildcard, True) then lDeleteRow := True; end; mkProcArgs: begin oRow.SetData(0, iRecNo); GetCrsData(0, 1); GetCrsData(1, 2); GetCrsData(2, 4); GetCrsData(3, 6); oRow.SetData(7, iRecNo); eParType := ptUnknown; iSize := 0; if FCursor.Columns[4].GetData(pData, iSize) then case PSIGNED16(pData)^ of 1: eParType := ptInput; 2: eParType := ptInputOutput; 3, 4: eParType := ptOutput; 5: eParType := ptResult; end; oRow.SetData(8, Smallint(eParType)); GetCrsData(6, 10); eAttrs := []; iSize := 0; if not FCursor.Columns[11].GetData(pData, iSize) or (PSIGNED16(pData)^ <> 0) then Include(eAttrs, caAllowNull); iSize := 0; { if FCursor.Columns[5].GetData(pData, iSize) then iAdsType := PSIGNED16(pData)^ else iAdsType := 0; } iSize := 0; if FCursor.Columns[7].GetData(pData, iSize) then iAdsSize := PInteger(pData)^ else iAdsSize := 0; iSize := 0; if FCursor.Columns[9].GetData(pData, iSize) then iAdsDec := PSIGNED16(pData)^ else iAdsDec := 0; DecodeColInfo(oRow.GetData(10), iAdsSize, iAdsDec, eType, eAttrs, iLen, iPrec, iScale); oRow.SetData(9, Smallint(eType)); oRow.SetData(11, PWord(@eAttrs)^); oRow.SetData(12, iPrec); oRow.SetData(13, iScale); oRow.SetData(14, iLen); end; end; if lDeleteRow then begin FDFree(oRow); Result := False; end else begin ATable.Rows.Add(oRow); Result := True; end; except FDFree(oRow); raise; end; end; {-------------------------------------------------------------------------------} function TFDPhysADSCommand.InternalFetchRowSet(ATable: TFDDatSTable; AParentRow: TFDDatSRow; ARowsetSize: LongWord): LongWord; procedure DoLock; var iTimeout: Cardinal; begin if FOptions.UpdateOptions.LockWait then iTimeout := FOptions.ResourceOptions.CmdExecTimeout else iTimeout := 0; FCursor.Lock(0, iTimeout); end; var i: LongWord; begin Result := 0; if not (GetMetaInfoKind in [mkNone, mkPackages]) and (ADSConnection.FServerVersion < caADS10) then for i := 1 to ARowsetSize do begin if FCursor.Eof then Break; if FetchMetaRow(ATable, AParentRow, Result + 1) then Inc(Result); FCursor.Skip(1); end else for i := 1 to ARowsetSize do begin if FCursor.Eof then Break; // Advantage has incompatible navigational and SQL locking systems. // A lock placed by AdsLockRecord will block SQL updates to the same // record in the same session and transaction. { case GetCommandKind of skSelectForLock: DoLock; skSelectForUnLock: FCursor.UnLock(0); end; } FetchRow(ATable, AParentRow); Inc(Result); FCursor.Skip(1); end; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSCommand.InternalAbort; begin ADSConnection.FConnection.Abort; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSCommand.InternalClose; begin if FCursor <> nil then FDFreeAndNil(FCursor); if FStmt <> nil then FStmt.Close; end; {-------------------------------------------------------------------------------} procedure TFDPhysADSCommand.InternalUnprepare; begin if FStmt = nil then Exit; FStmt.Unprepare; DestroyColInfos; DestroyParamInfos; FDFreeAndNil(FStmt); FMetainfoAddonView := nil; FPasswordsSet := False; end; {-------------------------------------------------------------------------------} initialization FDRegisterDriverClass(TFDPhysADSDriver); finalization FDUnregisterDriverClass(TFDPhysADSDriver); end.
unit uImageForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls; type TImageForm = class(TForm) imgImage: TImage; pbImage: TPaintBox; procedure pbImagePaint(Sender: TObject); private FImage: TGraphic; FImageIndex: Integer; function GetImageRect: TRect; procedure SetImage(const Value: TGraphic); procedure SetImageIndex(const Value: Integer); { Private declarations } public property Image: TGraphic read FImage write SetImage; property ImageIndex: Integer read FImageIndex write SetImageIndex; procedure DrawImage; end; implementation {$R *.dfm} { TImageForm } procedure TImageForm.DrawImage; begin pbImage.Canvas.Brush.Color := clBtnFace; pbImage.Canvas.FillRect(Rect(0, 0, pbImage.Width, pbImage.Height)); if FImage <> nil then pbImage.Canvas.StretchDraw(GetImageRect, FImage); end; function TImageForm.GetImageRect: TRect; var k: Double; begin Result := Rect(0, 0, 0 ,0); if (FImage <> nil) and (FImage.Width <> 0) and (FImage.Height <> 0) then begin k := FImage.Height / FImage.Width; if pbImage.Height / pbImage.Width < k then begin Result.Top := 0; Result.Bottom := pbImage.Height; Result.Left := Trunc((pbImage.Width - pbImage.Height / k) / 2); Result.Right := Trunc((pbImage.Width + pbImage.Height / k) / 2); end else begin Result.Left := 0; Result.Right := pbImage.Width; Result.Top := Trunc((pbImage.Height - pbImage.Width * k) / 2); Result.Bottom := Trunc((pbImage.Height + pbImage.Width * k) / 2); end; end; end; procedure TImageForm.pbImagePaint(Sender: TObject); begin DrawImage; end; procedure TImageForm.SetImage(const Value: TGraphic); begin if FImage <> Value then begin FImage := Value; DrawImage; end; end; procedure TImageForm.SetImageIndex(const Value: Integer); begin FImageIndex := Value; end; end.
unit LLVM.Imports.ObjectFile; interface //based on Object.h uses LLVM.Imports, LLVM.Imports.Types; type TLLVMObjectFileRef = type TLLVMRef; TLLVMSectionIteratorRef = type TLLVMRef; TLLVMSymbolIteratorRef = type TLLVMRef; TLLVMRelocationIteratorRef = type TLLVMRef; TLLVMBinaryType = ( LLVMBinaryTypeArchive, (* Archive file. *) LLVMBinaryTypeMachOUniversalBinary, (* Mach-O Universal Binary file. *) LLVMBinaryTypeCOFFImportFile, (* COFF Import file. *) LLVMBinaryTypeIR, (* LLVM IR. *) LLVMBinaryTypeWinRes, (* Windows resource (.res) file. *) LLVMBinaryTypeCOFF, (* COFF Object file. *) LLVMBinaryTypeELF32L, (* ELF 32-bit, little endian. *) LLVMBinaryTypeELF32B, (* ELF 32-bit, big endian. *) LLVMBinaryTypeELF64L, (* ELF 64-bit, little endian. *) LLVMBinaryTypeELF64B, (* ELF 64-bit, big endian. *) LLVMBinaryTypeMachO32L, (* MachO 32-bit, little endian. *) LLVMBinaryTypeMachO32B, (* MachO 32-bit, big endian. *) LLVMBinaryTypeMachO64L, (* MachO 64-bit, little endian. *) LLVMBinaryTypeMachO64B, (* MachO 64-bit, big endian. *) LLVMBinaryTypeWasm (* Web Assembly. *) ) ; (* * Create a binary file from the given memory buffer. * * The exact type of the binary file will be inferred automatically, and the * appropriate implementation selected. The context may be NULL except if * the resulting file is an LLVM IR file. * * The memory buffer is not consumed by this function. It is the responsibilty * of the caller to free it with \c LLVMDisposeMemoryBuffer. * * If NULL is returned, the \p ErrorMessage parameter is populated with the * error's description. It is then the caller's responsibility to free this * message by calling \c LLVMDisposeMessage. * * @see llvm::object::createBinary *) function LLVMCreateBinary(MemBuf: TLLVMMemoryBufferRef; Context: TLLVMContextRef; ErrorMessage: PLLVMChar):TLLVMBinaryRef; cdecl; external CLLVMLibrary; (* * Dispose of a binary file. * * The binary file does not own its backing buffer. It is the responsibilty * of the caller to free it with \c LLVMDisposeMemoryBuffer. *) procedure LLVMDisposeBinary(BR: TLLVMBinaryRef);cdecl; external CLLVMLibrary; (* * Retrieves a copy of the memory buffer associated with this object file. * * The returned buffer is merely a shallow copy and does not own the actual * backing buffer of the binary. Nevertheless, it is the responsibility of the * caller to free it with \c LLVMDisposeMemoryBuffer. * * @see llvm::object::getMemoryBufferRef *) function LLVMBinaryCopyMemoryBuffer(BR: TLLVMBinaryRef): TLLVMMemoryBufferRef;cdecl; external CLLVMLibrary; (* * Retrieve the specific type of a binary. * * @see llvm::object::Binary::getType *) function LLVMBinaryGetType(BR: TLLVMBinaryRef): TLLVMBinaryType; cdecl; external CLLVMLibrary; (* * For a Mach-O universal binary file, retrieves the object file corresponding * to the given architecture if it is present as a slice. * * If NULL is returned, the \p ErrorMessage parameter is populated with the * error's description. It is then the caller's responsibility to free this * message by calling \c LLVMDisposeMessage. * * It is the responsiblity of the caller to free the returned object file by * calling \c LLVMDisposeBinary. *) function LLVMMachOUniversalBinaryCopyObjectForArch(BR : TLLVMBinaryRef; Arch : PLLVMChar; ArchLen : TLLVMSizeT; ErrorMessage: PLLVMChar): TLLVMBinaryRef;cdecl; external CLLVMLibrary; (* * Retrieve a copy of the section iterator for this object file. * * If there are no sections, the result is NULL. * * The returned iterator is merely a shallow copy. Nevertheless, it is * the responsibility of the caller to free it with * \c LLVMDisposeSectionIterator. * * @see llvm::object::sections() *) function LLVMObjectFileCopySectionIterator(BR: TLLVMBinaryRef): TLLVMSectionIteratorRef; cdecl; external CLLVMLibrary; (* * Returns whether the given section iterator is at the end. * * @see llvm::object::section_end *) function LLVMObjectFileIsSectionIteratorAtEnd(BR: TLLVMBinaryRef; SI: TLLVMSectionIteratorRef): TLLVMBool; cdecl; external CLLVMLibrary; (* * Retrieve a copy of the symbol iterator for this object file. * * If there are no symbols, the result is NULL. * * The returned iterator is merely a shallow copy. Nevertheless, it is * the responsibility of the caller to free it with * \c LLVMDisposeSymbolIterator. * * @see llvm::object::symbols() *) function LLVMObjectFileCopySymbolIterator(BR: TLLVMBinaryRef): TLLVMSymbolIteratorRef; cdecl; external CLLVMLibrary; (* * Returns whether the given symbol iterator is at the end. * * @see llvm::object::symbol_end *) function LLVMObjectFileIsSymbolIteratorAtEnd(BR: TLLVMBinaryRef; SI: TLLVMSymbolIteratorRef): TLLVMBool; cdecl; external CLLVMLibrary; // ObjectFile Section iterators procedure LLVMDisposeSectionIterator(SI: TLLVMSectionIteratorRef); cdecl; external CLLVMLibrary; procedure LLVMMoveToNextSection(SI: TLLVMSectionIteratorRef); cdecl; external CLLVMLibrary; procedure LLVMMoveToContainingSection(Sect: TLLVMSectionIteratorRef; Sym: TLLVMSymbolIteratorRef); cdecl; external CLLVMLibrary; // ObjectFile Symbol iterators procedure LLVMDisposeSymbolIterator(SI: TLLVMSymbolIteratorRef); cdecl; external CLLVMLibrary; procedure LLVMMoveToNextSymbol(SI: TLLVMSymbolIteratorRef); cdecl; external CLLVMLibrary; // SectionRef accessors function LLVMGetSectionName(SI: TLLVMSectionIteratorRef): PLLVMChar; cdecl; external CLLVMLibrary; function LLVMGetSectionSize(SI: TLLVMSectionIteratorRef): UInt64; cdecl; external CLLVMLibrary; function LLVMGetSectionContents(SI: TLLVMSectionIteratorRef): PLLVMChar; cdecl; external CLLVMLibrary; function LLVMGetSectionAddress(SI: TLLVMSectionIteratorRef): UInt64; cdecl; external CLLVMLibrary; function LLVMGetSectionContainsSymbol(SI: TLLVMSectionIteratorRef; Sym: TLLVMSymbolIteratorRef): TLLVMBool; cdecl; external CLLVMLibrary; // Section Relocation iterators function LLVMGetRelocations(Section: TLLVMSectionIteratorRef): TLLVMRelocationIteratorRef; cdecl; external CLLVMLibrary; procedure LLVMDisposeRelocationIterator(RI: TLLVMRelocationIteratorRef); cdecl; external CLLVMLibrary; function LLVMIsRelocationIteratorAtEnd(Section: TLLVMSectionIteratorRef; RI: TLLVMRelocationIteratorRef): TLLVMBool; cdecl; external CLLVMLibrary; procedure LLVMMoveToNextRelocation(RI: TLLVMRelocationIteratorRef); cdecl; external CLLVMLibrary; // SymbolRef accessors function LLVMGetSymbolName(SI: TLLVMSymbolIteratorRef): PLLVMChar; cdecl; external CLLVMLibrary; function LLVMGetSymbolAddress(SI: TLLVMSymbolIteratorRef): UInt64; cdecl; external CLLVMLibrary; function LLVMGetSymbolSize(SI: TLLVMSymbolIteratorRef): UInt64; cdecl; external CLLVMLibrary; // RelocationRef accessors function LLVMGetRelocationOffset(RI: TLLVMRelocationIteratorRef): UInt64; cdecl; external CLLVMLibrary; function LLVMGetRelocationSymbol(RI: TLLVMRelocationIteratorRef): TLLVMSymbolIteratorRef; cdecl; external CLLVMLibrary; function LLVMGetRelocationType(RI: TLLVMRelocationIteratorRef): UInt64; cdecl; external CLLVMLibrary; // NOTE: Caller takes ownership of returned string of the two // following functions. function LLVMGetRelocationTypeName(RI: TLLVMRelocationIteratorRef): PLLVMChar; cdecl; external CLLVMLibrary; function LLVMGetRelocationValueString(RI: TLLVMRelocationIteratorRef): PLLVMChar; cdecl; external CLLVMLibrary; {/** Deprecated: Use LLVMCreateBinary instead. */} function LLVMCreateObjectFile(MemBuf: TLLVMMemoryBufferRef): TLLVMObjectFileRef; cdecl; external CLLVMLibrary; {/** Deprecated: Use LLVMDisposeBinary instead. */} procedure LLVMDisposeObjectFile(ObjectFile: TLLVMObjectFileRef); cdecl; external CLLVMLibrary; {/** Deprecated: Use LLVMObjectFileCopySectionIterator instead. */} function LLVMGetSections(ObjectFile: TLLVMObjectFileRef): TLLVMSectionIteratorRef; cdecl; external CLLVMLibrary; {/** Deprecated: Use LLVMObjectFileIsSectionIteratorAtEnd instead. */} function LLVMIsSectionIteratorAtEnd(ObjectFile: TLLVMObjectFileRef; SI: TLLVMSectionIteratorRef): TLLVMBool; cdecl; external CLLVMLibrary; {/** Deprecated: Use LLVMObjectFileCopySymbolIterator instead. */} function LLVMGetSymbols(ObjectFile: TLLVMObjectFileRef): TLLVMSymbolIteratorRef; cdecl; external CLLVMLibrary; {/** Deprecated: Use LLVMObjectFileIsSymbolIteratorAtEnd instead. */} function LLVMIsSymbolIteratorAtEnd(ObjectFile: TLLVMObjectFileRef; SI: TLLVMSymbolIteratorRef): TLLVMBool; cdecl; external CLLVMLibrary; implementation end.
{ LEOShell - Intérprete de comandos experimental Copyright (C) 2015 - Valentín Costa - Leandro Lonardi This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit Comandos; {$mode objfpc} interface uses BaseUnix, Unix, CRT, SysUtils, Controles; procedure ejecutar( comando: arregloStrings ); implementation { procedimiento BG: Envía a un proceso detenido la señal de continuación (SIGCONT) para que continúe su ejecución en segundo plano. Si no se especifica un PID, la señal es enviada al último proceso que ha sido detenido. En la terminal, el comando es: bg [pid] } procedure bg( argumentos: arregloStrings ); var pid: longint; begin // Si el comando no posee argumentos, trabaja con el PID del último proceso // detenido. if high( argumentos ) = 0 then pid := ultimoProceso else // Convierte el string a su valor numérico. val( argumentos[1], pid ); // Si la señal se envía con éxito, modifica el estado del proceso y // muestra un mensaje. if fpKill( pid, SIGCONT ) = 0 then begin modificarProceso( pid, 'Ejecutando' ); writeln( '(', pid, ') ', comandoProceso( pid ), ' &' ); end else writeLn( 'No existe el proceso.' ) end; { procedimiento CD: Cambia el directorio de trabajo actual utilizando la función fpChDir. Si no se especifican argumentos, cambia al directorio home. En la terminal, el comando es: cd [directorio] } procedure cd( argumentos: arregloStrings ); begin // Si el comando no posee argumentos, cambia el directorio a home. if high( argumentos ) = 0 then fpChDir( fpGetEnv( 'HOME' ) ) else // Si el directorio es incorrecto o el cambio no se puede efectuar, // muestra un mensaje. if fpChDir( argumentos[1] ) = -1 then writeLn( 'No existe el directorio.' ); end; { procedimiento CAT: Concatena uno o dos archivos con la salida estándar. En la terminal, el comando es: cat [archivo1] [archivo2] } procedure cat( argumentos: arregloStrings ); var archivo1, archivo2: text; texto: string; begin // Si el comando no posee argumentos, muestra un mensaje. if high(argumentos) = 0 then begin writeLn( 'Debe ingresar al menos un archivo como argumento.' ); writeLn( 'cat <archivo 1> <archivo 2>' ); end else begin {$I-} assign( archivo1, argumentos[1] ); reset( archivo1 ); {$I+} // Si hay error, muestra un mensaje. if IOResult <> 0 then writeln( 'No existe el primer archivo.' ) else begin // Mientras no llegue al final del archivo, lo lee y lo escribe. while not eof( archivo1 ) do begin readLn( archivo1, texto ); writeLn( texto ); end; close( archivo1 ); end; // Si el comando posee un segundo archivo, trabaja con él. if high( argumentos ) = 2 then begin {$I-} assign( archivo2, argumentos[2] ); reset( archivo2 ); {$I+} // Si hay error, muestra un mensaje. if IOResult <> 0 then writeln( 'No existe el segundo archivo.' ) else begin // Mientras no llegue al final del archivo, lo lee y lo escribe. while not eof( archivo2 ) do begin readLn( archivo2, texto ); writeLn( texto ); end; close( archivo2 ); end; end; end; end; { procedimiento HIJO TERMINÓ: Utilizado por externo() para reconocer que el proceso hijo a terminado, es decir, que el proceso padre recibió la señal SIGCHLD. } procedure hijoTermino( senal: longint ); cdecl; begin hijoTerminado := true; end; { procedimiento EXTERNO: Ejecuta un comando externo y controla la ejecución del mismo, pudiendo detenerlo o interrumpirlo. Utiliza fpFork() y fpExecLP() para realizarlo. Nota: el uso de la unit CRT provoca que la impresión de los comandos externos sea errónea. } procedure externo( argumentos: arregloStrings ); var args: array of ansistring; comando: string; i: byte; pid: longint; segundoPlano: boolean; tecla: char; begin // Inicializa tecla para que contenga algún valor. tecla := #0; // Establece que, al arrancar, el proceso hijo no ha terminado. hijoTerminado := false; // Almacena el comando "principal" (ej. 'wc', 'yes' o 'ps'). comando := argumentos[0]; // Por defecto asume que el comando externo no se ejecuta en segundo plano. segundoPlano := false; // Recorre los argumentos. for i := 1 to high( argumentos ) do // Si encuentra un '&', debe ejecutarse en segundo plano. if argumentos[i] = '&' then segundoPlano := true // Si no, guarda como argumento del comando externo. else begin setLength( args, i ); args[i-1] := argumentos[i]; end; pid := fpFork(); case pid of // En caso de error, muestra un mensaje. -1: writeLn( 'Error al crear el proceso hijo.' ); // Proceso hijo: ejecuta el comando externo. 0: fpExecLP( comando, args ); // Proceso padre: controla la ejecución del proceso hijo. else fpSignal( SIGCHLD, @hijoTermino ); if segundoPlano then // Agrega a la lista de procesos en segundo plano. agregarProceso( pid, entrada, 'Ejecutando' ) else begin // Mientras no se presione una tecla o termine el proceso hijo, // no sigue con la ejecución del código. Esto es necesario para no // tener que leer una tecla si el proceso hijo terminó enseguida // luego de su ejecución. while not (keyPressed() or hijoTerminado) do; // Se repite hasta que presione CTRL+Z/CTRL+C o el hijo termine. repeat // Si el proceso hijo no termió, lee una tecla. if not hijoTerminado then tecla := readKey(); case tecla of // CTRL+C #3: begin // Envía la señal de interrupción. fpKill( pid, SIGINT ); // Informa de su interrupción. writeLn( #10 + #13 + 'Proceso interrumpido (', pid, ').' ); // Agrega a la lista de procesos en segundo plano. agregarProceso( pid, entrada, 'Terminado' ); end; // CTRL+Z #26: begin // Envía la señal de detención. fpKill( pid, SIGSTOP ); // Almacena el PID como el último proceso detenido. ultimoProceso := pid; // Informa de su detención. writeLn( #10 + #13 + 'Proceso detenido (', pid, ').' ); // Agrega a la lista de procesos en segundo plano. agregarProceso( pid, entrada, 'Detenido' ); end; end; until (tecla = #3) or (tecla = #26) or hijoTerminado; end; // Salto de línea necesario para ubicar correctamente el prompt. writeln(); end; end; { procedimiento FG: Envía a un proceso detenido la señal de continuación (SIGCONT) para que continúe su ejecución en primer plano, siendo posible detenerlo o terminarlo. Si no se especifica un PID, la señal es enviada al último proceso que ha sido detenido. En la terminal, el comando es: fg [pid] } procedure fg( argumentos: arregloStrings ); var pid: longint; tecla: char; begin // Si el comando no posee argumentos, trabaja con el PID del último proceso // detenido. if high( argumentos ) = 0 then pid := ultimoProceso else // Convierte el string a su valor numérico. val( argumentos[1], pid ); // Si la señal no se envía con éxito, muestra un mensaje. if fpKill( pid, SIGCONT ) <> 0 then writeLn( 'No existe el proceso.' ) else begin // Se repite hasta que presione CTRL+Z o CTRL+C. repeat tecla := readKey(); case tecla of // CTRL+C #3: begin // Envía la señal de interrupción. fpKill( pid, SIGINT ); // Informa de su interrupción. writeLn( #10 + #13 + 'Proceso interrumpido (', pid, ').' ); // Modifica el estado del proceso. modificarProceso( pid, 'Terminado'); end; // CTRL+Z #26: begin // Envía la señal de detención. fpKill( pid, SIGSTOP ); // Almacena el PID como el último proceso detenido. ultimoProceso := pid; // Informa de su detención. writeLn( #10 + #13 + 'Proceso detenido (', pid, ').' ); // Modifica el estado del proceso. modificarProceso( pid, 'Detenido'); end; end; until (tecla = #3) or (tecla = #26); end end; { procedimiento JOBS: Muestra la lista de procesos ejecutados en segundo plano, junto con su PID, comando asociado y estado actual. En la terminal, el comando es: jobs } procedure jobs(); var i: byte; begin if cantidadProcesos <> 0 then for i := 0 to high( listaProcesos ) do with listaProcesos[i] do writeLn( '(', pid, ') ', comando, ' <', estado, '>') else writeLn( 'No hay trabajos.' ); end; { procedimiento KILL: Envía una señal a un proceso utilizando la función fpKill(). Si sólo se especifica un PID, la señal enviada es la de terminación (SIGTERM). En la terminal, el comando es: kill [número de señal] [pid] } procedure kill( argumentos: arregloStrings ); var pid, senal: integer; begin // Si el comando posee argumentos, muestra un mensaje. if high( argumentos ) = 0 then begin writeln('Debe ingresar un PID y una señal.'); writeln('kill [número de señal] [pid]'); end else begin // Si el comando sólo posee un argumento, asume que es un PID y envía // la señal de terminación (SIGTERM) al proceso. if high( argumentos ) = 1 then begin // Convierte el string a su valor numérico. val( argumentos[1], pid ); // Si la señal se envía con éxito, muestra un mensaje. if fpKill( pid, SIGTERM ) = 0 then writeLn( 'El proceso se ha terminado.' ) else writeLn( 'No existe el proceso.' ) end else begin // Convierte los strings a sus valores numéricos. val( argumentos[1], senal ); val( argumentos[2], pid ); // Si la señal se envía con éxito, muestra un mensaje. if fpKill( pid, senal ) = 0 then writeLn( 'Señal enviada.' ) else writeLn( 'No existe el proceso.' ); end; end; end; { procedimiento LS: Guarda en un arreglo todos los archivos encontrados en el directorio especificado para luego listarlos, de acuerdo a la opción pasada como argumento (opcional). Si ningún directorio es dado, utiliza el actual. En la terminal, el comando es: ls [opción] [directorio] } procedure ls( argumentos: arregloStrings ); var directorio: pDir; entrada: pDirent; i: word; lista: arregloDirents; opcion: char; ruta: string; begin // Índice del arreglo. i := 1; // Ruta a listar por defecto. ruta := directorioActual; // Recorre los argumentos (arreglo) hasta encontrar una ruta, es decir, // un argumento que comience con '/'. while (i <= high( argumentos )) and (ruta = directorioActual) do begin if argumentos[i][1] = '/' then ruta := argumentos[i]; inc( i ); end; // Abre el directorio directorio := fpOpenDir( ruta ); // Tamaño inicial del arreglo. i := 0; // Agrega todos los archivos del directorio a "lista" (arreglo). repeat entrada := fpReadDir( directorio^ ); if entrada <> nil then begin setLength( lista, i + 1 ); lista[i] := entrada^; inc( i ); end; until entrada = nil; // Cierra el directorio. fpCloseDir( directorio^ ); // Índice del arreglo. i := 1; // Opción por defecto para listar los archivos opcion := '_'; // Recorre los argumentos hasta encontrar una opción, es decir, un // argumento que comience con '-'. while (i <= high( argumentos )) and (opcion = '_') do begin // Si es una opción, guarda el segundo caracter (ej. 'a' de '-a'). if argumentos[i][1] = '-' then opcion := argumentos[i][2]; inc( i ); end; listarArchivos( lista, opcion ); end; { procedimiento TUBERÍA: Luego de definir el primer y segundo comando, ejecuta el primero para que el resultado del mismo sea utilizado como argumento del segundo, mediante un archivo. } procedure tuberia( comando: arregloStrings ); var archivo: ^file; i, j: byte; nombreArchivo: string; primerComando, segundoComando: arregloStrings; temporal: longint; begin // Índice del arreglo del primer comando. i := 0; // Mientras no encuentre '|', guarda en el arreglo "primerComando". while comando[i] <> '|' do begin setLength( primerComando, i + 1); primerComando[i] := comando[i]; inc( i ); end; // En este punto, "i" contiene el índice donde comienza el segundo comando. inc( i ); // Índice del arreglo del segundo comando. j := 0; // Mientras no se termine el comando, guarda en el arreglo "segundoComando". while i <= high( comando ) do begin setLength( segundoComando, j + 1); segundoComando[j] := comando[i]; inc( i ); inc( j ); end; // Nombre del archivo utilizado temporalmente durante la ejecución. nombreArchivo := primerComando[0]; // Crea una variable dinámica a partir del puntero "archivo". new( archivo ); // Asigna el nombre al archivo. assign( archivo^, nombreArchivo ); // Crea y abre el archivo para su escritura. reWrite( archivo^ ); // Almacena temporalmente el identificador de la salida estándar. temporal := fpDup( stdOutputHandle ); // Establece al archivo como salida estándar. fpDup2( fileRec( archivo^ ).handle, stdOutputHandle ); ejecutar( primerComando ); // Reestablece la salida estándar. fpDup2( temporal, stdOutputHandle ); close( archivo^ ); fpClose( temporal ); // Agrega el archivo como argumento. setLength( segundoComando, j+1 ); segundoComando[j] := nombreArchivo; ejecutar( segundoComando ); // Borra el archivo. deleteFile( nombreArchivo ); end; { procedimiento PWD: Muestra el directorio actual de trabajo. En la terminal, el comando es: pwd } procedure pwd(); begin writeLn( directorioActual ); end; { procedimiento REDIRECCIÓN: Luego de definir el comando, escribe su salida en el archivo especificado (si no existe, lo crea), sobreescibiéndolo o agregando al final del mismo, según corresponda. } procedure redireccion( comando: arregloStrings ); var archivo: ^text; i: byte; nombreArchivo, operador: string; primerComando: arregloStrings; temporal: longint; begin // Índice del arreglo del primer comando. i := 0; // Mientras no encuentre '|', guarda en el arreglo "primerComando". while (comando[i] <> '>') and (comando[i] <> '>>') do begin setLength( primerComando, i + 1); primerComando[i] := comando[i]; inc( i ); end; // Almacena el operador de redireccionamiento. operador := comando[i]; inc( i ); // Almacena el nombre del archivo al cual redireccionar la salida. nombreArchivo := comando[i]; // Crea una variable dinámica a partir del puntero "archivo". new( archivo ); // Asigna el nombre al archivo. assign( archivo^, nombreArchivo ); if operador = '>' then {$I-} // Abre el archivo para escitura y borra su contenido. Si no existe, // previamente lo crea. reWrite( archivo^ ) {$I+} else {$I-} // Si existe el archivo, lo abre para escribir al final. if fileExists( nombreArchivo ) then append( archivo^ ) // Si no, lo crea y abre para su escritura. else reWrite( archivo^ ); {$I+} // Almacena temporalmente el identificador de la salida estándar. temporal := fpDup( stdOutputHandle ); // Establece al archivo como salida estándar. fpDup2( textRec( archivo^ ).handle, stdOutputHandle ); // Si hay error, muestra un mensaje. if IOResult() <> 0 then writeLn( 'Error en la escritura del archivo.' ) else begin ejecutar( primerComando ); // Reestablece la salida estándar. fpDup2( temporal, stdOutputHandle ); close( archivo^ ); fpClose( temporal ); end; end; { procedimiento EJECUTAR: Llama al procedimiento correspondiente de acuerdo al comando solicitado, pasándole como parámetro el arreglo que contiene los argumentos necesarios para su ejecución. } procedure ejecutar( comando: arregloStrings ); begin if (hayOperador( comando ) = '>') or (hayOperador( comando ) = '>>') then redireccion( comando ) else if hayOperador( comando ) = '|' then tuberia( comando ) else if comando[0] = 'bg' then bg( comando ) else if comando[0] = 'cat' then cat( comando ) else if comando[0] = 'cd' then cd( comando ) else if comando[0] = 'fg' then fg( comando ) else if comando[0] = 'jobs' then jobs() else if comando[0] = 'kill' then kill( comando ) else if comando[0] = 'ls' then ls( comando ) else if comando[0] = 'pwd' then pwd() else externo( comando ); end; end.
unit llPDFImage; {$i pdf.inc} interface uses {$ifndef USENAMESPACE} Windows, SysUtils, Classes, Graphics, Math, Jpeg, {$else} WinAPI.Windows, System.SysUtils, System.Classes, Vcl.Graphics, System.Math, Vcl.Imaging.jpeg, {$endif} llPDFTypes,llPDFEngine; type TImgPoint = record x: integer; y: integer; end; TImgBorder = record LeftTop:TImgPoint; RightBottom:TImgPoint; end; TBWImage = class private FBuffer: PCardinalArray; FHeight: Integer; FWidth: Integer; FLineSize :Integer; FMemorySize: Integer; function GetPixel(X, Y: Integer): Boolean; function NormalizeSize(X,Y: integer;var W, H: integer): Boolean; procedure SetPixel(X, Y: Integer; const Value: Boolean); public constructor Create(W,H: Integer;InitialColorIsBlack:Boolean=False); overload; constructor Create(BMP: TBitmap);overload; constructor CreateCopy(Img: TBWImage); destructor Destroy;override; procedure ClearRectangle(X, Y, W, H: Integer); procedure CopyRectangleTo(Destination: TBWImage;SX, SY, DX, DY, W, H: Integer; ClearDestination: Boolean = False); procedure CopyToBitmap(BMP: TBitmap); function CheckNeighbor(X, Y, Level: integer): boolean; function GetBlackPoint(var BlackPoint: TImgPoint): Boolean; function GetBorder(StartPosition: TImgPoint): TImgBorder; procedure DrawHorLine(XStart,XEnd, Y:Integer;IsBlack:Boolean); procedure MoveAndClear(DestSymbol: TBWImage; StartPosition: TImgPoint;Border: TImgBorder); procedure InitBlackPoint(var BlackPoint: TImgPoint); procedure SaveToFile(FileName:String); property Pixel[X,Y: Integer]:Boolean read GetPixel write SetPixel; property Width: Integer read FWidth; property Height: Integer read FHeight; property Memory: PCardinalArray read FBuffer; property MemorySize: Integer read FMemorySize; end; TJBIG2Options = class( TPersistent) private FLossyLevel: Integer; FSkipBlackDots: Boolean; FBlackDotSize: Integer; FSymbolExtract: TImgCopyType; // FUseSingleDictionary: Boolean; public constructor Create; property LossyLevel: Integer read FLossyLevel write FLossyLevel ; property SkipBlackDots:Boolean read FSkipBlackDots write FSkipBlackDots; property BlackDotSize: Integer read FBlackDotSize write FBlackDotSize; property SymbolExtract:TImgCopyType read FSymbolExtract write FSymbolExtract; // property UseSingleDictionary: Boolean read FUseSingleDictionary write FUseSingleDictionary; end; TPDFImages = class; TPDFImage = class(TPDFObject) private FBitPerPixel: Integer; FBWInvert: Boolean; FCompression: TImageCompressionType; FData: TMemoryStream; FJBIG2Data: TMemoryStream; FGrayScale: Boolean; FHeight: Integer; FIsMask: Boolean; FLoaded: Boolean; FMaskIndex: Integer; FWidth: Integer; FOwner: TPDFImages; protected procedure Save;override; public constructor Create(Engine: TPDFEngine;AOwner: TPDFImages); destructor Destroy; override; procedure Load(Image:TGraphic; Compression: TImageCompressionType); property IsMask: Boolean read FIsMask write FIsMask; property BitPerPixel: Integer read FBitPerPixel; property GrayScale: Boolean read FGrayScale; property Height: Integer read FHeight; property Width:Integer read FWidth; end; TPDFImages = class(TPDFManager) private FJPEGQuality: Integer; {$ifndef BASE} FJBIG2Options: TJBIG2Options; FJBIG2Dictionary: TPDFObject; {$endif} function Add(Image:TPDFImage):Integer; function AddImageWithParams(Image: TGraphic; Compression: TImageCompressionType;MaskIndex:Integer = - 1): Integer; protected procedure Clear;override; function GetCount: Integer;override; procedure Save;override; public constructor Create(PDFEngine: TPDFEngine); destructor Destroy;override; function AddImage(Image: TGraphic; Compression: TImageCompressionType): Integer; overload; function AddImage(FileName:TFileName; Compression: TImageCompressionType): Integer; overload; function AddImageAsMask(Image: TGraphic; TransparentColor: TColor = -1): Integer; function AddImageWithMask(Image:TGraphic; Compression: TImageCompressionType;MaskIndex: Integer): Integer; function AddImageWithTransparency(Image: TGraphic; Compression: TImageCompressionType; TransparentColor: TColor = -1): Integer; property JPEGQuality: Integer read FJPEGQuality write FJPEGQuality ; {$ifndef BASE} property JBIG2Options: TJBIG2Options read FJBIG2Options; {$endif} end; implementation uses {$ifdef WIN64} System.ZLib, System.ZLibConst, {$else} llPDFFlate, {$endif} llPDFMisc, llPDFResources, llPDFCCITT, {$ifndef BASE}llPDFJBIG2, {$endif} llPDFSecurity, llPDFCrypt; { TPDFImages } { ********************************** TPDFImages ********************************** } function TPDFImages.AddImage(FileName: TFileName; Compression: TImageCompressionType): Integer; var Gr: TGraphic; MS: TMemoryStream; BMSig: Word; begin MS := TMemoryStream.Create; try MS.LoadFromFile ( FileName ); MS.Position := 0; MS.Read ( BMSig, 2 ); MS.Position := 0; if BMSig = 19778 then GR := TBitmap.Create else GR := TJPEGImage.Create; try Gr.LoadFromStream ( MS ); Result := AddImage ( Gr, Compression ); finally Gr.Free; end; finally MS.Free; end; end; function TPDFImages.AddImageWithParams(Image: TGraphic; Compression: TImageCompressionType;MaskIndex:Integer = - 1): Integer; var PDFImage: TPDFImage; DIB: DIBSECTION; B: TBitmap; begin if Compression >= itcCCITT3 then begin if not ( Image is TBitmap ) then raise EPDFException.Create ( SCCITTCompressionWorkOnlyForBitmap ); B := TBitmap ( Image ); if B.PixelFormat <> pf1bit then begin if B.PixelFormat = pfDevice then begin DIB.dsBmih.biSize := 0; GetObject( B.Handle, sizeof (DIB), @DIB); if DIB.dsBm.bmBitsPixel = 1 then B.PixelFormat := pf1bit else raise Exception.Create ( SCannotCompressNotMonochromeImageViaCCITT ); end else raise Exception.Create ( SCannotCompressNotMonochromeImageViaCCITT ); end; end; PDFImage := TPDFImage.Create( FEngine, self ); try PDFImage.Load( Image, Compression); except PDFImage.Free; raise; end; PDFImage.FIsMask := False; PDFImage.FMaskIndex := MaskIndex; PDFImage.Save; Result := Add (PDFImage); {$ifndef BASE} if TJBig2SymbolDictionary(FJBIG2Dictionary).TotalWidth > 131071 then begin FEngine.SaveObject(FJBIG2Dictionary); TJBig2SymbolDictionary(FJBIG2Dictionary).Clear; end; {$endif} end; function TPDFImages.AddImage(Image: TGraphic; Compression: TImageCompressionType): Integer; begin Result := AddImageWithParams(Image,Compression); end; function TPDFImages.AddImageAsMask(Image: TGraphic; TransparentColor: TColor = -1): Integer; var B: TBitmap; PDFImage: TPDFImage; begin Result := -1; if not ( Image is TBitmap ) then raise EPDFException.Create ( SCreateMaskAvailableOnlyForBitmapImages ); B := TBitmap.Create; try B.Assign ( Image ); B.PixelFormat := pf24bit; if TransparentColor = -1 then TransparentColor := B.TransparentColor; B.Mask ( TransparentColor ); B.Monochrome := True; B.PixelFormat := pf1bit; PDFImage := TPDFImage.Create( FEngine, Self ); try PDFImage.Load( B, itcCCITT4); except PDFImage.Free; raise; end; with PDFImage do begin FIsMask := True; FBitPerPixel := 1; FGrayScale := True; end; PDFImage.Save; Result := Add (PDFImage); finally B.Free; end; end; function TPDFImages.AddImageWithMask(Image:TGraphic; Compression: TImageCompressionType;MaskIndex: Integer): Integer; begin if MaskIndex >= Count then raise EPDFException.Create ( SUnknowMaskImageOutOfBound ); if not TPDFImage ( FEngine.Resources.Images [ MaskIndex ] ).FIsMask then raise EPDFException.Create ( SMaskImageNotMarkedAsMaskImage ); Result := AddImageWithParams(Image, Compression,MaskIndex); end; function TPDFImages.AddImageWithTransparency(Image: TGraphic; Compression: TImageCompressionType; TransparentColor: TColor = -1): Integer; var MaskIndex: Integer; begin MaskIndex := AddImageAsMask( Image, TransparentColor); Result := AddImageWithMask( Image, Compression, MaskIndex); end; procedure TPDFImages.Clear; var i: Integer; begin for i:= 0 to Length(FEngine.Resources.Images) -1 do begin TPDFImage( FEngine.Resources.Images[i]).Free; end; FEngine.Resources.Images := nil; {$ifndef BASE} TJBig2SymbolDictionary(FJBIG2Dictionary).ClearDictionary; {$endif} inherited; end; function TPDFImages.GetCount: Integer; begin Result := Length(FEngine.Resources.Images); end; procedure TPDFImages.Save; begin {$ifndef BASE} if TJBig2SymbolDictionary(FJBIG2Dictionary).TotalWidth > 0 then begin FEngine.SaveObject(FJBIG2Dictionary); TJBig2SymbolDictionary(FJBIG2Dictionary).Clear; end; {$endif} end; function TPDFImages.Add(Image: TPDFImage): Integer; var i: Integer; begin i := Length(FEngine.Resources.Images); SetLength(FEngine.Resources.Images, i+1); FEngine.Resources.Images[i]:= Image; Result := i; end; { TPDFImage } { ********************************** TPDFImage *********************************** } constructor TPDFImage.Create(Engine: TPDFEngine;AOwner: TPDFImages ); begin inherited Create ( Engine ); FLoaded := False; FMaskIndex := -1; FIsMask := False; FOwner := AOwner; FJBIG2Data := nil; end; destructor TPDFImage.Destroy; begin inherited; end; procedure TPDFImage.Load(Image:TGraphic; Compression: TImageCompressionType); var J: TJPEGImage; B: TBitmap; CS: TCompressionStream; {$ifndef BASE} Global: TJBig2SymbolDictionary; JBIG2Compression : TJBIG2Compression; {$endif} pb: PByteArray; bb: Byte; p: Byte; x, y: Integer; begin if not ( ( Image is TJPEGImage ) or ( Image is TBitmap ) ) then raise EPDFException.Create ( SNotValidImage ); if ( Image is TBitmap ) and ( TBitmap ( Image ).PixelFormat = pf1bit ) and ( Compression <> itcJpeg ) then begin pb := TBitmap ( Image ).ScanLine [ 0 ]; bb := pb [ 0 ] shr 7; if TBitmap ( Image ).Canvas.Pixels [ 0, 0 ] > 0 then p := 1 else p := 0; FBWInvert := p <> bb; end else FBWInvert := False; FWidth := Image.Width; FHeight := Image.Height; FCompression := Compression; FData := TMemoryStream.Create; // if FOwner.FJBIG2Options.UseSingleDictionary then // Global := TJBig2SymbolDictionary(FOwner.FJBIG2Dictionary) // else {$ifndef BASE} Global := nil; {$endif} case Compression of itcJpeg: begin J := TJPEGImage.Create; try J.Assign ( Image ); J.ProgressiveEncoding := False; J.CompressionQuality := FOwner.FJPEGQuality; J.SaveToStream ( FData ); if J.Grayscale then FGrayscale := True; FBitPerPixel := 8; finally J.Free; end; end; itcFlate: begin B := TBitmap.Create; try B.Assign ( Image ); b.PixelFormat := pf24bit; CS := TCompressionStream.Create ( clDefault, FData ); try for y := 0 to B.Height - 1 do begin pb := B.ScanLine [ y ]; x := 0; while x <= ( b.Width - 1 ) * 3 do begin bb := pb [ x ]; pb [ x ] := pb [ x + 2 ]; pb [ x + 2 ] := bb; x := x + 3; end; CS.Write ( pb^, b.Width * 3 ); end; finally CS.Free; end; FBitPerPixel := 8; FGrayScale := False; finally B.Free; end; end; itcCCITT3..{$ifndef BASE}itcJBIG2{$else} itcCCITT4{$endif}: begin B := TBitmap ( Image ); FBitPerPixel := 1; case Compression of itcCCITT3: SaveBMPtoCCITT ( B, FData, CCITT31D ); itcCCITT32d: SaveBMPtoCCITT ( B, FData, CCITT32D ); itcCCITT4: SaveBMPtoCCITT ( B, FData, CCITT42D ); {$ifndef BASE} itcJBIG2: begin JBIG2Compression := TJBIG2Compression.Create(Global,FOwner.JBIG2Options); try JBIG2Compression.Execute(FData,B); finally JBIG2Compression.Free; end; end; {$endif} end; end; end; FLoaded := True; end; procedure TPDFImage.Save; var Invert: AnsiString; begin Eng.StartObj ( ID ); Eng.SaveToStream ( '/Type /XObject' ); Eng.SaveToStream ( '/Subtype /Image' ); if ( FBitPerPixel <> 1 ) and ( not FGrayScale ) then Eng.SaveToStream ( '/ColorSpace /DeviceRGB' ) else Eng.SaveToStream ( '/ColorSpace /DeviceGray' ); Eng.SaveToStream ( '/BitsPerComponent ' + IStr ( FBitPerPixel ) ); Eng.SaveToStream ( '/Width ' + IStr ( FWidth ) ); Eng.SaveToStream ( '/Height ' + IStr ( FHeight ) ); if FIsMask then Eng.SaveToStream ( '/ImageMask true' ); if FMaskIndex <> -1 then Eng.SaveToStream ( '/Mask ' + TPDFImage ( Eng.Resources.Images [ FMaskIndex ] ).RefID ); case FCompression of itcJpeg: Eng.SaveToStream ( '/Filter /DCTDecode' ); itcFlate: Eng.SaveToStream ( '/Filter /FlateDecode' ); {$ifndef BASE} itcJBIG2: Eng.SaveToStream ( '/Filter /JBIG2Decode' ); {$endif} else begin Eng.SaveToStream ( '/Filter [/CCITTFaxDecode]' ); if FBWInvert then Invert := '/BlackIs1 true' else Invert := ''; end; end; Eng.SaveToStream ( '/Length ' + IStr ( CalcAESSize(Eng.SecurityInfo.State, FData.Size ) ) ); case FCompression of itcCCITT3: Eng.SaveToStream ( '/DecodeParms [<</K 0 /Columns ' + IStr ( FWidth ) + ' /Rows ' + IStr ( FHeight ) + Invert +'>>]' ); itcCCITT32d: Eng.SaveToStream ( '/DecodeParms [<</K 1 /Columns ' + IStr ( FWidth ) + ' /Rows ' + IStr ( FHeight ) + Invert + '>>]' ); itcCCITT4: Eng.SaveToStream ( '/DecodeParms [<</K -1 /Columns ' + IStr ( FWidth ) + ' /Rows ' + IStr ( FHeight ) + Invert + '>>]' ); {$ifndef BASE} itcJBIG2: begin // if FOwner.FJBIG2Options.FUseSingleDictionary then // Eng.SaveToStream('/DecodeParms <</JBIG2Globals '+IntToStr(FOwner.FJBIG2Dictionary.ID)+' 0 R >>'); end; {$endif} end; Eng.StartStream; CryptStream ( FData ); FData.Free; Eng.CloseStream; end; { TBWImage } procedure TBWImage.ClearRectangle(X, Y, W, H: Integer); var I,J: integer; Start,Finish,StartBit, FinishBit, Offset:Integer; Count : Integer; begin if not NormalizeSize(X,Y,W,H) then Exit; Offset := Y*FLineSize; Start := X shr 5 ; StartBit := X and 31; if StartBit = 0 then begin Count := W shr 5; FinishBit := W and 31; for i := 0 to H - 1 do begin for j := 0 to Count - 1 do FBuffer[Offset+Start+j] := 0; if FinishBit <> 0 then FBuffer[Offset+Start+Count] := FBuffer[Offset+Start+Count] and ($FFFFFFFF shr FinishBit); Inc(Offset,FLineSize); end; Exit; end; StartBit := 32 - StartBit; Finish := (X + W) shr 5; FinishBit := (X + W) and 31; for i := 0 to H - 1 do begin if Start <> Finish then begin FBuffer[Start+Offset] := FBuffer[Start+Offset] and ($FFFFFFFF shl StartBit); for j:= Start + 1 to Finish - 1 do FBuffer[j+Offset] := 0; if FinishBit <> 0 then FBuffer[Finish+Offset] := FBuffer[Finish+Offset] and ($FFFFFFFF shr FinishBit); end else begin FBuffer[Start+Offset] := FBuffer[Start+Offset] and (($FFFFFFFF shl StartBit) or ($FFFFFFFF shr FinishBit)); end; Inc(Offset,FLineSize); end; end; procedure TBWImage.CopyRectangleTo(Destination: TBWImage;SX, SY, DX, DY, W, H: Integer; ClearDestination: Boolean = False); var i, t, j: Integer; Tmp: TBWImage; Wrk, WrkDest: integer; Full, Part:Cardinal; Start,StartBit, Offset, C:Cardinal; OffsetDest: Cardinal; StartBitDest: Cardinal; StartDest: Cardinal; begin if not Destination.NormalizeSize(DX,DY,W,H) then Exit; if not NormalizeSize(SX,SY,W,H) then Exit; if Destination = Self then begin Tmp := TBWImage.Create(W,H); try CopyRectangleTo(Tmp,Sx,SY,0,0,W,H); Tmp.CopyRectangleTo(Tmp,0,0,Dx,Dy,W,H); finally Tmp.Free; end; Exit; end; if ClearDestination then Destination.ClearRectangle(DX,DY,W,H); Full := (W+31) shr 5; T := Full - 1; Part := W and 31; Start := SX shr 5 ; StartBit := SX and 31; Offset := SY*FLineSize; StartDest := DX shr 5 ; StartBitDest := DX and 31; OffsetDest := DY*Destination.FLineSize; Wrk := Offset + Start; WrkDest := OffsetDest + StartDest; for i := 0 to H - 1 do begin for j := 0 to Full - 1 do begin if StartBit = 0 then C := FBuffer[wrk+j] else begin C := FBuffer[wrk+j] shl StartBit or FBuffer[wrk+j+1] shr (32- StartBit); end; if (Part <> 0) and (j = t) then C := C and ($FFFFFFFF shl (32-Part)); if StartBitDest = 0 then begin Destination.FBuffer[WrkDest+j] := Destination.FBuffer[WrkDest+j] or C; end else begin Destination.FBuffer[WrkDest+j] := Destination.FBuffer[WrkDest+j] or (C shr StartBitDest); Destination.FBuffer[WrkDest+j+1] := Destination.FBuffer[WrkDest+j+1] or (C shl (32 - StartBitDest)); end; end; Inc(Wrk,FLineSize); Inc(WrkDest,Destination.FLineSize); end; end; procedure TBWImage.CopyToBitmap(BMP: TBitmap); var i,j: Cardinal; Off: Cardinal; Dst:PCardinalArray; begin bmp.PixelFormat := pf1bit; bmp.Width := Width; bmp.Height := Height; Off := 0; for j := 0 to FHeight - 1 do begin Dst := BMP.ScanLine[j]; for i := 0 to FLineSize - 1 do Dst[i] := not ByteSwap(FBuffer[off+i]); inc(off,FLineSize); end; end; constructor TBWImage.Create(W,H: Integer;InitialColorIsBlack:Boolean=False); var I: Integer; Color:Cardinal; begin FWidth := W; FHeight := H; FLineSize := (W+31) shr 5; FMemorySize := H * FLineSize; FBuffer := GetMemory((FMemorySize+1) shl 5 ); if InitialColorIsBlack then Color := $FFFFFFFF else Color := 0; for I := 0 to FMemorySize do FBuffer[i] := Color; end; constructor TBWImage.CreateCopy(Img: TBWImage); begin FWidth := Img.Width; FHeight := Img.FHeight; FLineSize := (FWidth+31) shr 5; FMemorySize := FHeight * FLineSize; FBuffer := GetMemory((FMemorySize+1) shl 5 ); Move(Img.FBuffer[0],FBuffer[0], (FMemorySize+1) shl 5 ); end; constructor TBWImage.Create(BMP: TBitmap); var i,J: Cardinal; Off: Cardinal; inverse:Boolean; MemBlack,CanvasBlack:Boolean; C: Cardinal; Src:PCardinalArray; Bits: Integer; Mask : Cardinal; begin if bmp.PixelFormat <> pf1bit then raise Exception.Create('Creation possible for b/w images only'); Create(BMP.Width,BMP.Height); MemBlack := PByte(BMP.ScanLine[0])^ and $80 <> 0; CanvasBlack:= BMP.Canvas.Pixels[0,0]= clBlack; inverse := MemBlack <> CanvasBlack; Off := 0; Bits := FWidth and 31; if Bits <> 0 then Mask := not($FFFFFFFF shr Bits) else Mask := $FFFFFFFF; for i := 0 to FHeight - 1 do begin Src := BMP.ScanLine[i]; for j := 0 to FLineSize - 1 do begin C := byteswap(Src[j]); if inverse then C := not C; FBuffer[off+j] := C; end; inc(off,FLineSize); if Bits <> 0 then FBuffer[Off - 1] := FBuffer[Off - 1] and Mask; end; end; destructor TBWImage.Destroy; begin FreeMemory(FBuffer); inherited; end; procedure TBWImage.SetPixel(X, Y: Integer; const Value: Boolean); var C, Mask: Cardinal; begin C := Y * FLineSize+ X shr 5; Mask := 1 shl (31 - X and 31); if Value then FBuffer[C] := FBuffer[C] or Mask else FBuffer[C] := FBuffer[C] and not Mask; end; procedure TBWImage.DrawHorLine(XStart, XEnd, Y: Integer; IsBlack: Boolean); var I,J: Integer; Start,Finish,StartBit, FinishBit, Offset:Integer; Count : Integer; Color: Cardinal; W: Integer; begin if Y >= FHeight then Exit; if XStart >= FWidth then Exit; if XEnd < XStart then Exit; if XEnd >= FWidth then XEnd := FWidth - 1; if XStart = XEnd then begin Pixel[XStart,Y] := IsBlack; Exit; end; Offset := Y*FLineSize; Start := XStart shr 5 ; StartBit := XStart and 31; if not IsBlack then Color := 0 else Color := $FFFFFFFF; W := XEnd - XStart + 1; if StartBit = 0 then begin Count := W shr 5; for i := 0 to Count - 1 do FBuffer[Offset+Start+i] := Color; FinishBit := W and 31; if FinishBit <> 0 then begin if IsBlack then FBuffer[Offset+Start+Count] := FBuffer[Offset+Start+Count] or (not ($FFFFFFFF shr FinishBit)) else FBuffer[Offset+Start+Count] := FBuffer[Offset+Start+Count] and ($FFFFFFFF shr FinishBit); end; Exit; end; Finish := XEnd shr 5; FinishBit := XEnd and 31; if Start <> Finish then begin if IsBlack then FBuffer[Start+Offset] := FBuffer[Start+Offset] or ($FFFFFFFF shr StartBit) else FBuffer[Start+Offset] := FBuffer[Start+Offset] and not($FFFFFFFF shr StartBit); for j:= Start + 1 to Finish - 1 do FBuffer[j+Offset] := Color; if FinishBit <> 31 then begin if IsBlack then FBuffer[Finish+Offset] := FBuffer[Finish+Offset] or (not($FFFFFFFF shr (FinishBit+1))) else FBuffer[Finish+Offset] := FBuffer[Finish+Offset] and ($FFFFFFFF shr (FinishBit+1)) end else begin FBuffer[Finish+Offset] := Color; end; end else begin if IsBlack then FBuffer[Start+Offset] := FBuffer[Start+Offset] or (($FFFFFFFF shr StartBit) and ($FFFFFFFF shl (31-FinishBit))) else FBuffer[Start+Offset] := FBuffer[Start+Offset] and ( not (($FFFFFFFF shr StartBit) and ($FFFFFFFF shl (31 - FinishBit)))); end; end; function TBWImage.GetBlackPoint(var BlackPoint: TImgPoint): Boolean; var i,j, off: Integer; begin result := false; if (BlackPoint.y < 0) or (BlackPoint.y >=FHeight) then Exit; off := FLineSize * BlackPoint.y; for i := BlackPoint.y to FHeight - 1 do begin for j := 0 to FLineSize - 1 do if FBuffer[off+j] <> 0 then begin BlackPoint.y := i; BlackPoint.x := (j shl 5 ) + (31 - Log32(FBuffer[off+j])); result := true; Exit; end; inc(off, FLineSize); end; end; function TBWImage.GetBorder(StartPosition: TImgPoint): TImgBorder; type TBorderDirection = (bdRight, bdBottom, bdLeft, bdTop); var Direction: TBorderDirection; CurrentPoint:TImgPoint; procedure GetNext(var Point: TImgPoint;Direction: TBorderDirection); begin Case Direction of bdRight: Inc(Point.x); bdBottom: Inc(Point.y); bdLeft: Dec(Point.x); bdTop: Dec(Point.y); end end; procedure MakeStep(var Point: TImgPoint;var Direction: TBorderDirection); var D: TBorderDirection; IsBlack: Boolean; TmpPoint, TmpPoint2:TImgPoint; begin TmpPoint := Point; D := Direction; GetNext(TmpPoint,D); IsBlack := GetPixel(TmpPoint.x,TmpPoint.y); if IsBlack then begin if D <> bdRight then dec(D) else D := bdTop; TmpPoint2 := TmpPoint; GetNext(TmpPoint2,D); if GetPixel(TmpPoint2.x,TmpPoint2.y) then begin Direction := D; Point := TmpPoint2; Exit; end; Point := TmpPoint; Exit; end; if D <> bdTop then Inc(D) else D := bdRight; tmpPoint := Point; GetNext(TmpPoint,D); IsBlack := GetPixel(TmpPoint.x,TmpPoint.y); if IsBlack then begin Point := tmpPoint; Exit; end; if D <> bdTop then Inc(D) else D := bdRight; Direction := D; end; begin Result.LeftTop := StartPosition; Result.RightBottom := StartPosition; CurrentPoint := StartPosition; Direction := bdRight; MakeStep(CurrentPoint,Direction); while (CurrentPoint.x <> StartPosition.x) or (CurrentPoint.y <> StartPosition.y) do begin if CurrentPoint.x < result.LeftTop.x then Result.LeftTop.x := CurrentPoint.x; if CurrentPoint.y < result.LeftTop.y then Result.LeftTop.y := CurrentPoint.y; if CurrentPoint.x > result.RightBottom.x then Result.RightBottom.x := CurrentPoint.x; if CurrentPoint.y > result.RightBottom.y then Result.RightBottom.y := CurrentPoint.y; MakeStep(CurrentPoint,Direction); end; end; function TBWImage.GetPixel(X, Y: Integer): Boolean; var C, Mask: Cardinal; begin if (X >= FWidth) or ( Y >= FHeight) or (X < 0) or ( Y < 0) then begin Result := False; Exit; end; C := FBuffer[Y * FLineSize+ X shr 5]; Mask := 1 shl (31 - X and 31); Result := C and Mask > 0; end; procedure TBWImage.InitBlackPoint(var BlackPoint: TImgPoint); begin BlackPoint.x := 0; BlackPoint.y := 0; end; procedure TBWImage.MoveAndClear(DestSymbol: TBWImage; StartPosition: TImgPoint;Border: TImgBorder); var Stack: array of TImgPoint; StackSize:Integer; WrkPoint,TmpPoint: TImgPoint; Y, X, XLeft, XRight:Integer; fnd :Boolean; procedure StackGrow; var Delta, Capacity: Integer; begin Capacity := Length(Stack); if Capacity > 64 then Delta := Capacity shr 2 else if Capacity > 8 then Delta := 16 else Delta := 4; SetLength(Stack, Capacity + Delta); end; procedure Push(Point: TImgPoint); var i: Integer; begin for i := 0 to StackSize-1 do if (Point.x = Stack[i].x) and (Point.y = Stack[i].y) then Exit; if Length(Stack) = StackSize then StackGrow; Stack[StackSize] := Point; inc(StackSize); end; function Pop(var Point: TImgPoint):Boolean; begin if StackSize = 0 then begin Result := false; Exit end; dec(StackSize); Point := Stack[StackSize]; result := true; end; procedure CheckLine(YLine:Integer); begin X := XLeft; while X <= XRight do begin fnd := false; while GetPixel(X,YLine) and (fnd or (X <= XRight)) do begin fnd := true; inc(x); end; if fnd then begin TmpPoint.y := YLine; TmpPoint.x := X - 1; Push(TmpPoint); end; inc(X); end; end; procedure GetLR; begin Dec(X); while GetPixel(X,Y) do Dec(x); XLeft := X + 1; X := WrkPoint.x; Inc(X); while GetPixel(X,Y) do Inc(x); XRight := X - 1; end; begin StackSize := 0; Stack := nil; push(StartPosition); while Pop(WrkPoint) do begin X := WrkPoint.x; Y := WrkPoint.y; GetLR; if y-1 >= Border.LeftTop.y then CheckLine(Y-1); if y+1 <= Border.RightBottom.y then CheckLine(Y+1); DestSymbol.DrawHorLine(XLeft - Border.LeftTop.x,XRight - Border.LeftTop.x,WrkPoint.y - Border.LeftTop.y,True); DrawHorLine(XLeft,XRight,WrkPoint.y,False); end; end; function TBWImage.NormalizeSize(X,Y: integer;var W, H: integer): Boolean; begin Result := False; if X >= Width then begin W := 0; Exit; end; if Y >= Height then begin H := 0; Exit; end; Result := True; if X + W > Width then W := Width - X; if Y + H > Height then H := Height - Y; end; function TBWImage.CheckNeighbor(X, Y, Level: integer):boolean; var cnt: Integer; h,w: integer; begin cnt := 0; result := true; for w := x-1 to x+1 do for h := y-1 to y+1 do begin if (w<>x) or (h<>y) then begin if Pixel[w,h] then inc(Cnt); if Cnt = Level then exit; end; end; result := false; end; procedure TBWImage.SaveToFile(FileName: String); var BMP : TBitmap; begin BMP := TBitmap.Create; try CopyToBitmap(BMP); BMP.SaveToFile(FileName); finally BMP.Free; end; end; { TJBIG2Options } constructor TJBIG2Options.Create; begin FLossyLevel := 5; FSkipBlackDots := True; FBlackDotSize := 3; FSymbolExtract := icImageOnly; // FUseSingleDictionary := True; end; constructor TPDFImages.Create(PDFEngine: TPDFEngine); begin FJPEGQuality := 80; {$ifndef BASE} FJBIG2Options := TJBIG2Options.Create; FJBIG2Dictionary := TJBig2SymbolDictionary.Create(PDFEngine,FJBIG2Options); {$endif} inherited Create(PDFEngine); end; destructor TPDFImages.Destroy; begin {$ifndef BASE} FJBIG2Dictionary.Free; FJBIG2Options.Free; {$endif} inherited; end; end.
unit TelePars; //****************************************************************************** // UNIT NAME TelePars // USED BY PROJECTS TelescopeAgent // AUTHOR Yiftah Lipkin // DESCRIPTION Various Telescope and Site paraemters // LAST MODIFIED 2004 Apr 02 //****************************************************************************** interface uses Windows; const //Site Parameters SiteName :string = 'Wise Observatory'; SiteEastLong :real = 0.606714554348564;//+34:45:43.86; SiteNorthLat :real = 0.534024354440983; //+30:35:50.43; //Note Geocentroc latitude is : 0.5310862517367 SiteGeodAlt :real = 882.9; //m Datum :string = 'WGS84'; //TimeZone :Integer = +2; //DayLightSaving :Integer = 0; //Setting Safety Constants AltLimit0 : real = 0.34907; //[rad] 20deg; Do not allow TeleMove below this value AMLimit0 : integer = 9; // Absolute AM Limit. Must be smaller than 9.9, the uppper limit of CalcAM DefaultAMLimit0 = 2.9; // Default AM limit var //Telescope Variables UTnow, LTnow : _SYSTEMTIME; STnow, JDnow, Epochnow, AMnow, AltNow, Aznow : extended; SunAlt, MoonAlt, MoonIllum, MoonRA, MoonDec, MoonDist : extended; TargetRA, TargetDec, TargetHA, TargetEpoch, TargetAlt, TargetAz, TargetAM, TargetDomeAz: extended; //Teaget coordinates [rad] CoordOK : Boolean = FALSE; //Is input Data in RA/HA/Offset window valid? ScopeHA : extended; ScopeRA : extended; ScopeDec : extended; //Setting Safety Parameters AltLimit : real; //[rad]; Do not allow TeleMove below this value AMLimit : integer; // Absolute AM Limit. Must be smaller than 9.9, the uppper limit of CalcAM DefaultAMLimit : real; // Default AM limit implementation end.
unit CardDeck; { Author: Kees Hemerik Version history: 0.1 d.d. 20080316 } interface uses Graphics, CardPiles; type //---------------------------------------------------------------------------- // TCardDeck provides data needed for textual and graphical representation of // the various elements of a deck of cards. // Short decription of operations: // - LongSuitName(ASuit) yields the long name of a TSuit value, e.g. 'Hearts' // - ShortSuitName(ASuit) yields the short name of a TSuit value, e.g. 'H' // - CardText(ACard) yields a text representation of a card, e.g. '07H' // - CardBitmap(ACard) yields a bitmap representing the face of ACard // - CardBitmap2(AValue, ASuit) yields a bitmap representing the card with // value AValue and suit ASuit // - BottomSuit(ASuit) yields bitmap representing empty suitpile for ASuit // - Bottom yields bitmap representing other empty piles // - Back yields bitmap representing back of cards // // - LoadFromFiles(APath) loads all data for a TCardDeck object from set of // .bmp files in directory with path APath. // It is assumed that the filename for card ACard is nnn.bmp , // where nnn is CardText(ACard) //---------------------------------------------------------------------------- TCardDeck = class(TObject) protected FCardBitmaps: array[TValue, TSuit] of TBitmap; FBottomSuit: array [TSuit] of TBitmap; FBottom: TBitmap; FBack: TBitmap; public // construction/destruction constructor Create; destructor Destroy; override; // queries function LongSuitName(ASuit: TSuit): String; function ShortSuitName(ASuit: TSuit): String; function CardText(ACard: TCard): String; function Cardtext2(AValue: TValue; ASuit: TSuit): String; function CardBitmap(ACard: TCard): TBitmap; function CardBitmap2(AValue: TValue; ASuit: TSuit): TBitmap; function BottomSuit(ASuit: TSuit): TBitmap; function Bottom: TBitmap; function Back: TBitmap; // commands procedure LoadFromFiles(APath: String); end; implementation //=============================================================== uses SysUtils; { TCardDeck } function TCardDeck.Back: TBitmap; begin Result := FBack; end; function TCardDeck.Bottom: TBitmap; begin Result := FBottom; end; function TCardDeck.BottomSuit(ASuit: TSuit): TBitmap; begin Result := FBottomSuit[ASuit]; end; function TCardDeck.CardBitmap(ACard: TCard): TBitmap; begin Result := CardBitmap2(ACard.Value, ACard.Suit); end; function TCardDeck.CardBitmap2(AValue: TValue; ASuit: TSuit): TBitmap; begin Result := FCardBitmaps[AValue, ASuit]; end; function TCardDeck.CardText(ACard: TCard): String; begin with ACard do if FaceUp then Result := CardText2(Value, Suit) else Result := 'X'; end; function TCardDeck.CardText2(AValue: TValue; ASuit: TSuit): String; begin Result := Format('%.2d%s', [AValue, ShortSuitName(ASuit)] ) end; constructor TCardDeck.Create; var VSuit: TSuit; VValue: TValue; begin inherited Create; // create bitmaps for all cards for VValue := Low(TValue) to High(TValue) do for VSuit := Low(TSuit) to High(TSuit) do FCardBitmaps[VValue, VSuit] := TBitmap.Create; // create bitmaps for all suits for VSuit := Low(TSuit) to High(TSuit) do FBottomSuit[VSuit] := TBitmap.Create; // create bitmaps for bottom and back FBottom := TBitmap.Create; FBack := TBitmap.Create; end; destructor TCardDeck.Destroy; var VSuit: TSuit; VValue: TValue; begin // free bitmaps for all cards for VValue := Low(TValue) to High(TValue) do for VSuit := Low(TSuit) to High(TSuit) do FCardBitmaps[VValue, VSuit].Free; // free bitmaps for suits for VSuit := Low(TSuit) to High(TSuit) do FBottomSuit[VSuit].Free; // free bitmaps for bottom and back FBottom.Free; FBack.Free; inherited; end; procedure TCardDeck.LoadFromFiles(APath: String); var VValue: TValue; VSuit: TSuit; VFileName: String; begin // load bitmaps for faces of all cards for VValue := Low(TValue) to High(TValue) do for VSuit := Low(TSuit) to High(TSuit) do begin // compose filename from APath, VValue and VSuit VFileName := Format('%s%s.bmp', [APath, CardText2(VValue, VSuit)] ); // load bitmap from file FCardBitmaps[VValue, VSuit].LoadFromFile(VFileName); end; // load bitmaps for bottoms of suits FBottomSuit[suHeart].LoadFromFile(APath + 'bottom06.bmp'); FBottomSuit[suClub].LoadFromFile(APath + 'bottom04.bmp'); FBottomSuit[suDiamond].LoadFromFile(APath + 'bottom07.bmp'); FBottomSuit[suSpade].LoadFromFile(APath + 'bottom05.bmp'); // load bitmaps for bottom and back FBottom.LoadFromFile(APath + 'bottom02.bmp'); FBack.LoadFromFile(APath + 'back111.bmp'); end; function TCardDeck.LongSuitName(ASuit: TSuit): String; const Names: array[TSuit] of String = ('Hearts', 'Clubs', 'Diamonds', 'Spades'); begin Result := Names[ASuit]; end; function TCardDeck.ShortSuitName(ASuit: TSuit): String; const Names: array[TSuit] of String = ('H', 'C', 'D', 'S'); begin Result := Names[ASuit]; end; end.
program FuncArray; const size = 5; type a = array [1..size] of integer; var balance: a; average: real; function avg( var arr: a) : real; var i :1..size; sum: integer; begin writeln('here2'); sum := 0; for i := 1 to size do sum := sum + arr[i]; writeln('here3'); avg := sum / size; writeln('here4'); end; begin writeln('here0'); balance[1] := 1000; balance[2] := 2; balance[3] := 3; balance[4] := 17; balance[5] := 50; writeln('here1'); average := avg( balance ) ; writeln('here5'); writeln('Average: ', average); writeln('here6'); end.
{*******************************************************} { } { Delphi DBX Framework } { } { Copyright(c) 1995-2011 Embarcadero Technologies, Inc. } { } {*******************************************************} unit Data.DBXSqlScanner; interface uses Data.DBXPlatform; type TDBXSqlScanner = class public constructor Create(const QuoteChar: UnicodeString; const QuotePrefix: UnicodeString; const QuoteSuffix: UnicodeString); destructor Destroy; override; procedure RegisterId(const Id: UnicodeString; const Token: Integer); procedure Init(const Query: UnicodeString); overload; procedure Init(const Query: UnicodeString; const StartIndex: Integer); overload; function LookAtNextToken: Integer; function NextToken: Integer; function IsKeyword(const Keyword: UnicodeString): Boolean; protected function GetId: UnicodeString; private class function ToQuoteChar(const QuoteString: UnicodeString): WideChar; static; procedure ResetId; function ScanNumber: Integer; function QuotedToken: Integer; function PrefixQuotedToken: Integer; function UnquotedToken: Integer; function ScanSymbol: Integer; procedure SkipToEndOfLine; private FQuotePrefix: UnicodeString; FQuoteSuffix: UnicodeString; FQuote: UnicodeString; FQuotePrefixChar: WideChar; FQuoteSuffixChar: WideChar; FQuoteChar: WideChar; FKeywords: TDBXObjectStore; FQuery: UnicodeString; FQueryLength: Integer; FIndex: Integer; FStartOfId: Integer; FEndOfId: Integer; FId: UnicodeString; FWasId: Boolean; FWasQuoted: Boolean; FSymbol: WideChar; public property Id: UnicodeString read GetId; property Quoted: Boolean read FWasQuoted; property Symbol: WideChar read FSymbol; property SqlQuery: UnicodeString read FQuery; property NextIndex: Integer read FIndex; public const TokenEos = -1; const TokenId = -2; const TokenComma = -3; const TokenPeriod = -4; const TokenSemicolon = -5; const TokenOpenParen = -6; const TokenCloseParen = -7; const TokenNumber = -8; const TokenSymbol = -9; const TokenError = -10; end; implementation uses Data.DBXMetaDataUtil, System.SysUtils, Data.DBXCommonResStrs; constructor TDBXSqlScanner.Create(const QuoteChar: UnicodeString; const QuotePrefix: UnicodeString; const QuoteSuffix: UnicodeString); begin inherited Create; self.FQuotePrefix := QuotePrefix; self.FQuoteSuffix := QuoteSuffix; self.FQuote := QuoteChar; self.FQuotePrefixChar := ToQuoteChar(QuotePrefix); self.FQuoteSuffixChar := ToQuoteChar(QuoteSuffix); self.FQuoteChar := ToQuoteChar(QuoteChar); end; destructor TDBXSqlScanner.Destroy; begin FreeAndNil(FKeywords); inherited Destroy; end; procedure TDBXSqlScanner.RegisterId(const Id: UnicodeString; const Token: Integer); begin if FKeywords = nil then FKeywords := TDBXObjectStore.Create; FKeywords[WideLowerCase(Id)] := TDBXInt32Object.Create(Token); end; procedure TDBXSqlScanner.Init(const Query: UnicodeString); begin Init(Query, 0); end; procedure TDBXSqlScanner.Init(const Query: UnicodeString; const StartIndex: Integer); begin self.FQuery := Query; self.FQueryLength := Length(Query); self.FIndex := StartIndex; ResetId; end; class function TDBXSqlScanner.ToQuoteChar(const QuoteString: UnicodeString): WideChar; begin if (StringIsNil(QuoteString)) or (Length(QuoteString) = 0) then Result := #$0 else if Length(QuoteString) > 1 then raise Exception.Create(SIllegalArgument) else Result := QuoteString[1+0]; end; function TDBXSqlScanner.LookAtNextToken: Integer; var Save: Integer; Token: Integer; begin Save := FIndex; Token := NextToken; FIndex := Save; Result := Token; end; function TDBXSqlScanner.NextToken: Integer; var Ch: WideChar; begin ResetId; while FIndex < FQueryLength do begin Ch := FQuery[1+IncrAfter(FIndex)]; case Ch of ' ', #$9, #$d, #$a:; '(': begin FSymbol := Ch; Exit(TokenOpenParen); end; ')': begin FSymbol := Ch; Exit(TokenCloseParen); end; ',': begin FSymbol := Ch; Exit(TokenComma); end; '.': begin FSymbol := Ch; Exit(TokenPeriod); end; ';': begin FSymbol := Ch; Exit(TokenSemicolon); end; '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': Exit(ScanNumber); else if Ch = FQuoteChar then Exit(QuotedToken) else if Ch = FQuotePrefixChar then Exit(PrefixQuotedToken) else if IsIdentifierStart(Ch) then Exit(UnquotedToken) else if (Ch = '-') and (FIndex < FQueryLength) and (FQuery[1+FIndex] = '-') then SkipToEndOfLine else Exit(ScanSymbol); end; end; Result := TokenEos; end; function TDBXSqlScanner.GetId: UnicodeString; begin if StringIsNil(FId) then begin FId := Copy(FQuery,FStartOfId+1,FEndOfId-(FStartOfId)); if FWasQuoted then FId := TDBXMetaDataUtil.UnquotedIdentifier(FId, FQuote, FQuotePrefix, FQuoteSuffix); end; Result := FId; end; function TDBXSqlScanner.IsKeyword(const Keyword: UnicodeString): Boolean; begin Result := FWasId and (Keyword = Id); end; procedure TDBXSqlScanner.ResetId; begin FId := NullString; FStartOfId := 0; FEndOfId := 0; FWasId := False; FWasQuoted := False; FSymbol := #$0; end; function TDBXSqlScanner.ScanNumber: Integer; var Ch: WideChar; begin FStartOfId := FIndex - 1; while FIndex < FQueryLength do begin Ch := FQuery[1+IncrAfter(FIndex)]; case Ch of '.', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':; else begin Dec(FIndex); FEndOfId := FIndex; Exit(TokenNumber); end; end; end; FEndOfId := FIndex - 1; Result := TokenNumber; end; function TDBXSqlScanner.QuotedToken: Integer; var Ch: WideChar; begin FStartOfId := FIndex - 1; while FIndex < FQueryLength do begin Ch := FQuery[1+IncrAfter(FIndex)]; if Ch = FQuoteChar then begin if (FIndex = FQueryLength) or (FQuery[1+FIndex] <> FQuoteChar) then begin FEndOfId := FIndex; FWasId := True; FWasQuoted := True; Exit(TokenId); end; IncrAfter(FIndex); end; end; Result := TokenError; end; function TDBXSqlScanner.PrefixQuotedToken: Integer; var Ch: WideChar; begin FStartOfId := FIndex - 1; while FIndex < FQueryLength do begin Ch := FQuery[1+IncrAfter(FIndex)]; if Ch = FQuoteSuffixChar then begin FEndOfId := FIndex; FWasId := True; FWasQuoted := True; Exit(TokenId); end; end; Result := TokenError; end; function TDBXSqlScanner.UnquotedToken: Integer; var Token: Integer; Ch: WideChar; Keyword: TDBXInt32Object; begin Token := TokenId; FStartOfId := FIndex - 1; while FIndex < FQueryLength do begin Ch := FQuery[1+IncrAfter(FIndex)]; if not IsIdentifierPart(Ch) then begin Dec(FIndex); break; end; end; FEndOfId := FIndex; FWasId := True; if FKeywords <> nil then begin Keyword := TDBXInt32Object(FKeywords[WideLowerCase(Id)]); if Keyword <> nil then Token := Keyword.IntValue; end; Result := Token; end; function TDBXSqlScanner.ScanSymbol: Integer; begin FSymbol := FQuery[1+FIndex - 1]; Result := TokenSymbol; end; procedure TDBXSqlScanner.SkipToEndOfLine; var Ch: WideChar; begin Ch := '-'; while ((Ch <> #$d) and (Ch <> #$a)) and (FIndex < FQueryLength) do Ch := FQuery[1+IncrAfter(FIndex)]; end; end.
{$INCLUDE ..\cDefines.inc} unit cDynLib; { } { Dynamically Loaded Libraries 3.02 } { } { This unit is copyright © 2001-2004 by David J Butler } { } { This unit is part of Delphi Fundamentals. } { Its original file name is cDynLib.pas } { The latest version is available from the Fundamentals home page } { http://fundementals.sourceforge.net/ } { } { I invite you to use this unit, free of charge. } { I invite you to distibute this unit, but it must be for free. } { I also invite you to contribute to its development, } { but do not distribute a modified copy of this file. } { } { A forum is available on SourceForge for general discussion } { http://sourceforge.net/forum/forum.php?forum_id=2117 } { } { Revision history: } { 2001/06/26 1.01 Added TDynamicLibrary. } { 2002/06/06 3.02 Created cDynLib unit from cSysUtils. } { } interface uses { Delphi } Windows, SysUtils; { } { DLL functions } { } type EDynamicLibrary = class (Exception); function LoadDLL(const FileName: String): HMODULE; procedure UnloadDLL(const Handle: HMODULE); function LoadAnyDLL(const FileNames: Array of String): HMODULE; function GetDLLProcAddress(const Handle: HMODULE; const ProcName: String): FARPROC; { } { TDynamicLibrary } { } type TDynamicLibrary = class protected FHandle : HMODULE; function GetProcAddress(const ProcName: String): FARPROC; public constructor Create(const FileName: String); overload; constructor Create(const FileNames: Array of String); overload; destructor Destroy; override; property Handle: HMODULE read FHandle; property ProcAddress[const ProcName: String]: FARPROC read GetProcAddress; default; end; implementation { } { Dynamic Libraries } { } function DoLoadLibrary(const FileName: String): HMODULE; begin Result := LoadLibrary(PChar(FileName)); end; function LoadDLL(const FileName: String): HMODULE; begin Result := DoLoadLibrary(FileName); if Result <= HINSTANCE_ERROR then raise EDynamicLibrary.Create('Could not load DLL: ' + FileName + ': Error #' + IntToStr(GetLastError)); end; function LoadAnyDLL(const FileNames: Array of String): HMODULE; var I : Integer; begin For I := 0 to Length(FileNames) - 1 do begin Result := DoLoadLibrary(FileNames [I]); if Result <> 0 then exit; end; raise EDynamicLibrary.Create('Could not load DLLs: Error #' + IntToStr(GetLastError)); end; procedure UnloadDLL(const Handle: HMODULE); begin FreeLibrary(Handle); end; function GetDLLProcAddress(const Handle: HMODULE; const ProcName: String): FARPROC; begin Result := GetProcaddress(Handle, PChar(ProcName)); if Result = nil then raise EDynamicLibrary.Create('Could not import function from DLL: ' + ProcName + ': Error #' + IntToStr(GetLastError)); end; { } { TDynamicLibrary } { } constructor TDynamicLibrary.Create(const FileName: String); begin inherited Create; FHandle := LoadDLL(FileName); Assert(FHandle <> 0, 'FHandle <> 0'); end; constructor TDynamicLibrary.Create(const FileNames: Array of String); begin inherited Create; FHandle := LoadAnyDLL(FileNames); Assert(FHandle <> 0, 'FHandle <> 0'); end; destructor TDynamicLibrary.Destroy; begin if FHandle <> 0 then begin UnloadDLL(FHandle); FHandle := 0; end; inherited Destroy; end; function TDynamicLibrary.GetProcAddress(const ProcName: String): FARPROC; begin Assert(FHandle <> 0, 'FHandle <> 0'); Result := GetDLLProcAddress(FHandle, ProcName); end; end.
// // Copyright (c) 2009-2010 Mikko Mononen memon@inside.org // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // {$POINTERMATH ON} unit RN_RecastDebugDraw; interface uses Math, RN_Helper, RN_Recast, RN_DebugDraw; procedure duDebugDrawTriMesh(dd: TduDebugDraw; const verts: PSingle; nverts: Integer; const tris: PInteger; const normals: PSingle; ntris: Integer; const flags: PByte; const texScale: Single); procedure duDebugDrawTriMeshSlope(dd: TduDebugDraw; const verts: PSingle; nverts: Integer; const tris: PInteger; const normals: PSingle; ntris: Integer; const walkableSlopeAngle: Single; const texScale: Single); procedure duDebugDrawHeightfieldSolid(dd: TduDebugDraw; const hf: PrcHeightfield); procedure duDebugDrawHeightfieldWalkable(dd: TduDebugDraw; const hf: PrcHeightfield); procedure duDebugDrawCompactHeightfieldSolid(dd: TduDebugDraw; const chf: PrcCompactHeightfield); procedure duDebugDrawCompactHeightfieldRegions(dd: TduDebugDraw; const chf: PrcCompactHeightfield); procedure duDebugDrawCompactHeightfieldDistance(dd: TduDebugDraw; const chf: PrcCompactHeightfield); {procedure duDebugDrawHeightfieldLayer(duDebugDraw* dd, const struct rcHeightfieldLayer& layer, const int idx); procedure duDebugDrawHeightfieldLayers(duDebugDraw* dd, const struct rcHeightfieldLayerSet& lset); procedure duDebugDrawHeightfieldLayersRegions(duDebugDraw* dd, const struct rcHeightfieldLayerSet& lset);} procedure duDebugDrawRegionConnections(dd: TduDebugDraw; const cset: PrcContourSet; const alpha: Single = 1.0); procedure duDebugDrawRawContours(dd: TduDebugDraw; const cset: PrcContourSet; const alpha: Single = 1.0); procedure duDebugDrawContours(dd: TduDebugDraw; const cset: PrcContourSet; const alpha: Single = 1.0); procedure duDebugDrawPolyMesh(dd: TduDebugDraw; const mesh: PrcPolyMesh); procedure duDebugDrawPolyMeshDetail(dd: TduDebugDraw; const dmesh: PrcPolyMeshDetail); implementation procedure duDebugDrawTriMesh(dd: TduDebugDraw; const verts: PSingle; nverts: Integer; const tris: PInteger; const normals: PSingle; ntris: Integer; const flags: PByte; const texScale: Single); var uva,uvb,uvc: array [0..1] of Single; unwalkable,color: Cardinal; i: Integer; norm,va,vb,vc: PSingle; a: Byte; ax,ay: Integer; begin if (dd = nil) then Exit; if (verts = nil) then Exit; if (tris = nil) then Exit; if (normals = nil) then Exit; unwalkable := duRGBA(192,128,0,255); dd.texture(true); dd.&begin(DU_DRAW_TRIS); for i := 0 to ntris - 1 do begin norm := @normals[i*3]; a := Byte(Trunc(220*(2+norm[0]+norm[1])/4)); if (flags <> nil) and (not flags[i] <> 0) then color := duLerpCol(duRGBA(a,a,a,255), unwalkable, 64) else color := duRGBA(a,a,a,255); va := @verts[tris[i*3+0]*3]; vb := @verts[tris[i*3+1]*3]; vc := @verts[tris[i*3+2]*3]; ax := 0; ay := 0; if (Abs(norm[1]) > Abs(norm[ax])) then ax := 1; if (Abs(norm[2]) > Abs(norm[ax])) then ax := 2; ax := (1 shl ax) and 3; // +1 mod 3 ay := (1 shl ax) and 3; // +1 mod 3 uva[0] := va[ax]*texScale; uva[1] := va[ay]*texScale; uvb[0] := vb[ax]*texScale; uvb[1] := vb[ay]*texScale; uvc[0] := vc[ax]*texScale; uvc[1] := vc[ay]*texScale; dd.vertex(va, color, @uva[0]); dd.vertex(vb, color, @uvb[0]); dd.vertex(vc, color, @uvc[0]); end; dd.&end(); dd.texture(false); end; procedure duDebugDrawTriMeshSlope(dd: TduDebugDraw; const verts: PSingle; nverts: Integer; const tris: PInteger; const normals: PSingle; ntris: Integer; const walkableSlopeAngle: Single; const texScale: Single); //var walkableThr: Single; uva,uvb,uvc: array [0..1] of Single; unwalkable,color: Cardinal; i: Integer; norm,va,vb,vc: PSingle; a: Byte; //ax,ay: Integer; begin //Delphi: Not sure why, but this mode blackens everything way too much {if (dd = nil) then Exit; if (verts = nil) then Exit; if (tris = nil) then Exit; if (normals = nil) then Exit; walkableThr := cos(walkableSlopeAngle/180.0*PI); dd.texture(true); unwalkable := duRGBA(192,128,0,255); dd.&begin(DU_DRAW_TRIS); for i := 0 to ntris - 1 do begin norm := @normals[i*3]; a := Byte(Trunc(220*(2+norm[0]+norm[1])/4)); if (norm[1] < walkableThr) then color := duLerpCol(duRGBA(a,a,a,255), unwalkable, 64) else color := duRGBA(a,a,a,255); va := @verts[tris[i*3+0]*3]; vb := @verts[tris[i*3+1]*3]; vc := @verts[tris[i*3+2]*3]; ax := 0; ay := 0; if (Abs(norm[1]) > Abs(norm[ax])) then ax := 1; if (Abs(norm[2]) > Abs(norm[ax])) then ax := 2; ax := (1 shl ax) and 3; // +1 mod 3 ay := (1 shl ax) and 3; // +1 mod 3 uva[0] := va[ax]*texScale; uva[1] := va[ay]*texScale; uvb[0] := vb[ax]*texScale; uvb[1] := vb[ay]*texScale; uvc[0] := vc[ax]*texScale; uvc[1] := vc[ay]*texScale; dd.vertex(va, color, @uva); dd.vertex(vb, color, @uvb); dd.vertex(vc, color, @uvc); end; dd.&end(); dd.texture(false);} end; procedure duDebugDrawHeightfieldSolid(dd: TduDebugDraw; const hf: PrcHeightfield); var orig: PSingle; cs,ch: Single; w,h: Integer; fcol: array [0..5] of Cardinal; x,y: Integer; fx,fz: Single; s: PrcSpan; begin if (dd = nil) then Exit; orig := @hf.bmin[0]; cs := hf.cs; ch := hf.ch; w := hf.width; h := hf.height; //unsigned int fcol[6]; duCalcBoxColors(fcol, duRGBA(255,255,255,255), duRGBA(255,255,255,255)); dd.&begin(DU_DRAW_QUADS); for y := 0 to h - 1 do begin for x := 0 to w - 1 do begin fx := orig[0] + x*cs; fz := orig[2] + y*cs; s := hf.spans[x + y*w]; while (s <> nil) do begin duAppendBox(dd, fx, orig[1]+s.smin*ch, fz, fx+cs, orig[1] + s.smax*ch, fz+cs, @fcol[0]); s := s.next; end; end; end; dd.&end(); end; procedure duDebugDrawHeightfieldWalkable(dd: TduDebugDraw; const hf: PrcHeightfield); var orig: PSingle; cs,ch: Single; w,h: Integer; fcol: array [0..5] of Cardinal; x,y: Integer; fx,fz: Single; s: PrcSpan; begin if (dd = nil) then Exit; orig := @hf.bmin[0]; cs := hf.cs; ch := hf.ch; w := hf.width; h := hf.height; //unsigned int fcol[6]; duCalcBoxColors(fcol, duRGBA(255,255,255,255), duRGBA(217,217,217,255)); dd.&begin(DU_DRAW_QUADS); for y := 0 to h - 1 do begin for x := 0 to w - 1 do begin fx := orig[0] + x*cs; fz := orig[2] + y*cs; s := hf.spans[x + y*w]; while (s <> nil) do begin if (s.area = RC_WALKABLE_AREA) then fcol[0] := duRGBA(64,128,160,255) else if (s.area = RC_NULL_AREA) then fcol[0] := duRGBA(64,64,64,255) else fcol[0] := duMultCol(duIntToCol(s.area, 255), 200); duAppendBox(dd, fx, orig[1]+s.smin*ch, fz, fx+cs, orig[1] + s.smax*ch, fz+cs, @fcol[0]); s := s.next; end; end; end; dd.&end(); end; procedure duDebugDrawCompactHeightfieldSolid(dd: TduDebugDraw; const chf: PrcCompactHeightfield); var cs,ch: Single; x,y,i: Integer; fx,fy,fz: Single; c: PrcCompactCell; s: PrcCompactSpan; color: Cardinal; begin if (dd = nil) then Exit; cs := chf.cs; ch := chf.ch; dd.&begin(DU_DRAW_QUADS); for y := 0 to chf.height - 1 do begin for x := 0 to chf.width - 1 do begin fx := chf.bmin[0] + x*cs; fz := chf.bmin[2] + y*cs; c := @chf.cells[x+y*chf.width]; for i := c.index to Integer(c.index+c.count) - 1 do begin s := @chf.spans[i]; if (chf.areas[i] = RC_WALKABLE_AREA) then color := duRGBA(0,192,255,64) else if (chf.areas[i] = RC_NULL_AREA) then color := duRGBA(0,0,0,64) else color := duIntToCol(chf.areas[i], 255); fy := chf.bmin[1] + (s.y+1)*ch; dd.vertex(fx, fy, fz, color); dd.vertex(fx, fy, fz+cs, color); dd.vertex(fx+cs, fy, fz+cs, color); dd.vertex(fx+cs, fy, fz, color); end; end; end; dd.&end(); end; procedure duDebugDrawCompactHeightfieldRegions(dd: TduDebugDraw; const chf: PrcCompactHeightfield); var cs,ch: Single; x,y,i: Integer; fx,fy,fz: Single; c: PrcCompactCell; s: PrcCompactSpan; color: Cardinal; begin if (dd = nil) then Exit; cs := chf.cs; ch := chf.ch; dd.&begin(DU_DRAW_QUADS); for y := 0 to chf.height - 1 do begin for x := 0 to chf.width - 1 do begin fx := chf.bmin[0] + x*cs; fz := chf.bmin[2] + y*cs; c := @chf.cells[x+y*chf.width]; for i := c.index to Integer(c.index+c.count) - 1 do begin s := @chf.spans[i]; fy := chf.bmin[1] + (s.y)*ch; if (s.reg <> 0) then color := duIntToCol(s.reg, 192) else color := duRGBA(0,0,0,64); dd.vertex(fx, fy, fz, color); dd.vertex(fx, fy, fz+cs, color); dd.vertex(fx+cs, fy, fz+cs, color); dd.vertex(fx+cs, fy, fz, color); end; end; end; dd.&end(); end; procedure duDebugDrawCompactHeightfieldDistance(dd: TduDebugDraw; const chf: PrcCompactHeightfield); var cs,ch,maxd,dscale: Single; x,y,i: Integer; fx,fy,fz: Single; c: PrcCompactCell; s: PrcCompactSpan; cd: Byte; color: Cardinal; begin if (dd = nil) then Exit; //if (!chf.dist) return; cs := chf.cs; ch := chf.ch; maxd := chf.maxDistance; if (maxd < 1.0) then maxd := 1; dscale := 255.0 / maxd; dd.&begin(DU_DRAW_QUADS); for y := 0 to chf.height - 1 do begin for x := 0 to chf.width - 1 do begin fx := chf.bmin[0] + x*cs; fz := chf.bmin[2] + y*cs; c := @chf.cells[x+y*chf.width]; for i := c.index to Integer(c.index+c.count) - 1 do begin s := @chf.spans[i]; fy := chf.bmin[1] + (s.y+1)*ch; cd := Trunc(chf.dist[i] * dscale); color := duRGBA(cd,cd,cd,255); dd.vertex(fx, fy, fz, color); dd.vertex(fx, fy, fz+cs, color); dd.vertex(fx+cs, fy, fz+cs, color); dd.vertex(fx+cs, fy, fz, color); end; end; end; dd.&end(); end; {procedure drawLayerPortals(duDebugDraw* dd, const rcHeightfieldLayer* layer) begin const float cs := layer.cs; const float ch := layer.ch; const int w := layer.width; const int h := layer.height; unsigned int pcol := duRGBA(255,255,255,255); const int segs[4*4] := begin0,0,0,1, 0,1,1,1, 1,1,1,0, 1,0,0,0end;; // Layer portals dd.&begin(DU_DRAW_LINES, 2.0f); for y := 0 to h - 1 do begin for x := 0 to w - 1 do begin const int idx := x+y*w; const int lh := (int)layer.heights[idx]; if (lh == 255) continue; for dir := 0 to 3 do begin if (layer.cons[idx] & (1<<(dir+4))) begin const int* seg := &segs[dir*4]; const float ax := layer.bmin[0] + (x+seg[0])*cs; const float ay := layer.bmin[1] + (lh+2)*ch; const float az := layer.bmin[2] + (y+seg[1])*cs; const float bx := layer.bmin[0] + (x+seg[2])*cs; const float by := layer.bmin[1] + (lh+2)*ch; const float bz := layer.bmin[2] + (y+seg[3])*cs; dd.vertex(ax, ay, az, pcol); dd.vertex(bx, by, bz, pcol); end; end; end; end; dd.&end(); end; procedure duDebugDrawHeightfieldLayer(duDebugDraw* dd, const struct rcHeightfieldLayer& layer, const int idx) begin const float cs := layer.cs; const float ch := layer.ch; const int w := layer.width; const int h := layer.height; unsigned int color := duIntToCol(idx+1, 255); // Layer bounds float bmin[3], bmax[3]; bmin[0] := layer.bmin[0] + layer.minx*cs; bmin[1] := layer.bmin[1]; bmin[2] := layer.bmin[2] + layer.miny*cs; bmax[0] := layer.bmin[0] + (layer.maxx+1)*cs; bmax[1] := layer.bmax[1]; bmax[2] := layer.bmin[2] + (layer.maxy+1)*cs; duDebugDrawBoxWire(dd, bmin[0],bmin[1],bmin[2], bmax[0],bmax[1],bmax[2], duTransCol(color,128), 2.0f); // Layer height dd.&begin(DU_DRAW_QUADS); for y := 0 to h - 1 do begin for x := 0 to w - 1 do begin const int lidx := x+y*w; const int lh := (int)layer.heights[lidx]; if (h == 0xff) continue; const unsigned char area := layer.areas[lidx]; unsigned int col; if (area == RC_WALKABLE_AREA) col := duLerpCol(color, duRGBA(0,192,255,64), 32); else if (area == RC_NULL_AREA) col := duLerpCol(color, duRGBA(0,0,0,64), 32); else col := duLerpCol(color, duIntToCol(area, 255), 32); const float fx := layer.bmin[0] + x*cs; const float fy := layer.bmin[1] + (lh+1)*ch; const float fz := layer.bmin[2] + y*cs; dd.vertex(fx, fy, fz, col); dd.vertex(fx, fy, fz+cs, col); dd.vertex(fx+cs, fy, fz+cs, col); dd.vertex(fx+cs, fy, fz, col); end; end; dd.&end(); // Portals drawLayerPortals(dd, &layer); end; procedure duDebugDrawHeightfieldLayers(duDebugDraw* dd, const struct rcHeightfieldLayerSet& lset) begin if (!dd) return; for (int i := 0; i < lset.nlayers; ++i) duDebugDrawHeightfieldLayer(dd, lset.layers[i], i); end; /* procedure duDebugDrawLayerContours(duDebugDraw* dd, const struct rcLayerContourSet& lcset) begin if (!dd) return; const float* orig := lcset.bmin; const float cs := lcset.cs; const float ch := lcset.ch; const unsigned char a := 255;// (unsigned char)(alpha*255.0f); const int offs[2*4] := begin-1,0, 0,1, 1,0, 0,-1end;; dd.&begin(DU_DRAW_LINES, 2.0f); for (int i := 0; i < lcset.nconts; ++i) begin const rcLayerContour& c := lcset.conts[i]; unsigned int color := 0; color := duIntToCol(i, a); for (int j := 0; j < c.nverts; ++j) begin const int k := (j+1) % c.nverts; const unsigned char* va := &c.verts[j*4]; const unsigned char* vb := &c.verts[k*4]; const float ax := orig[0] + va[0]*cs; const float ay := orig[1] + (va[1]+1+(i&1))*ch; const float az := orig[2] + va[2]*cs; const float bx := orig[0] + vb[0]*cs; const float by := orig[1] + (vb[1]+1+(i&1))*ch; const float bz := orig[2] + vb[2]*cs; unsigned int col := color; if ((va[3] & 0xf) != 0xf) begin col := duRGBA(255,255,255,128); int d := va[3] & 0xf; const float cx := (ax+bx)*0.5f; const float cy := (ay+by)*0.5f; const float cz := (az+bz)*0.5f; const float dx := cx + offs[d*2+0]*2*cs; const float dy := cy; const float dz := cz + offs[d*2+1]*2*cs; dd.vertex(cx,cy,cz,duRGBA(255,0,0,255)); dd.vertex(dx,dy,dz,duRGBA(255,0,0,255)); end; duAppendArrow(dd, ax,ay,az, bx,by,bz, 0.0f, cs*0.5f, col); end; end; dd.&end(); dd.&begin(DU_DRAW_POINTS, 4.0f); for (int i := 0; i < lcset.nconts; ++i) begin const rcLayerContour& c := lcset.conts[i]; unsigned int color := 0; for (int j := 0; j < c.nverts; ++j) begin const unsigned char* va := &c.verts[j*4]; color := duDarkenCol(duIntToCol(i, a)); if (va[3] & 0x80) color := duRGBA(255,0,0,255); float fx := orig[0] + va[0]*cs; float fy := orig[1] + (va[1]+1+(i&1))*ch; float fz := orig[2] + va[2]*cs; dd.vertex(fx,fy,fz, color); end; end; dd.&end(); end; procedure duDebugDrawLayerPolyMesh(duDebugDraw* dd, const struct rcLayerPolyMesh& lmesh) begin if (!dd) return; const int nvp := lmesh.nvp; const float cs := lmesh.cs; const float ch := lmesh.ch; const float* orig := lmesh.bmin; const int offs[2*4] := begin-1,0, 0,1, 1,0, 0,-1end;; dd.&begin(DU_DRAW_TRIS); for (int i := 0; i < lmesh.npolys; ++i) begin const unsigned short* p := &lmesh.polys[i*nvp*2]; unsigned int color; if (lmesh.areas[i] == RC_WALKABLE_AREA) color := duRGBA(0,192,255,64); else if (lmesh.areas[i] == RC_NULL_AREA) color := duRGBA(0,0,0,64); else color := duIntToCol(lmesh.areas[i], 255); unsigned short vi[3]; for (int j := 2; j < nvp; ++j) begin if (p[j] == RC_MESH_NULL_IDX) break; vi[0] := p[0]; vi[1] := p[j-1]; vi[2] := p[j]; for (int k := 0; k < 3; ++k) begin const unsigned short* v := &lmesh.verts[vi[k]*3]; const float x := orig[0] + v[0]*cs; const float y := orig[1] + (v[1]+1)*ch; const float z := orig[2] + v[2]*cs; dd.vertex(x,y,z, color); end; end; end; dd.&end(); // Draw neighbours edges const unsigned int coln := duRGBA(0,48,64,32); dd.&begin(DU_DRAW_LINES, 1.5f); for (int i := 0; i < lmesh.npolys; ++i) begin const unsigned short* p := &lmesh.polys[i*nvp*2]; for j := 0 to nvp - 1 do begin if (p[j] == RC_MESH_NULL_IDX) break; if (p[nvp+j] & 0x8000) continue; const int nj := (j+1 >= nvp || p[j+1] == RC_MESH_NULL_IDX) ? 0 : j+1; int vi[2] := beginp[j], p[nj]end;; for (int k := 0; k < 2; ++k) begin const unsigned short* v := &lmesh.verts[vi[k]*3]; const float x := orig[0] + v[0]*cs; const float y := orig[1] + (v[1]+1)*ch + 0.1f; const float z := orig[2] + v[2]*cs; dd.vertex(x, y, z, coln); end; end; end; dd.&end(); // Draw boundary edges const unsigned int colb := duRGBA(0,48,64,220); dd.&begin(DU_DRAW_LINES, 2.5f); for (int i := 0; i < lmesh.npolys; ++i) begin const unsigned short* p := &lmesh.polys[i*nvp*2]; for j := 0 to nvp - 1 do begin if (p[j] == RC_MESH_NULL_IDX) break; if ((p[nvp+j] & 0x8000) == 0) continue; const int nj := (j+1 >= nvp || p[j+1] == RC_MESH_NULL_IDX) ? 0 : j+1; int vi[2] := beginp[j], p[nj]end;; unsigned int col := colb; if ((p[nvp+j] & 0xf) != 0xf) begin const unsigned short* va := &lmesh.verts[vi[0]*3]; const unsigned short* vb := &lmesh.verts[vi[1]*3]; const float ax := orig[0] + va[0]*cs; const float ay := orig[1] + (va[1]+1+(i&1))*ch; const float az := orig[2] + va[2]*cs; const float bx := orig[0] + vb[0]*cs; const float by := orig[1] + (vb[1]+1+(i&1))*ch; const float bz := orig[2] + vb[2]*cs; const float cx := (ax+bx)*0.5f; const float cy := (ay+by)*0.5f; const float cz := (az+bz)*0.5f; int d := p[nvp+j] & 0xf; const float dx := cx + offs[d*2+0]*2*cs; const float dy := cy; const float dz := cz + offs[d*2+1]*2*cs; dd.vertex(cx,cy,cz,duRGBA(255,0,0,255)); dd.vertex(dx,dy,dz,duRGBA(255,0,0,255)); col := duRGBA(255,255,255,128); end; for (int k := 0; k < 2; ++k) begin const unsigned short* v := &lmesh.verts[vi[k]*3]; const float x := orig[0] + v[0]*cs; const float y := orig[1] + (v[1]+1)*ch + 0.1f; const float z := orig[2] + v[2]*cs; dd.vertex(x, y, z, col); end; end; end; dd.&end(); dd.&begin(DU_DRAW_POINTS, 3.0f); const unsigned int colv := duRGBA(0,0,0,220); for (int i := 0; i < lmesh.nverts; ++i) begin const unsigned short* v := &lmesh.verts[i*3]; const float x := orig[0] + v[0]*cs; const float y := orig[1] + (v[1]+1)*ch + 0.1f; const float z := orig[2] + v[2]*cs; dd.vertex(x,y,z, colv); end; dd.&end(); end; */} procedure getContourCenter(const cont: PrcContour; const orig: PSingle; cs,ch: Single; center: PSingle); var i: Integer; v: PInteger; s: Single; begin center[0] := 0; center[1] := 0; center[2] := 0; if (cont.nverts = 0) then Exit; for i := 0 to cont.nverts - 1 do begin v := @cont.verts[i*4]; center[0] := center[0] + v[0]; center[1] := center[1] + v[1]; center[2] := center[2] + v[2]; end; s := 1.0 / cont.nverts; center[0] := center[0] * s * cs; center[1] := center[1] * s * ch; center[2] := center[2] * s * cs; center[0] := center[0] + orig[0]; center[1] := center[1] + orig[1] + 4*ch; center[2] := center[2] + orig[2]; end; function findContourFromSet(const cset: PrcContourSet; reg: Word): PrcContour; var i: Integer; begin for i := 0 to cset.nconts - 1 do begin if (cset.conts[i].reg = reg) then Exit(@cset.conts[i]); end; Result := nil; end; procedure duDebugDrawRegionConnections(dd: TduDebugDraw; const cset: PrcContourSet; const alpha: Single = 1.0); var orig: PSingle; cs,ch: Single; pos,pos2: array [0..2] of Single; color: Cardinal; i,j: Integer; cont,cont2: PrcContour; v: PInteger; a: Byte; col: Cardinal; begin if (dd = nil) then Exit; orig := @cset.bmin[0]; cs := cset.cs; ch := cset.ch; // Draw centers color := duRGBA(0,0,0,196); dd.&begin(DU_DRAW_LINES, 2.0); for i := 0 to cset.nconts - 1 do begin cont := @cset.conts[i]; getContourCenter(cont, orig, cs, ch, @pos[0]); for j := 0 to cont.nverts - 1 do begin v := @cont.verts[j*4]; if (Word(v[3]) = 0) or (Word(v[3]) < cont.reg) then continue; cont2 := findContourFromSet(cset, Word(v[3])); if (cont2 <> nil) then begin getContourCenter(cont2, orig, cs, ch, @pos2[0]); duAppendArc(dd, pos[0],pos[1],pos[2], pos2[0],pos2[1],pos2[2], 0.25, 0.6, 0.6, color); end; end; end; dd.&end(); a := Trunc(alpha * 255.0); dd.&begin(DU_DRAW_POINTS, 7.0); for i := 0 to cset.nconts - 1 do begin cont := @cset.conts[i]; col := duDarkenCol(duIntToCol(cont.reg,a)); getContourCenter(cont, orig, cs, ch, @pos[0]); dd.vertex(@pos[0], col); end; dd.&end(); end; procedure duDebugDrawRawContours(dd: TduDebugDraw; const cset: PrcContourSet; const alpha: Single = 1.0); var orig: PSingle; cs,ch: Single; a: Byte; i,j: Integer; c: PrcContour; color,colv: Cardinal; v: PInteger; fx,fy,fz: Single; off: Single; begin if (dd = nil) then Exit; orig := @cset.bmin[0]; cs := cset.cs; ch := cset.ch; a := Trunc(alpha*255.0); dd.&begin(DU_DRAW_LINES, 2.0); for i := 0 to cset.nconts - 1 do begin c := @cset.conts[i]; color := duIntToCol(c.reg, a); for j := 0 to c.nrverts - 1 do begin v := @c.rverts[j*4]; fx := orig[0] + v[0]*cs; fy := orig[1] + (v[1]+1+(i and 1))*ch; fz := orig[2] + v[2]*cs; dd.vertex(fx,fy,fz,color); if (j > 0) then dd.vertex(fx,fy,fz,color); end; // Loop last segment. v := @c.rverts[0]; fx := orig[0] + v[0]*cs; fy := orig[1] + (v[1]+1+(i and 1))*ch; fz := orig[2] + v[2]*cs; dd.vertex(fx,fy,fz,color); end; dd.&end(); dd.&begin(DU_DRAW_POINTS, 2.0); for i := 0 to cset.nconts - 1 do begin c := @cset.conts[i]; color := duDarkenCol(duIntToCol(c.reg, a)); for j := 0 to c.nrverts - 1 do begin v := @c.rverts[j*4]; off := 0; colv := color; if (v[3] and RC_BORDER_VERTEX) <> 0 then begin colv := duRGBA(255,255,255,a); off := ch*2; end; fx := orig[0] + v[0]*cs; fy := orig[1] + (v[1]+1+(i and 1))*ch + off; fz := orig[2] + v[2]*cs; dd.vertex(fx,fy,fz, colv); end; end; dd.&end(); end; procedure duDebugDrawContours(dd: TduDebugDraw; const cset: PrcContourSet; const alpha: Single = 1.0); var orig: PSingle; cs,ch: Single; a: Byte; i,j,k: Integer; c: PrcContour; color,bcolor,col,colv: Cardinal; va,vb,v: PInteger; fx,fy,fz: Single; off: Single; begin if (dd = nil) then Exit; orig := @cset.bmin[0]; cs := cset.cs; ch := cset.ch; a := Trunc(alpha*255.0); dd.&begin(DU_DRAW_LINES, 2.5); for i := 0 to cset.nconts - 1 do begin c := @cset.conts[i]; if (c.nverts = 0) then continue; color := duIntToCol(c.reg, a); bcolor := duLerpCol(color,duRGBA(255,255,255,a),128); //for (int j := 0, k := c.nverts-1; j < c.nverts; k=j++) j := 0; k := c.nverts-1; while (j < c.nverts) do begin va := @c.verts[k*4]; vb := @c.verts[j*4]; col := IfThen(va[3] and RC_AREA_BORDER <> 0, bcolor, color); fx := orig[0] + va[0]*cs; fy := orig[1] + (va[1]+1+(i and 1))*ch; fz := orig[2] + va[2]*cs; dd.vertex(fx,fy,fz, col); fx := orig[0] + vb[0]*cs; fy := orig[1] + (vb[1]+1+(i and 1))*ch; fz := orig[2] + vb[2]*cs; dd.vertex(fx,fy,fz, col); k := j; Inc(j); end; end; dd.&end(); dd.&begin(DU_DRAW_POINTS, 3.0); for i := 0 to cset.nconts - 1 do begin c := @cset.conts[i]; color := duDarkenCol(duIntToCol(c.reg, a)); for j := 0 to c.nverts - 1 do begin v := @c.verts[j*4]; off := 0; colv := color; if (v[3] and RC_BORDER_VERTEX) <> 0 then begin colv := duRGBA(255,255,255,a); off := ch*2; end; fx := orig[0] + v[0]*cs; fy := orig[1] + (v[1]+1+(i and 1))*ch + off; fz := orig[2] + v[2]*cs; dd.vertex(fx,fy,fz, colv); end; end; dd.&end(); end; procedure duDebugDrawPolyMesh(dd: TduDebugDraw; const mesh: PrcPolyMesh); var nvp: Integer; cs,ch: Single; orig: PSingle; i,j,k: Integer; p,v: PWord; color,col,coln,colb,colv: Cardinal; vi: array [0..2] of Word; x,y,z: Single; nj: Integer; begin if (dd = nil) then Exit; nvp := mesh.nvp; cs := mesh.cs; ch := mesh.ch; orig := @mesh.bmin[0]; dd.&begin(DU_DRAW_TRIS); for i := 0 to mesh.npolys - 1 do begin p := @mesh.polys[i*nvp*2]; if (mesh.areas[i] = RC_WALKABLE_AREA) then color := duRGBA(0,192,255,64) else if (mesh.areas[i] = RC_NULL_AREA) then color := duRGBA(0,0,0,64) else color := duIntToCol(mesh.areas[i], 255); for j := 2 to nvp - 1 do begin if (p[j] = RC_MESH_NULL_IDX) then break; vi[0] := p[0]; vi[1] := p[j-1]; vi[2] := p[j]; for k := 0 to 2 do begin v := @mesh.verts[vi[k]*3]; x := orig[0] + v[0]*cs; y := orig[1] + (v[1]+1)*ch; z := orig[2] + v[2]*cs; dd.vertex(x,y,z, color); end; end; end; dd.&end(); // Draw neighbours edges coln := duRGBA(0,48,64,32); dd.&begin(DU_DRAW_LINES, 1.5); for i := 0 to mesh.npolys - 1 do begin p := @mesh.polys[i*nvp*2]; for j := 0 to nvp - 1 do begin if (p[j] = RC_MESH_NULL_IDX) then break; if (p[nvp+j] and $8000 <> 0) then continue; nj := IfThen((j+1 >= nvp) or (p[j+1] = RC_MESH_NULL_IDX), 0, j+1); vi[0] := p[j]; vi[1] := p[nj]; for k := 0 to 1 do begin v := @mesh.verts[vi[k]*3]; x := orig[0] + v[0]*cs; y := orig[1] + (v[1]+1)*ch + 0.1; z := orig[2] + v[2]*cs; dd.vertex(x, y, z, coln); end; end; end; dd.&end(); // Draw boundary edges colb := duRGBA(0,48,64,220); dd.&begin(DU_DRAW_LINES, 2.5); for i := 0 to mesh.npolys - 1 do begin p := @mesh.polys[i*nvp*2]; for j := 0 to nvp - 1 do begin if (p[j] = RC_MESH_NULL_IDX) then break; if ((p[nvp+j] and $8000) = 0) then continue; nj := IfThen((j+1 >= nvp) or (p[j+1] = RC_MESH_NULL_IDX), 0, j+1); vi[0] := p[j]; vi[1] := p[nj]; col := colb; if ((p[nvp+j] and $f) <> $f) then col := duRGBA(255,255,255,128); for k := 0 to 1 do begin v := @mesh.verts[vi[k]*3]; x := orig[0] + v[0]*cs; y := orig[1] + (v[1]+1)*ch + 0.1; z := orig[2] + v[2]*cs; dd.vertex(x, y, z, col); end; end; end; dd.&end(); dd.&begin(DU_DRAW_POINTS, 3.0); colv := duRGBA(0,0,0,220); for i := 0 to mesh.nverts - 1 do begin v := @mesh.verts[i*3]; x := orig[0] + v[0]*cs; y := orig[1] + (v[1]+1)*ch + 0.1; z := orig[2] + v[2]*cs; dd.vertex(x,y,z, colv); end; dd.&end(); end; procedure duDebugDrawPolyMeshDetail(dd: TduDebugDraw; const dmesh: PrcPolyMeshDetail); var i,j,k,kp: Integer; m: PCardinal; bverts, btris: Cardinal; ntris: Integer; verts: PSingle; tris,t: PByte; color,coli,cole,colv: Cardinal; ef: Byte; nverts: Integer; begin if (dd = nil) then Exit; dd.&begin(DU_DRAW_TRIS); for i := 0 to dmesh.nmeshes - 1 do begin m := @dmesh.meshes[i*4]; bverts := m[0]; btris := m[2]; ntris := integer(m[3]); verts := @dmesh.verts[bverts*3]; tris := @dmesh.tris[btris*4]; color := duIntToCol(i, 192); for j := 0 to ntris - 1 do begin dd.vertex(@verts[tris[j*4+0]*3], color); dd.vertex(@verts[tris[j*4+1]*3], color); dd.vertex(@verts[tris[j*4+2]*3], color); end; end; dd.&end(); // Internal edges. dd.&begin(DU_DRAW_LINES, 1.0); coli := duRGBA(0,0,0,64); for i := 0 to dmesh.nmeshes - 1 do begin m := @dmesh.meshes[i*4]; bverts := m[0]; btris := m[2]; ntris := Integer(m[3]); verts := @dmesh.verts[bverts*3]; tris := @dmesh.tris[btris*4]; for j := 0 to ntris - 1 do begin t := @tris[j*4]; k := 0; kp := 2; while (k < 3) do begin ef := (t[3] shr (kp*2)) and $3; if (ef = 0) then begin // Internal edge if (t[kp] < t[k]) then begin dd.vertex(@verts[t[kp]*3], coli); dd.vertex(@verts[t[k]*3], coli); end; end; kp := k; Inc(k); end; end; end; dd.&end(); // External edges. dd.&begin(DU_DRAW_LINES, 2.0); cole := duRGBA(0,0,0,64); for i := 0 to dmesh.nmeshes - 1 do begin m := @dmesh.meshes[i*4]; bverts := m[0]; btris := m[2]; ntris := Integer(m[3]); verts := @dmesh.verts[bverts*3]; tris := @dmesh.tris[btris*4]; for j := 0 to ntris - 1 do begin t := @tris[j*4]; k := 0; kp := 2; while (k < 3) do begin ef := (t[3] shr (kp*2)) and $3; if (ef <> 0) then begin // Ext edge dd.vertex(@verts[t[kp]*3], cole); dd.vertex(@verts[t[k]*3], cole); end; kp := k; Inc(k); end; end; end; dd.&end(); dd.&begin(DU_DRAW_POINTS, 3.0); colv := duRGBA(0,0,0,64); for i := 0 to dmesh.nmeshes - 1 do begin m := @dmesh.meshes[i*4]; bverts := m[0]; nverts := Integer(m[1]); verts := @dmesh.verts[bverts*3]; for j := 0 to nverts - 1 do dd.vertex(@verts[j*3], colv); end; dd.&end(); end; end.
unit BowlingGame; interface uses Generics.Collections; type TRollTotal = (rtZero, rtOne, rtTwo, rtThree, rtFour, rtFive, rtSix, rtSeven, rtEight, rtNine, rtStrike, rtSpare); // if 10 is rolled it will be rtStrike. TFrame = class; TFrameRollsCtrl = class frame: TFrame; Over: Boolean; FrameRolls: TList<TRollTotal>; private function GetScore: integer; function NumPinsToRollTotal(NumPins: integer): TRollTotal; function RollTotalToNumberOfPins(RollTotal: TRollTotal): integer; function RollTotalAsString(RollTotal: TRollTotal): string; public property Score: integer read GetScore; procedure RecordRoll(NumPins: integer); constructor Create(xownr: TFrame); destructor Destroy(); override; end; TFramesCtrl = class; TBowlingGame = class; TFrame = class private FScore: integer; FRunningTotal: integer; function GetOpenFrame: Boolean; procedure SetScore(const Value: integer); procedure SetRunningTotal(const Value: integer); public StrikeCount, SpareCount: integer; FramesCtrl: TFramesCtrl; FrameRollsCtrl: TFrameRollsCtrl; Game: TBowlingGame; Number: integer; Scored: Boolean; function NumPinsStanding(): integer; procedure Reset(); function CheckRollInput(NumOfPins: integer): Boolean; property OpenFrame: Boolean read GetOpenFrame; function NeedRollsRecordedInFutureFrame: Boolean; property Score: integer read FScore write SetScore; property RunningTotal: integer read FRunningTotal write SetRunningTotal; Constructor Create(xFrameNum: integer; xFramesCtrl: TFramesCtrl; xGame: TBowlingGame); destructor Destroy(); override; end; TFrames = array [1 .. 10] of TFrame; TFramesCtrl = class private Frames: TFrames; CurrentFrame: integer; public function GetCurrent(): TFrame; function Next(): Boolean; procedure Init(); constructor Create(xGame: TBowlingGame); destructor Destroy(); override; end; TPendingScoreFrame = class FrameNum: integer; FramesCtrl: TFramesCtrl; BonusPoints: TList<integer>; private function ReadyToScore(): Boolean; procedure Score(); public constructor Create(xFrameNum: integer; xFramesCtrl: TFramesCtrl); destructor Destroy; override; end; // frames with strike/spare; they need a roll in a future frame in order to score TPendingFrames = class FramesPending: TList<TPendingScoreFrame>; private function Any(): Boolean; procedure Add(FrameNum: integer; xFramesCtrl: TFramesCtrl); procedure AddBonusPoints(pts: integer); public constructor Create(); destructor Destroy; override; end; TScoreByFrame = record Number: integer; Status: string; GameScore: integer; FrameScore: string; FrameScoreInPoints: integer; end; TScoreCtrl = class FramesCtrl: TFramesCtrl; Pending: TPendingFrames; ScoreByFrames: TList<TScoreByFrame>; procedure Score(); procedure Init(); function GetScoreByFrame(): TList<TScoreByFrame>; constructor Create(xFramesCtrl: TFramesCtrl); destructor Destroy(); override; end; TBowlingGame = class private FTotalScore: integer; public FramesCtrl: TFramesCtrl; ScoreCtrl: TScoreCtrl; GameOver: Boolean; // starts a new game of bowling procedure Start(); // takes the number of pins knocked down for each roll procedure Roll(NumOfPins: integer); // score for each frame that has occurred so far function ScoreByFrame(): TList<TScoreByFrame>; // returns the total score for that game up to the given point property TotalScore: integer read FTotalScore write FTotalScore; constructor Create(); destructor Destroy(); override; end; implementation uses Dialogs, SysUtils, System.UITypes; { TBowlingGame } constructor TBowlingGame.Create; begin FramesCtrl := TFramesCtrl.Create(self); ScoreCtrl := TScoreCtrl.Create(FramesCtrl); end; destructor TBowlingGame.Destroy; begin FramesCtrl.Free(); ScoreCtrl.Free(); inherited; end; procedure TBowlingGame.Roll(NumOfPins: integer); var frame: TFrame; IsNextFrame: Boolean; function ValidInput(): Boolean; begin Result := NumOfPins in [0 .. 10]; end; begin if GameOver then begin MessageDlg('Game Over', mtInformation, [mbOK], 0); Exit; end; if not ValidInput() then begin MessageDlg('Invalid input, Roll = ' + IntToStr(NumOfPins), mtError, [mbOK], 0); Exit; end; frame := FramesCtrl.GetCurrent(); if not frame.CheckRollInput(NumOfPins) then begin MessageDlg('Possible invalid input, roll > pins standing = ' + IntToStr(NumOfPins), mtInformation, [mbOK], 0); end; frame.FrameRollsCtrl.RecordRoll(NumOfPins); if ScoreCtrl.Pending.Any then ScoreCtrl.Pending.AddBonusPoints(NumOfPins); ScoreCtrl.Score(); // current and pending if frame.FrameRollsCtrl.Over then begin IsNextFrame := FramesCtrl.Next(); GameOver := not IsNextFrame; end; end; function TBowlingGame.ScoreByFrame: TList<TScoreByFrame>; begin Result := ScoreCtrl.GetScoreByFrame(); end; procedure TBowlingGame.Start; begin GameOver := False; ScoreCtrl.Init(); FramesCtrl.Init(); end; { TFrame } // input: NumOfPins int, the number of pins knocked down in this roll // output: boolean, True if NumOfPins is <= pins standing in the current frame, else false function TFrame.CheckRollInput(NumOfPins: integer): Boolean; begin Result := NumOfPins <= NumPinsStanding(); end; constructor TFrame.Create(xFrameNum: integer; xFramesCtrl: TFramesCtrl; xGame: TBowlingGame); begin Number := xFrameNum; FramesCtrl := xFramesCtrl; FrameRollsCtrl := TFrameRollsCtrl.Create(self); Game := xGame; end; destructor TFrame.Destroy; begin FrameRollsCtrl.Destroy(); inherited; end; function TFrame.NeedRollsRecordedInFutureFrame: Boolean; begin if Number = 10 then Result := False else Result := not OpenFrame; end; function TFrame.NumPinsStanding: integer; begin // 10th frame can have strike/spare and still be 'active frame' Result := 10 - (FrameRollsCtrl.GetScore() mod 10); end; procedure TFrame.Reset; begin Score := 0; Scored := False; StrikeCount := 0; SpareCount := 0; RunningTotal := 0; FrameRollsCtrl.FrameRolls.Clear(); FrameRollsCtrl.Over := False; end; function TFrame.GetOpenFrame: Boolean; begin Result := (StrikeCount + SpareCount) = 0; end; procedure TFrame.SetScore(const Value: integer); begin FScore := Value; Scored := True; if Number = 1 then RunningTotal := Value else RunningTotal := FramesCtrl.Frames[Number - 1].RunningTotal + Value; end; procedure TFrame.SetRunningTotal(const Value: integer); begin FRunningTotal := Value; Game.TotalScore := Value; end; { TFramesCtrl } constructor TFramesCtrl.Create(xGame: TBowlingGame); var i: integer; begin for i := 1 to 10 do begin Frames[i] := TFrame.Create(i, self, xGame); end; end; destructor TFramesCtrl.Destroy; var i: integer; begin for i := 1 to 10 do begin Frames[i].Free(); end; inherited; end; function TFramesCtrl.GetCurrent(): TFrame; begin Result := Frames[CurrentFrame]; end; procedure TFramesCtrl.Init; var i: integer; begin CurrentFrame := 1; for i := 1 to 10 do begin Frames[i].Reset(); Frames[i].Scored := False; end; end; function TFramesCtrl.Next: Boolean; begin if CurrentFrame < 10 then begin Inc(CurrentFrame); Result := True; end else begin Result := False; end; end; { TFrameRollsCtrl } constructor TFrameRollsCtrl.Create(xownr: TFrame); begin frame := xownr; FrameRolls := TList<TRollTotal>.Create(); // CurrentRoll := 0; end; destructor TFrameRollsCtrl.Destroy; begin FrameRolls.Free(); inherited; end; function TFrameRollsCtrl.GetScore: integer; function SumFrameRolls(): integer; var i: integer; begin Result := 0; for i := 0 to FrameRolls.Count - 1 do begin if FrameRolls[i] = rtStrike then Inc(Result, 10) else if RollTotalToNumberOfPins(FrameRolls[i]) in [0 .. 9] then Inc(Result, RollTotalToNumberOfPins(FrameRolls[i])) else if FrameRolls[i] = rtSpare then begin Dec(Result, RollTotalToNumberOfPins(FrameRolls[i - 1])); Inc(Result, 10); end; end; end; begin Result := SumFrameRolls(); // todo and 1 + 2 + 3 if 10th end; function TFrameRollsCtrl.NumPinsToRollTotal(NumPins: integer): TRollTotal; function IsSpare(): Boolean; begin Result := (FrameRolls.Count > 0) and (NumPins <> 0) and (RollTotalToNumberOfPins(FrameRolls[FrameRolls.Count - 1]) in [0 .. 9]) and (RollTotalToNumberOfPins(FrameRolls[FrameRolls.Count - 1]) + NumPins = 10); end; function IsStrike(): Boolean; begin Result := (not IsSpare()) and (NumPins = 10); end; begin if IsStrike() then begin Result := rtStrike; Inc(frame.StrikeCount); Exit; end; if IsSpare() then begin Result := rtSpare; Inc(frame.SpareCount); Exit; end; Result := TRollTotal(NumPins); end; procedure TFrameRollsCtrl.RecordRoll(NumPins: integer); begin FrameRolls.Add(NumPinsToRollTotal(NumPins)); // is frame done if frame.Number < 10 then begin if ((frame.StrikeCount + frame.SpareCount) > 0) or (FrameRolls.Count = 2) then Over := True; end else Over := (frame.OpenFrame and (FrameRolls.Count = 2)) or ((not frame.OpenFrame) and (FrameRolls.Count = 3)); end; function TFrameRollsCtrl.RollTotalAsString(RollTotal: TRollTotal): string; begin case RollTotal of rtZero .. rtNine: Result := IntToStr(ord(RollTotal)); rtStrike: Result := 'X'; rtSpare: Result := '/'; end; end; function TFrameRollsCtrl.RollTotalToNumberOfPins(RollTotal: TRollTotal) : integer; begin Result := -1; case RollTotal of rtZero .. rtNine: Result := ord(RollTotal); rtStrike, rtSpare: Result := 10; end; end; { TScoreCtrl } constructor TScoreCtrl.Create(xFramesCtrl: TFramesCtrl); begin FramesCtrl := xFramesCtrl; Pending := TPendingFrames.Create(); ScoreByFrames := TList<TScoreByFrame>.Create(); end; destructor TScoreCtrl.Destroy; begin Pending.Free(); ScoreByFrames.Free(); inherited; end; function TScoreCtrl.GetScoreByFrame: TList<TScoreByFrame>; var frame: TFrame; i: integer; sbf: TScoreByFrame; TotalScore: integer; function InitScoreByFrame(): TScoreByFrame; var i: integer; function GetFrameStaus(): string; begin if frame.FrameRollsCtrl.Over then begin if frame.Scored then Result := 'Scored' else Result := 'Pending'; end else begin if frame.FrameRollsCtrl.FrameRolls.Count > 0 then Result := 'In Play' else Result := ''; end; end; begin Result.Number := frame.Number; Result.Status := GetFrameStaus(); Result.FrameScoreInPoints := frame.Score; Inc(TotalScore, frame.Score); Result.GameScore := TotalScore; Result.FrameScore := ''; if Result.Status <> '' then begin for i := 0 to frame.FrameRollsCtrl.FrameRolls.Count - 1 do begin Result.FrameScore := Result.FrameScore + frame.FrameRollsCtrl.RollTotalAsString(frame.FrameRollsCtrl.FrameRolls [i]) + ' '; end; Delete(Result.FrameScore, Length(Result.FrameScore), 1); end; end; begin ScoreByFrames.Clear(); TotalScore := 0; // get frames scored so far for i := 1 to 10 do begin frame := FramesCtrl.Frames[i]; if frame.Scored then ScoreByFrames.Add(InitScoreByFrame()) else Break; end; // get pending frames for i := 0 to Pending.FramesPending.Count - 1 do begin frame := Pending.FramesPending[i].FramesCtrl.Frames [Pending.FramesPending[i].FrameNum]; ScoreByFrames.Add(InitScoreByFrame()) end; // current in progress frame := FramesCtrl.Frames[FramesCtrl.CurrentFrame]; sbf := InitScoreByFrame(); if sbf.Status = 'In Play' then ScoreByFrames.Add(sbf); Result := ScoreByFrames; end; procedure TScoreCtrl.Init; begin FramesCtrl.Init(); Pending.FramesPending.Clear(); ScoreByFrames.Clear(); end; procedure TScoreCtrl.Score; var frame: TFrame; i: integer; begin frame := FramesCtrl.GetCurrent(); // process pending score if Pending.Any then begin for i := Pending.FramesPending.Count - 1 downto 0 do begin if Pending.FramesPending[i].ReadyToScore() then begin Pending.FramesPending[i].Score(); Pending.FramesPending[i].Free(); Pending.FramesPending.Delete(i); end; end; end; if frame.FrameRollsCtrl.Over then begin if (not frame.NeedRollsRecordedInFutureFrame()) then begin frame.Score := frame.FrameRollsCtrl.GetScore(); end else Pending.Add(frame.Number, FramesCtrl); end; end; { TPendingScoreFrame } constructor TPendingScoreFrame.Create(xFrameNum: integer; xFramesCtrl: TFramesCtrl); begin FrameNum := xFrameNum; FramesCtrl := xFramesCtrl; BonusPoints := TList<integer>.Create(); end; destructor TPendingScoreFrame.Destroy; begin BonusPoints.Free(); inherited; end; function TPendingScoreFrame.ReadyToScore: Boolean; begin Result := False; if FramesCtrl.Frames[FrameNum].StrikeCount = 1 then Result := BonusPoints.Count = 2 else if FramesCtrl.Frames[FrameNum].SpareCount = 1 then Result := BonusPoints.Count = 1; end; procedure TPendingScoreFrame.Score; var frame: TFrame; begin frame := FramesCtrl.Frames[FrameNum]; if frame.StrikeCount = 1 then begin frame.Score := frame.FrameRollsCtrl.GetScore() + BonusPoints[0] + BonusPoints[1]; end else if frame.SpareCount = 1 then begin frame.Score := frame.FrameRollsCtrl.GetScore() + BonusPoints[0]; end; end; { TPendingFrames } procedure TPendingFrames.Add(FrameNum: integer; xFramesCtrl: TFramesCtrl); var PendingScoreFrame: TPendingScoreFrame; begin PendingScoreFrame := TPendingScoreFrame.Create(FrameNum, xFramesCtrl); FramesPending.Add(PendingScoreFrame); end; procedure TPendingFrames.AddBonusPoints(pts: integer); var i: integer; begin for i := 0 to FramesPending.Count - 1 do begin FramesPending[i].BonusPoints.Add(pts); end; end; function TPendingFrames.Any: Boolean; begin Result := FramesPending.Count > 0; end; constructor TPendingFrames.Create; begin FramesPending := TList<TPendingScoreFrame>.Create(); end; destructor TPendingFrames.Destroy; var i: integer; begin for i := FramesPending.Count - 1 downto 0 do FramesPending[i].Free(); FramesPending.Free(); inherited; end; end.
{*******************************************************} { } { Delphi LiveBindings Framework } { } { Copyright(c) 2011 Embarcadero Technologies, Inc. } { } {*******************************************************} {$HPPEMIT '#pragma link "Data.Bind.EngExt"'} {Do not Localize} unit Data.Bind.EngExt; // Register binding engine extensions interface implementation uses Data.Bind.Components, System.Bindings.EvalProtocol, System.SysUtils, System.Classes, Data.Bind.Consts, System.Rtti, System.Bindings.Methods; function GetCheckedState(AObject: TObject): string; var LEditor: IBindCheckBoxEditor; begin Result := ''; if Supports(GetBindEditor(AObject, IBindCheckBoxEditor), IBindCheckBoxEditor, LEditor) then begin case LEditor.State of cbChecked: Result := BoolToStr(True, True); cbUnchecked: Result := BoolToStr(False, True); cbGrayed: Result := ''; end; end; end; function GetSelectedText(AObject: TObject): string; var LEditor: IBindListEditor; begin Result := ''; if Supports(GetBindEditor(AObject, IBindListEditor), IBindListEditor, LEditor) then begin Result := LEditor.SelectedText; end; end; function GetSelectedItem(AObject: TObject): TObject; var LEditor: IBindListEditor; begin Result := nil; if Supports(GetBindEditor(AObject, IBindListEditor), IBindListEditor, LEditor) then begin Result := LEditor.SelectedItem; end; end; procedure SetCheckedState(AObject: TObject; const AValue: string); var LEditor: IBindCheckBoxEditor; BoolVal: Boolean; begin if Assigned(AObject) then if Supports(GetBindEditor(AObject, IBindCheckBoxEditor), IBindCheckBoxEditor, LEditor) then begin if TryStrToBool(AValue, BoolVal) then begin if BoolVal then LEditor.State := cbChecked else LEditor.State := cbUnchecked; end else if LEditor.AllowGrayed then LEditor.State := cbGrayed else LEditor.State := cbUnchecked; end; end; procedure SetSelectedText(AObject: TObject; const AValue: string); var LEditor: IBindListEditor; begin if AObject <> nil then if Supports(GetBindEditor(AObject, IBindListEditor), IBindListEditor, LEditor) then begin LEditor.SelectedText := AValue; end; end; function MakeCheckedState: IInvokable; begin Result := MakeInvokable(function(Args: TArray<IValue>): IValue var v: IValue; begin if Length(Args) <> 1 then raise EEvaluatorError.Create(sArgCount); v := Args[0]; Result := MakeLocation(TypeInfo(string), function: TValue begin if v.GetValue.IsEmpty then Result := TValue.Empty else Result := GetCheckedState(v.GetValue.AsObject); end, procedure(x: TValue) begin SetCheckedState(v.GetValue.AsObject, x.AsString); end); end); end; function MakeSelectedText: IInvokable; begin Result := MakeInvokable(function(Args: TArray<IValue>): IValue var v: IValue; // loc: ILocation; begin if Length(Args) <> 1 then raise EEvaluatorError.Create(sArgCount); v := Args[0]; Result := MakeLocation(TypeInfo(string), function: TValue begin if v.GetValue.IsEmpty then Result := TValue.Empty else Result := GetSelectedText(v.GetValue.AsObject); end, procedure(x: TValue) begin SetSelectedText(v.GetValue.AsObject, x.AsString); end); end); end; function MakeSelectedItem: IInvokable; begin Result := MakeInvokable(function(Args: TArray<IValue>): IValue var v: IValue; // loc: ILocation; begin if Length(Args) <> 1 then raise EEvaluatorError.Create(sArgCount); v := Args[0]; if v.GetValue.IsEmpty then Result := TValueWrapper.Create(nil) else Result := TValueWrapper.Create(GetSelectedItem(v.GetValue.AsObject)); end); end; const sIDCheckedState = 'CheckedState'; sIDSelectedText = 'SelectedText'; sIDSelectedItem = 'SelectedItem'; sThisUnit = 'Data.Bind.EngExt'; procedure RegisterMethods; begin TBindingMethodsFactory.RegisterMethod( TMethodDescription.Create( MakeCheckedState, sIDCheckedState, sCheckedState, sThisUnit, True, sCheckedStateDesc, nil) ); TBindingMethodsFactory.RegisterMethod( TMethodDescription.Create( MakeSelectedText, sIDSelectedText, sSelectedText, sThisUnit, True, sSelectedTextDesc, nil) ); TBindingMethodsFactory.RegisterMethod( TMethodDescription.Create( MakeSelectedItem, sIDSelectedItem, sSelectedItem, sThisUnit, True, sSelectedItemDesc, nil) ); end; procedure UnregisterMethods; begin TBindingMethodsFactory.UnRegisterMethod(sIDSelectedText); TBindingMethodsFactory.UnRegisterMethod(sIDSelectedItem); TBindingMethodsFactory.UnRegisterMethod(sIDCheckedState); end; initialization RegisterMethods; finalization UnregisterMethods; end.
unit SQLNodeReader; interface uses SysUtils, GMGlobals, GMSqlQuery, BaseNodeReader, Generics.Collections; type TSQLNodeReader = class (TBaseNodeReader) private procedure ReaderProc(q: TGMSqlQuery; obj: pointer); public procedure ReadChildren(ID_Node: int); override; procedure AddNew(ID_Parent: int; p: PVTNodeData); override; procedure NewCaption(p: PVTNodeData); override; procedure Delete(p: PVTNodeData); override; end; implementation uses Math; { TSQLNodeReader } procedure TSQLNodeReader.ReaderProc(q: TGMSqlQuery; obj: pointer); var v: TVTNodeData; begin InitVND(@v); if obj <> nil then // Nodes begin v.sTxt := q.FieldByName('Name').AsString; v.ObjType := q.FieldByName('ID_NodeType').AsInteger; v.ID_Obj := q.FieldByName('ID_Node').AsInteger; end else begin // node channels v.sTxt := q.FieldByName('ChnName').AsString; v.ID_Obj := q.FieldByName('ID_Node').AsInteger; v.ID_Prm := q.FieldByName('ID_Chn').AsInteger; v.ID_PT := q.FieldByName('ID_PT').AsInteger; v.ID_MeaUnit := q.FieldByName('ID_MeaUnit').AsInteger; v.sOpcTag := q.FieldByName('OpcTag').AsString; v.BaseChn := q.FieldByName('BaseChn').AsInteger; end; FReadResults.Add(v); end; procedure TSQLNodeReader.AddNew(ID_Parent: int; p: PVTNodeData); var a: ArrayOfString; begin if p.ObjType > 0 then begin p.ID_Obj := StrToInt( QueryResult( Format('insert into Nodes(ID_Parent, ID_NodeType, Name) select NullIf(%d, 0), %d, %s returning ID_Node', [ID_Parent, p.ObjType, QuotedStr(p.sTxt)]))); end else begin a := QueryResultArray_FirstRow(Format('insert into NodeChannels(ID_Node, ID_PT, Name, BaseChn) ' + ' select %d, %d, %s, %d returning ID_Node, case when Name = '''' then PrmName(BaseChn, 30, ''.'') else Name end', [ID_Parent, p.ID_PT, QuotedStr(p.sTxt), p.BaseChn])); p.ID_Prm := StrToInt(a[0]); p.sTxt := a[1]; end; end; procedure TSQLNodeReader.Delete(p: PVTNodeData); begin if p.ID_Prm > 0 then ExecSQL(Format('delete from NodeChannels where ID_Chn = %d', [p.ID_Prm])) else ExecSQL(Format('delete from Nodes where ID_Node = %d', [p.ID_Obj])); end; procedure TSQLNodeReader.NewCaption(p: PVTNodeData); begin if p.ID_Prm > 0 then ExecSQL(Format('update NodeChannels set Name = %s where ID_Chn = %d', [QuotedStr(p.sTxt), p.ID_Prm])) else ExecSQL(Format('update Nodes set Name = %s where ID_Node = %d', [QuotedStr(p.sTxt), p.ID_Obj])); end; procedure TSQLNodeReader.ReadChildren(ID_Node: int); begin FReadResults.Clear(); ReadFromQuery('select * from Nodes where coalesce(ID_Parent, 0) = ' + IntToStr(max(ID_Node, 0)), ReaderProc, self); if ID_Node > 0 then ReadFromQuery('select *, case when Name = '''' then PrmName(BaseChn, 30, ''.'') else Name end as ChnName from Nodechannels where ID_Node = ' + IntToStr(ID_Node), ReaderProc); end; end.
unit primsieve; //{$O+,R+} {$IFDEF FPC} {$MODE objFPC} {$CODEALIGN proc=32,loop=1} {$IFEND} {segmented sieve of Erathostenes using only odd numbers} {using presieved sieve of small primes, to reduce the most time consuming} interface procedure InitPrime; procedure NextSieve; function SieveStart:Uint64; function SieveSize :LongInt; function Nextprime: Uint64; function TotalCount :Uint64; function PosOfPrime: Uint64; implementation uses sysutils; const smlPrimes :array [0..10] of Byte = (2,3,5,7,11,13,17,19,23,29,31); maxPreSievePrimeNum = 7; maxPreSievePrime = 17;//smlPrimes[maxPreSievePrimeNum]; cSieveSize = 16384 * 4; //<= High(Word)+1 // Level I Data Cache type tSievePrim = record svdeltaPrime:word;//diff between actual and new prime svSivOfs:word; //Offset in sieve svSivNum:LongWord;//1 shl (1+16+32) = 5.6e14 end; tpSievePrim = ^tSievePrim; var //sieved with primes 3..maxPreSievePrime.here about 255255 Byte {$ALIGN 32} preSieve :array[0..3*5*7*11*13*17-1] of Byte;//must be > cSieveSize {$ALIGN 32} Sieve :array[0..cSieveSize-1] of Byte; {$ALIGN 32} //prime = FoundPrimesOffset + 2*FoundPrimes[0..FoundPrimesCnt] FoundPrimes : array[0..12252] of Word; {$ALIGN 32} sievePrimes : array[0..78498] of tSievePrim;// 1e6^2 ->1e12 //sievePrimes : array[0..1077863] of tSievePrim;// maximum 1e14 FoundPrimesOffset : Uint64; FoundPrimesCnt, FoundPrimesIdx, FoundPrimesTotal, SieveNum, SieveMaxIdx, preSieveOffset, LastInsertedSievePrime :NativeUInt; procedure CopyPreSieveInSieve; forward; procedure CollectPrimes; forward; procedure sieveOneSieve; forward; procedure Init0Sieve; forward; procedure SieveOneBlock; forward; //**************************************** procedure preSieveInit; var i,pr,j,umf : NativeInt; Begin fillchar(preSieve[0],SizeOf(preSieve),#1); i := 1; pr := 3;// starts with pr = 3 umf := 1; repeat IF preSieve[i] =1 then Begin pr := 2*i+1; j := i; repeat preSieve[j] := 0; inc(j,pr); until j> High(preSieve); umf := umf*pr; end; inc(i); until (pr = maxPreSievePrime)OR(umf>High(preSieve)) ; preSieveOffset := 0; end; function InsertSievePrimes(PrimPos:NativeInt):NativeInt; var j :NativeUINt; i,pr : NativeUInt; begin i := 0; //ignore first primes already sieved with if SieveNum = 0 then i := maxPreSievePrimeNum; pr :=0; j := Uint64(SieveNum)*cSieveSize*2-LastInsertedSievePrime; with sievePrimes[PrimPos] do Begin pr := FoundPrimes[i]*2+1; svdeltaPrime := pr+j; j := pr; end; inc(PrimPos); for i := i+1 to FoundPrimesCnt-1 do Begin IF PrimPos > High(sievePrimes) then BREAK; with sievePrimes[PrimPos] do Begin pr := FoundPrimes[i]*2+1; svdeltaPrime := (pr-j); j := pr; end; inc(PrimPos); end; LastInsertedSievePrime :=Uint64(SieveNum)*cSieveSize*2+pr; result := PrimPos; end; procedure CalcSievePrimOfs(lmt:NativeUint); //lmt High(sievePrimes) var i,pr : NativeUInt; sq : Uint64; begin pr := 0; i := 0; repeat with sievePrimes[i] do Begin pr := pr+svdeltaPrime; IF sqr(pr) < (cSieveSize*2) then Begin svSivNum := 0; svSivOfs := (pr*pr-1) DIV 2; end else Begin SieveMaxIdx := i; pr := pr-svdeltaPrime; BREAK; end; end; inc(i); until i > lmt; for i := i to lmt do begin with sievePrimes[i] do Begin pr := pr+svdeltaPrime; sq := sqr(pr); svSivNum := sq DIV (2*cSieveSize); svSivOfs := ( (sq - Uint64(svSivNum)*(2*cSieveSize))-1)DIV 2; end; end; end; procedure sievePrimesInit; var i,j,pr,PrimPos:NativeInt; Begin LastInsertedSievePrime := 0; preSieveOffset := 0; SieveNum :=0; CopyPreSieveInSieve; //normal sieving of first sieve i := 1; // start with 3 repeat while Sieve[i] = 0 do inc(i); pr := 2*i+1; inc(i); j := ((pr*pr)-1) DIV 2; if j > High(Sieve) then BREAK; repeat Sieve[j] := 0; inc(j,pr); until j > High(Sieve); until false; CollectPrimes; PrimPos := InsertSievePrimes(0); LastInsertedSievePrime := FoundPrimes[PrimPos]*2+1; IF PrimPos < High(sievePrimes) then Begin Init0Sieve; //Erste Sieb nochmals, aber ohne Eintrag sieveOneBlock; repeat sieveOneBlock; dec(SieveNum); PrimPos := InsertSievePrimes(PrimPos); inc(SieveNum); until PrimPos > High(sievePrimes); end; Init0Sieve; end; procedure Init0Sieve; begin FoundPrimesTotal :=0; preSieveOffset := 0; SieveNum :=0; CalcSievePrimOfs(High(sievePrimes)); end; procedure CopyPreSieveInSieve; var lmt : NativeInt; Begin lmt := preSieveOffset+cSieveSize; lmt := lmt-(High(preSieve)+1); IF lmt<= 0 then begin Move(preSieve[preSieveOffset],Sieve[0],cSieveSize); if lmt <> 0 then inc(preSieveOffset,cSieveSize) else preSieveOffset := 0; end else begin Move(preSieve[preSieveOffset],Sieve[0],cSieveSize-lmt); Move(preSieve[0],Sieve[cSieveSize-lmt],lmt); preSieveOffset := lmt end; end; procedure sieveOneSieve; var sp:tpSievePrim; pSieve :pByte; i,j,pr,sn,dSievNum :NativeUint; Begin pr := 0; sn := sieveNum; sp := @sievePrimes[0]; pSieve := @Sieve[0]; For i := SieveMaxIdx downto 0 do with sp^ do begin pr := pr+svdeltaPrime; IF svSivNum = sn then Begin j := svSivOfs; repeat pSieve[j] := 0; inc(j,pr); until j > High(Sieve); dSievNum := j DIV cSieveSize; svSivOfs := j-dSievNum*cSieveSize; svSivNum := sn+dSievNum; // svSivNum := svSivNum+dSievNum; end; inc(sp); end; i := SieveMaxIdx+1; repeat if i > High(SievePrimes) then BREAK; with sp^ do begin if svSivNum > sn then Begin SieveMaxIdx := I-1; Break; end; pr := pr+svdeltaPrime; j := svSivOfs; repeat Sieve[j] := 0; inc(j,pr); until j > High(Sieve); dSievNum := j DIV cSieveSize; svSivOfs := j-dSievNum*cSieveSize; svSivNum := sn+dSievNum; end; inc(i); inc(sp); until false; end; procedure CollectPrimes; //extract primes to FoundPrimes // var pSieve : pbyte; pFound : pWord; i,idx : NativeUint; Begin FoundPrimesOffset := SieveNum*2*cSieveSize; FoundPrimesIdx := 0; pFound :=@FoundPrimes[0]; i := 0; idx := 0; IF SieveNum = 0 then //include small primes used to pre-sieve Begin repeat pFound[idx]:= (smlPrimes[idx]-1) DIV 2; inc(idx); until smlPrimes[idx]>maxPreSievePrime; i := (smlPrimes[idx] -1) DIV 2; end; //grabbing the primes without if then -> reduces time extremly //primes are born to let branch-prediction fail. pSieve:= @Sieve[Low(Sieve)]; repeat //store every value until a prime aka 1 is found pFound[idx]:= i; inc(idx,pSieve[i]); inc(i); until i>High(Sieve); FoundPrimesCnt:= idx; inc(FoundPrimesTotal,Idx); end; procedure SieveOneBlock; begin CopyPreSieveInSieve; sieveOneSieve; CollectPrimes; inc(SieveNum); end; procedure NextSieve; Begin SieveOneBlock; end; function Nextprime:Uint64; Begin result := FoundPrimes[FoundPrimesIdx]*2+1+FoundPrimesOffset; if (FoundPrimesIdx=0) AND (sievenum = 1) then inc(result); inc(FoundPrimesIdx); If FoundPrimesIdx>= FoundPrimesCnt then SieveOneBlock; end; function PosOfPrime: Uint64; Begin result := FoundPrimesTotal-FoundPrimesCnt+FoundPrimesIdx; end; function TotalCount :Uint64; begin result := FoundPrimesTotal; end; function SieveSize :LongInt; Begin result := 2*cSieveSize; end; function SieveStart:Uint64; Begin result := (SieveNum-1)*2*cSieveSize; end; procedure InitPrime; Begin Init0Sieve; SieveOneBlock; end; begin preSieveInit; sievePrimesInit; InitPrime; end. {compiler: fpc/3.2.0/ppcx64 -Xs -O4 "%f" 50851378 in 1000079360 dauerte 529 ms 455052800 in 10000007168 dauerte 6297 ms 4118057696 in 100000071680 dauerte 93783 ms }
unit g_class_gameobject; interface uses OpenGL, u_math; type TGameObject = class (TObject) // Сдужебное Index : Integer; // Индекс в массиве объектов Parent : TObject; // Родительский объект // Все что требуется для физики объекта Pos : TGamePos; // Позиция в игровом мире MVector : TGamePos; // Вектор движения (не нормализован) Angle : Single; // Угол поворота объекта Acceler : Single; // Ускорение объекта Mass : Single; // Масса объекта Speed : Single; // Скорость Speen : Single; // Вращение (O_O ?!) // Игровое Health : Single; Radius : Single; Collision : Boolean; Fake : TObject; Freeze : Boolean; Hide : Boolean; Unkill : Boolean; procedure Move; virtual; abstract; procedure _render_bcircle; procedure Render; virtual; abstract; procedure DoCollision(Vector : TGamePos; CoObject : TObject); virtual; abstract; procedure Death; virtual; abstract; end; implementation { TGameObject } procedure TGameObject._render_bcircle; var i : Integer; begin glPushMatrix; glTranslatef(Pos.x, Pos.y, Pos.z); glColor3f(1.0, 0.0, 0.0); glBegin(GL_LINE_LOOP); for i := 0 to 17 do begin glVertex3f(Cosinus(i)*Radius, Pos.y+1, Sinus(i)*Radius); end; glEnd; glPopMatrix; end; end.
unit TestConstRecords; { AFS 27 August 2K This unit compiles but is not semantically meaningfull it is test cases for the code formatting utility This unit contains test cases for layout of const record declarations } interface type TMap = record s1: string; i1: integer; i2: integer; end; type FiveInts = array [0..4] of integer; // simple constants, with brackets const c_foo = 1 + 1; c_bar = (2 + 2); c_baz = ((3) + (3)); c_fish = (((42))); const // array an_array: array[0..5] of integer = (5,4,3,2,1,0); another_array: array[0..3] of integer = ((5+1),((4 + 1) + 2),((3)),(((2)))); AnFiveInts: FiveInts = (5,6,7,8,9); type UberMemes = (Soy, HatBaby, AllOfYourBase, monkey, WilliamShatner); const Memes_Array: array[0..6] of UberMemes = (monkey, monkey, monkey, WilliamShatner, monkey, AllOfYourBase, Soy); // multi-dim array type TLameEnum = (aValue); const cEvents: array[TLameEnum, boolean] of integer = ((42, 124)); cEvents2: array[boolean, boolean] of integer = ((43, 44), (45, 46)); cEventsSilly: array[TLameEnum, TLameEnum, TLameEnum, boolean] of integer = ((((42, 124)))); cEventsSilly2: array[TLameEnum, boolean, TLameEnum, boolean] of integer = ((((42, 124)), ((34, 35)))); // one record const AREC: TMap = (s1: 'Foo'; i1: 1; i2: 4); // array of records const THE_MAP: array [0..5] of TMap = ({ reserved words } (s1: 'Foo'; i1: 1; i2: 4), (s1: 'bar'; i1: 2; i2: 5), (s1: 'baz'; i1: 3; i2: 6), (s1: 'wibble'; i1: 4; i2: 7), (s1: 'fish'; i1: 5; i2: 8), (s1: 'spon'; i1: 6; i2: 9) ); THE_POORLY_FORMATTED_MAP: array [0..5] of TMap = ({ reserved words } (s1: 'Foo'; i1: 1; i2: 4), (s1: 'bar'; i1: 2; i2: 5), (s1: 'baz'; i1: 3; i2: 6), (s1: 'wibble'; i1: 4; i2: 7), (s1: 'fish'; i1: 5; i2: 8), (s1: 'spon'; i1: 6; i2: 9)); THE_LONG_STRING_MAP: array [0..3] of TMap = ({ reserved words } (s1: 'Foo was here. Foo foo Foo foo Foo foo Foo foo Foo foo Foo foo Foo foo Foo foo'; i1: 1; i2: 4), (s1: 'bar moo moo moo moo moo moo moo moo moo moo moo moo moo moo moo moo moo moo'; i1: 2; i2: 5), (s1: 'baz moo moo moo moo moo moo'; i1: 3; i2: 6), (s1: 'wibble moo moo moo moo'; i1: 4; i2: 7) ); implementation end.
unit IdThread; interface uses Classes, SysUtils; type TIdThreadStopMode = (smTerminate, smSuspend); TIdExceptionEvent = procedure(Sender: TObject; E: Exception) of object; TIdThread = class(TThread) protected FData: TObject; FStopMode: TIdThreadStopMode; FStopped: Boolean; FTerminatingException: string; FOnException: TIdExceptionEvent; function GetStopped: Boolean; procedure Execute; override; procedure Run; virtual; abstract; procedure AfterRun; virtual; procedure BeforeRun; virtual; public constructor Create(ACreateSuspended: Boolean = True); virtual; destructor Destroy; override; procedure Start; procedure Stop; procedure Synchronize(Method: TThreadMethod); procedure TerminateAndWaitFor; virtual; property TerminatingException: string read FTerminatingException; property Data: TObject read FData write FData; property StopMode: TIdThreadStopMode read FStopMode write FStopMode; property Stopped: Boolean read GetStopped; property OnException: TIdExceptionEvent read FOnException write FOnException; property Terminated; end; TIdThreadClass = class of TIdThread; implementation uses IdGlobal; procedure TIdThread.TerminateAndWaitFor; begin Terminate; FStopped := True; WaitFor; end; procedure TIdThread.AfterRun; begin end; procedure TIdThread.BeforeRun; begin end; procedure TIdThread.Execute; begin try while not Terminated do try if Stopped then begin Suspended := True; if Terminated then begin Break; end; end; BeforeRun; while not Stopped do begin Run; end; finally AfterRun; end; except on E: exception do begin FTerminatingException := E.Message; if Assigned(FOnException) then FOnException(self, E); Terminate; end; end; end; procedure TIdThread.Synchronize(Method: TThreadMethod); begin inherited Synchronize(Method); end; constructor TIdThread.Create(ACreateSuspended: Boolean); begin inherited; FStopped := ACreateSuspended; end; destructor TIdThread.Destroy; begin FreeAndNil(FData); inherited; end; procedure TIdThread.Start; begin if Stopped then begin FStopped := False; Suspended := False; end; end; procedure TIdThread.Stop; begin if not Stopped then begin case FStopMode of smTerminate: Terminate; smSuspend: ; end; FStopped := True; end; end; function TIdThread.GetStopped: Boolean; begin Result := Terminated or FStopped; end; end.
{ Copyright (c) 2006, Loginov Dmitry Sergeevich All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } unit SearchDBGrid; interface uses Windows, Messages, SysUtils, Classes, Forms, Menus, Controls, DBGrids, DB, ExtCtrls; const CBMSG_KEYDOWN = 45078; CBMSG_KEYPRESS = 48386; type // Определяет тип процедуры, которая будет вызывается в начале, // в процессе и в конце поиска TSearchUpdate = procedure(Sender: TObject; InSearchMode: Boolean; SearchText: string) of object; TSearchDBGrid = class(TComponent) private FShortCut: TShortCut; FAltShortCut: TShortCut; FIsSearchMode: Boolean; FOnSearchUpdate: TSearchUpdate; FSearchText: string; FDBGridList: TList; FDBGridListOptions: TList; FOnKeyDown: TKeyEvent; FOnKeyPress: TKeyPressEvent; FTimer: TTimer; FCanFastSearch: Boolean; procedure SetIsSearchMode(const Value: Boolean); // Определяет, можно ли в принципе выполнять поиск (фокус должен быть) // на компоненте DBGrid function CanSearch: Boolean; // Определяет, находится ли компонент на активном окне приложения function IsOnActiveForm: Boolean; procedure SetAltShortCut(const Value: TShortCut); procedure SetShortCut(const Value: TShortCut); procedure SetOnKeyDown(const Value: TKeyEvent); procedure SetOnKeyPress(const Value: TKeyPressEvent); procedure ProcOnTimer(Sender: TObject); { Private declarations } protected { Protected declarations } public { Public declarations } function LocateRecByText(Txt: string): Boolean; procedure ProcKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ProcKeyPress(Sender: TObject; var Key: Char); constructor Create(AOwner: TComponent); override; destructor Destroy; override; // Возвращает True, если пользователь нажал одну из 2-х заданных // горячих клавич (если они конечно заданы!) function IsAssignedShortCut(AShortCut: TShortCut): Boolean; // Свойство устанавливает или сбрасывает режим поиска property IsSearchMode: Boolean read FIsSearchMode write SetIsSearchMode; property CanFastSearch: Boolean read FCanFastSearch write FCanFastSearch; property SearchText: string read FSearchText; published { Published declarations } // Назначаются быстрые клавиши. property ShortCut: TShortCut read FShortCut write SetShortCut default 0; // Альтернативные быстные клавиши property AltShortCut: TShortCut read FAltShortCut write SetAltShortCut default 0; property OnSearchUpdate: TSearchUpdate read FOnSearchUpdate write FOnSearchUpdate; // Обработчики, заданные этими свойствами, будут вызываться // на наше усмотрение. Эти обработчики круче, чем при использовании // KeyPreview - у них приоритет выше property OnKeyDown: TKeyEvent read FOnKeyDown write SetOnKeyDown; property OnKeyPress: TKeyPressEvent read FOnKeyPress write SetOnKeyPress; end; procedure Register; implementation procedure Register; begin RegisterComponents('loginOFF', [TSearchDBGrid]); end; var Hook: HHOOK; SearchDBGridList: TList; function CallBackWndProc(Code, Flag, PData: Integer): Integer; stdcall; var Msg: TCWPStruct; AKey: Word; AChar: Char; ShiftState: TShiftState; I: Integer; Obj: TSearchDBGrid; begin Result := 0; try Msg := PCWPStruct(PData)^; case Msg.message of CBMSG_KEYDOWN: begin ShiftState := KeyDataToShiftState(Msg.lParam); AKey := Msg.wParam; // Посылаем сообщение всем элементам списка for I := 0 to SearchDBGridList.Count - 1 do begin Obj := SearchDBGridList[I]; if Obj.CanSearch then Obj.ProcKeyDown(Obj, AKey, ShiftState); if Obj.IsOnActiveForm and (AKey <> 0) and (Assigned(Obj.FOnKeyDown)) then begin Obj.FOnKeyDown(Obj, AKey, ShiftState); if AKey = 0 then Exit; end; end; end; CBMSG_KEYPRESS: begin AChar := Chr(Msg.wParam); for I := 0 to SearchDBGridList.Count - 1 do begin Obj := SearchDBGridList[I]; if Obj.CanSearch then Obj.ProcKeyPress(Obj, AChar); if Obj.IsOnActiveForm and (Ord(AChar) <> 0) and Assigned(Obj.FOnKeyPress) then begin Obj.FOnKeyPress(Obj, AChar); if Ord(AChar) = 0 then Exit; end; end; end; end; finally Result := CallNextHookEx(Hook, Code, Flag, PData); end; end; { TSearchDBGrid } function TSearchDBGrid.CanSearch: Boolean; var Grid: TDBGrid; DataSet: TDataSet; begin Result := False; if (not FCanFastSearch) or (not IsOnActiveForm) then Exit; if not (TForm(Owner).ActiveControl is TDBGrid) then Exit; Grid := TDBGrid(TForm(Owner).ActiveControl); if Grid.SelectedField = nil then Exit; DataSet := Grid.DataSource.DataSet; if not Assigned(DataSet) or not DataSet.Active then Exit; Result := True; end; constructor TSearchDBGrid.Create(AOwner: TComponent); begin inherited; FTimer := TTimer.Create(Self); FTimer.Enabled := False; FTimer.OnTimer := ProcOnTimer; FTimer.Interval := 2000; // Если владелец не форма, то отменяем создание if not (AOwner is TForm) then raise Exception.Create('Владелец компонента TSearchDBGrid должен быть формой'); FDBGridList := TList.Create; FDBGridListOptions := TList.Create; SearchDBGridList.Add(Self); FCanFastSearch := True; end; destructor TSearchDBGrid.Destroy; begin FDBGridList.Free; FDBGridListOptions.Free; SearchDBGridList.Remove(Self); inherited; end; function TSearchDBGrid.IsAssignedShortCut(AShortCut: TShortCut): Boolean; begin Result := ((FShortCut <> 0) and (FShortCut = AShortCut)) or ((FShortCut <> 0) and (FAltShortCut = AShortCut)); end; function TSearchDBGrid.IsOnActiveForm: Boolean; begin Result := TForm(Owner) = Screen.ActiveForm; end; function TSearchDBGrid.LocateRecByText(Txt: string): Boolean; var DataSet: TDataSet; FieldName: string; begin Result := False; if CanSearch then begin DataSet := TDBGrid(TForm(Owner).ActiveControl).DataSource.DataSet; FieldName := TDBGrid(TForm(Owner).ActiveControl).SelectedField.FieldName; try Result := DataSet.Locate(FieldName, Txt, [loCaseInsensitive, loPartialKey]); // Если тип поля не строковый, то скорее всего сразу выполнить поиск // не получится, поэтому все-же вернем True if TDBGrid(TForm(Owner).ActiveControl).SelectedField.DataType <> ftString then Result := True; except end; end; end; procedure TSearchDBGrid.ProcKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin // Если в режиме поиска была нажата клавиша VK_BACK, то стираем последний символ if (Key = VK_BACK) and IsSearchMode and (FSearchText <> '') then begin // Удаляем последний символ Delete(FSearchText, Length(FSearchText), 1); LocateRecByText(FSearchText); if Assigned(FOnSearchUpdate) then FOnSearchUpdate(Self, True, FSearchText); // Сбрасываем таймер FTimer.Enabled := False; FTimer.Enabled := True; Key := 0; end; // Если нажали ESCAPE, то в первый раз очищаем строку поиска, а второй - // выходим из режима поиска if (Key = VK_ESCAPE) and IsSearchMode then begin if FSearchText <> '' then begin FSearchText := ''; LocateRecByText(FSearchText); if Assigned(FOnSearchUpdate) then FOnSearchUpdate(Self, True, FSearchText); end else IsSearchMode := False; Key := 0; end; // Если в режиме поиска нажали Enter, то завершаем поиск if (Key = VK_RETURN) and IsSearchMode then begin IsSearchMode := False; Key := 0; end; // Здесь регистрируется только факт начала поиска и завершения поиска if (Key <> 0) and IsAssignedShortCut(Menus.ShortCut(Key, Shift)) then begin IsSearchMode := not IsSearchMode; Key := 0; end; end; procedure TSearchDBGrid.ProcKeyPress(Sender: TObject; var Key: Char); begin // Регистрирует только клавиши, код которых не меньше кода пробела if Ord(Key) < VK_SPACE then Exit; if IsSearchMode then begin if LocateRecByText(FSearchText + Key) then FSearchText := FSearchText + Key; // Сбрасываем таймер FTimer.Enabled := False; FTimer.Enabled := True; if Assigned(FOnSearchUpdate) then FOnSearchUpdate(Self, True, FSearchText); Key := Chr(0); end; end; // Устанавливает или сбрасывает режим поиска procedure TSearchDBGrid.ProcOnTimer(Sender: TObject); begin FSearchText := ''; if Assigned(FOnSearchUpdate) then FOnSearchUpdate(Self, True, FSearchText); FTimer.Enabled := False; end; procedure TSearchDBGrid.SetAltShortCut(const Value: TShortCut); begin FAltShortCut := Value; end; procedure TSearchDBGrid.SetIsSearchMode(const Value: Boolean); var I: Integer; sp: TSmallPoint; begin if Value then begin // Мы не может перейти в режим поиска, если активный компонент - не сетка if not CanSearch then Exit; // Запоминаем все сетки DBGrid, находящиеся на форме FDBGridList.Clear; FDBGridListOptions.Clear; for I := 0 to TForm(Owner).ComponentCount - 1 do if TForm(Owner).Components[I] is TDBGrid then begin FDBGridList.Add(TForm(Owner).Components[I]); with TDBGrid(FDBGridList[FDBGridList.Count - 1]) do begin // Запоминаем настройки sp.x := SmallInt(ReadOnly); sp.y := SmallInt(dgEditing in Options); if Assigned(DataSource) then if Assigned(DataSource.DataSet) and (DataSource.DataSet.State in [dsEdit, dsInsert]) then DataSource.DataSet.Cancel; FDBGridListOptions.Add(Pointer(sp)); // Меняем настройки ReadOnly := True; Options := Options - [dgEditing]; Repaint; end; end; // of if end else begin // Восстанавливаем настройки сеток for I := 0 to FDBGridList.Count - 1 do begin sp := TSmallPoint(FDBGridListOptions[I]); with TDBGrid(FDBGridList[I]) do begin ReadOnly := Boolean(sp.x); if Boolean(sp.y) then Options := Options + [dgEditing]; Repaint; end; end; // Очищаем ненужные списки FDBGridList.Clear; FDBGridListOptions.Clear; FTimer.Enabled := False; end; FIsSearchMode := Value; FSearchText := ''; if Assigned(FOnSearchUpdate) then FOnSearchUpdate(Self, Value, FSearchText); end; procedure TSearchDBGrid.SetOnKeyDown(const Value: TKeyEvent); begin FOnKeyDown := Value; end; procedure TSearchDBGrid.SetOnKeyPress(const Value: TKeyPressEvent); begin FOnKeyPress := Value; end; procedure TSearchDBGrid.SetShortCut(const Value: TShortCut); begin FShortCut := Value; end; initialization Hook := SetWindowsHookEx(WH_CALLWNDPROC, CallBackWndProc, 0, GetCurrentThreadId); SearchDBGridList := TList.Create; finalization UnhookWindowsHookEx(Hook); SearchDBGridList.Free; end.
unit Ths.Erp.Helper.Button; interface {$I ThsERP.inc} uses Winapi.Windows, Winapi.Messages, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.ComCtrls, Vcl.Menus, Math, StrUtils, Vcl.ActnList, System.Actions, Vcl.AppEvnts, Vcl.StdCtrls, Vcl.Samples.Spin, Vcl.ExtCtrls, System.Classes, Dialogs, System.SysUtils, System.UITypes; type TButton = class(Vcl.StdCtrls.TButton) private ShowBackColor : Boolean; FCanvas : TCanvas; IsFocused : Boolean; FBackColor : TColor; FForeColor : TColor; FHoverColor : TColor; procedure SetBackColor(const Value: TColor); procedure SetForeColor(const Value: TColor); procedure SetHoverColor(const Value: TColor); protected procedure CreateParams(var Params: TCreateParams); override; procedure WndProc(var Message : TMessage); override; procedure SetButtonStyle(Value: Boolean); override; procedure DrawButton(Rect: TRect; State: UINT); procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED; procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; procedure CNMeasureItem(var Message: TWMMeasureItem); message CN_MEASUREITEM; procedure CNDrawItem(var Message: TWMDrawItem); message CN_DRAWITEM; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property BackColor : TColor read FBackColor write SetBackColor default clBtnFace; property ForeColor : TColor read FForeColor write SetForeColor default clBtnText; property HoverColor: TColor read FHoverColor write SetHoverColor default clBtnFace; end; implementation { TButton } constructor TButton.Create(AOwner: TComponent); begin inherited Create(AOwner); ShowBackColor := True; FCanvas := TCanvas.Create; BackColor := clBtnFace; ForeColor := clBtnText; HoverColor := clBtnFace; end; destructor TButton.Destroy; begin FreeAndNil(FCanvas); inherited Destroy; end; procedure TButton.WndProc(var Message : TMessage); begin if (Message.Msg = CM_MOUSELEAVE) then begin ShowBackColor := True; Invalidate; end; if (Message.Msg = CM_MOUSEENTER) then begin ShowBackColor := False; Invalidate; end; inherited; end; procedure TButton.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params do Style := Style or BS_OWNERDRAW; end; procedure TButton.SetButtonStyle(Value: Boolean); begin if Value <> IsFocused then begin IsFocused := Value; Invalidate; end; end; procedure TButton.CNMeasureItem(var Message: TWMMeasureItem); begin with Message.MeasureItemStruct^ do begin itemWidth := Width; itemHeight := Height; end; end; procedure TButton.CNDrawItem(var Message: TWMDrawItem); var SaveIndex: Integer; begin with Message.DrawItemStruct^ do begin SaveIndex := SaveDC(hDC); FCanvas.Lock; try FCanvas.Handle := hDC; FCanvas.Font := Font; FCanvas.Brush := Brush; DrawButton(rcItem, itemState); finally FCanvas.Handle := 0; FCanvas.Unlock; RestoreDC(hDC, SaveIndex); end; end; Message.Result := 1; end; procedure TButton.CMEnabledChanged(var Message: TMessage); begin inherited; Invalidate; end; procedure TButton.CMFontChanged(var Message: TMessage); begin inherited; Invalidate; end; procedure TButton.SetBackColor(const Value: TColor); begin if FBackColor <> Value then begin FBackColor:= Value; Invalidate; end; end; procedure TButton.SetForeColor(const Value: TColor); begin if FForeColor <> Value then begin FForeColor:= Value; Invalidate; end; end; procedure TButton.SetHoverColor(const Value: TColor); begin if FHoverColor <> Value then begin FHoverColor:= Value; Invalidate; end; end; procedure TButton.DrawButton(Rect: TRect; State: UINT); var Flags, OldMode: Longint; IsDown, IsDefault, IsDisabled: Boolean; OldColor: TColor; OrgRect: TRect; NewCaption : string; begin NewCaption := Caption; OrgRect := Rect; Flags := DFCS_BUTTONPUSH or DFCS_ADJUSTRECT; IsDown := State and ODS_SELECTED <> 0; IsDisabled := State and ODS_DISABLED <> 0; IsDefault := State and ODS_FOCUS <> 0; if IsDown then Flags := Flags or DFCS_PUSHED; if IsDisabled then Flags := Flags or DFCS_INACTIVE; if (IsFocused or IsDefault) then begin FCanvas.Pen.Color := clWindowFrame; FCanvas.Pen.Width := 1; FCanvas.Brush.Style := bsClear; FCanvas.Rectangle(Rect.Left, Rect.Top, Rect.Right, Rect.Bottom); InflateRect(Rect, - 1, - 1); end; if IsDown then begin FCanvas.Pen.Color := clBtnShadow; FCanvas.Pen.Width := 1; FCanvas.Brush.Color := clBtnFace; FCanvas.Rectangle(Rect.Left, Rect.Top, Rect.Right, Rect.Bottom); InflateRect(Rect, - 1, - 1); end else begin DrawFrameControl(FCanvas.Handle, Rect, DFC_BUTTON, Flags); end; if IsDown then OffsetRect(Rect, 1, 1); OldColor := FCanvas.Brush.Color; if ShowBackColor then FCanvas.Brush.Color := BackColor else FCanvas.Brush.Color := HoverColor; FCanvas.FillRect(Rect); FCanvas.Brush.Color := OldColor; OldMode := SetBkMode(FCanvas.Handle, TRANSPARENT); FCanvas.Font.Color := ForeColor; if IsDisabled then DrawState(FCanvas.Handle, FCanvas.Brush.Handle, nil, Integer(NewCaption), 0, ((Rect.Right - Rect.Left) - FCanvas.TextWidth(NewCaption)) div 2, ((Rect.Bottom - Rect.Top) - FCanvas.TextHeight(NewCaption)) div 2, 0, 0, DST_TEXT or DSS_DISABLED) else begin InflateRect(Rect, -4, -4); //ferhat yazıyı dikey olarak ortalaması için bu satır eklendi. if (Rect.Bottom - Rect.Top) > FCanvas.TextHeight(NewCaption) then InflateRect(Rect, 0, ( -1* (Rect.Top+((((Rect.Bottom - Rect.Top) div 2) - FCanvas.TextHeight(NewCaption)) div 2)) )); DrawText(FCanvas.Handle, PChar(NewCaption), - 1, Rect, DT_WORDBREAK or DT_CENTER); end; SetBkMode(FCanvas.Handle, OldMode); if (IsFocused and IsDefault) then begin Rect := OrgRect; InflateRect(Rect, - 4, - 4); FCanvas.Pen.Color := clWindowFrame; FCanvas.Brush.Color := clBtnFace; DrawFocusRect(FCanvas.Handle, Rect); end; end; end.
unit IdTime; interface uses Classes, IdTCPClient; type TIdTime = class(TIdTCPClient) protected FBaseDate: TDateTime; FRoundTripDelay: Cardinal; FTimeout: Integer; function GetDateTimeCard: Cardinal; function GetDateTime: TDateTime; public constructor Create(AOwner: TComponent); override; function SyncTime: boolean; property DateTimeCard: Cardinal read GetDateTimeCard; property DateTime: TDateTime read GetDateTime; property RoundTripDelay: Cardinal read FRoundTripDelay; published property BaseDate: TDateTime read FBaseDate write FBaseDate; property Timeout: Integer read FTimeout write FTimeout default 2500; end; implementation uses IdGlobal, IdTCPConnection, SysUtils; constructor TIdTime.Create(AOwner: TComponent); begin inherited; Port := IdPORT_TIME; FBaseDate := 2; FTimeout := 2500; end; function TIdTime.GetDateTime: TDateTime; var BufCard: Cardinal; begin BufCard := GetDateTimeCard; if BufCard <> 0 then begin Result := ((BufCard / (24 * 60 * 60) + (FRoundTripDelay div 1000)) + Int(fBaseDate)) - IdGlobal.TimeZoneBias; end else begin Result := 0; end; end; function TIdTime.GetDateTimeCard: Cardinal; var TimeBeforeRetrieve: Cardinal; begin Result := 0; Connect; try TimeBeforeRetrieve := IdGlobal.GetTickCount; repeat if ReadFromStack(True, FTimeout) = 0 then begin Exit; end; until (CurrentReadBufferSize >= SizeOf(Result)); Result := ReadCardinal; if IdGlobal.GetTickCount >= TimeBeforeRetrieve then begin FRoundTripDelay := (IdGlobal.GetTickCount - TimeBeforeRetrieve) div 2 end else begin FRoundTripDelay := (High(Cardinal) - TimeBeforeRetrieve + IdGlobal.GetTickCount) div 2; end; finally Disconnect; end; end; function TIdTime.SyncTime: boolean; var BufTime: TDateTime; begin BufTime := DateTime; result := BufTime <> 0; if result then begin result := SetLocalTime(BufTime); end; end; end.
{*******************************************************} { } { CodeGear Delphi Runtime Library } { } { Copyright(c) 1995-2018 Embarcadero Technologies, Inc. } { All rights reserved } { } {*******************************************************} unit Androidapi.NativeActivity; interface uses Posix.SysTypes, Androidapi.AssetManager, Androidapi.Input, Androidapi.NativeWindow, Androidapi.Rect, Androidapi.Jni; (*$HPPEMIT '#include <android/native_activity.h>' *) {$I Androidapi.inc} { Flags for ANativeActivity_showSoftInput; see the Java InputMethodManager API for documentation. } const ANATIVEACTIVITY_SHOW_SOFT_INPUT_IMPLICIT = $0001; {$EXTERNALSYM ANATIVEACTIVITY_SHOW_SOFT_INPUT_IMPLICIT} ANATIVEACTIVITY_SHOW_SOFT_INPUT_FORCED = $0002; {$EXTERNALSYM ANATIVEACTIVITY_SHOW_SOFT_INPUT_FORCED} { Flags for ANativeActivity_hideSoftInput; see the Java InputMethodManager API for documentation. } const ANATIVEACTIVITY_HIDE_SOFT_INPUT_IMPLICIT_ONLY = $0001; {$EXTERNALSYM ANATIVEACTIVITY_HIDE_SOFT_INPUT_IMPLICIT_ONLY} ANATIVEACTIVITY_HIDE_SOFT_INPUT_NOT_ALWAYS = $0002; {$EXTERNALSYM ANATIVEACTIVITY_HIDE_SOFT_INPUT_NOT_ALWAYS} { This structure defines the native side of an Androidapi.app.NativeActivity. It is created by the framework, and handed to the application's native code as it is being launched. } type PANativeActivityCallbacks = ^ANativeActivityCallbacks; ANativeActivity = record { Pointer to the callback function table of the native application. You can set the functions here to your own callbacks. The callbacks pointer itself here should not be changed; it is allocated and managed for you by the framework. } callbacks : PANativeActivityCallbacks; { The global handle on the process's Java VM.} vm : PJavaVM; { JNI context for the main thread of the app. Note that this field can ONLY be used from the main thread of the process; that is, the thread that calls into the ANativeActivityCallbacks. } env : PJNIEnv; { The NativeActivity Java class. } clazz : JNIObject; { Path to this application's internal data directory. } internalDataPath : MarshaledAString; { Path to this application's external (removable/mountable) data directory. } externalDataPath : MarshaledAString; { The platform's SDK version code. } sdkVersion : Int32; { This is the native instance of the application. It is not used by the framework, but can be set by the application to its own instance state. } instance : Pointer; { Pointer to the Asset Manager instance for the application. The application uses this to access binary assets bundled inside its own .apk file. } assetManager : PAAssetManager; end; {$EXTERNALSYM ANativeActivity} PANativeActivity = ^ANativeActivity; { ANativeActivityCallbacks } { NativeActivity has started. See Java documentation for Activity.onStart() for more information.} TOnStartCallback = procedure(Activity: PANativeActivity); cdecl; { NativeActivity has resumed. See Java documentation for Activity.onResume() for more information. } TOnResumeCallback = procedure(Activity: PANativeActivity); cdecl; { Framework is asking NativeActivity to save its current instance state. See Java documentation for Activity.onSaveInstanceState() for more information. The returned pointer needs to be created with malloc(); the framework will call free() on it for you. You also must fill in outSize with the number of bytes in the allocation. Note that the saved state will be persisted, so it can not contain any active entities (pointers to memory, file descriptors, etc). } TOnSaveInstanceStateCallback = function(Activity: PANativeActivity; OutSize: Psize_t): Pointer; cdecl; { NativeActivity has paused. See Java documentation for Activity.onPause() for more information. } TOnPauseCallback = procedure(Activity: PANativeActivity); cdecl; { NativeActivity has stopped. See Java documentation for Activity.onStop() for more information. } TOnStopCallback = procedure(Activity: PANativeActivity); cdecl; { NativeActivity is being destroyed. See Java documentation for Activity.onDestroy() for more information. } TOnDestroyCallback = procedure(Activity: PANativeActivity); cdecl; { Focus has changed in this NativeActivity's window. This is often used, for example, to pause a game when it loses input focus. } TOnWindowFocusChangedCallback = procedure(Activity: PANativeActivity; HasFocus: Integer); cdecl; { The drawing window for this native Activity has been created. You can use the given native window object to start drawing. } TOnNativeWindowCreatedCallback = procedure(Activity: PANativeActivity; Window: PANativeWindow); cdecl; { The drawing window for this native activity has been resized. You should retrieve the new size from the window and ensure that your rendering in it now matches. } TOnNativeWindowResizedCallback = procedure(Activity: PANativeActivity; Window: PANativeWindow); cdecl; { The drawing window for this native activity needs to be redrawn. To avoid transient artifacts during screen changes (such resizing after rotation), applications should not return from this function until they have finished drawing their window in its current state. } TOnNativeWindowRedrawNeededCallback = procedure(Activity: PANativeActivity; Window: PANativeWindow); cdecl; { The drawing window for this native activity is going to be destroyed. You MUST ensure that you do not touch the window object after returning from this function: in the common case of drawing to the window from another thread, that means the implementation of this callback must properly synchronize with the other thread to stop its drawing before returning from here. } TOnNativeWindowDestroyedCallback = procedure(Activity: PANativeActivity; Window: PANativeWindow); cdecl; { The input queue for this native activity's window has been created. You can use the given input queue to start retrieving input events. } TOnInputQueueCreatedCallback = procedure(Activity: PANativeActivity; Queue: PAInputQueue); cdecl; { The input queue for this native activity's window is being destroyed. You should no longer try to reference this object upon returning from this function. } TOnInputQueueDestroyedCallback = procedure(Activity: PANativeActivity; Queue: PAInputQueue); cdecl; { The rectangle in the window in which content should be placed has changed. } TOnContentRectChangedCallback = procedure(Activity: PANativeActivity; Rect: PARect); cdecl; { The current device AConfiguration has changed. The new configuration can be retrieved from assetManager. } TOnConfigurationChangedCallback = procedure(Activity: PANativeActivity); cdecl; { The system is running low on memory. Use this callback to release resources you do not need, to help the system avoid killing more important processes. } TOnLowMemoryCallback = procedure(Activity: PANativeActivity); cdecl; { These are the callbacks the framework makes into a native application. All of these callbacks happen on the main thread of the application. By default, all callbacks are NULL; set to a pointer to your own function to have it called. } ANativeActivityCallbacks = record onStart: TOnStartCallback; onResume: TOnResumeCallback; onSaveInstanceState : TOnSaveInstanceStateCallback; onPause : TOnPauseCallback; onStop : TOnStopCallback; onDestroy : TOnDestroyCallback; onWindowFocusChanged : TOnWindowFocusChangedCallback; onNativeWindowCreated : TOnNativeWindowCreatedCallback; onNativeWindowResized : TOnNativeWindowResizedCallback; onNativeWindowRedrawNeeded : TOnNativeWindowRedrawNeededCallback; onNativeWindowDestroyed : TOnNativeWindowDestroyedCallback; onInputQueueCreated : TOnInputQueueCreatedCallback; onInputQueueDestroyed : TOnInputQueueDestroyedCallback; onContentRectChanged : TOnContentRectChangedCallback; onConfigurationChanged : TOnConfigurationChangedCallback; onLowMemory : TOnLowMemoryCallback; end; {$EXTERNALSYM ANativeActivityCallbacks} { This is the function that must be in the native code to instantiate the application's native activity. It is called with the activity instance (see above); if the code is being instantiated from a previously saved instance, the savedState will be non-NULL and point to the saved data. You must make any copy of this data you need -- it will be released after you return from this function. } ANativeActivity_createFunc = procedure(Activity: PANativeActivity; SavedState: Pointer; SavedStateSize: size_t); cdecl; { The name of the function that NativeInstance looks for when launching its native code. This is the default function that is used, you can specify "Androidapi.app.func_name" string meta-data in your manifest to use a different function. } var ANativeActivity_onCreate : ANativeActivity_createFunc; { external AndroidLib name 'ANativeActivity_onCreate' {$EXTERNALSYM ANativeActivity_onCreate} { Finish the given activity. Its finish() method will be called, causing it to be stopped and destroyed. Note that this method can be called from *any* thread; it will send a message to the main thread of the process where the Java finish call will take place. } procedure ANativeActivity_finish(Activity: PANativeActivity); cdecl; external AndroidLib name 'ANativeActivity_finish' {$EXTERNALSYM ANativeActivity_finish} { Change the window format of the given activity. Calls getWindow().setFormat() of the given activity. Note that this method can be called from *any* thread; it will send a message to the main thread of the process where the Java finish call will take place. } procedure ANativeActivity_setWindowFormat(Activity: PANativeActivity; Format: Int32); cdecl; external AndroidLib name 'ANativeActivity_setWindowFormat' {$EXTERNALSYM ANativeActivity_setWindowFormat} { Change the window flags of the given activity. Calls getWindow().setFlags() of the given activity. Note that this method can be called from *any* thread; it will send a message to the main thread of the process where the Java finish call will take place. See window.h for flag constants. } procedure ANativeActivity_setWindowFlags(Activity: PANativeActivity; AddFlags, RemoveFlags: UInt32); cdecl; external AndroidLib name 'ANativeActivity_setWindowFlags' {$EXTERNALSYM ANativeActivity_setWindowFlags} { Show the IME while in the given activity. Calls InputMethodManager.showSoftInput() for the given activity. Note that this method can be called from *any* thread; it will send a message to the main thread of the process where the Java finish call will take place. } procedure ANativeActivity_showSoftInput(Activity: PANativeActivity; Flags: UInt32); cdecl; external AndroidLib name 'ANativeActivity_showSoftInput' {$EXTERNALSYM ANativeActivity_showSoftInput} { Hide the IME while in the given activity. Calls InputMethodManager.hideSoftInput() for the given activity. Note that this method can be called from *any* thread; it will send a message to the main thread of the process where the Java finish call will take place. } procedure ANativeActivity_hideSoftInput(Activity: PANativeActivity; Flags: UInt32); cdecl; external AndroidLib name 'ANativeActivity_hideSoftInput' {$EXTERNALSYM ANativeActivity_hideSoftInput} implementation end.
(*============================================================================ COSNaming Server Demo for VisiBroker 4 for Delphi The naming service changed significantly from VisiBroker 3.3 to VisiBroker 4. Now it is a java application that must be started with a command line that tells the Name Service which port to use for communications. In addition, all clients and servers must use the same command line parameter as well. The command line is used to "bootstrap" the Orb so that it knows which port to use for the Name Service. The naming service must be started before either the client or server. Once the Name Service is up and running in a command window, its IOR will be displayed in the window. Then the server and the client can be started (in that order). Sample batch files have been provided with this example to show how to start each application. In a DOS window, run StartNS.bat first. This brings up the Naming Service. Then run StartServer.bat. After the server is up and running, run StartClient.bat ===========================================================================*) unit ServerMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Corba, COSNaming, Account_c, Account_i, Account_impl, Account_s, StdCtrls; type TForm1 = class(TForm) Memo1: TMemo; procedure FormCreate(Sender: TObject); private { private declarations } protected { protected declarations } Acct : Account; // skeleton object RootContext : NamingContext; nameComp : NameComponent; nameArray : COSNaming.Name; procedure InitCorba; public { public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.InitCorba; begin CorbaInitialize; // Create the server and register with the BOA Acct := TAccountSkeleton.Create('Jack B Quick', TAccount.Create); BOA.ObjIsReady(Acct as _Object); //Get the Naming Service Root Context via the ORB RootContext := TNamingContextHelper.Narrow(Orb.ResolveInitialReferences('NameService'), True); //create the naming component -- match server id and kind values nameComp := TNameComponent.Create('Account', 'Jack B Quick'); //set up the Name sequence SetLength(NameArray, 1); NameArray[0] := nameComp; // now bind with the Nameing Service RootContext.rebind(NameArray, Acct as CorbaObject); end; procedure TForm1.FormCreate(Sender: TObject); begin initCorba; end; end.
unit rhlMD2; interface uses rhlCore, SysUtils; type { TrhlMD2 } TrhlMD2 = class(TrhlHash) private FStates: TBytes; FChecksum: TBytes; protected procedure UpdateBlock(const AData); override; public constructor Create; override; procedure Init; override; procedure Final(var ADigest); override; end; implementation { TrhlMD2 } const PI_TAB: array[0..255] of byte = ( $29,$2E,$43,$C9,$A2,$D8,$7C,$01,$3D,$36,$54,$A1,$EC,$F0,$06,$13, $62,$A7,$05,$F3,$C0,$C7,$73,$8C,$98,$93,$2B,$D9,$BC,$4C,$82,$CA, $1E,$9B,$57,$3C,$FD,$D4,$E0,$16,$67,$42,$6F,$18,$8A,$17,$E5,$12, $BE,$4E,$C4,$D6,$DA,$9E,$DE,$49,$A0,$FB,$F5,$8E,$BB,$2F,$EE,$7A, $A9,$68,$79,$91,$15,$B2,$07,$3F,$94,$C2,$10,$89,$0B,$22,$5F,$21, $80,$7F,$5D,$9A,$5A,$90,$32,$27,$35,$3E,$CC,$E7,$BF,$F7,$97,$03, $FF,$19,$30,$B3,$48,$A5,$B5,$D1,$D7,$5E,$92,$2A,$AC,$56,$AA,$C6, $4F,$B8,$38,$D2,$96,$A4,$7D,$B6,$76,$FC,$6B,$E2,$9C,$74,$04,$F1, $45,$9D,$70,$59,$64,$71,$87,$20,$86,$5B,$CF,$65,$E6,$2D,$A8,$02, $1B,$60,$25,$AD,$AE,$B0,$B9,$F6,$1C,$46,$61,$69,$34,$40,$7E,$0F, $55,$47,$A3,$23,$DD,$51,$AF,$3A,$C3,$5C,$F9,$CE,$BA,$C5,$EA,$26, $2C,$53,$0D,$6E,$85,$28,$84,$09,$D3,$DF,$CD,$F4,$41,$81,$4D,$52, $6A,$DC,$37,$C8,$6C,$C1,$AB,$FA,$24,$E1,$7B,$08,$0C,$BD,$B1,$4A, $78,$88,$95,$8B,$E3,$63,$E8,$6D,$E9,$CB,$D5,$FE,$3B,$00,$1D,$39, $F2,$EF,$B7,$0E,$66,$58,$D0,$E4,$A6,$77,$72,$F8,$EB,$75,$4B,$0A, $31,$44,$50,$B4,$8F,$ED,$1F,$1A,$DB,$99,$8D,$33,$9F,$11,$83,$14); procedure TrhlMD2.UpdateBlock(const AData); var Data: array[0..15] of byte absolute AData; temp: TBytes; i, j, t: DWord; begin SetLength(temp, 48); Move(FStates[0], temp[0], 16); Move(Data[0], temp[16], 16); for i := 0 to 15 do temp[i + 32] := FStates[i] xor Data[i]; t := 0; for i := 0 to 17 do begin for j := 0 to 47 do begin temp[j] := temp[j] xor PI_TAB[t]; t := temp[j]; end; t := (t + DWord(i)) and $FF; end; Move(temp[0], FStates[0], 16); t := FChecksum[15]; for i := 0 to BlockSize - 1 do begin FChecksum[i] := FChecksum[i] xor PI_TAB[Data[i] xor t]; t := FChecksum[i]; end; end; constructor TrhlMD2.Create; begin HashSize := 16; BlockSize := 16; SetLength(FStates, 16); SetLength(FChecksum, 16); end; procedure TrhlMD2.Init; begin inherited Init; FillChar(FStates[0], Length(FStates), 0); FillChar(FChecksum[0], Length(FChecksum), 0); end; procedure TrhlMD2.Final(var ADigest); var padLen: DWord; pad: TBytes; i: integer; begin padLen := 16 - FBuffer.Pos; SetLength(pad, padLen); for i := 0 to padLen - 1 do pad[i] := padLen; UpdateBytes(pad[0], padLen); UpdateBytes(FChecksum[0], 16); Move(FStates[0], ADigest, Length(FStates)); end; end.