text
stringlengths
14
6.51M
{ Subroutine SST_CHARH_INFO (CHAR_H,FNAM,LNUM) * * Return the source file name and line number for a particular source * character. CHAR_H is the handle to the source character. This originally * came from the syntaxer. } module sst_CHARH_INFO; define sst_charh_info; %include 'sst2.ins.pas'; procedure sst_charh_info ( {get info from handle to source character} in char_h: syo_char_t; {handle to source character} in out fnam: univ string_var_arg_t; {name of source file for first char} out lnum: sys_int_machine_t); {source file line number of first char} var ichar: sys_int_machine_t; {char number within line (unused)} cnum: sys_int_machine_t; {char index into source line (unused)} sline: string_var80_t; {raw source line (unused)} begin sline.max := sizeof(sline.str); {init local var string} if char_h.crange_p = nil then begin {there is no character here ?} fnam.len := 0; lnum := 0; return; end; syo_get_char_line ( {get info about this source character} char_h, {handle to source character} ichar, cnum, sline, {unused returned arguments} lnum, {line number within source file} fnam); {name of source file} end;
{**************************************************************************} { Parameter controls property editor } { } { Copyright © 2001 - 2012 } { TMS Software } { Email : info@tmssoftware.com } { Web : http://www.tmssoftware.com } { } {**************************************************************************} unit paramedit; {$I TMSDEFS.INC} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TParamInfo = class(TForm) Label1: TLabel; pid: TEdit; Label2: TLabel; pval: TEdit; Label3: TLabel; phint: TEdit; Label4: TLabel; ptype: TComboBox; Label5: TLabel; pextra: TEdit; Button1: TButton; Button2: TButton; private { Private declarations } public { Public declarations } end; var ParamInfo: TParamInfo; implementation {$R *.dfm} end.
unit vtDialogsRes; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "VT$Core" // Автор: Люлин А.В. // Модуль: "w:/common/components/gui/Garant/VT/vtDialogsRes.pas" // Начат: 03.03.2010 16:43 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<UtilityPack::Class>> Shared Delphi::VT$Core::Dialogs::vtDialogsRes // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\VT\vtDefine.inc} interface uses l3StringIDEx ; var { Локализуемые строки TvtMiscMessages } str_vtDefaultOpenDlgFilter : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtDefaultOpenDlgFilter'; rValue : 'Все файлы|*.*'); { 'Все файлы|*.*' } {$If not defined(Nemesis)} var { Локализуемые строки MsgDlg } str_vtMsgDlgWarning : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgWarning'; rValue : 'Warning'); { 'Warning' } str_vtMsgDlgError : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgError'; rValue : 'Error'); { 'Error' } str_vtMsgDlgInformation : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgInformation'; rValue : 'Information'); { 'Information' } str_vtMsgDlgConfirm : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgConfirm'; rValue : 'Confirm'); { 'Confirm' } {$IfEnd} //not Nemesis {$If defined(Nemesis)} var { Локализуемые строки MsgDlgNemesis } str_vtMsgDlgWarning : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgWarning'; rValue : 'Предупреждение'); { 'Предупреждение' } str_vtMsgDlgError : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgError'; rValue : 'Ошибка'); { 'Ошибка' } str_vtMsgDlgInformation : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgInformation'; rValue : 'Информация'); { 'Информация' } str_vtMsgDlgConfirm : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgConfirm'; rValue : 'Подтверждение'); { 'Подтверждение' } {$IfEnd} //Nemesis var { Локализуемые строки Custom } str_vtMsgDlgCustom : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgCustom'; rValue : ''); { '' } var { Локализуемые строки MsgDlgButtons } str_vtMsgDlgYes : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgYes'; rValue : '&Да'); { '&Да' } str_vtMsgDlgNo : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgNo'; rValue : '&Нет'); { '&Нет' } str_vtMsgDlgOK : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgOK'; rValue : 'OK'); { 'OK' } str_vtMsgDlgCancel : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgCancel'; rValue : '&Отмена'); { '&Отмена' } str_vtMsgDlgAbort : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgAbort'; rValue : '&Прервать'); { '&Прервать' } str_vtMsgDlgRetry : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgRetry'; rValue : 'Пов&торить'); { 'Пов&торить' } str_vtMsgDlgIgnore : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgIgnore'; rValue : '&Игнорировать'); { '&Игнорировать' } str_vtMsgDlgAll : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgAll'; rValue : '&Все'); { '&Все' } str_vtMsgDlgNoToAll : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgNoToAll'; rValue : '&Нет для всех'); { '&Нет для всех' } str_vtMsgDlgYesToAll : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgYesToAll'; rValue : '&Да для всех'); { '&Да для всех' } str_vtMsgDlgHelp : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vtMsgDlgHelp'; rValue : '&Справка'); { '&Справка' } implementation uses l3MessageID ; initialization // Инициализация str_vtDefaultOpenDlgFilter str_vtDefaultOpenDlgFilter.Init; {$If not defined(Nemesis)} // Инициализация str_vtMsgDlgWarning str_vtMsgDlgWarning.Init; {$IfEnd} //not Nemesis {$If not defined(Nemesis)} // Инициализация str_vtMsgDlgError str_vtMsgDlgError.Init; {$IfEnd} //not Nemesis {$If not defined(Nemesis)} // Инициализация str_vtMsgDlgInformation str_vtMsgDlgInformation.Init; {$IfEnd} //not Nemesis {$If not defined(Nemesis)} // Инициализация str_vtMsgDlgConfirm str_vtMsgDlgConfirm.Init; {$IfEnd} //not Nemesis {$If defined(Nemesis)} // Инициализация str_vtMsgDlgWarning str_vtMsgDlgWarning.Init; {$IfEnd} //Nemesis {$If defined(Nemesis)} // Инициализация str_vtMsgDlgError str_vtMsgDlgError.Init; {$IfEnd} //Nemesis {$If defined(Nemesis)} // Инициализация str_vtMsgDlgInformation str_vtMsgDlgInformation.Init; {$IfEnd} //Nemesis {$If defined(Nemesis)} // Инициализация str_vtMsgDlgConfirm str_vtMsgDlgConfirm.Init; {$IfEnd} //Nemesis // Инициализация str_vtMsgDlgCustom str_vtMsgDlgCustom.Init; // Инициализация str_vtMsgDlgYes str_vtMsgDlgYes.Init; // Инициализация str_vtMsgDlgNo str_vtMsgDlgNo.Init; // Инициализация str_vtMsgDlgOK str_vtMsgDlgOK.Init; // Инициализация str_vtMsgDlgCancel str_vtMsgDlgCancel.Init; // Инициализация str_vtMsgDlgAbort str_vtMsgDlgAbort.Init; // Инициализация str_vtMsgDlgRetry str_vtMsgDlgRetry.Init; // Инициализация str_vtMsgDlgIgnore str_vtMsgDlgIgnore.Init; // Инициализация str_vtMsgDlgAll str_vtMsgDlgAll.Init; // Инициализация str_vtMsgDlgNoToAll str_vtMsgDlgNoToAll.Init; // Инициализация str_vtMsgDlgYesToAll str_vtMsgDlgYesToAll.Init; // Инициализация str_vtMsgDlgHelp str_vtMsgDlgHelp.Init; end.
// Notifier for expanding macro templates after pressing space unit GX_MacroExpandNotifier; interface uses GX_EditorChangeServices; // Use a timer to delay expansion by a short amount, so the user can cancel // the expansion by pressing some key other than space. {$DEFINE EXPAND_WITH_TIMER} const DefExpandChar = #32; type TProcessMacroEvent = procedure (const ATemplateName, ATemplateCode: string; var Accepted: Boolean) of object; IMacroExpandNotifier = interface(IGxEditorNotification) ['{159DF04C-C199-475A-9857-DEA5A81E7517}'] procedure Detach; procedure SetExpandDelay(Value: Integer); end; function PrepareNewExpandMacroNotifier(AOnProcessMacro: TProcessMacroEvent): IMacroExpandNotifier; implementation uses {$IFOPT D+} GX_DbugIntf, {$ENDIF} Classes, SysUtils, ExtCtrls, Forms, ToolsAPI, GX_OtaUtils, GX_GenericUtils, GX_IdeUtils, GX_MacroTemplates; type TMacroExpandNotifier = class(TNotifierObject, IGxEditorNotification, IMacroExpandNotifier) private FOnProcessMacro: TProcessMacroEvent; FNotifierIndex: Integer; FCheckTimer: TTimer; FExpandChar: Char; FExpandDelay: Integer; FEventLock: Integer; FQueuedTemplateName: string; procedure CheckExpand; procedure HandleCheckTimer(Sender: TObject); procedure StartCheckTimer; procedure StopCheckTimer; procedure CheckMacroCodePlacement(const SourceEditor: IOTASourceEditor); function DetermineReplacement(const Element: Integer; const SyntaxHighlighter: TGXSyntaxHighlighter): Boolean; procedure TryExpand(const ATemplateName, ATemplateCode: string); procedure LockEvents; procedure TryExpandLater(const ATemplateName: string); procedure UnlockEvents; procedure HandleNotification(const SourceEditor: IOTASourceEditor); protected // IGxEditorNotification procedure NewModuleOpened(const Module: IOTAModule); procedure SourceEditorModified(const SourceEditor: IOTASourceEditor); procedure FormEditorModified(const FormEditor: IOTAFormEditor); procedure ComponentRenamed(const FormEditor: IOTAFormEditor; Component: IOTAComponent; const OldName, NewName: string); function EditorKeyPressed(const SourceEditor: IOTASourceEditor; CharCode: Word; KeyData: Integer): Boolean; function GetIndex: Integer; protected procedure Attach; public constructor Create(AOnProcessMacro: TProcessMacroEvent); destructor Destroy; override; procedure Detach; procedure SetExpandDelay(Value: Integer); property ExpandChar: Char read FExpandChar; property ExpandDelay: Integer read FExpandDelay; end; function PrepareNewExpandMacroNotifier(AOnProcessMacro: TProcessMacroEvent): IMacroExpandNotifier; begin Result := TMacroExpandNotifier.Create(AOnProcessMacro) as IMacroExpandNotifier; end; { TMacroExpandNotifier } constructor TMacroExpandNotifier.Create(AOnProcessMacro: TProcessMacroEvent); begin inherited Create; FOnProcessMacro := AOnProcessMacro; FNotifierIndex := -1; FExpandChar := DefExpandChar; FExpandDelay := DefExpandDelay; Attach; end; destructor TMacroExpandNotifier.Destroy; begin Detach; inherited; end; procedure TMacroExpandNotifier.Attach; begin Assert(FNotifierIndex = -1); FNotifierIndex := GxEditorChangeServices.AddNotifier(Self); end; procedure TMacroExpandNotifier.Detach; begin {$IFDEF EXPAND_WITH_TIMER} StopCheckTimer; {$ENDIF EXPAND_WITH_TIMER} GxEditorChangeServices.RemoveNotifierIfNecessary(FNotifierIndex); end; procedure TMacroExpandNotifier.ComponentRenamed(const FormEditor: IOTAFormEditor; Component: IOTAComponent; const OldName, NewName: string); begin // empty end; procedure TMacroExpandNotifier.FormEditorModified(const FormEditor: IOTAFormEditor); begin // empty end; function TMacroExpandNotifier.GetIndex: Integer; begin Result := FNotifierIndex; end; procedure TMacroExpandNotifier.NewModuleOpened(const Module: IOTAModule); begin // empty end; function TMacroExpandNotifier.EditorKeyPressed(const SourceEditor: IOTASourceEditor; CharCode: Word; KeyData: Integer): Boolean; var ShiftState: TShiftState; begin {$IFOPT D+} SendDebug('Key pressed: '+IntToStr(CharCode)+'/'+Char(byte(CharCode))); {$ENDIF D+} ShiftState := KeyDataToShiftState(KeyData); if (ShiftState = []) and (CharCode = Ord(DefExpandChar)) then begin // Disabled until this hook is working properly (without crashing) //HandleNotification(SourceEditor); end; Result := False; end; procedure TMacroExpandNotifier.LockEvents; begin Inc(FEventLock); end; procedure TMacroExpandNotifier.UnlockEvents; begin if FEventLock > 0 then Dec(FEventLock); end; procedure TMacroExpandNotifier.SourceEditorModified(const SourceEditor: IOTASourceEditor); begin {$IFOPT D+} SendDebug('SourceEditorModified'); {$ENDIF} HandleNotification(SourceEditor); end; procedure TMacroExpandNotifier.HandleNotification(const SourceEditor: IOTASourceEditor); begin if FEventLock > 0 then Exit; {$IFDEF EXPAND_WITH_TIMER} StopCheckTimer; {$ENDIF EXPAND_WITH_TIMER} LockEvents; try if IsReplaceConfirmDialogOnScreen then Exit; // Only correct when the active form is an IDE TEditWindow. // This prevents some unwanted corrections when other experts, // the form designer, or the IDE make changes. if not GxOtaCurrentlyEditingSource then Exit; CheckMacroCodePlacement(SourceEditor); finally UnlockEvents; end; end; procedure TMacroExpandNotifier.CheckMacroCodePlacement(const SourceEditor: IOTASourceEditor); var LineText: string; Element: Integer; LineFlag: Integer; EditView: IOTAEditView; CursorPos: TOTAEditPos; SyntaxHighlighter: TGXSyntaxHighlighter; Index: Integer; TemplateName: string; begin if not GxOtaTryGetTopMostEditView(SourceEditor, EditView) then Exit; LineText := GxOtaGetPreceedingCharactersInLine(EditView); if Trim(LineText) = '' then Exit; if StrCharAt(LineText, Length(LineText)) = ExpandChar then begin CursorPos := EditView.CursorPos; EditView.GetAttributeAtPos(CursorPos, False, Element, LineFlag); if Element = atWhiteSpace then begin if GxOtaIsWhiteSpaceInComment(EditView, CursorPos) then Element := atComment else if GxOtaIsWhiteSpaceInString(EditView, CursorPos) then Element := atString; end; SyntaxHighlighter := GxOtaGetCurrentSyntaxHighlighter(SourceEditor); if not DetermineReplacement(Element, SyntaxHighlighter) then Exit; Index := Length(LineText) - 1; while (Index > 0) and IsCharIdentifier(LineText[Index]) do Dec(Index); TemplateName := Copy(LineText, Index + 1, Length(LineText) - Index - 1); if TemplateName<>'' then {$IFDEF EXPAND_WITH_TIMER} TryExpandLater(TemplateName); {$ELSE !EXPAND_WITH_TIMER} TryExpand(TemplateName, TemplateName+ExpandChar); {$ENDIF !EXPAND_WITH_TIMER} end; end; function TMacroExpandNotifier.DetermineReplacement(const Element: Integer; const SyntaxHighlighter: TGXSyntaxHighlighter): Boolean; const shsSource = [atWhiteSpace, atReservedWord, atIdentifier, atSymbol, atNumber, atFloat, atOctal, atHex, atCharacter, atIllegal, SyntaxOff]; begin Result := ((SyntaxHighlighter = gxpPAS) and (Element in shsSource)) or ((SyntaxHighlighter = gxpCPP) and (Element in shsSource)) or ((SyntaxHighlighter = gxpCPP) and (Element in [atPreproc])) or ((SyntaxHighlighter = gxpSQL) and (Element in shsSource)) or (Element in [atAssembler]); // No corrections are done in atString/atComment end; procedure TMacroExpandNotifier.StartCheckTimer; begin if FCheckTimer = nil then begin FCheckTimer := TTimer.Create(nil); FCheckTimer.OnTimer := Self.HandleCheckTimer; end; FCheckTimer.Enabled := False; FCheckTimer.Interval := Self.ExpandDelay; FCheckTimer.Enabled := True; end; procedure TMacroExpandNotifier.StopCheckTimer; begin if Assigned(FCheckTimer) then begin FCheckTimer.Enabled := False; FCheckTimer.OnTimer := nil; FreeAndNil(FCheckTimer); end; end; procedure TMacroExpandNotifier.HandleCheckTimer(Sender: TObject); begin if Assigned(FCheckTimer) then FCheckTimer.Enabled := False; CheckExpand; end; procedure TMacroExpandNotifier.TryExpandLater(const ATemplateName: string); begin FQueuedTemplateName := ATemplateName; StartCheckTimer; end; procedure TMacroExpandNotifier.TryExpand(const ATemplateName, ATemplateCode: string); var Accepted: Boolean; begin LockEvents; try if Assigned(FOnProcessMacro) then FOnProcessMacro(ATemplateName, ATemplateCode, Accepted); finally UnlockEvents; end; end; procedure TMacroExpandNotifier.CheckExpand; var TemplateName: string; begin if FQueuedTemplateName <> '' then begin TemplateName := FQueuedTemplateName; FQueuedTemplateName := ''; TryExpand(TemplateName, TemplateName+ExpandChar); end; end; procedure TMacroExpandNotifier.SetExpandDelay(Value: Integer); begin FExpandDelay := Value; end; end.
unit FileUtilUnit; interface uses Classes, Windows, SysUtils, StrUtils; type TDriveRec = record ID: integer; Name: string; Path: string; DriveType: string; VolumeLabel: string; SerialNumber: string; FileSystem: string; end; type ADriveRec = array of TDriveRec; procedure GetDriveInfo(VolumeName: string;var VolumeLabel, SerialNumber, FileSystem: string); function GetAllDrive(var ADrive: ADriveRec): byte; function IsFileMasked(AFileName, AMasks: string): boolean; implementation procedure GetDriveInfo(VolumeName: string; var VolumeLabel, SerialNumber, FileSystem: string); var VolLabel, FileSysName: array[0..255] of char; SerNum: pdword; MaxCompLen, FileSysFlags: dword; begin New(SerNum); GetVolumeInformation(PChar(VolumeName), VolLabel, 255, SerNum, MaxCompLen, FileSysFlags, FileSysName, 255); VolumeLabel := VolLabel; SerialNumber := Format('%x', [SerNum^]); FileSystem := FileSysName; Dispose(SerNum); end; function GetAllDrive(var ADrive: ADriveRec): byte; var VolLabel, SN, FS: string; i, mask: integer; s: string; lenArr: byte; begin lenArr := 0; SetLength(ADrive, lenArr); mask := GetLogicalDrives; i := 0; while mask <> 0 do begin s := chr(ord('a') + i) + ':\'; if (mask and 1) <> 0 then begin GetDriveInfo(S, VolLabel, SN, FS); lenArr := lenArr + 1; SetLength(ADrive, lenArr); with ADrive[ lenArr -1 ] do begin ID := ord('a') + i; Name := chr(ord('a') + i) + ':'; Path := s; VolumeLabel := VolLabel; SerialNumber:= SN; FileSystem := FS; end; case GetDriveType(PChar(s)) of 0: ADrive[ lenArr -1 ].DriveType := 'unknown'; 1: ADrive[ lenArr -1 ].DriveType := 'not exist'; DRIVE_REMOVABLE: ADrive[ lenArr -1 ].DriveType := 'removable'; DRIVE_FIXED: ADrive[ lenArr -1 ].DriveType :='fixed'; DRIVE_REMOTE: ADrive[ lenArr -1 ].DriveType :='network'; DRIVE_CDROM: ADrive[ lenArr -1 ].DriveType :='CD-ROM'; DRIVE_RAMDISK: ADrive[ lenArr -1 ].DriveType :='RAM'; end; end; inc(i); mask := mask shr 1; end; Result := lenArr; end; function IsFileMasked(AFileName, AMasks: string): boolean; var maskIndex: integer; maskList : TStringList; maskExists: boolean; begin maskList := TStringList.Create; maskList.CommaText := AMasks; maskExists := False; for maskIndex := 0 to maskList.Count - 1 do if ExtractFileExt(AFileName) = maskList[ maskIndex ] then maskExists := True; Result := maskExists; end; end.
unit WaveConvert; interface uses Windows, MMSystem, ACM, SysUtils; const strConvNotPossible = 'Conversion is not possible'; strConversionError = 'Conversion error'; type EACMConverter = class(Exception); TDataProc = function(var Data; Size : integer) : integer of object; TConvertProc = procedure(SourceInc, DestInc : integer) of object; TACMConverter = class public constructor Create(const aSourceFormat, aDestFormat : TWaveFormatEx); destructor Destroy; override; private function OpenMethod : boolean; public procedure CreateBuffers(Frames : dword); // buffersize = 1 second / Frames procedure Reset; virtual; private procedure Prepare; procedure Unprepare; private fHandle : hACMStream; fSourceFormat : TWaveFormatEx; fDestFormat : TWaveFormatEx; fSourceSize : dword; fDestSize : dword; fSourceBuffer : PByteArray; fDestBuffer : PByteArray; fHeader : TACMStreamHeader; end; TACMConverterIn = class(TACMConverter) public procedure Reset; override; function Read(var Data; Size : integer) : integer; private fDestPos : dword; fSourceRead : dword; private procedure Feed; private fOnRead : TDataProc; fOnConvert : TConvertProc; public property OnRead : TDataProc read fOnRead write fOnRead; property OnConvert : TConvertProc read fOnConvert write fOnConvert; end; TACMConverterOut = class(TACMConverter) public destructor Destroy; override; public procedure Reset; override; function Write(const Data; Size : integer) : boolean; private fSourcePos : dword; private function Flush : boolean; private fOnWrite : TDataProc; fOnConvert : TConvertProc; public property OnWrite : TDataProc read fOnWrite write fOnWrite; property OnConvert : TConvertProc read fOnConvert write fOnConvert; end; implementation uses D3Math; // TACMConverter constructor TACMConverter.Create(const aSourceFormat, aDestFormat : TWaveFormatEx); var opened : boolean; begin inherited Create; fSourceFormat := aSourceFormat; fDestFormat := aDestFormat; opened := OpenMethod; if not opened then raise EACMConverter.Create(strConvNotPossible); CreateBuffers(16); // Keep the buffer as small as possible end; destructor TACMConverter.Destroy; begin Unprepare; if fSourceBuffer <> nil then freemem(fSourceBuffer); if fDestBuffer <> nil then freemem(fDestBuffer); if fHandle <> 0 then acmStreamClose(fHandle, 0); inherited; end; function TACMConverter.OpenMethod : boolean; var r : integer; begin r := acmStreamOpen(fHandle, 0, @fSourceFormat, @fDestFormat, nil, 0, 0, 0); if r <> MMSYSERR_NOERROR then r := acmStreamOpen(fHandle, 0, @fSourceFormat, @fDestFormat, nil, 0, 0, ACM_STREAMOPENF_NONREALTIME); Result := r = MMSYSERR_NOERROR; end; procedure TACMConverter.CreateBuffers(Frames : dword); var ReqSize : dword; begin //...Here we have the implementation for "One second of source data" (tested) ReqSize := fSourceFormat.nAvgBytesPerSec div Frames; fSourceSize := ReqSize - (ReqSize mod fSourceFormat.nBlockAlign); if fSourceSize = 0 then fSourceSize := fSourceFormat.nBlockAlign; if acmStreamSize(fHandle, fSourceSize, fDestSize, ACM_STREAMSIZEF_SOURCE) <> MMSYSERR_NOERROR then raise EACMConverter.Create(strConvNotPossible); { //...Here we have the implementation for "One second of destination data" (tested) ReqSize := fDestFormat.nAvgBytesPerSec; fDestSize := ReqSize - (ReqSize mod fDestFormat.nBlockAlign); if acmStreamSize(fHandle, fDestSize, fSourceSize, ACM_STREAMSIZEF_DESTINATION) <> MMSYSERR_NOERROR then raise EACMConverter.Create(strConvNotPossible); } if fSourceBuffer <> nil then freemem(fSourceBuffer); if fDestBuffer <> nil then freemem(fDestBuffer); getmem(fSourceBuffer, fSourceSize); getmem(fDestBuffer, fDestSize); Reset; end; procedure TACMConverter.Reset; begin Unprepare; Prepare; end; procedure TACMConverter.Prepare; begin Assert(fHeader.fdwStatus and ACMSTREAMHEADER_STATUSF_PREPARED = 0, 'TACMConverter.Prepare: Stream already prepared'); with fHeader do begin cbStruct := sizeof(fHeader); fdwStatus := 0; dwUser := 0; pbSrc := fSourceBuffer; cbSrcLength := fSourceSize; cbSrcLengthUsed := fSourceSize; // Buffer is dirty at start dwSrcUser := 0; pbDst := fDestBuffer; cbDstLength := fDestSize; cbDstLengthUsed := fDestSize; // Buffer is dirty at start dwDstUser := 0; end; if acmStreamPrepareHeader(fHandle, @fHeader, 0) <> MMSYSERR_NOERROR then raise EACMConverter.Create(strConversionError); end; procedure TACMConverter.Unprepare; begin if fHeader.fdwStatus and ACMSTREAMHEADER_STATUSF_PREPARED <> 0 then begin fHeader.cbSrcLength := fSourceSize; fHeader.cbDstLength := fDestSize; acmStreamUnprepareHeader(fHandle, @fHeader, 0); end; end; // TACMConverterIn procedure TACMConverterIn.Reset; begin inherited; fSourceRead := fSourceSize; fDestPos := fDestSize; end; function TACMConverterIn.Read(var Data; Size : integer) : integer; var DataBytes : TByteArray absolute Data; SizeLeft : integer; BufferLeft : integer; ToCopy : integer; DataPos : integer; begin DataPos := 0; SizeLeft := Size; repeat BufferLeft := fHeader.cbDstLengthUsed - fDestPos; if BufferLeft = 0 then begin Feed; BufferLeft := fHeader.cbDstLengthUsed; end; ToCopy := Min(SizeLeft, BufferLeft); move(PByteArray(fHeader.pbDst)[fDestPos], DataBytes[DataPos], ToCopy); inc(DataPos, ToCopy); inc(fDestPos, ToCopy); dec(SizeLeft, ToCopy); until (SizeLeft = 0) or (BufferLeft = 0); Result := Size - SizeLeft; end; procedure TACMConverterIn.Feed; var LastBytes : dword; Flags : dword; begin Assert(assigned(fOnRead), 'TACMConverter.Feed: No data source'); LastBytes := fSourceRead - fHeader.cbSrcLengthUsed; move(fSourceBuffer[fHeader.cbSrcLengthUsed], fSourceBuffer[0], LastBytes); fSourceRead := LastBytes + dword(fOnRead(fSourceBuffer[LastBytes], fSourceSize - LastBytes)); fHeader.cbSrcLength := fSourceRead; fHeader.cbDstLengthUsed := 0; if fSourceRead <> 0 then Flags := ACM_STREAMCONVERTF_BLOCKALIGN else Flags := ACM_STREAMCONVERTF_END; if acmStreamConvert(fHandle, @fHeader, Flags) <> MMSYSERR_NOERROR then raise EACMConverter.Create(strConversionError); if assigned(fOnConvert) then fOnConvert(fHeader.cbSrcLengthUsed, fHeader.cbDstLengthUsed); fDestPos := 0; end; // TACMConverterOut destructor TACMConverterOut.Destroy; begin try if fSourcePos > 0 then Flush; except // Conversion error, ignored end; inherited; end; procedure TACMConverterOut.Reset; begin inherited; fSourcePos := 0; end; function TACMConverterOut.Write(const Data; Size : integer) : boolean; var DataBytes : TByteArray absolute Data; SizeLeft : integer; BufferLeft : dword; ToCopy : integer; DataPos : integer; begin Result := true; DataPos := 0; SizeLeft := Size; repeat BufferLeft := fSourceSize - fSourcePos; if BufferLeft = 0 then begin Result := Flush; BufferLeft := fSourceSize - fSourcePos; end; ToCopy := Min(SizeLeft, BufferLeft); move(DataBytes[DataPos], PByteArray(fHeader.pbSrc)[fSourcePos], ToCopy); inc(DataPos, ToCopy); inc(fSourcePos, ToCopy); dec(SizeLeft, ToCopy); until (SizeLeft = 0) or (BufferLeft = 0) or not Result; end; function TACMConverterOut.Flush : boolean; var Flags : DWORD; begin Assert(assigned(fOnWrite), 'TACMConverter.Flush: No data destination'); fHeader.cbSrcLength := fSourcePos; fHeader.cbDstLengthUsed := 0; if fSourcePos = fSourceSize then Flags := ACM_STREAMCONVERTF_BLOCKALIGN else Flags := ACM_STREAMCONVERTF_END; if acmStreamConvert(fHandle, @fHeader, Flags) <> MMSYSERR_NOERROR then raise EACMConverter.Create(strConversionError); if assigned(fOnConvert) then fOnConvert(fHeader.cbSrcLengthUsed, fHeader.cbDstLengthUsed); Result := fOnWrite(fDestBuffer^, fHeader.cbDstLengthUsed) = integer(fHeader.cbDstLengthUsed); fSourcePos := fSourcePos - fHeader.cbSrcLengthUsed; move(fSourceBuffer[fHeader.cbSrcLengthUsed], fSourceBuffer[0], fSourcePos); end; end.
unit MainUnit; {$mode delphi}{$H+} interface uses Windows, Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, CP.ChromaPrint, XMLRead, XMLWrite, DOM, BASS; type { TfrmFingerprintTest } TfrmFingerprintTest = class(TForm) btnInitBASS: TButton; btnDeInitBASS: TButton; btnSelectAudioFile: TButton; btnCalcFingerprint: TButton; btnMBInfo: TButton; EdDuration: TEdit; EdFilename: TEdit; EdSampleRate: TEdit; EdChannels: TEdit; GroupBox1: TGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; MemoMB: TMemo; MemoFP: TMemo; OpenDialog1: TOpenDialog; procedure btnCalcFingerprintClick(Sender: TObject); procedure btnInitBASSClick(Sender: TObject); procedure btnDeInitBASSClick(Sender: TObject); procedure btnSelectAudioFileClick(Sender: TObject); procedure btnMBInfoClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure GroupBox1Click(Sender: TObject); private { private declarations } FAudioEnabled: boolean; FAudioStream: HSTREAM; FFileName: WideString; FSampleRate: integer; FChannels: integer; FDuration: integer; FCP: TChromaPrint; public { public declarations } end; var frmFingerprintTest: TfrmFingerprintTest; implementation uses httpsend, CP.Def; {$R *.lfm} procedure ReadXMLDocRecordingContent(AXMLDocument: TXMLDocument; out Artist: WideString; out Title: WideString); var i, m: uint; ts: WideString; lSubNode, lRecordingNode, lArtistNode: TDOMNode; begin m := AXMLDocument.DocumentElement.ChildNodes.Count; with AXMLDocument.DocumentElement.ChildNodes do begin lRecordingNode := Item[0]; m := lRecordingNode.ChildNodes.Count; for i := 0 to (m - 1) do begin lSubNode := lRecordingNode.ChildNodes.Item[i]; ts := lSubNode.NodeName; if ts = 'title' then begin Title :={UTF8Decode}(lSubNode.TextContent); end; if ts = 'artist-credit' then begin lArtistNode := lSubNode.ChildNodes.Item[0].ChildNodes.Item[0].ChildNodes.Item[0]; ts := lArtistNode.NodeName; Artist := UTF8Decode(lArtistNode.TextContent); end; end; end; end; procedure GetRecordingDetails(ARecordingID: WideString; out Artist: WideString; out Title: WideString); var HTTP: THTTPSend; FURLXML: string; XMLDocument: TXMLDocument; begin FURLXML := 'http://musicbrainz.org/ws/2/recording/' + ARecordingID + '?inc=artists'; HTTP := THTTPSend.Create; try if HTTP.HTTPMethod('GET', FURLXML) then begin ReadXMLFile(XMLDocument, HTTP.Document); ReadXMLDocRecordingContent(XMLDocument, Artist, Title); end; finally HTTP.Free; end; end; { TfrmFingerprintTest } procedure TfrmFingerprintTest.btnInitBASSClick(Sender: TObject); var lVersion: word; begin // check the correct BASS was loaded lVersion := HIWORD(BASS_GetVersion); if (lVersion <> BASSVERSION) then begin FAudioEnabled := False; end else begin // Initialize audio - default device, 44100hz, stereo, 16 bits FAudioEnabled := BASS_Init(-1, 44100, 0, Handle, nil); BASS_SetConfig(BASS_CONFIG_UPDATETHREADS, 2); end; FCP := TChromaPrint.Create; end; procedure TfrmFingerprintTest.btnCalcFingerprintClick(Sender: TObject); var fp: string; lBufferLength: integer; lRemaining: integer; lBytesRead: integer; lBuffer: TSmallintArray; begin if FAudioStream = 0 then Exit; FCP.New(Ord(CHROMAPRINT_ALGORITHM_TEST2)); FCP.Start(FSampleRate, FChannels); lBufferLength := FSampleRate * FChannels; lRemaining := 120 * lBufferLength; SetLength(lBuffer, lBufferLength); while lRemaining > 0 do begin BASS_SetDevice(0); lBytesRead := BASS_ChannelGetData(FAudioStream, @lBuffer[0], lBufferLength * 2); if lBytesRead > 0 then FCP.Feed(lBuffer, lBytesRead div 2); lRemaining := lRemaining - lBytesRead div 2; end; FCP.Finish; FCP.GetFingerprint(fp); MemoFP.Lines.Add(fp); SetLength(lBuffer, 0); btnMBInfo.Enabled := True; end; procedure TfrmFingerprintTest.btnDeInitBASSClick(Sender: TObject); begin if FAudioEnabled then BASS_Free; end; procedure TfrmFingerprintTest.btnSelectAudioFileClick(Sender: TObject); var FFileName: WideString; lChannelInfo: BASS_CHANNELINFO; fp: string; lDurationByte: QWord; begin if OpenDialog1.Execute then begin FFileName := OpenDialog1.Filename; if FAudioStream <> 0 then BASS_StreamFree(FAudioStream); BASS_SetDevice(0); FAudioStream := BASS_StreamCreateFile(False, PWideChar(FFileName), 0, 0, BASS_UNICODE or BASS_STREAM_DECODE); if FAudioStream <> 0 then begin BASS_ChannelGetInfo(FAudioStream, lChannelInfo); lDurationByte := BASS_ChannelGetLength(FAudioStream, BASS_POS_BYTE); FDuration := Trunc(BASS_ChannelBytes2Seconds(FAudioStream, lDurationByte)); FSampleRate := lChannelInfo.freq; FChannels := lChannelInfo.chans; EdFilename.Text := FFileName; EdDuration.Text := IntToStr(FDuration); EdChannels.Text := IntToStr(FChannels); EdSampleRate.Text := IntToStr(FSampleRate); btnCalcFingerprint.Enabled := True; btnMBInfo.Enabled := False; end; end; end; procedure TfrmFingerprintTest.btnMBInfoClick(Sender: TObject); var i, n, j: integer; lAcoustIDInfo: TAcoustIDResult; lArtist, lTitle: WideString; begin FCP.SearchAcoustID(ansistring(MemoFP.Lines.Text), FDuration); MemoMB.Clear; n := FCP.GetSearchCount; MemoMB.Lines.Add('Search Result Count: ' + IntToStr(n)); for i := 0 to n - 1 do begin FCP.GetMusicBrainzInfo(i, lAcoustIDInfo); MemoMB.Lines.Add('Score: ' + FloatToStrF(lAcoustIDInfo.Score, ffNumber, 8, 6)); for j := 0 to Length(lAcoustIDInfo.MusicBrainzRecordingID) - 1 do begin GetRecordingDetails(lAcoustIDInfo.MusicBrainzRecordingID[j], lArtist, lTitle); MemoMB.Lines.Add('ID: ' + lAcoustIDInfo.MusicBrainzRecordingID[j] + '; Artist & Title: ' + lArtist + ' - ' + lTitle); end; end; end; procedure TfrmFingerprintTest.FormCreate(Sender: TObject); begin FAudioEnabled := False; btnCalcFingerprint.Enabled := False; btnMBInfo.Enabled := False; end; procedure TfrmFingerprintTest.GroupBox1Click(Sender: TObject); begin end; end.
// Written at 01/2004 by Alexey Torgashin // Based on VersionInfo unit by Sortland Automasjon unit ATxVersionInfo; interface const vsCompanyName = 'CompanyName'; vsFileDescription = 'FileDescription'; vsFileVersion = 'FileVersion'; vsInternalName = 'InternalName'; vsOriginalFilename = 'OriginalFilename'; vsProductName = 'ProductName'; vsProductVersion = 'ProductVersion'; vsLegalCopyright = 'LegalCopyright'; vsLegalTrademarks = 'LegalTrademarks'; vsComments = 'Comments'; vsPrivateBuild = 'PrivateBuild'; vsSpecialBuild = 'SpecialBuild'; function FGetVersionInfo(const FileName: WideString; const vsKey: string): string; implementation uses Windows, SysUtils; function SwapLong(L: Longint): Longint; assembler; asm rol eax, 16; end; function FGetVersionInfo(const FileName: WideString; const vsKey: string): string; var buf: pointer; bufSize, n: DWORD; OK: boolean; pInfo: PVSFixedFileInfo; p: pointer; begin Result:= ''; if Win32Platform = VER_PLATFORM_WIN32_NT then bufSize:= GetFileVersionInfoSizeW(PWChar(FileName), n) else bufSize:= GetFileVersionInfoSizeA(PAnsiChar(AnsiString(FileName)), n); if bufSize = 0 then Exit; GetMem(buf, bufSize); if Win32Platform = VER_PLATFORM_WIN32_NT then OK:= GetFileVersionInfoW(PWChar(FileName), 0, bufSize, buf) else OK:= GetFileVersionInfoA(PAnsiChar(AnsiString(FileName)), 0, bufSize, buf); if OK then if vsKey='' then begin if VerQueryValue(buf, '\', pointer(pInfo), n) then Result:= Format('%d.%d.%d.%d', [HiWord(pInfo.dwFileVersionMS), LoWord(pInfo.dwFileVersionMS), HiWord(pInfo.dwFileVersionLS), LoWord(pInfo.dwFileVersionLS)]); end else begin if VerQueryValue(buf, '\VarFileInfo\Translation', p, n) and VerQueryValue(buf, PChar(Format('\StringFileInfo\%.8x\%s', [SwapLong(Longint(p^)), vsKey])), p, n) then Result:= string(PChar(p)); end; FreeMem(buf, bufSize); 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.StdCtrls, Vcl.ComCtrls; type TForm3 = class(TForm) GroupBox1: TGroupBox; GroupBox2: TGroupBox; GroupBox3: TGroupBox; ProgressBar1: TProgressBar; Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; Label1: TLabel; Label2: TLabel; Label3: TLabel; Button5: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Button5Click(Sender: TObject); private { Private declarations } procedure UploadProgress(Current, Max: Int64); procedure UploadStatus(const AStatusText: string); procedure UploadFinished(Sender: TObject); public { Public declarations } end; var Form3: TForm3; implementation {$R *.dfm} uses Unit2; var ThreadUpload : TFtpThread = nil; //----------------------------------------------------------------------------- procedure TForm3.Button1Click(Sender: TObject); begin if (ThreadUpload <> nil) then Exit; Label2.Caption := ''; Label3.Caption := 'Init...'; ThreadUpload := TFtpThread.Create('ftp.servage.net', 21, Application.ExeName,Application.ExeName+'_',stftpupload); ThreadUpload.OnProgress := UploadProgress; ThreadUpload.OnStatus := UploadStatus; ThreadUpload.OnTerminate := UploadFinished; ThreadUpload.DoFtpWork:=stFtpUpload; ThreadUpload.Start; Button1.Enabled := False; Button2.Enabled := True; Button3.Enabled := False; Button4.Enabled := True; end; //------------------------------------------------------------------------------ procedure TForm3.Button2Click(Sender: TObject); begin if ThreadUpload <> nil then ThreadUpload.Pause; Button2.Enabled := False; Button3.Enabled := True; end; //------------------------------------------------------------------------------ procedure TForm3.Button3Click(Sender: TObject); begin if ThreadUpload <> nil then ThreadUpload.Unpause; Button2.Enabled := True; Button3.Enabled := False; end; //----------------------------------------------------------------------------- procedure TForm3.Button4Click(Sender: TObject); begin if ThreadUpload <> nil then begin ThreadUpload.Terminate; ThreadUpload.Unpause; end; Button2.Enabled := False; Button3.Enabled := False; Button4.Enabled := False; end; procedure TForm3.Button5Click(Sender: TObject); begin if (ThreadUpload <> nil) then Exit; Label2.Caption := ''; Label3.Caption := 'Init download...'; ThreadUpload := TFtpThread.Create('ftp.servage.net', 21, Application.ExeName,Application.ExeName+'_',stFtpDownload); ThreadUpload.OnProgress := UploadProgress; ThreadUpload.OnStatus := UploadStatus; ThreadUpload.OnTerminate := UploadFinished; ThreadUpload.DoFtpWork:=stFtpDownload; // ThreadUpload.Start; Button1.Enabled := False; Button2.Enabled := True; Button3.Enabled := False; Button4.Enabled := True; end; procedure TForm3.FormCreate(Sender: TObject); begin end; //------------------------------------------------------------------------------ procedure TForm3.UploadProgress(Current, Max: Int64); begin ProgressBar1.Position := Current; ProgressBar1.Max := Max; end; //------------------------------------------------------------------------------ procedure TForm3.UploadStatus(const AStatusText: string); begin Label3.Caption := 'Status: ' + AStatusText; end; //------------------------------------------------------------------------------ procedure TForm3.UploadFinished(Sender: TObject); begin ThreadUpload := nil; ProgressBar1.Position := 0; Label3.Caption := 'End.'; Button1.Enabled := True; Button2.Enabled := False; Button3.Enabled := False; Button4.Enabled := False; if TFtpThread(Sender).ReturnValue <> 1 then Label2.Caption := TFtpThread(Sender).ErrorMessage; end; //------------------------------------------------------------------------------ end.
//Exercicio 62: Uma pessoa aplicou um capital de R$ 6.000,00 a juros mensais de 26,5% durante um ano. //Escreva um algoritmo que determine e exiba o montante de cada mês durante esse período. { Solução em Portugol Algoritmo Exercicio 62; Const capital_inicial = 6000; juros = 1,265 Var mes: inteiro; Inicio exiba("Programa que calcula quanto de dinheiro a pessoa terá após 1 ano."); para mes <- 1 até 12 faça exiba("No ",mes,"º mês o valor foi de", (capital_inicial * juros ^ mes)," reais."); fimpara; Fim. } // Solução em Pascal Program Exercicio62; uses crt; Const capital_inicial = 6000; juros = 1.265; Var mes: integer; begin clrscr; writeln('Programa que calcula quanto de dinheiro a pessoa terá após 1 ano.'); for mes := 1 to 12 do writeln('No ',mes,'º mês o valor foi de ', (capital_inicial * (exp(mes*ln(juros)))):0:2,' reais.'); repeat until keypressed; end.
unit msmConcreteModels; // Модуль: "w:\common\components\gui\Garant\msm\msmConcreteModels.pas" // Стереотип: "Interfaces" // Элемент модели: "msmConcreteModels" MUID: (57ADC53E00B6) {$Include w:\common\components\gui\Garant\msm\msm.inc} interface uses l3IntfUses , l3Interfaces {$If NOT Defined(NoScripts)} , tfwScriptingInterfaces {$IfEnd} // NOT Defined(NoScripts) , msmModelElements , msmControllers , msmElementViews , msmUsualData , msmModels , msmDefaultModels , msmEvents ; type PmsmElementSelection = ^ImsmElementSelection; ImsmElementSelection_ProcessSelectedF_Action = function(const anItem: ImsmModelElement): Boolean; {* Тип подитеративной функции для ImsmElementSelection.ProcessSelectedF } ImsmElementSelection = interface ['{07A764C8-B32C-4DA5-B3D3-1CB8495E2368}'] function Get_CurrentElement: ImsmModelElement; procedure Set_CurrentElement(const aValue: ImsmModelElement); procedure SelectElement(const anElement: ImsmModelElement); procedure DeselectElement(const anElement: ImsmModelElement); procedure InvertElement(const anElement: ImsmModelElement); function IsElementSelected(const anElement: ImsmModelElement): Boolean; procedure Clear; procedure ProcessSelectedF(anAction: ImsmElementSelection_ProcessSelectedF_Action); function Empty: Boolean; function IsElementSelectedOrCurrent(const anElement: ImsmModelElement): Boolean; function Clone: ImsmElementSelection; function AsArray: ItfwArray; procedure SelectElements(const anElements: ItfwArray); property CurrentElement: ImsmModelElement read Get_CurrentElement write Set_CurrentElement; end;//ImsmElementSelection ImsmCaptionModel = msmControllers.ImsmCaptionModel; ImsmListLikeModelPrim = interface(ImsmCaptionModel) ['{4206D8FC-70C8-44A4-B35C-C6EB9AA41961}'] function Get_ElementToAction: ImsmModelElement; procedure Set_ElementToAction(const aValue: ImsmModelElement); function Get_CurrentElement: ImsmModelElement; procedure Set_CurrentElement(const aValue: ImsmModelElement); function Get_Selection: ImsmElementSelection; procedure Paste(const aSelection: ImsmElementSelection); overload; procedure Paste(const aDataObject: IDataObject); overload; procedure Paste; overload; procedure Paste(const anArray: ItfwArray); overload; function Drop(const anElement: ImsmModelElement; const aPoint: Tl3SPoint): Boolean; overload; function CanPaste(const aSelection: ImsmElementSelection): Boolean; function CanAddNewElement: Boolean; procedure AddNewElement(const anElementName: AnsiString; const anElementStereotype: ImsmModelElement; const aKeyValues: ItfwArray); procedure DeleteSelection; function CanDeleteSelection: Boolean; procedure ChangeProperties(const aKeyValues: ItfwArray); function CanChangeProperties: Boolean; function PropertiesForNewElement: ItfwArray; function Properties: ItfwArray; function Drop(aFormat: Tl3ClipboardFormat; const aMedium: Tl3StoragePlace; var dwEffect: Integer; const aPoint: Tl3SPoint): Boolean; overload; function DragOver(const aData: IDataObject; const aPoint: TPoint): Boolean; property ElementToAction: ImsmModelElement read Get_ElementToAction write Set_ElementToAction; property CurrentElement: ImsmModelElement read Get_CurrentElement write Set_CurrentElement; property Selection: ImsmElementSelection read Get_Selection; end;//ImsmListLikeModelPrim ImsmListLikeModel = interface(ImsmListLikeModelPrim) ['{23235321-6626-4491-B79E-CC6CB840C9DE}'] function Get_List: ImsmModelElementStringList; procedure ShowElementAsList(const anElement: ImsmModelElement); function As_ImsmDragAndDropModel: ImsmDragAndDropModel; {* Метод приведения нашего интерфейса к ImsmDragAndDropModel } property List: ImsmModelElementStringList read Get_List; end;//ImsmListLikeModel ImsmListModel = interface(ImsmListLikeModel) ['{6FDB2833-1A88-49C8-9015-D0240B72FBB3}'] procedure SetList(const aList: ImsmModelElementStringList); end;//ImsmListModel ImsmTreeModel = interface(ImsmListLikeModel) ['{D4BC6105-5126-472E-B6F1-C01B4AB7E068}'] function Get_Tree: ImsmModelElementTree; property Tree: ImsmModelElementTree read Get_Tree; end;//ImsmTreeModel SelectionChangedEvent = {final} class(TmsmModelEvent) public class function Instance: SelectionChangedEvent; {* Метод получения экземпляра синглетона SelectionChangedEvent } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } end;//SelectionChangedEvent ImsmDrawingModel = interface(ImsmListModel) ['{6E29F5F1-D00D-4FF4-A55B-50DE59E80BF4}'] end;//ImsmDrawingModel CaptionChangedEvent = msmControllers.CaptionChangedEvent; function L2ImsmElementSelectionProcessSelectedFAction(anAction: Pointer): ImsmElementSelection_ProcessSelectedF_Action; {* Функция формирования заглушки для ЛОКАЛЬНОЙ подитеративной функции для ImsmElementSelection.ProcessSelectedF } implementation uses l3ImplUses , l3Base , SysUtils ; var g_SelectionChangedEvent: SelectionChangedEvent = nil; {* Экземпляр синглетона SelectionChangedEvent } function L2ImsmElementSelectionProcessSelectedFAction(anAction: Pointer): ImsmElementSelection_ProcessSelectedF_Action; {* Функция формирования заглушки для ЛОКАЛЬНОЙ подитеративной функции для ImsmElementSelection.ProcessSelectedF } asm jmp l3LocalStub end;//L2ImsmElementSelectionProcessSelectedFAction procedure SelectionChangedEventFree; {* Метод освобождения экземпляра синглетона SelectionChangedEvent } begin l3Free(g_SelectionChangedEvent); end;//SelectionChangedEventFree class function SelectionChangedEvent.Instance: SelectionChangedEvent; {* Метод получения экземпляра синглетона SelectionChangedEvent } begin if (g_SelectionChangedEvent = nil) then begin l3System.AddExitProc(SelectionChangedEventFree); g_SelectionChangedEvent := Create; end; Result := g_SelectionChangedEvent; end;//SelectionChangedEvent.Instance class function SelectionChangedEvent.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_SelectionChangedEvent <> nil; end;//SelectionChangedEvent.Exists end.
unit untFiltreModificationHistogrammePoints; interface uses StdCtrls, Controls, ExtCtrls, Classes, contnrs, Windows, untHFiltreImage, untCalcImage; type THistogramme = (hRouge, hVert, hBleu); TPointHistogramme = class public X, Y : Integer; Visible : Boolean; constructor Create; destructor Destroy; override; procedure ChangerPosition(PX, PY : Integer); end; TParametreCub = record A, B, C, D : Double; X1, X2 : Integer; end; type TfrmFiltreModificationHistogrammePoints = class(TfrmHFiltreImage) grbHistogrammes: TGroupBox; imgRouge: TImage; imgVert: TImage; imgBleu: TImage; chkTravailleGris: TCheckBox; procedure btnOKClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure imgRougeMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure imgRougeMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure imgRougeMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure imgVertMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure imgBleuMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure imgVertMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure imgBleuMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure imgVertMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure imgBleuMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure chkTravailleGrisClick(Sender: TObject); private { Déclarations privées } public { Déclarations publiques } PointsHistogrammes : array[THistogramme] of TObjectList; NombrePoints : array[THistogramme] of Integer; Parametres : array[THistogramme] of array of TParametreCub; ListePoints : array[THistogramme] of array of TPoint; Selection : Integer; procedure AfficherPoints(Histogramme : THistogramme); procedure TriePoints(Histogramme : THistogramme); procedure PrevisualiseResultat; override; procedure CalculParametres(Histogramme : THistogramme); procedure AjouterPoint(X, Y: Integer; Histogramme : THistogramme); procedure VisiblePoints(Histogramme : THistogramme); procedure SupprimeNonVisible(Histogramme : THistogramme); procedure ActMouseDown(Histogramme : THistogramme; X, Y : Integer; Shift : TShiftState); procedure ActMouseMove(Histogramme : THistogramme; X, Y : Integer; Shift : TShiftState); end; procedure CalculerOperation(Image : TCalcImage; ParametresRouge, ParametresVert, ParametresBleu : array of TParametreCub; var ImageResultat : TCalcImage); var frmFiltreModificationHistogrammePoints: TfrmFiltreModificationHistogrammePoints; implementation uses SysUtils, Graphics, Math, untMDIImage, untPrincipale; {$R *.DFM} { TfrmFiltreModificationHistogrammePoints } procedure TfrmFiltreModificationHistogrammePoints.PrevisualiseResultat; var X, Y : Integer; X2, Y2 : Integer; begin if EnabledOK then // Si l'image est "compatible" begin for X := 0 to CalcImagePrevisualisation.TailleX - 1 do begin X2 := X * (TfrmMDIImage(Image).CalcImage.TailleX - 1) div (CalcImagePrevisualisation.TailleX - 1); // Calcul le pixel correspondant sur les images d'origines for Y := 0 to CalcImagePrevisualisation.TailleY - 1 do begin Y2 := Y * (TfrmMDIImage(Image).CalcImage.TailleY - 1) div (CalcImagePrevisualisation.TailleY - 1); // Calcul le pixel correspondant sur les images d'origines CalcImagePrev.Image[X, Y] := TfrmMDIImage(Image).CalcImage.Image[X2, Y2]; // Copie les pixels des images d'origine sur les images de prévisualisation end; end; CalculerOperation(CalcImagePrev, Parametres[hRouge], Parametres[hBleu], Parametres[HVert], CalcImagePrevisualisation); // Calcul l'image résultat de la prévisualisation AffichePrevisualisation; // Affiche la prévisualisation end; end; procedure CalculerOperation(Image : TCalcImage; ParametresRouge, ParametresVert, ParametresBleu : array of TParametreCub; var ImageResultat : TCalcImage); var X, Y : Integer; NumParametre : Integer; NumeroParametre : array[THistogramme] of array[0..255] of Integer; CouleurRouge : Integer; CouleurVert : Integer; CouleurBleu : Integer; begin for NumParametre := 1 to Length(ParametresRouge) - 1 do // Permet de for X := ParametresRouge[NumParametre].X1 to ParametresRouge[NumParametre].X2 do // gagner NumeroParametre[hRouge][X] := NumParametre; // du temps for NumParametre := 1 to Length(ParametresVert) - 1 do // Permet de for X := ParametresVert[NumParametre].X1 to ParametresVert[NumParametre].X2 do // gagner NumeroParametre[hVert][X] := NumParametre; // du temps for NumParametre := 1 to Length(ParametresBleu) - 1 do // Permet de for X := ParametresBleu[NumParametre].X1 to ParametresBleu[NumParametre].X2 do // gagner NumeroParametre[hBleu][X] := NumParametre; // du temps frmPrincipale.ChangeStatus('Calcul'); frmPrincipale.ProgressBar.Max := Image.TailleX - 1; for X := 0 to Image.TailleX - 1 do // Parcourt tous les pixels begin frmPrincipale.ProgressBar.Position := X; for Y := 0 to Image.TailleY - 1 do // de l'image begin CouleurRouge := LimiteCouleur(Image.Image[X, Y].Rouge); ImageResultat.Image[X, Y].Rouge := Power(CouleurRouge, 3) * ParametresRouge[NumeroParametre[hRouge][CouleurRouge]].A + Sqr(CouleurRouge) * ParametresRouge[NumeroParametre[hRouge][CouleurRouge]].B + CouleurRouge * ParametresRouge[NumeroParametre[hRouge][CouleurRouge]].C + ParametresRouge[NumeroParametre[hRouge][CouleurRouge]].D; CouleurVert := LimiteCouleur(Image.Image[X, Y].Vert); ImageResultat.Image[X, Y].Vert := Power(CouleurVert, 3) * ParametresVert[NumeroParametre[hVert][CouleurVert]].A + Sqr(CouleurVert) * ParametresVert[NumeroParametre[hVert][CouleurVert]].B + CouleurVert * ParametresVert[NumeroParametre[hVert][CouleurVert]].C + ParametresVert[NumeroParametre[hVert][CouleurVert]].D; CouleurBleu := LimiteCouleur(Image.Image[X, Y].Bleu); ImageResultat.Image[X, Y].Bleu := Power(CouleurBleu, 3) * ParametresBleu[NumeroParametre[hBleu][CouleurBleu]].A + Sqr(CouleurBleu) * ParametresBleu[NumeroParametre[hBleu][CouleurBleu]].B + CouleurBleu * ParametresBleu[NumeroParametre[hBleu][CouleurBleu]].C + ParametresBleu[NumeroParametre[hBleu][CouleurBleu]].D; end; end; frmPrincipale.FinCalcul; end; procedure TfrmFiltreModificationHistogrammePoints.btnOKClick(Sender: TObject); begin inherited; TfrmMDIImage(ListeImages.Last).Caption := Format('ModifieHistogrammes(%s)', [TfrmMDIImage(Image).Caption]); // Affiche le titre de l'image CalculerOperation(TfrmMDIImage(Image).CalcImage, Parametres[hRouge], Parametres[hBleu], Parametres[HVert], TfrmMDIImage(ListeImages.Last).CalcImage); // Calcul le résultat TfrmMDIImage(ListeImages.Last).AfficheImage; // Affiche le résultat end; procedure TfrmFiltreModificationHistogrammePoints.FormCreate( Sender: TObject); begin inherited; PointsHistogrammes[hRouge] := TObjectList.Create; // Crée les listes PointsHistogrammes[hVert] := TObjectList.Create; // contenants les points PointsHistogrammes[hBleu] := TObjectList.Create; // des équations AjouterPoint(0, 0, hRouge); // Ajoute 2 fois AjouterPoint(0, 0, hRouge); // chaque point AjouterPoint(0, 0, hVert); // car ils seront AjouterPoint(0, 0, hVert); // utilisés dans la AjouterPoint(0, 0, hBleu); // fonction cubique AjouterPoint(0, 0, hBleu); // du troisième degré AjouterPoint(255, 255, hRouge); // Ajoute 2 fois AjouterPoint(255, 255, hRouge); // chaque point AjouterPoint(255, 255, hVert); // car ils seront AjouterPoint(255, 255, hVert); // utilisés dans la AjouterPoint(255, 255, hBleu); // fonction cubique AjouterPoint(255, 255, hBleu); // du troisième degré imgRouge.Canvas.Brush.Color := clBlack; imgVert.Canvas.Brush.Color := clBlack; imgBleu.Canvas.Brush.Color := clBlack; imgRouge.Canvas.Pen.Color := clRed; imgVert.Canvas.Pen.Color := clGreen; imgBleu.Canvas.Pen.Color := clBlue; TriePoints(hRouge); TriePoints(hVert); TriePoints(hBleu); CalculParametres(hRouge); CalculParametres(hVert); CalculParametres(hBleu); AfficherPoints(hRouge); AfficherPoints(hVert); AfficherPoints(hBleu); end; procedure TfrmFiltreModificationHistogrammePoints.FormShow( Sender: TObject); begin inherited; imgRouge.Canvas.Rectangle(0, 0, 256, 256); // Efface les précédents imgVert.Canvas.Rectangle(0, 0, 256, 256); // points dessinés imgBleu.Canvas.Rectangle(0, 0, 256, 256); // de les images AfficherPoints(hRouge); AfficherPoints(hVert); AfficherPoints(hBleu); end; procedure TfrmFiltreModificationHistogrammePoints.imgRougeMouseDown( Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var NumSelection : Integer; begin NumSelection := Selection; // Sauvegarde la valeur de Selection ActMouseDown(hRouge, X, Y, Shift); if chkTravailleGris.Checked then begin Selection := NumSelection; // Remet la valeur de selection pour eviter des bugs ActMouseDown(hVert, X, Y, Shift); Selection := NumSelection; // Remet la valeur de selection pour eviter des bugs ActMouseDown(hBleu, X, Y, Shift); end; end; procedure TfrmFiltreModificationHistogrammePoints.AfficherPoints(Histogramme: THistogramme); var NumPoint : Integer; X : Integer; begin if Histogramme = hRouge then begin imgRouge.Canvas.Rectangle(0, 0, 256, 256); // Efface les précédents points dessinés dans l'image imgRouge.Canvas.MoveTo(0, 255); for NumPoint := 2 to NombrePoints[Histogramme] - 2 do // Parcourt tous les points begin imgRouge.Canvas.Rectangle(TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).X - 2, 255 - TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).Y - 2, TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).X + 2, 255 - TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).Y + 2); // Affiche le point for X := TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint - 1]).X to TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).X do begin imgRouge.Canvas.LineTo(X, 255 - Round(Power(X, 3) * Parametres[Histogramme][NumPoint - 1].A + Sqr(X) * Parametres[Histogramme][NumPoint - 1].B + X * Parametres[Histogramme][NumPoint - 1].C + Parametres[Histogramme][NumPoint - 1].D)); // Affiche la courbe end; end; end; if Histogramme = hVert then begin imgVert.Canvas.Rectangle(0, 0, 256, 256); // Efface les précédents points dessinés dans l'image imgVert.Canvas.MoveTo(0, 255); for NumPoint := 2 to NombrePoints[Histogramme] - 2 do // Parcourt tous les points begin imgVert.Canvas.Rectangle(TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).X - 2, 255 - TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).Y - 2, TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).X + 2, 255 - TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).Y + 2); // Affiche le point for X := TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint - 1]).X to TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).X do begin imgVert.Canvas.LineTo(X, 255 - Round(Power(X, 3) * Parametres[Histogramme][NumPoint - 1].A + Sqr(X) * Parametres[Histogramme][NumPoint - 1].B + X * Parametres[Histogramme][NumPoint - 1].C + Parametres[Histogramme][NumPoint - 1].D)); // Affiche la courbe end; end; end; if Histogramme = hBleu then begin imgBleu.Canvas.Rectangle(0, 0, 256, 256); // Efface les précédents points dessinés dans l'image imgBleu.Canvas.MoveTo(0, 255); for NumPoint := 2 to NombrePoints[Histogramme] - 2 do // Parcourt tous les points begin imgBleu.Canvas.Rectangle(TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).X - 2, 255 - TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).Y - 2, TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).X + 2, 255 - TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).Y + 2); // Affiche le point for X := TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint - 1]).X to TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).X do begin imgBleu.Canvas.LineTo(X, 255 - Round(Power(X, 3) * Parametres[Histogramme][NumPoint - 1].A + Sqr(X) * Parametres[Histogramme][NumPoint - 1].B + X * Parametres[Histogramme][NumPoint - 1].C + Parametres[Histogramme][NumPoint - 1].D)); // Affiche la courbe end; end; end; end; procedure TfrmFiltreModificationHistogrammePoints.TriePoints(Histogramme: THistogramme); procedure Swap(var Point1, Point2 : Integer); var Point : Integer; begin Point := Point1; // Inverse Point1 := Point2; // les deux Point2 := Point; // points end; var NumPoint : Integer; NumPoint2 : Integer; begin NombrePoints[Histogramme] := 0; for NumPoint := 0 to PointsHistogrammes[Histogramme].Count - 1 do if TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).Visible then // Compte le nombre Inc(NombrePoints[Histogramme]); // de points visibles for NumPoint := 0 to NombrePoints[Histogramme] - 2 do if not TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).Visible then begin Swap(TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).X, TPointHistogramme(PointsHistogrammes[Histogramme].Items[PointsHistogrammes[Histogramme].Count - 1]).X); // Met les points Swap(TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).Y, TPointHistogramme(PointsHistogrammes[Histogramme].Items[PointsHistogrammes[Histogramme].Count - 1]).Y); // visibles "devants" TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).Visible := True; // les points TPointHistogramme(PointsHistogrammes[Histogramme].Items[PointsHistogrammes[Histogramme].Count - 1]).Visible := False; // non visibles end; for NumPoint := 0 to NombrePoints[Histogramme] - 2 do for NumPoint2 := NumPoint + 1 to NombrePoints[Histogramme] - 1 do if TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).X > TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint2]).X then begin if Selection = NumPoint then Selection := NumPoint2 else if Selection = NumPoint2 then Selection := NumPoint; Swap(TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).X, TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint2]).X); // Trie par ordre croissant Swap(TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).Y, TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint2]).Y); // les points visibles end; end; procedure TfrmFiltreModificationHistogrammePoints.CalculParametres(Histogramme: THistogramme); var NumPoint : Integer; X1, Y1, X2, Y2, X3, Y3 : Integer; X12, X13, X22, X23 : Single; Den : Single; YY1, YY2 : Single; begin SetLength(Parametres[Histogramme], NombrePoints[Histogramme] - 2); YY2 := 0; for NumPoint := 0 to NombrePoints[Histogramme] - 3 do begin X1 := TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).X; // Permet Y1 := TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).Y; // de X2 := TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint + 1]).X; // prendre Y2 := TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint + 1]).Y; // moins X3 := TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint + 2]).X; // de Y3 := TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint + 2]).Y; // place YY1 := YY2; if X3 = X1 then YY2 := (Y3 - Y1) / 0.01 else YY2 := (Y3 - Y1) / (X3 - X1); if X1 - X2 = 0 then Den := 0.01 else Den := X1 - X2; Den := Den * Den * Den; X12 := Sqr(X1); X13 := X12 * X1; X22 := Sqr(X2); X23 := X22 * X2; Parametres[Histogramme][NumPoint].A := (x1 * yy1 + x1 * yy2 + 2 * y2 - 2 * y1 - yy1 * x2 - yy2 * x2) / Den; // Calcul des paramètres de la fonction cubique Parametres[Histogramme][NumPoint].B := -(x12 * yy1 + 2 * x12 * yy2 - 3 * x1 * y1 - x1 * yy2 * x2 + 3 * x1 * y2 + x1 * yy1 * x2 - 2 * yy1 * x22 - 3 * x2 * y1 - x22 * yy2 +3 * x2 * y2) / Den; // Cette partie du code Parametres[Histogramme][NumPoint].C := (yy2 * x13 + 2 * x12 * yy1 * x2 + x12 * yy2 * x2 - 6 * x1 * y1 * x2 - 2 * x22 * X1 * yy2 + 6 * x1 * y2 * x2 -yy1 * x22 * x1 - yy1 * x23) / Den; // viens de la source : http://www.delphifr.com/code.aspx?id=17067 Parametres[Histogramme][NumPoint].D := -(-x13 * y2 + yy2 * x13 * x2 - x12 * x22 * yy2 + 3 * x12 * x2 * y2 + yy1 *x22 * x12 - 3 * y1 * x22 * x1 - x1 * yy1 * x23 + y1 * x23) / Den; // de daniel.maho Parametres[Histogramme][NumPoint].X1 := X1; Parametres[Histogramme][NumPoint].X2 := X2; end; end; procedure TfrmFiltreModificationHistogrammePoints.AjouterPoint(X, Y: Integer; Histogramme : THistogramme); var Point : TPointHistogramme; begin Point := TPointHistogramme.Create; Point.ChangerPosition(X, Y); PointsHistogrammes[Histogramme].Add(Point); end; procedure TfrmFiltreModificationHistogrammePoints.VisiblePoints(Histogramme : THistogramme); var NumPoint : Integer; begin for NumPoint := 0 to PointsHistogrammes[Histogramme].Count - 1 do TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).Visible := True; for NumPoint := 0 to PointsHistogrammes[Histogramme].Count - 1 do if (NumPoint <> Selection) and (TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).X = TPointHistogramme(PointsHistogrammes[Histogramme].Items[Selection]).X) then TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).Visible := False else TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).Visible := True; end; procedure TfrmFiltreModificationHistogrammePoints.SupprimeNonVisible(Histogramme : THistogramme); var NumPoint : Integer; begin for NumPoint := PointsHistogrammes[Histogramme].Count - 1 downto 0 do if not TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).Visible then PointsHistogrammes[Histogramme].Delete(NumPoint) // Supprime les points non visibles else Break; end; { TPointHistogramme } procedure TPointHistogramme.ChangerPosition(PX, PY : Integer); begin X := PX; Y := PY; end; constructor TPointHistogramme.Create; begin X := 0; // Initialise les positions du Y := 0; // points au valeur (0, 0) Visible := True; end; destructor TPointHistogramme.Destroy; begin inherited; end; procedure TfrmFiltreModificationHistogrammePoints.imgRougeMouseMove( Sender: TObject; Shift: TShiftState; X, Y: Integer); var NumSelection : Integer; begin NumSelection := Selection; // Sauvegarde la valeur de Selection ActMouseMove(hRouge, X, Y, Shift); if chkTravailleGris.Checked then begin Selection := NumSelection; // Remet la valeur de selection pour eviter des bugs ActMouseMove(hVert, X, Y, Shift); Selection := NumSelection; // Remet la valeur de selection pour eviter des bugs ActMouseMove(hBleu, X, Y, Shift); end; end; procedure TfrmFiltreModificationHistogrammePoints.imgRougeMouseUp( Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin SupprimeNonVisible(hRouge); if chkTravailleGris.Checked then begin SupprimeNonVisible(hVert); SupprimeNonVisible(hBleu); end; PrevisualiseResultat; end; procedure TfrmFiltreModificationHistogrammePoints.imgVertMouseDown( Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var NumSelection : Integer; begin NumSelection := Selection; // Sauvegarde la valeur de Selection ActMouseDown(hVert, X, Y, Shift); if chkTravailleGris.Checked then begin Selection := NumSelection; // Remet la valeur de selection pour eviter des bugs ActMouseDown(hRouge, X, Y, Shift); Selection := NumSelection; // Remet la valeur de selection pour eviter des bugs ActMouseDown(hBleu, X, Y, Shift); end; end; procedure TfrmFiltreModificationHistogrammePoints.imgBleuMouseDown( Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var NumSelection : Integer; begin NumSelection := Selection; // Sauvegarde la valeur de Selection ActMouseDown(hBleu, X, Y, Shift); if chkTravailleGris.Checked then begin Selection := NumSelection; // Remet la valeur de selection pour eviter des bugs ActMouseDown(hRouge, X, Y, Shift); Selection := NumSelection; // Remet la valeur de selection pour eviter des bugs ActMouseDown(hVert, X, Y, Shift); end; end; procedure TfrmFiltreModificationHistogrammePoints.imgVertMouseMove( Sender: TObject; Shift: TShiftState; X, Y: Integer); var NumSelection : Integer; begin NumSelection := Selection; // Sauvegarde la valeur de Selection ActMouseMove(hVert, X, Y, Shift); if chkTravailleGris.Checked then begin Selection := NumSelection; // Remet la valeur de selection pour eviter des bugs ActMouseMove(hRouge, X, Y, Shift); Selection := NumSelection; // Remet la valeur de selection pour eviter des bugs ActMouseMove(hBleu, X, Y, Shift); end; end; procedure TfrmFiltreModificationHistogrammePoints.imgBleuMouseMove( Sender: TObject; Shift: TShiftState; X, Y: Integer); var NumSelection : Integer; begin NumSelection := Selection; // Sauvegarde la valeur de Selection ActMouseMove(hBleu, X, Y, Shift); if chkTravailleGris.Checked then begin Selection := NumSelection; // Remet la valeur de selection pour eviter des bugs ActMouseMove(hRouge, X, Y, Shift); Selection := NumSelection; // Remet la valeur de selection pour eviter des bugs ActMouseMove(hVert, X, Y, Shift); end; end; procedure TfrmFiltreModificationHistogrammePoints.imgVertMouseUp( Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin SupprimeNonVisible(hVert); if chkTravailleGris.Checked then begin SupprimeNonVisible(hRouge); SupprimeNonVisible(hBleu); end; PrevisualiseResultat; end; procedure TfrmFiltreModificationHistogrammePoints.imgBleuMouseUp( Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin SupprimeNonVisible(hBleu); if chkTravailleGris.Checked then begin SupprimeNonVisible(hRouge); SupprimeNonVisible(hVert); end; PrevisualiseResultat; end; procedure TfrmFiltreModificationHistogrammePoints.ActMouseDown( Histogramme: THistogramme; X, Y: Integer; Shift: TShiftState); var NumPoint : Integer; MinDistance : Double; Distance : Double; NumeroPoint : Integer; begin if ssLeft in Shift then begin NumeroPoint := -1; // Aucun point n'est sélectionné MinDistance := 5; // Aucun point n'est sélectionné si il n'est pas à moins de 5 pixels de la souris for NumPoint := 2 to PointsHistogrammes[Histogramme].Count - 3 do // Parcourt tous les points "utilisateur" begin Distance := Sqrt(Sqr(TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).X - X) + Sqr(TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).Y - (255 - Y))); // Calcul la distance entre la souris et le Point if Distance < MinDistance then // Si il est plus proche de la souris que le dernier begin MinDistance := Distance; // La distance minimale est mise à jour NumeroPoint := NumPoint; // Le point sélectionné est le point le plus proche end; end; if NumeroPoint <> -1 then // Si un point est selectionné begin Selection := NumeroPoint; // On le sélectionne TPointHistogramme(PointsHistogrammes[Histogramme].Items[Selection]).X := X; // On met à jour TPointHistogramme(PointsHistogrammes[Histogramme].Items[Selection]).Y := 255 - Y; // sa position end else begin AjouterPoint(X, 255 - Y, Histogramme); // On l'ajoute Selection := PointsHistogrammes[Histogramme].Count - 1; end; Histogramme := Histogramme; VisiblePoints(Histogramme); TriePoints(Histogramme); CalculParametres(Histogramme); AfficherPoints(Histogramme); end; if ssRight in Shift then begin NumeroPoint := -1; // Aucun point ne peut-être effacé MinDistance := 5; // Aucun point n'est supprimé si il n'est pas à moins de 5 pixels de la souris for NumPoint := 2 to PointsHistogrammes[Histogramme].Count - 3 do // Parcourt tous les points "utilisateur" begin Distance := Sqrt(Sqr(TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).X - X) + Sqr(TPointHistogramme(PointsHistogrammes[Histogramme].Items[NumPoint]).Y - (255 - Y))); // Calcul la distance entre la souris et le Point if Distance < MinDistance then // Si il est plus proche de la souris que le dernier begin MinDistance := Distance; // La distance minimale est mise à jour NumeroPoint := NumPoint; // Le point sélectionné est le point le plus proche end; end; if NumeroPoint <> -1 then // Si un point est selectionné PointsHistogrammes[Histogramme].Delete(NumeroPoint); // On le supprime TriePoints(Histogramme); CalculParametres(Histogramme); AfficherPoints(Histogramme); end; end; procedure TfrmFiltreModificationHistogrammePoints.ActMouseMove( Histogramme: THistogramme; X, Y: Integer; Shift: TShiftState); begin if (ssLeft in Shift) and (X > 0) and (X < 255) and (Y > 0) and (Y < 255) then begin TPointHistogramme(PointsHistogrammes[Histogramme].Items[Selection]).ChangerPosition(X, 255 - Y); VisiblePoints(Histogramme); TriePoints(Histogramme); CalculParametres(Histogramme); AfficherPoints(Histogramme); end; end; procedure TfrmFiltreModificationHistogrammePoints.chkTravailleGrisClick( Sender: TObject); var NumPoint : Integer; begin if chkTravailleGris.Checked then begin NombrePoints[hVert] := NombrePoints[hRouge]; NombrePoints[hBleu] := NombrePoints[hRouge]; PointsHistogrammes[hVert].Clear; PointsHistogrammes[hBleu].Clear; for NumPoint := 0 to PointsHistogrammes[hRouge].Count - 1 do begin AjouterPoint(TPointHistogramme(PointsHistogrammes[hRouge].Items[NumPoint]).X, TPointHistogramme(PointsHistogrammes[hRouge].Items[NumPoint]).Y, hVert); AjouterPoint(TPointHistogramme(PointsHistogrammes[hRouge].Items[NumPoint]).X, TPointHistogramme(PointsHistogrammes[hRouge].Items[NumPoint]).Y, hBleu); TPointHistogramme(PointsHistogrammes[hVert].Items[NumPoint]).Visible := TPointHistogramme(PointsHistogrammes[hRouge].Items[NumPoint]).Visible; TPointHistogramme(PointsHistogrammes[hBleu].Items[NumPoint]).Visible := TPointHistogramme(PointsHistogrammes[hRouge].Items[NumPoint]).Visible; end; CalculParametres(hVert); CalculParametres(hBleu); AfficherPoints(hVert); AfficherPoints(hBleu); end; end; end.
{ Clever Internet Suite Copyright (C) 2013 Clever Components All Rights Reserved www.CleverComponents.com } unit clIpAddress; interface {$I clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, Windows, WinSock, {$ELSE} System.Classes, System.SysUtils, Winapi.Windows, Winapi.WinSock, {$ENDIF} clWinSock2, clWUtils; type TclIPAddress = class protected function GetIsIpV6: Boolean; virtual; abstract; function GetAddress: PSockAddrGen; virtual; abstract; function GetAddressFamily: Integer; virtual; abstract; function GetAddressLength: Integer; virtual; abstract; function GetPort: Integer; virtual; abstract; procedure Clear; virtual; abstract; public class function IsHostIP(const AHost: string): Boolean; class function CreateIpAddress(const AHost: string): TclIPAddress; class function CreateNone(AddrFamily: Integer): TclIPAddress; class function CreateAny(AddrFamily: Integer): TclIPAddress; class function CreateBindingIpAddress(const AHost: string): TclIPAddress; overload; class function CreateBindingIpAddress(const AHost: string; AddrFamily: Integer): TclIPAddress; overload; function Parse(const AHost: string): Boolean; virtual; abstract; procedure None(AddrFamily: Integer); virtual; abstract; procedure Any(AddrFamily: Integer); virtual; abstract; procedure SetPort(const Value: Integer); virtual; {$IFNDEF DELPHI2009} function ToString: string; virtual; abstract; {$ENDIF} property Address: PSockAddrGen read GetAddress; property AddressLength: Integer read GetAddressLength; property AddressFamily: Integer read GetAddressFamily; property IsIpV6: Boolean read GetIsIpV6; property Port: Integer read GetPort; end; TclIPAddress4 = class(TclIPAddress) private FSockAddr: TSockAddrIn; protected function GetIsIpV6: Boolean; override; function GetAddress: PSockAddrGen; override; function GetAddressFamily: Integer; override; function GetAddressLength: Integer; override; function GetPort: Integer; override; procedure Clear; override; public class function AddrToStr(Addr: in_addr): string; class function IsPrivateUseIP(const AIP: string): Boolean; function Parse(const AHost: string): Boolean; override; procedure None(AddrFamily: Integer); override; procedure Any(AddrFamily: Integer); override; procedure SetPort(const Value: Integer); override; function ToString: string; override; end; TclIPAddress6 = class(TclIPAddress) private FAddrInfo: Paddrinfo; protected function GetIsIpV6: Boolean; override; function GetAddress: PSockAddrGen; override; function GetAddressFamily: Integer; override; function GetAddressLength: Integer; override; function GetPort: Integer; override; procedure Clear; override; public destructor Destroy; override; class function AddrToStr(Addr: IN_ADDR6): string; function Parse(const AHost: string): Boolean; override; procedure None(AddrFamily: Integer); override; procedure Any(AddrFamily: Integer); override; procedure SetPort(const Value: Integer); override; function ToString: string; override; end; var IsIpV6Preferred: Boolean = False; implementation uses clUtils, clSocketUtils; const cAddressFamilies: array[Boolean] of Integer = (AF_INET, AF_INET6); { TclIPAddress } class function TclIPAddress.CreateNone(AddrFamily: Integer): TclIPAddress; begin Result := nil; try if IsIpV6Available() then begin Result := TclIPAddress6.Create(); end else begin Result := TclIPAddress4.Create(); end; Result.None(AddrFamily); except Result.Free(); raise; end; end; class function TclIPAddress.IsHostIP(const AHost: string): Boolean; var addr: TclIPAddress; begin if (AHost = '') then begin Result := False; Exit; end; addr := nil; try addr := TclIPAddress6.Create(); Result := addr.Parse(AHost); if Result then Exit; FreeAndNil(addr); addr := TclIPAddress4.Create(); Result := addr.Parse(AHost); if Result then Exit; finally addr.Free(); end; end; class function TclIPAddress.CreateAny(AddrFamily: Integer): TclIPAddress; begin Result := nil; try if IsIpV6Available() then begin Result := TclIPAddress6.Create(); end else begin Result := TclIPAddress4.Create(); end; Result.Any(AddrFamily); except Result.Free(); raise; end; end; class function TclIPAddress.CreateBindingIpAddress(const AHost: string; AddrFamily: Integer): TclIPAddress; begin if (AHost = '') then begin Result := CreateAny(AddrFamily); Exit; end; Result := CreateIpAddress(AHost); end; class function TclIPAddress.CreateBindingIpAddress(const AHost: string): TclIPAddress; begin Result := CreateBindingIpAddress(AHost, cAddressFamilies[IsIpV6Preferred]); end; class function TclIPAddress.CreateIpAddress(const AHost: string): TclIPAddress; begin Result := nil; try Result := TclIPAddress6.Create(); if Result.Parse(AHost) then Exit; FreeAndNil(Result); Result := TclIPAddress4.Create(); if Result.Parse(AHost) then Exit; FreeAndNil(Result); RaiseSocketError(InvalidAddress, InvalidAddressCode); except Result.Free(); raise; end; end; procedure TclIPAddress.SetPort(const Value: Integer); begin if (Value < 0) then begin RaiseSocketError(InvalidPort, InvalidPortCode); end; end; { TclIPAddress4 } procedure TclIPAddress4.Any(AddrFamily: Integer); begin None(AddrFamily); FSockAddr.sin_addr.S_addr := INADDR_ANY; end; procedure TclIPAddress4.Clear; begin ZeroMemory(@FSockAddr, AddressLength); end; procedure TclIPAddress4.None(AddrFamily: Integer); begin if (AF_INET <> AddrFamily) then begin RaiseSocketError(InvalidAddressFamily, InvalidAddressFamilyCode); end; Clear(); FSockAddr.sin_family := AddrFamily; end; function TclIPAddress4.GetAddress: PSockAddrGen; begin Result := @FSockAddr; end; function TclIPAddress4.GetAddressFamily: Integer; begin Result := FSockAddr.sin_family; end; function TclIPAddress4.GetAddressLength: Integer; begin Result := SizeOf(TSockAddrIn); end; function TclIPAddress4.GetIsIpV6: Boolean; begin Result := False; end; function TclIPAddress4.GetPort: Integer; begin Result := ntohs(FSockAddr.sin_port); end; class function TclIPAddress4.IsPrivateUseIP(const AIP: string): Boolean; var b: Byte; begin Result := False; // 10.0.0.0 - 10.255.255.255 (10/8 prefix) // 172.16.0.0 - 172.31.255.255 (172.16/12 prefix) // 192.168.0.0 - 192.168.255.255 (192.168/16 prefix) if (Pos('192.168.', AIP) = 1) or (Pos('10.', AIP) = 1) then begin Result := True; end else if (Pos('172.', AIP) = 1) then begin b := Byte(StrToIntDef(ExtractWord(2, AIP, ['.']), 0)); if (b in [16..31]) then begin Result := True; end; end; end; class function TclIPAddress4.AddrToStr(Addr: in_addr): string; var p: PclChar; begin p := inet_ntoa(Addr); if (p <> nil) then begin SetLength(Result, Length(p)); Result := string(System.Copy(p, 0, Length(p))); end else begin Result := ''; end; end; function TclIPAddress4.Parse(const AHost: string): Boolean; var addr: Integer; begin Clear(); addr := inet_addr(PclChar(GetTclString(AHost))); Result := (addr <> Integer(INADDR_NONE)); if Result then begin FSockAddr.sin_addr.S_addr := addr; FSockAddr.sin_family := AF_INET; end; end; procedure TclIPAddress4.SetPort(const Value: Integer); begin inherited SetPort(Value); FSockAddr.sin_port := htons(Value); end; function TclIPAddress4.ToString: string; begin Result := AddrToStr(FSockAddr.sin_addr); end; { TclIPAddress6 } procedure TclIPAddress6.Any(AddrFamily: Integer); begin None(AddrFamily); if (AF_INET = AddrFamily) then begin Address.AddressIn.sin_addr.S_addr := INADDR_ANY; end; end; procedure TclIPAddress6.Clear; begin if IsIpV6Available() then begin freeaddrinfo(FAddrInfo); FAddrInfo := nil; end; end; destructor TclIPAddress6.Destroy; begin Clear(); inherited Destroy(); end; procedure TclIPAddress6.None(AddrFamily: Integer); var ip: string; begin if not (AddrFamily in [AF_INET, AF_INET6]) then begin RaiseSocketError(InvalidAddressFamily, InvalidAddressFamilyCode); end; if (AF_INET6 = AddrFamily) then begin ip := '::'; end else begin ip := '0.0.0.0'; end; if not Parse(ip) then begin RaiseSocketError(InvalidAddress, InvalidAddressCode); end; end; function TclIPAddress6.GetAddress: PSockAddrGen; begin if (FAddrInfo <> nil) then begin Result := FAddrInfo.ai_addr; end else begin Result := nil; end; end; function TclIPAddress6.GetAddressFamily: Integer; begin if (FAddrInfo <> nil) then begin Result := FAddrInfo.ai_family; end else begin Result := AF_UNSPEC; end; end; function TclIPAddress6.GetAddressLength: Integer; begin if (FAddrInfo <> nil) then begin Result := FAddrInfo.ai_addrlen; end else begin Result := 0; end; end; function TclIPAddress6.GetIsIpV6: Boolean; begin Result := (AF_INET6 = AddressFamily); end; function TclIPAddress6.GetPort: Integer; begin Result := 0; if (FAddrInfo <> nil) then begin if (AddressFamily = AF_INET) then begin Result := ntohs(FAddrInfo.ai_addr.Address.sin_port); end else if (AddressFamily = AF_INET6) then begin Result := ntohs(FAddrInfo.ai_addr.AddressIn6Old.sin6_port); end; end; end; class function TclIPAddress6.AddrToStr(Addr: IN_ADDR6): string; var ind: Integer; w: Word; duplicated: Integer; begin Result := ''; ind := 0; duplicated := 0; while (ind < 15) do begin w := Byte(Addr.s6_addr_[ind]) shl 8; Inc(ind); w := w or Byte(Addr.s6_addr_[ind]); Inc(ind); if (duplicated > -1) and (w = 0) then begin Inc(duplicated); end else if (duplicated = 1) then begin if (Result <> '') then begin Result := Result + ':'; end; Result := Result + '0:' + IntToHex(w, 1); duplicated := -1; end else if (duplicated > 1) then begin Result := Result + '::' + IntToHex(w, 1); duplicated := -1; end else begin if (Result <> '') then begin Result := Result + ':'; end; Result := Result + IntToHex(w, 1); end; end; if (duplicated > 0) then begin if (Result <> '') then begin Result := Result + ':'; end; Result := Result + '0'; end; if (Result = '0') then begin Result := '::'; end; end; function TclIPAddress6.Parse(const AHost: string): Boolean; var hints: Taddrinfo; begin Clear(); Result := IsIpV6Available(); if not Result then Exit; ZeroMemory(@hints, SizeOf(Taddrinfo)); hints.ai_flags := AI_NUMERICHOST; hints.ai_family := AF_UNSPEC; Result := (getaddrinfo(PclChar(GetTclString(AHost)), nil, @hints, @FAddrInfo) = 0); end; procedure TclIPAddress6.SetPort(const Value: Integer); begin inherited SetPort(Value); if (AddressFamily = AF_INET) then begin FAddrInfo.ai_addr.Address.sin_port := htons(Value); FAddrInfo.ai_protocol := Value; end else if (AddressFamily = AF_INET6) then begin FAddrInfo.ai_addr.AddressIn6Old.sin6_port := htons(Value); FAddrInfo.ai_protocol := Value; end else begin RaiseSocketError(InvalidAddress, InvalidAddressCode); end; end; function TclIPAddress6.ToString: string; begin Result := ''; if (FAddrInfo <> nil) then begin if (AddressFamily = AF_INET) then begin Result := TclIPAddress4.AddrToStr(FAddrInfo.ai_addr.Address.sin_addr); end else if (AddressFamily = AF_INET6) then begin Result := AddrToStr(FAddrInfo.ai_addr.AddressIn6Old.sin6_addr); end; end; end; end.
unit Model.ExtraviosMultas; interface uses Common.ENum, FireDAC.Comp.Client, System.Classes, DAO.Conexao, System.SysUtils, Control.Sistema; type TExtraviosMultas = class private FAcao: TAcao; FPercentual: Double; FSequencia: Integer; FObs: String; FEnvioCorrespondencia: String; FVerbaFranquia: Double; FValorProduto: Double; FNN: String; FRestricao: String; FDescricao: String; FExecutor: String; FIDExtrato: Integer; FTotal: Double; FNumeroExtrato: String; FID: Integer; FMulta: Double; FDataFranquia: TDateTime; FEntregador: Integer; FVerba: Double; FAgente: Integer; FManutencao: TDateTime; FRetornoCorrespondencia: String; FValorFranquia: Double; FTipo: Integer; FExtrato: String; FData: TDateTime; FConexao : TConexao; FQuery: TFDQuery; function Insert(): Boolean; function Update(): Boolean; function Delete(): Boolean; public property ID: Integer read FID write FID; property Descricao: String read FDescricao write FDescricao; property NN: String read FNN write FNN; property Agente: Integer read FAgente write FAgente; property ValorProduto: Double read FValorProduto write FValorProduto; property Data: TDateTime read FData write FData; property Multa: Double read FMulta write FMulta; property Verba: Double read FVerba write FVerba; property Total: Double read FTotal write FTotal; property Restricao: String read FRestricao write FRestricao; property Entregador: Integer read FEntregador write FEntregador; property Tipo: Integer read FTipo write FTipo; property VerbaFranquia: Double read FVerbaFranquia write FVerbaFranquia; property ValorFranquia: Double read FValorFranquia write FValorFranquia; property Extrato: String read FExtrato write FExtrato; property DataFranquia: TDateTime read FDataFranquia write FDataFranquia; property EnvioCorrespondencia: String read FEnvioCorrespondencia write FEnvioCorrespondencia; property RetornoCorrespondencia: String read FRetornoCorrespondencia write FRetornoCorrespondencia; property Obs: String read FObs write FObs; property Percentual: Double read FPercentual write FPercentual; property IDExtrato: Integer read FIDExtrato write FIDExtrato; property Executor: String read FExecutor write FExecutor; property Manutencao: TDateTime read FManutencao write FManutencao; property Sequencia: Integer read FSequencia write FSequencia; property NumeroExtrato: String read FNumeroExtrato write FNumeroExtrato; property Query: TFDQuery read FQuery write FQuery; property Acao: TAcao read FAcao write FAcao; constructor Create; function Localizar(aParam: array of variant): TFDQuery; function Gravar(): Boolean; function EncerraExtravio(aParam: Array of variant): Boolean; function CancelaFechamento(iExtrato: Integer): Boolean; function ExtravioExiste(): Integer; function RetornaTotaisExtravios(aParam: Array of variant): TFDQuery; function ExtraviosExtrato(): TFDquery; function ExtraviosExtratoEntregadores(): Boolean; function GetID(): Integer; end; const TABLENAME = 'tbextravios'; SQLINSERT = 'INSERT INTO ' + TABLENAME + '(COD_EXTRAVIO, DES_EXTRAVIO, NUM_NOSSONUMERO, COD_AGENTE, VAL_PRODUTO, DAT_EXTRAVIO,' + 'VAL_MULTA, VAL_VERBA, VAL_TOTAL, DOM_RESTRICAO, COD_ENTREGADOR, COD_TIPO, VAL_VERBA_FRANQUIA, ' + 'VAL_EXTRATO_FRANQUIA, DOM_EXTRATO_FRANQUIA, DAT_EXTRAVIO_FRANQUIA, DES_ENVIO_CORRESPONDENCIA, ' + 'DES_RETORNO_CORRESPONDENCIA, DES_OBSERVACOES, VAL_PERCENTUAL_PAGO, ID_EXTRATO, SEQ_ACAREACAO, ' + 'NOM_EXECUTOR, DAT_MANUTENCAO, NUM_EXTRATO) ' + 'VALUES ' + '(:COD_EXTRAVIO, :DES_EXTRAVIO, :NUM_NOSSONUMERO, :COD_AGENTE, :VAL_PRODUTO, :DAT_EXTRAVIO, :VAL_MULTA, ' + ':VAL_VERBA, :VAL_TOTAL, :DOM_RESTRICAO, :COD_ENTREGADOR, :COD_TIPO, :VAL_VERBA_FRANQUIA, :VAL_EXTRATO_FRANQUIA, ' + ':DOM_EXTRATO_FRANQUIA, :DAT_EXTRAVIO_FRANQUIA, :DES_ENVIO_CORRESPONDENCIA, :DES_RETORNO_CORRESPONDENCIA, ' + ':DES_OBSERVACOES, :VAL_PERCENTUAL_PAGO, :ID_EXTRATO, :SEQ_ACAREACAO, :NOM_EXECUTOR, :DAT_MANUTENCAO, ' + ':NUM_EXTRATO) '; SQLUPDATE = 'UPDATE ' + TABLENAME + ' SET ' + 'DES_EXTRAVIO = :DES_EXTRAVIO, NUM_NOSSONUMERO = :NUM_NOSSONUMERO, COD_AGENTE = :COD_AGENTE, ' + 'VAL_PRODUTO = :VAL_PRODUTO, DAT_EXTRAVIO = :DAT_EXTRAVIO, VAL_MULTA = :VAL_MULTA, VAL_VERBA = :VAL_VERBA, ' + 'VAL_TOTAL = :VAL_TOTAL, DOM_RESTRICAO = :DOM_RESTRICAO, COD_ENTREGADOR = :COD_ENTREGADOR, COD_TIPO = :COD_TIPO, ' + 'VAL_VERBA_FRANQUIA = :VAL_VERBA_FRANQUIA, VAL_EXTRATO_FRANQUIA = :VAL_EXTRATO_FRANQUIA, ' + 'DOM_EXTRATO_FRANQUIA = :DOM_EXTRATO_FRANQUIA, DAT_EXTRAVIO_FRANQUIA = :DAT_EXTRAVIO_FRANQUIA, ' + 'DES_ENVIO_CORRESPONDENCIA = :DES_ENVIO_CORRESPONDENCIA, ' + 'DES_RETORNO_CORRESPONDENCIA = :DES_RETORNO_CORRESPONDENCIA, DES_OBSERVACOES = :DES_OBSERVACOES, ' + 'VAL_PERCENTUAL_PAGO = :VAL_PERCENTUAL_PAGO, ID_EXTRATO = :ID_EXTRATO, SEQ_ACAREACAO = :SEQ_ACAREACAO, ' + 'NOM_EXECUTOR = :NOM_EXECUTOR, DAT_MANUTENCAO = :DAT_MANUTENCAO, NUM_EXTRATO = :NUM_EXTRATO ' + 'WHERE COD_EXTRAVIO = :COD_EXTRAVIO;'; SQLQUERY = 'SELECT COD_EXTRAVIO, DES_EXTRAVIO, NUM_NOSSONUMERO, COD_AGENTE, VAL_PRODUTO, DAT_EXTRAVIO, VAL_MULTA, VAL_VERBA, ' + 'VAL_TOTAL, DOM_RESTRICAO, COD_ENTREGADOR, COD_TIPO, VAL_VERBA_FRANQUIA, VAL_EXTRATO_FRANQUIA, ' + 'DOM_EXTRATO_FRANQUIA, DAT_EXTRAVIO_FRANQUIA, DES_ENVIO_CORRESPONDENCIA, DES_RETORNO_CORRESPONDENCIA, ' + 'DES_OBSERVACOES, VAL_PERCENTUAL_PAGO, ID_EXTRATO, SEQ_ACAREACAO, NOM_EXECUTOR, DAT_MANUTENCAO, NUM_EXTRATO ' + 'FROM ' + TABLENAME; implementation { TExtraviosMultas } function TExtraviosMultas.CancelaFechamento(iExtrato: Integer): Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('UPDATE ' + TABLENAME + ' SET ID_EXTRATO = 0 WHERE ID_EXTRATO = :ID', [iExtrato]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; constructor TExtraviosMultas.Create; begin FConexao := TSistemaControl.GetInstance.Conexao; end; function TExtraviosMultas.Delete: Boolean; var sSQL : String; FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL('DELETE FROM ' + TABLENAME + ' WHERE COD_EXTRAVIO = :ID',[Id]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TExtraviosMultas.EncerraExtravio(aParam: array of variant): Boolean; var FDQuery: TFDQuery; sExtrato: String; iEntregador: Integer; sSQL : String; begin try Result := False; FDQuery := FConexao.ReturnQuery(); sExtrato := aParam[0]; iEntregador := aParam[1]; sSQL := 'UPDATE ' + TABLENAME + ' SET ' + 'VAL_PERCENTUAL_PAGO = 100, NUM_EXTRATO = ' + QuotedStr(sExtrato) + ' WHERE COD_ENTREGADOR = ' + iEntregador.ToString + ' AND VAL_PERCENTUAL_PAGO < 100 AND DOM_RESTRICAO = "S";'; FDQuery.ExecSQL(sSQL); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TExtraviosMultas.ExtravioExiste: Integer; var FDQuery: TFDQuery; begin try Result := 0; FDQuery := FConexao.ReturnQuery(); FDQuery.SQL.Clear; FDQuery.SQL.Add('select COD_EXTRAVIO from ' + TABLENAME + ' where NUM_NOSSONUMERO = :NUM_NOSSONUMERO and COD_TIPO = :COD_TIPO ' + 'and DOM_RESTRICAO <> ' + QuotedStr('E')); FDQuery.ParamByName('NUM_NOSSONUMERO').AsString := NN; FDQuery.ParamByName('COD_TIPO').AsInteger := Tipo; FDQuery.Open(); if FDQuery.IsEmpty then Exit; Result := FDquery.FieldByName('COD_EXTRAVIO').asInteger; finally FDQuery.Close; FDQuery.Connection.Close; FDquery.Free; end; end; function TExtraviosMultas.ExtraviosExtrato: TFDquery; var sSQL: String; fdQuery : TFDQuery; begin sSQL := 'select tbextravios.cod_agente as cod_agente, tbextravios.cod_entregador as cod_entregador,' + 'sum(tbextravios.val_total) as val_total ' + 'from ' + TABLENAME + ' where tbextravios.dom_restricao = "S" and tbextravios.val_percentual_pago < 100 ' + 'group by tbextravios.cod_agente, tbextravios.cod_entregador;'; fdQuery := FConexao.ReturnQuery; fdQuery.SQL.Add(sSQL); FDQuery.Open(); Result := FDQuery; end; function TExtraviosMultas.ExtraviosExtratoEntregadores: Boolean; var sSQL: String; fdQuery : TFDQuery; begin try Result := False; sSQL := 'select tbextravios.cod_agente as cod_agente, tbextravios.cod_entregador as cod_entregador,' + 'sum(tbextravios.val_total) as val_total ' + 'from ' + TABLENAME + ' where tbextravios.dom_restricao = "S" and tbextravios.val_percentual_pago < 100 ' + 'group by tbextravios.cod_agente, tbextravios.cod_entregador;'; fdQuery := FConexao.ReturnQuery; fdQuery.SQL.Add(sSQL); FDQuery.Open(); if fdQuery.IsEmpty then begin Exit; end; FQuery := fdQuery; Result := True; finally FDQuery.Close; fdQuery.Connection.Close; fdQuery.Free; end; end; function TExtraviosMultas.GetID: Integer; var FDQuery: TFDQuery; begin try FDQuery := FConexao.ReturnQuery; FDQuery.Open('select coalesce(max(COD_EXTRAVIO),0) + 1 from ' + TABLENAME); try Result := FDQuery.Fields[0].AsInteger; finally FDQuery.Close; end; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TExtraviosMultas.Gravar: Boolean; begin Result := False; case FAcao of Common.ENum.tacIncluir: Result := Insert(); Common.ENum.tacAlterar: Result := Update(); Common.ENum.tacExcluir: Result := Delete(); end; end; function TExtraviosMultas.Insert: Boolean; var FDQuery: TFDQuery; begin try Result := False; Id := GetID; FDQuery := FConexao.ReturnQuery(); FDQuery.ExecSQL(SQLINSERT, [ID, Descricao, NN, Agente, ValorProduto, Data, Multa, Verba, Total, Restricao, Entregador, Tipo, VerbaFranquia, ValorFranquia, Extrato, DataFranquia, EnvioCorrespondencia, RetornoCorrespondencia, Obs, Percentual, IDExtrato, Sequencia, Executor, Manutencao, NumeroExtrato]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TExtraviosMultas.Localizar(aParam: array of variant): TFDQuery; var FDQuery: TFDQuery; begin FDQuery := FConexao.ReturnQuery; if Length(aParam) < 2 then Exit; FDQuery.SQL.Clear; FDQuery.SQL.Add(SQLQUERY); if aParam[0] = 'CODIGO' then begin FDQuery.SQL.Add('WHERE COD_EXTRAVIO = :CODIGO'); FDQuery.ParamByName('CODIGO').AsInteger := aParam[1]; end; if aParam[0] = 'ENTREGADOR' then begin FDQuery.SQL.Add('WHERE COD_ENTREGADOR = :ENTREGADOR'); FDQuery.ParamByName('ENTREGADOR').AsInteger := aParam[1]; end; if aParam[0] = 'DESCRICAO' then begin FDQuery.SQL.Add('WHERE DES_EXTRAVIO = :DESCRICAO'); FDQuery.ParamByName('DESCRICAO').AsString := aParam[1]; end; if aParam[0] = 'NN' then begin FDQuery.SQL.Add('WHERE NUM_NOSSONUMERO = :NN'); FDQuery.ParamByName('NN').AsString := aParam[1]; end; if aParam[0] = 'AGENTE' then begin FDQuery.SQL.Add('WHERE COD_AGENTE = :AGENTE'); FDQuery.ParamByName('AGENTE').AsInteger := aParam[1]; end; if aParam[0] = 'SEQUENCIA' then begin FDQuery.SQL.Add('WHERE SEQ_ACAREACAO = :SEQUENCIA'); FDQuery.ParamByName('SEQUENCIA').AsInteger := aParam[1]; end; if aParam[0] = 'EXTRATO' then begin FDQuery.SQL.Add('WHERE ID_EXTRATO = :EXTRATO AND VAL_PERCENTUAL_PAGO < 100'); FDQuery.ParamByName('EXTRATO').AsInteger := aParam[1]; end; if aParam[0] = 'DATA' then begin if Length(aParam) = 2 then begin FDQuery.SQL.Add('WHERE DAT_EXTRAVIO = :DATA'); FDQuery.ParamByName('DATA').AsDate := aParam[1]; end else if Length(aParam) = 3 then begin FDQuery.SQL.Add('WHERE DAT_EXTRAVIO BETWEEN :DATA AND :DATA1'); FDQuery.ParamByName('DATA').AsDate := aParam[1]; FDQuery.ParamByName('DATA1').AsDate := aParam[1]; end; end; if aParam[0] = 'DATAFRANQUIA' then begin if Length(aParam) = 2 then begin FDQuery.SQL.Add('WHERE DAT_EXTRAVIO_FRANQUIA = :DATA'); FDQuery.ParamByName('DATA').AsDate := aParam[1]; end else if Length(aParam) = 3 then begin FDQuery.SQL.Add('WHERE DAT_EXTRAVIO_FRANQUIA BETWEEN :DATA AND :DATA1'); FDQuery.ParamByName('DATA').AsDate := aParam[1]; FDQuery.ParamByName('DATA1').AsDate := aParam[2]; end; end; if aParam[0] = 'TIPO' then begin FDQuery.SQL.Add('WHERE NUM_NOSSONUMERO = :NN AND COD_TIPO = :TIPO'); FDQuery.ParamByName('NN').AsString := aParam[1]; FDQuery.ParamByName('TIPO').AsInteger := aParam[2]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('where ' + aParam[1]); end; if aParam[0] = 'APOIO' then begin FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT ' + aParam[1] + ' FROM ' + TABLENAME + ' ' + aParam[2]); end; FDQuery.Open(); Result := FDQuery; end; function TExtraviosMultas.RetornaTotaisExtravios(aParam: array of variant): TFDQuery; var FDQuery: TFDQuery; begin FDQuery := FConexao.ReturnQuery; FDQuery.SQL.Clear; FDQuery.SQL.Add('select count(num_nossonumero) as itens, sum(val_total) as total from ' + TABLENAME); FDQuery.SQL.Add('where id_extrato in (' + aParam[0] + ')'); FDQuery.Open(); Result := FDQuery; end; function TExtraviosMultas.Update: Boolean; var FDQuery: TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; FDQuery.ExecSQL(SQLUPDATE, [Descricao, NN, Agente, ValorProduto, Data, Multa, Verba, Total, Restricao, Entregador, Tipo, VerbaFranquia, ValorFranquia, Extrato, DataFranquia, EnvioCorrespondencia, RetornoCorrespondencia, Obs, Percentual, IDExtrato, Sequencia, Executor, Manutencao, NumeroExtrato,ID]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; end.
unit PatternsCollection; interface uses FuncList, DLLList; procedure ApplyPatternsAndGetLists(var InputStr: string; ADList: TDescInfList; ADLLList: TDLLList); implementation uses System.RegularExpressions; procedure FunctionWithParameters(var InputStr: string; ADList: TDescInfList; ADLLList: TDLLList); var rx, rp: TRegEx; rs1, rs2: string; mc: TMatchCollection; gc: TGroupCollection; i: integer; t: DescInf; begin rs1 := '^(.*)function\s(\w*)\(([a-zA-Z\:\;\=\/à-ÿÀ-ß\,0-9\(\)_\/\<\+\-\%\*\\\=\!\>\~\|\&\^\[\]\{\}\.\s]*)\)([a-zA-Z\:\;\=\/à-ÿÀ-ß\,0-9\(\)_\/\<\+\-\%\*\\\=\!\>\~\|\&\^\[\]\{\}\.\s]*)\:\s*(\w*)\;\s*stdcall;\s*external\s*\''(\w*)\.dll\''\s*name\s*\''(.*)\''(.*)'; rs2 := '$1function $2($3): $5$8 $4'; rx := TRegEx.Create(rs1, [roIgnoreCase, roMultiLine, roCompiled]); rp := TRegEx.Create(rs1, [roIgnoreCase, roMultiLine, roCompiled]); mc := rx.Matches(InputStr); for i := 0 to mc.Count - 1 do begin t.Reset; gc := mc.Item[i].Groups; t.fullStr := gc.Item[0].Value; t.fn := tdFn; t.Start := gc.Item[1].Value; t.Name := gc.Item[2].Value; t.Params := gc.Item[3].Value; t.CommentRes := gc.Item[4].Value; t.Result := gc.Item[5].Value; t.DLL := gc.Item[6].Value; t.ExtName := gc.Item[7].Value; t.Tail := gc.Item[8].Value; t.Replacer := rp.Replace(t.fullStr, rs2); ADList.Add(t); ADLLList.AddUniq(t.DLL); end; InputStr := rx.Replace(InputStr, rs2); end; procedure FunctionWithoutParametersAndWithBrace(var InputStr: string; ADList: TDescInfList; ADLLList: TDLLList); var rx, rp: TRegEx; rs1, rs2: string; mc: TMatchCollection; gc: TGroupCollection; i: integer; t: DescInf; begin rs1 := '^(.*)function\s(\w*)[\w\s]*\:\s*(\w*)\;\s*stdcall;\s*external\s*\''(\w*)\.dll\''\s*name\s*\''(.*)\''(.*)'; rs2 := '$1function $2: $3;'; rx := TRegEx.Create(rs1, [roIgnoreCase, roMultiLine, roCompiled]); rp := TRegEx.Create(rs1, [roIgnoreCase, roMultiLine, roCompiled]); mc := rx.Matches(InputStr); for i := 0 to mc.Count - 1 do begin t.Reset; gc := mc.Item[i].Groups; t.fullStr := gc.Item[0].Value; t.fn := tdFn; t.Start := gc.Item[1].Value; t.Name := gc.Item[2].Value; t.Params := ''; t.Result := gc.Item[3].Value; t.DLL := gc.Item[4].Value; t.ExtName := gc.Item[5].Value; t.Tail := gc.Item[6].Value; t.Replacer := rp.Replace(t.fullStr, rs2); ADList.Add(t); ADLLList.AddUniq(t.DLL); end; InputStr := rx.Replace(InputStr, rs2); end; procedure FunctionWithoutParametersAndWithoutBrace(var InputStr: string; ADList: TDescInfList; ADLLList: TDLLList); var rx, rp: TRegEx; rs1, rs2: string; mc: TMatchCollection; gc: TGroupCollection; i: integer; t: DescInf; begin rs1 := '^(.*)function\s(\w*)\(\s*\)\:\s*(\w*)\;\s*stdcall;\s*external\s*\''(\w*)\.dll\''\s*name\s*\''(.*)\''(.*)'; rs2 := '$1function $2(): $3;'; rx := TRegEx.Create(rs1, [roIgnoreCase, roMultiLine, roCompiled]); rp := TRegEx.Create(rs1, [roIgnoreCase, roMultiLine, roCompiled]); mc := rx.Matches(InputStr); for i := 0 to mc.Count - 1 do begin t.Reset; gc := mc.Item[i].Groups; t.fullStr := gc.Item[0].Value; t.fn := tdFn; t.Start := gc.Item[1].Value; t.Name := gc.Item[2].Value; t.Params := ''; t.Result := gc.Item[3].Value; t.DLL := gc.Item[4].Value; t.ExtName := gc.Item[5].Value; t.Tail := gc.Item[6].Value; t.Replacer := rp.Replace(t.fullStr, rs2); ADList.Add(t); ADLLList.AddUniq(t.DLL); end; InputStr := rx.Replace(InputStr, rs2); end; procedure ProcedureWithParameters(var InputStr: string; ADList: TDescInfList; ADLLList: TDLLList); var rx, rp: TRegEx; rs1, rs2: string; mc: TMatchCollection; gc: TGroupCollection; i: integer; t: DescInf; begin rs1 := '^(.*)procedure\s(\w*)\(([a-zA-Z\:\;\=\/à-ÿÀ-ß\,0-9\(\)_\/\<\+\-\%\*\\\=\!\>\~\|\&\^\[\]\{\}\.\s]*)\)\;\s*stdcall;\s*external\s*\''(\w*)\.dll\''\s*name\s*\''(.*)\''(.*)'; rs2 := '$1procedure $2($3);'; rx := TRegEx.Create(rs1, [roIgnoreCase, roMultiLine, roCompiled]); rp := TRegEx.Create(rs1, [roIgnoreCase, roMultiLine, roCompiled]); mc := rx.Matches(InputStr); for i := 0 to mc.Count - 1 do begin t.Reset; gc := mc.Item[i].Groups; t.fullStr := gc.Item[0].Value; t.fn := tdProc; t.Start := gc.Item[1].Value; t.Name := gc.Item[2].Value; t.Params := gc.Item[3].Value; t.Result := ''; t.DLL := gc.Item[4].Value; t.ExtName := gc.Item[5].Value; t.Tail := gc.Item[6].Value; t.Replacer := rp.Replace(t.fullStr, rs2); ADList.Add(t); ADLLList.AddUniq(t.DLL); end; InputStr := rx.Replace(InputStr, rs2); end; procedure ApplyPatternsAndGetLists(var InputStr: string; ADList: TDescInfList; ADLLList: TDLLList); begin FunctionWithParameters(InputStr, ADList, ADLLList); FunctionWithoutParametersAndWithBrace(InputStr, ADList, ADLLList); FunctionWithoutParametersAndWithoutBrace(InputStr, ADList, ADLLList); ProcedureWithParameters(InputStr, ADList, ADLLList); end; end.
unit bombaDao; interface uses Bomba, DB, DM, IBQuery, IBDataBase, Classes; type T_BombaDao = class(TObject) private F_Qr: TIBQuery; F_Lista: TList; public constructor Create(db: TIBDataBase); destructor Destroy(); function NewID(): Integer; function incluir(bomba: T_Bomba): Integer; procedure atualizar(bomba: T_Bomba); procedure remover(bomba: T_Bomba); overload; procedure remover(bomba_id: Integer); overload; function listarTudo(): TList; function get(id: Integer): T_Bomba; function getByNumero(numero: Integer): T_Bomba; end; implementation const SQL_ID = 'SELECT GEN_ID( BOMBA_ID_GEN, 1 ) AS ID FROM RDB$DATABASE; '; SQL_INCLUIR = 'INSERT INTO BOMBA(Id, Tanque_ID, Numero ) '#13#10 + 'VALUES( :id , :tanque_id , :numero ) '; SQL_ATUALIZAR = 'UPDATE BOMBA '#13#10 + 'SET '#13#10 + ' Tanque_ID = :tanque_id , '#13#10 + ' Numero = :numero '#13#10 + 'WHERE Id = :id '#13#10; SQL_EXCLUIR = 'DELETE FROM BOMBA WHERE Id = :id '; SQL_LISTARTUDO = 'SELECT * FROM BOMBA ORDER BY Numero ASC '; SQL_GET = 'SELECT * FROM BOMBA WHERE ID = :id '; SQL_GETBYNUMERO = 'SELECT * FROM BOMBA WHERE Numero = :numero '; constructor T_BombaDao.Create(db: TIBDataBase); begin F_Qr := TIBQuery.Create(db); F_Qr.Database := db; F_QR.Transaction := db.DefaultTransaction; F_Lista := TList.Create(); end; destructor T_BombaDao.Destroy(); begin F_Lista.Free(); end; function T_BombaDao.NewID(): Integer; var id: Integer; begin F_Qr.Active := False; F_Qr.SQL.Clear(); F_Qr.SQL.Text := SQL_ID; F_Qr.Open(); result := F_Qr.FieldByName('Id').AsInteger; F_Qr.Active := False; end; function T_BombaDao.incluir(bomba: T_Bomba): Integer; var id: Integer; begin id := NewID(); F_QR.Active := False; F_QR.SQL.Clear(); F_Qr.SQL.Text := SQL_INCLUIR; F_Qr.ParamByName('id').Value := id; F_Qr.ParamByName('tanque_id').Value := bomba.Tanque_Id; F_Qr.ParamByName('numero').Value := bomba.Numero; F_QR.Prepare(); F_Qr.ExecSQL(); bomba.Id := id; end; procedure T_BombaDao.atualizar(bomba: T_Bomba); begin F_Qr.SQL.Text := SQL_ATUALIZAR; F_Qr.ParamByName('id').Value := bomba.id; F_Qr.ParamByName('tanque_id').Value := bomba.Tanque_Id; F_Qr.ParamByName('numero').Value := bomba.Numero; F_Qr.ExecSQL(); end; procedure T_BombaDao.remover(bomba: T_Bomba); begin F_Qr.SQL.Text := SQL_EXCLUIR; F_Qr.ParamByName('id').Value := bomba.Id; F_Qr.Delete(); end; procedure T_BombaDao.remover(bomba_id: Integer); begin F_Qr.SQL.Text := SQL_EXCLUIR; F_Qr.ParamByName('id').Value := bomba_id; F_Qr.Delete(); end; function T_BombaDao.listarTudo(): TList; var a: T_Bomba; begin F_Qr.SQL.Text := SQL_LISTARTUDO; F_Qr.Open(); result := TList.Create(); F_Qr.First(); while not F_Qr.Eof do begin result.Add( T_Bomba.Create( F_Qr.FieldByName('Id').AsInteger, F_Qr.FieldByName('Tanque_Id').AsInteger, F_Qr.FieldByName('Numero').AsInteger) ); F_Qr.Next(); end; if F_Qr.Active then F_Qr.Close(); end; function T_BombaDao.get(id: Integer): T_Bomba; var a: T_Bomba; begin F_Qr.SQL.Text := SQL_GET; F_Qr.ParamByName('id').Value := id; F_Qr.Open(); result := nil; if not F_Qr.Eof then begin result := T_Bomba.Create( F_Qr.FieldByName('Id').AsInteger, F_Qr.FieldByName('Tanque_Id').AsInteger, F_Qr.FieldByName('Numero').AsInteger) end; if F_Qr.Active then F_Qr.Close(); end; function T_BombaDao.getByNumero(numero: Integer): T_Bomba; var a: T_Bomba; begin F_Qr.SQL.Text := SQL_GETBYNUMERO; F_Qr.ParamByName('numero').Value := numero; F_Qr.Open(); result := nil; if not F_Qr.Eof then begin result := T_Bomba.Create( F_Qr.FieldByName('Id').AsInteger, F_Qr.FieldByName('Tanque_Id').AsInteger, F_Qr.FieldByName('Numero').AsInteger) end; if F_Qr.Active then F_Qr.Close(); end; end.
unit SyncPath; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons; const SMARTSYNC_TYPE_ESTABLISH = 1; SMARTSYNC_TYPE_ANALYSE = 2; SMARTSYNC_TYPE_SYNC = 3; SMARTSYNC_TYPE_COMPLETE = 99; type TSyncCallBack = procedure(nType: integer; const szSubFile: PChar; const szNewFileSize: PChar; const szLastModiTime: PChar; const szOldFileSize: PChar; const szOldModiTime: PChar; nDirCount: integer; nFileCount: integer);stdcall; TfrmSyncPath = class(TForm) edtSrcPath: TEdit; Label1: TLabel; edtDestPath: TEdit; sbSrcPath: TSpeedButton; sbDestPath: TSpeedButton; btnIndex: TBitBtn; btnAnalyse: TBitBtn; btnSyc: TBitBtn; mmInfo: TMemo; procedure FormCanResize(Sender: TObject; var NewWidth, NewHeight: Integer; var Resize: Boolean); procedure sbSrcPathClick(Sender: TObject); procedure sbDestPathClick(Sender: TObject); procedure btnIndexClick(Sender: TObject); procedure btnAnalyseClick(Sender: TObject); procedure btnSycClick(Sender: TObject); private function BrowserDirectory(const strCaption, S: string): string; { Private declarations } public { Public declarations } end; TSyncThread = class(TThread) private FFrm: TfrmSyncPath; FSyncType: integer; FCompleted: Boolean; protected procedure Execute;override; procedure DisplayInfo; procedure ThreadDisplayInfo(bComplete: Boolean); public FSubFileName: string; FNewFileSize: string; FLastModiTime: string; FOldFileSize: string; FOldModiTime: string; FDirCount: integer; FFileCount: integer; constructor Create(Frm: TfrmSyncPath; nType: integer); end; procedure ShowSyncPath; implementation uses ShellApi, ShlObj; var FCurrThread: TSyncThread; function SmartSyncPath(const szSrcPath: PChar; const szDestPath: PChar; pCallBack: TSyncCallBack): BOOL; stdcall; external 'smartsync.dll' name 'SmartSyncPath'; function EstablishSyncPath(const szPath: PChar; pCallBack: TSyncCallBack): BOOL; stdcall; external 'smartsync.dll' name 'EstablishSyncPath'; function AnalyseSyncPath(const szSrcPath: PChar; const szDestPath: PChar; pCallBack: TSyncCallBack): BOOL; stdcall; external 'smartsync.dll' name 'AnalyseSyncPath'; procedure SyncCallback(nType: integer; const szSubFile: PChar; const szNewFileSize: PChar; const szLastModiTime: PChar; const szOldFileSize: PChar; const szOldModiTime: PChar; nDirCount: integer; nFileCount: integer);stdcall; begin if nType = SMARTSYNC_TYPE_COMPLETE then begin if FCurrThread <> nil then begin FCurrThread.FDirCount := nDirCount; FCurrThread.FFileCount := nFileCount; FCurrThread.ThreadDisplayInfo(True); FCurrThread := nil; end; end else begin if FCurrThread <> nil then begin if szSubFile <> nil then FCurrThread.FSubFileName := szSubFile else FCurrThread.FSubFileName := ''; if szNewFileSize <> nil then FCurrThread.FNewFileSize := szNewFileSize else FCurrThread.FNewFileSize := '0'; if szLastModiTime <> nil then FCurrThread.FLastModiTime := szLastModiTime else FCurrThread.FLastModiTime := ''; if szOldFileSize <> nil then FCurrThread.FOldFileSize := szOldFileSize else FCurrThread.FOldFileSize := '0'; if szOldModiTime <> nil then FCurrThread.FOldModiTime := szOldModiTime else FCurrThread.FOldModiTime := ''; FCurrThread.FDirCount := nDirCount; FCurrThread.FFileCount := nFileCount; FCurrThread.ThreadDisplayInfo(False); end; end; end; {$R *.dfm} procedure ShowSyncPath; var Frm: TfrmSyncPath; begin FCurrThread := nil; Frm := TfrmSyncPath.Create(Application); frm.ShowModal; frm.Free; end; { TSyncThread } constructor TSyncThread.Create(Frm: TfrmSyncPath; nType: integer); begin inherited Create(TRUE); FFrm := Frm; FCompleted := False; FSyncType := nType; FreeOnTerminate := True; Resume; end; procedure TSyncThread.DisplayInfo; var Str: string; begin case FSyncType of SMARTSYNC_TYPE_ESTABLISH: if FCompleted then Str := '创建索引完毕, 目录数:' + IntToStr(FDirCount) + ' 文件数:' + IntToStr(FFileCount) else Str := ''; SMARTSYNC_TYPE_ANALYSE: if FCompleted then Str := '比较目录完毕, 目录数:' + IntToStr(FDirCount) + ' 文件数:' + IntToStr(FFileCount) else Str := '文件: ' + FSubFileName + ' 大小:' + FNewFileSize + ' 最后修改时间:' + FLastModiTime + ' 原有版本时间:' + FOldModiTime; SMARTSYNC_TYPE_SYNC: if FCompleted then Str := '同步完毕, 目录数:' + IntToStr(FDirCount) + ' 文件数:' + IntToStr(FFileCount) else Str := '文件: ' + FSubFileName + ' 大小:' + FNewFileSize + ' 最后修改时间:' + FLastModiTime + ' 原有版本时间:' + FOldModiTime; end; if (FFrm <> nil) and (Str <> '') then FFrm.mmInfo.Lines.Add(Str); end; procedure TSyncThread.Execute; begin case FSyncType of SMARTSYNC_TYPE_ESTABLISH: EstablishSyncPath(PChar(FFrm.edtDestPath.Text), SyncCallback); SMARTSYNC_TYPE_ANALYSE: AnalyseSyncPath(PChar(FFrm.edtSrcPath.Text), PChar(FFrm.edtDestPath.Text), SyncCallBack); SMARTSYNC_TYPE_SYNC: SmartSyncPath(PChar(FFrm.edtSrcPath.Text), PChar(FFrm.edtDestPath.Text), SyncCallBack); end; end; procedure TfrmSyncPath.FormCanResize(Sender: TObject; var NewWidth, NewHeight: Integer; var Resize: Boolean); begin Resize := False; end; procedure TfrmSyncPath.sbSrcPathClick(Sender: TObject); var Str: string; begin Str := BrowserDirectory('选择源目录', edtSrcPath.Text); if Str <> '' then edtSrcPath.Text := Str; end; function TfrmSyncPath.BrowserDirectory(const strCaption: string; const S: string): string; var lpItemID : PItemIDList; BrowseInfo : TBrowseInfo; DisplayName : array[0..MAX_PATH] of char; TempPath : array[0..MAX_PATH] of char; begin Result := ''; FillChar(BrowseInfo, sizeof(TBrowseInfo), #0); BrowseInfo.hwndOwner := Handle; BrowseInfo.pszDisplayName := @DisplayName; BrowseInfo.lpszTitle := PChar(strCaption); BrowseInfo.ulFlags := BIF_RETURNONLYFSDIRS; lpItemID := SHBrowseForFolder(BrowseInfo); if lpItemId <> nil then begin SHGetPathFromIDList(lpItemID, TempPath); Result := TempPath; GlobalFreePtr(lpItemID); end; end; procedure TfrmSyncPath.sbDestPathClick(Sender: TObject); var Str: string; begin Str := BrowserDirectory('选择目标路径', edtDestPath.Text); if Str <> '' then edtDestPath.Text := Str; end; procedure TfrmSyncPath.btnIndexClick(Sender: TObject); begin if (FCurrThread = nil) then FCurrThread := TSyncThread.Create(Self, SMARTSYNC_TYPE_ESTABLISH); end; procedure TfrmSyncPath.btnAnalyseClick(Sender: TObject); begin mmInfo.Lines.Clear; mmInfo.Lines.Add('分析结果:'); if (FCurrThread = nil) then FCurrThread := TSyncThread.Create(Self, SMARTSYNC_TYPE_ANALYSE); end; procedure TfrmSyncPath.btnSycClick(Sender: TObject); begin mmInfo.Lines.Clear; mmInfo.Lines.Add('同步结果:'); if (FCurrThread = nil) then FCurrThread := TSyncThread.Create(Self, SMARTSYNC_TYPE_SYNC); end; procedure TSyncThread.ThreadDisplayInfo(bComplete: Boolean); begin FCompleted := bComplete; Synchronize(DisplayInfo); end; end.
unit ServiceControll; interface uses windows, Classes, SysUtils, WinSvc; function GetServiceStatusString(Code: Integer): string; function ServiceIsinstalled(ServiceName: string): Boolean; procedure StopService(ServiceName: string); procedure StartService(ServiceName: string); procedure UnInstallService(ServName: string); function GetServiceStatusCode(ServiceName: string): Integer; procedure PauseService(ServiceName: string); procedure UnPauseService(ServiceName: string); implementation resourcestring svContinue = 'Запускается после паузы'; svStarting = 'Запускается'; svStop = 'Остановлен'; svStoping = 'Останавливается'; svPause = 'Пауза'; svPausing = 'Останавливается на паузу'; svRun = 'Запущен'; const // Таймоут операций с сервисами: ms ServiceOperationTimeout = 200000; function GetServiceStatusString(Code: Integer): string; begin Result := 'Не установлен'; case Code of // SERVICE_STOPPED: Result := svStop; SERVICE_START_PENDING: Result := svStarting; SERVICE_STOP_PENDING: Result := svStoping; SERVICE_RUNNING: Result := svRun; SERVICE_CONTINUE_PENDING: Result := svContinue; SERVICE_PAUSE_PENDING: Result := svPausing; SERVICE_PAUSED: Result := svPause; end; // case end; function ServiceIsinstalled(ServiceName: string): Boolean; var Svc, SvcMgr: Integer; begin Result := False; SvcMgr := OpenSCManager(nil, nil, SC_MANAGER_CONNECT); if SvcMgr <> 0 then begin Svc := OpenService(SvcMgr, PChar(ServiceName), SERVICE_QUERY_CONFIG); if Svc <> 0 then begin CloseServiceHandle(Svc); Result := True; end; CloseServiceHandle(SvcMgr); end; end; procedure StopService(ServiceName: string); var Svc, SvcMgr: Integer; SS: TServiceStatus; Tm: DWord; begin SvcMgr := OpenSCManager(nil, nil, SC_MANAGER_CONNECT); if SvcMgr <> 0 then begin try Svc := OpenService(SvcMgr, PChar(ServiceName), SERVICE_ALL_ACCESS); if Svc <> 0 then begin try ControlService(Svc, SERVICE_CONTROL_STOP, SS); Tm := GetTickCount + ServiceOperationTimeout; repeat // В цикле ожидаем остановки сервиса Sleep(100); QueryServiceStatus(Svc, SS); until (SS.dwCurrentState = SERVICE_STOPPED) or (GetTickCount > Tm) finally CloseServiceHandle(Svc); end; end else begin RaiseLastOSError; end; finally CloseServiceHandle(SvcMgr); end; end else begin RaiseLastOSError; end; end; procedure StartService(ServiceName: string); var Svc, SvcMgr: Integer; P: PChar; Tm: DWord; SS: TServiceStatus; b: Boolean; begin SvcMgr := OpenSCManager(nil, nil, SC_MANAGER_CONNECT); if SvcMgr <> 0 then begin try Svc := OpenService(SvcMgr, PChar(ServiceName), SERVICE_ALL_ACCESS); if Svc <> 0 then begin try P := nil; b := WinSvc.StartService(Svc, 0, P); Tm := GetTickCount + ServiceOperationTimeout; repeat // В цикле ожидаем запуска сервиса Sleep(100); QueryServiceStatus(Svc, SS); until (SS.dwCurrentState = SERVICE_RUNNING) or (not b) or (SS.dwCurrentState = SERVICE_STOPPED) or (GetTickCount > Tm) finally CloseServiceHandle(Svc); end; end else begin RaiseLastOSError; end; finally CloseServiceHandle(SvcMgr); end; end else begin RaiseLastOSError end; end; procedure PauseService(ServiceName: string); var Svc, SvcMgr: Integer; SS: TServiceStatus; Tm: DWord; begin SvcMgr := OpenSCManager(nil, nil, SC_MANAGER_CONNECT); if SvcMgr <> 0 then begin try Svc := OpenService(SvcMgr, PChar(ServiceName), SERVICE_ALL_ACCESS); if Svc <> 0 then begin try ControlService(Svc, SERVICE_CONTROL_PAUSE, SS); Tm := GetTickCount + ServiceOperationTimeout; repeat // В цикле ожидаем остановки сервиса SERVICE_PAUSED: Result := svPause; Sleep(100); QueryServiceStatus(Svc, SS); until (SS.dwCurrentState = SERVICE_PAUSED) or (GetTickCount > Tm) finally CloseServiceHandle(Svc); end; end else begin RaiseLastOSError; end; finally CloseServiceHandle(SvcMgr); end; end else begin RaiseLastOSError; end; end; procedure UnPauseService(ServiceName: string); var Svc, SvcMgr: Integer; SS: TServiceStatus; Tm: DWord; begin SvcMgr := OpenSCManager(nil, nil, SC_MANAGER_CONNECT); if SvcMgr <> 0 then begin try Svc := OpenService(SvcMgr, PChar(ServiceName), SERVICE_ALL_ACCESS); if Svc <> 0 then begin try ControlService(Svc, SERVICE_CONTROL_CONTINUE, SS); Tm := GetTickCount + ServiceOperationTimeout; repeat // В цикле ожидаем остановки сервиса SERVICE_PAUSED: Result := svPause; Sleep(100); QueryServiceStatus(Svc, SS); until (SS.dwCurrentState = SERVICE_RUNNING) or (GetTickCount > Tm) finally CloseServiceHandle(Svc); end; end else begin RaiseLastOSError; end; finally CloseServiceHandle(SvcMgr); end; end else begin RaiseLastOSError; end; end; procedure UnInstallService(ServName: string); var Svc, SvcMgr, I: Integer; begin SvcMgr := OpenSCManager(nil, nil, SC_MANAGER_CONNECT); if SvcMgr <> 0 then begin Svc := OpenService(SvcMgr, PChar(ServName), SERVICE_ALL_ACCESS); if Svc <> 0 then begin WinSvc.DeleteService(Svc); CloseServiceHandle(Svc); end; I := GetLastError; CloseServiceHandle(SvcMgr); SetLastError(I); end; end; function GetServiceStatusCode(ServiceName: string): Integer; var Svc, SvcMgr: Integer; SS: TServiceStatus; begin Result := -1; SvcMgr := OpenSCManager(nil, nil, SC_MANAGER_CONNECT); if SvcMgr <> 0 then begin try Svc := OpenService(SvcMgr, PChar(ServiceName), SERVICE_QUERY_STATUS); if Svc <> 0 then begin try QueryServiceStatus(Svc, SS); Result := SS.dwCurrentState; finally CloseServiceHandle(Svc); end; end; finally CloseServiceHandle(SvcMgr); end; end; end; end.
unit UGTasksTabletDemo; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.TMSCloudBase, FMX.TMSCloudBaseFMX, FMX.TMSCloudCustomGoogle, FMX.TMSCloudGoogleFMX, FMX.TMSCloudCustomGTasks, FMX.TMSCloudGTasks, System.Rtti, FMX.Edit, FMX.DateTimeCtrls, FMX.StdCtrls, FMX.ListBox, FMX.Layouts, FMX.Grid, FMX.TMSCloudListView, IOUtils; type TForm98 = class(TForm) TMSFMXCloudGTasks1: TTMSFMXCloudGTasks; lstvTaskLists: TTMSFMXCloudListView; lstTaskList: TListBox; Label1: TLabel; btnNextPage: TButton; Label2: TLabel; btnNextPageTasks: TButton; btnRemoveTaskList: TButton; btnRemoveTask: TButton; Label3: TLabel; Label4: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; edListTitle: TEdit; edTitle: TEdit; cbCompleted: TCheckBox; dtDue: TCalendarEdit; lblLastUpdated: TLabel; lblTaskListId: TLabel; lblTaskId: TLabel; btnSaveTask: TButton; btnSaveList: TButton; btnConnect: TButton; btnAddTask: TButton; btnAddList: TButton; btnAddChildTask: TButton; Label9: TLabel; Label10: TLabel; procedure btnConnectClick(Sender: TObject); procedure TMSFMXCloudGTasks1ReceivedAccessToken(Sender: TObject); procedure btnSaveTaskClick(Sender: TObject); procedure lstTaskListClick(Sender: TObject); procedure btnNextPageClick(Sender: TObject); procedure btnRemoveTaskListClick(Sender: TObject); procedure btnAddListClick(Sender: TObject); procedure btnSaveListClick(Sender: TObject); procedure btnRemoveTaskClick(Sender: TObject); procedure btnAddTaskClick(Sender: TObject); procedure btnAddChildTaskClick(Sender: TObject); procedure btnNextPageTasksClick(Sender: TObject); procedure lstvTaskListsClick(Sender: TObject); procedure FormCreate(Sender: TObject); private procedure AddChildTask; procedure AddTask(parent: string = ''); procedure AddTaskList; procedure ClearListFields; procedure ClearTaskFields; procedure EnableTaskListsElements; procedure EnableTasksElements; procedure GetNextPage; procedure GetNextTasksPage; procedure GetTaskLists; procedure GetTasks; procedure GetTasksList; procedure RemoveTask; procedure RemoveTaskList; procedure SaveTask; procedure SaveTaskList; procedure ShowTasks(item: TGTaskListItem); { Private declarations } public { Public declarations } end; var Form98: TForm98; implementation {$R *.fmx} {$I APPIDS.INC} procedure TForm98.btnAddChildTaskClick(Sender: TObject); begin AddChildTask(); end; procedure TForm98.btnAddListClick(Sender: TObject); begin AddTaskList(); end; procedure TForm98.btnAddTaskClick(Sender: TObject); begin AddTask(); end; procedure TForm98.btnConnectClick(Sender: TObject); begin TMSFMXCloudGTasks1.App.Key := GAppkey; TMSFMXCloudGTasks1.App.Secret := GAppSecret; TMSFMXCloudGTasks1.PersistTokens.Key := TPath.GetDocumentsPath + '/gtasks.ini';// --> IOS / Android // TMSFMXCloudGTasks1.PersistTokens.Key := ExtractFilePath(ParamStr(0)) + 'gtasks.ini';// --> Windows / Mac OSX TMSFMXCloudGTasks1.PersistTokens.Section := 'tokens'; TMSFMXCloudGTasks1.LoadTokens; if TMSFMXCloudGTasks1.TestTokens then begin // Get the list GetTaskLists(); end else TMSFMXCloudGTasks1.DoAuth; end; procedure TForm98.btnNextPageClick(Sender: TObject); begin GetNextPage(); end; procedure TForm98.btnNextPageTasksClick(Sender: TObject); begin GetNextTasksPage(); end; procedure TForm98.btnRemoveTaskClick(Sender: TObject); begin RemoveTask(); end; procedure TForm98.btnRemoveTaskListClick(Sender: TObject); begin RemoveTaskList; end; procedure TForm98.btnSaveListClick(Sender: TObject); begin SaveTaskList; end; procedure TForm98.btnSaveTaskClick(Sender: TObject); begin SaveTask; end; // CLICK EVENTS // EVENT METHODS procedure TForm98.AddChildTask(); var parentId : string; begin parentId := lblTaskId.Text; AddTask(parentId); end; procedure TForm98.AddTask( parent : string = '' ); var TaskListItem : TGTaskListItem; TaskListIndex: integer; TaskItem : TGTaskItem; Completed : string; begin // Get all the stuff TaskListIndex := lstTaskList.ItemIndex; if (TaskListIndex >= 0) then begin TaskListItem := TGTaskListItem(lstTaskList.Items.Objects[TaskListIndex]); // Set all the stuff TaskItem := TGTaskItem(TaskListItem.TaskItems.Add); TaskItem.Title := edTitle.Text; TaskItem.Due := dtDue.DateTime; TaskItem.Parent := parent; if cbCompleted.IsChecked then begin TaskItem.Status := 'completed'; Completed := 'Yes'; end else begin TaskItem.Status := 'needsAction'; Completed := 'No'; end; // Sent insert to api TaskListItem.AddTaskToList(TaskItem); TaskListItem.GetTaskItems; ShowTasks(TaskListItem); // Select the added item // lstvTaskLists.Items[0].MakeVisible(true); lstvTaskLists.SetFocus(); //lstvTaskLists.ItemIndex := 0; lstvTaskLists.Selected := TListItem(lstTaskList.Items.Objects[TaskListIndex]); end; end; procedure TForm98.SaveTask; var TaskListItem : TGTaskListItem; TaskListIndex: integer; TaskItem : TGTaskItem; TaskIndex: integer; Completed : string; begin TaskListIndex := lstTaskList.ItemIndex; TaskIndex := lstvTaskLists.ItemIndex; TaskListItem := TGTaskListItem(lstTaskList.Items.Objects[TaskListIndex]); if TaskIndex >= 0 then begin TaskItem := TGTaskItem(lstvTaskLists.Items[TaskIndex].Data); // Set the values TaskItem.Title := edTitle.Text; edTitle.SetFocus(); TaskItem.Due := dtDue.DateTime; if cbCompleted.IsChecked then begin TaskItem.Status := 'completed'; Completed := 'Yes'; end else begin TaskItem.Status := 'needsAction'; Completed := 'No'; end; // if dtDue.IsChecked = false then // begin // TaskItem.Due := Date; // end; TaskListItem.UpdateTask(TaskItem); // Add the task to the list // ListView lstvTaskLists.Items[TaskIndex].Text := TaskItem.Title; lstvTaskLists.Items[TaskIndex].SubItems[0] := DateToStr(TaskItem.Due); lstvTaskLists.Items[TaskIndex].SubItems[1] := Completed; lstvTaskLists.Items[TaskIndex].Data := TaskItem; end; end; procedure TForm98.RemoveTask; var TaskListItem : TGTaskListItem; TaskListIndex: integer; TaskItem : TGTaskItem; TaskIndex: integer; begin TaskListIndex := lstTaskList.ItemIndex; TaskIndex := lstvTaskLists.ItemIndex; if TaskIndex >= 0 then begin // Get the items TaskListItem := TGTaskListItem(lstTaskList.Items.Objects[TaskListIndex]); TaskItem := TGTaskItem(lstvTaskLists.Items[TaskIndex].Data); // Sent delete to api TaskListItem.DeleteTask(TaskItem); // remove from listview lstvTaskLists.Items.Delete(TaskIndex); // Go to previous selected item if (TaskIndex - 1 ) >= 0 then begin lstvTaskLists.ItemIndex := (TaskIndex -1 ); // Scroll into view //lstvTaskLists.Items[(TaskIndex -1 )].MakeVisible(true); end else begin ClearTaskFields(); btnRemoveTask.Enabled := false; btnSaveTask.Enabled := false; end; end; end; procedure TForm98.AddTaskList; var TaskListItem : TGTaskListItem; begin // Sent insert to api TaskListItem := TMSFMXCloudGTasks1.AddTaskList(edListTitle.Text); // Add listbox item lstTaskList.Items.AddObject(TaskListItem.Title, TaskListItem); lstTaskList.ItemIndex := lstTaskList.Items.Count - 1; lstTaskList.OnClick(Self); edListTitle.SetFocus(); end; procedure TForm98.SaveTaskList; var TaskListItem : TGTaskListItem; TaskListIndex: integer; begin // Sent insert to api TaskListIndex := lstTaskList.ItemIndex; if TaskListIndex >= 0 then begin TaskListItem := TGTaskListItem(lstTaskList.Items.Objects[TaskListIndex]); TaskListItem.Title := edListTitle.Text; TMSFMXCloudGTasks1.UpdateTaskList(TaskListItem); // Update listbox item lstTaskList.Items[TaskListIndex] := edListTitle.Text; // Visuals lstTaskList.ItemIndex := TaskListIndex; lstTaskList.OnClick(Self); edListTitle.SetFocus(); end else begin ClearListFields(); end; end; procedure TForm98.RemoveTaskList; var TaskListItem : TGTaskListItem; TaskListIndex: integer; begin // Get Index & Build Object TaskListIndex := lstTaskList.ItemIndex; TaskListItem := TGTaskListItem(lstTaskList.Items.Objects[TaskListIndex]); // Delete TMSFMXCloudGTasks1.DeleteTaskList(TaskListItem); //Remove from list lstTaskList.Items.Delete(TaskListIndex); // Select another if (TaskListIndex -1) >= 0 then begin lstTaskList.ItemIndex := (TaskListIndex -1); lstTaskList.OnClick(Self) end; end; procedure TForm98.GetNextPage; var List: TObject; Name : string; index: integer; begin // Get the index index := lstTaskList.ItemIndex; // Fill it lstTaskList.Clear; TMSFMXCloudGTasks1.GetNextTaskListItems(); // Show it for List in TMSFMXCloudGTasks1.TaskLists do begin Name := 'No name given...'; if TGTaskListItem(List).Title <> '' then begin Name := TGTaskListItem(List).Title; end; lstTaskList.Items.AddObject(Name, List); end; // Make button visible if there's a next page btnNextPage.Enabled := TMSFMXCloudGTasks1.HasNextPage; // Select same item if index >= 0 then begin lstTaskList.ItemIndex := index; lstTaskList.OnClick(Self) end; end; procedure TForm98.GetNextTasksPage(); var Id : string; listIndex, taskIndex: integer; TaskListItem : TGTaskListItem; begin // Get some stuff listIndex := lstTaskList.ItemIndex; taskIndex := lstvTaskLists.ItemIndex; TaskListItem := TGTaskListItem(lstTaskList.Items.Objects[listIndex]); Id := TaskListItem.Id; lstvTaskLists.Items.BeginUpdate; lstvTaskLists.Items.Clear; TaskListItem.GetNextTaskItems; // Fill the task list ShowTasks(TaskListItem); lstvTaskLists.Items.EndUpdate; // Visuals if (taskindex >= 0) then begin lstvTaskLists.ItemIndex := taskIndex; lstvTaskLists.Items[taskIndex].Selected := true; end; end; procedure TForm98.GetTasks; var item: TGTaskListItem; selitem: integer; begin // Visual Stuff... ClearTaskFields(); EnableTaskListsElements(); EnableTasksElements(); // Get the list item selitem := lstTaskList.ItemIndex; if selitem >= 0 then begin btnRemoveTask.Enabled := false; btnSaveTask.Enabled := false; // Clear all previous tasks in the list lstvTaskLists.Items.Clear; if selitem >= 0 then begin item := TGTaskListItem(lstTaskList.Items.Objects[selitem]); // Set the list detail info edListTitle.Text := item.Title; lblTaskListId.Text := item.Id; lblLastUpdated.Text := DateTimeToStr(item.Updated); // Get all tasks item.GetTaskItems; // Fill the task list ShowTasks(item); end; // Visuals edListTitle.SetFocus(); end else begin ClearListFields(); ClearTaskFields(); end; end; procedure TForm98.ShowTasks(item : TGTaskListItem); var TaskItem: TObject; Completed, Child : string; Itm: TListItem; Name : string; begin // First remove all items lstvTaskLists.Items.Clear; for TaskItem in item.TaskItems do begin // In case we have an empty name Name := 'No Taskname given'; if TGTaskItem(TaskItem).Title <> '' then begin // Fill the name Name := TGTaskItem(TaskItem).Title; end; if TGTaskItem(TaskItem).Status = 'completed' then begin Completed := 'Yes'; end else begin Completed := 'No'; end; if TGTaskItem(TaskItem).Parent = '' then begin Child := 'Yes'; end else begin Child := 'No'; end; // ListView Itm := lstvTaskLists.Items.Add; Itm.Text := Name; Itm.SubItems.Add(DateTimeToStr(TGTaskItem(TaskItem).Due)); Itm.SubItems.Add(Completed); Itm.SubItems.Add(Child); Itm.Data := TGTaskItem(TaskItem); end; // Make button visible if there's a next page if item.HasNextPage then begin btnNextPageTasks.Enabled := true; end else begin btnNextPageTasks.Enabled := false; end; end; procedure TForm98.TMSFMXCloudGTasks1ReceivedAccessToken(Sender: TObject); begin //lstTaskList.Items.Add('got token'); TMSFMXCloudGTasks1.SaveTokens; //TMSFMXCloudGTasks1.GetTaskListItems; GetTaskLists; end; procedure TForm98.GetTasksList; var task: TGTaskItem; selitem: integer; myYear, myMonth, myDay : Word; begin // Visual Stuff... EnableTasksElements(); btnAddChildTask.Enabled := true; // Get the selected task object selitem := lstvTaskLists.ItemIndex; if selitem >= 0 then begin task := TGTaskItem(lstvTaskLists.Items[selitem].Data); if task <> nil then begin // Set the task details edTitle.SetFocus(); lblTaskId.Text := task.Id; edTitle.Text := task.Title; DecodeDate(task.Due, myYear, myMonth, myDay); // 1970 = Default sql - no known - date if myYear > 1970 then begin dtDue.DateTime := task.Due; // dtDue.IsChecked := true; end; // else // dtDue.IsChecked := false; if task.Status = 'completed' then begin cbCompleted.IsChecked := true; end else cbCompleted.IsChecked := false; end; end else begin ClearTaskFields(); end; end; procedure TForm98.lstTaskListClick(Sender: TObject); begin GetTasks; end; procedure TForm98.lstvTaskListsClick(Sender: TObject); begin GetTasksList; end; procedure TForm98.ClearTaskFields; begin edTitle.Text := EmptyStr; // dtDue.IsChecked := false; dtDue.DateTime:= Date; cbCompleted.IsChecked := false; lblTaskId.Text := EmptyStr; end; procedure TForm98.ClearListFields; begin edListTitle.Text := ''; lblLastUpdated.Text := EmptyStr; lblTaskListId.Text := EmptyStr; end; procedure TForm98.EnableTaskListsElements; begin edListTitle.Enabled := true; btnAddList.Enabled := true; btnSaveList.Enabled := true; btnRemoveTaskList.Enabled := true; // remove btn end; procedure TForm98.EnableTasksElements; begin edTitle.Enabled := true; dtDue.Enabled := true; cbCompleted.Enabled := true; btnAddTask.Enabled := true; // add btn btnSaveTask.Enabled := true; // save btn btnRemoveTask.Enabled := true; // remove btn end; procedure TForm98.FormCreate(Sender: TObject); begin edListTitle.Width := 369; lblLastUpdated.Width := 369; lblTaskListId.Width := 369; edTitle.Width := 369; dtDue.Width := 369; lblTaskId.Width := 369; end; procedure TForm98.GetTaskLists; var List: TObject; Name : string; begin lstTaskList.Items.Clear; ClearTaskFields; TMSFMXCloudGTasks1.GetTaskListItems; for List in TMSFMXCloudGTasks1.TaskLists do begin Name := 'No name given...'; if TGTaskListItem(List).Title <> '' then begin Name := TGTaskListItem(List).Title; end; // listbox lstTaskList.Items.AddObject(Name, List); end; // btnNextPage.Enabled := TMSFMXCloudGTasks1.HasNextPage; end; end.
unit atUserJournalHelper; // Модуль: "w:\quality\test\garant6x\AdapterTest\AdapterHelpers\atUserJournalHelper.pas" // Стереотип: "SimpleClass" // Элемент модели: "TatUserJournalHelper" MUID: (4D0A033202D2) interface uses l3IntfUses , UserJournalUnit , Contnrs , DocumentUnit , SearchUnit , DynamicTreeUnit , BaseTypesUnit , l3_Base ; type _EntityInterface_ = IJournalBookmark; {$Include w:\quality\test\garant6x\AdapterTest\AdapterHelpers\atEntityWithName.imp.pas} TatJournalBookmark = class(_atEntityWithName_) protected function pm_GetDocument: IDocument; virtual; function pm_GetPara: TParaId; virtual; function pm_GetFullName: AnsiString; virtual; public constructor Create(const anEntityBase: IEntityBase); override; public property Document: IDocument read pm_GetDocument; property Para: TParaId read pm_GetPara; property FullName: AnsiString read pm_GetFullName; end;//TatJournalBookmark TatUserJournalHelper = class private class procedure ReadJournalNode(const aNode: INodeBase); class procedure ReadJournalBookmark(const aJournalBookmark: IJournalBookmark); class procedure ReadJournalQuery(const aQuery: IQuery); class function UserJournal: IUserJournal; public class procedure AddBookmark(const aBookmark: IJournalBookmark); class procedure AddQuery(const aQuery: IQuery); class procedure Clear; class procedure ReadAll; class procedure ReadHistory(aMaxItems: Integer); class function GetElements(aDate: Double = 0): TObjectList; class function GetQueryHistory(aType: TQueryType; aMaxCount: Integer): TObjectList; end;//TatUserJournalHelper implementation uses l3ImplUses , atNodeHelper , atGblAdapterWorker , IOUnit , atLogger , SysUtils , atQuery //#UC START# *4D0A033202D2impl_uses* //#UC END# *4D0A033202D2impl_uses* ; {$Include w:\quality\test\garant6x\AdapterTest\AdapterHelpers\atEntityWithName.imp.pas} function TatJournalBookmark.pm_GetDocument: IDocument; //#UC START# *4FC8EDB701E9_4FC8EC8900FEget_var* //#UC END# *4FC8EDB701E9_4FC8EC8900FEget_var* begin //#UC START# *4FC8EDB701E9_4FC8EC8900FEget_impl* f_Entity.GetDocument(Result); //#UC END# *4FC8EDB701E9_4FC8EC8900FEget_impl* end;//TatJournalBookmark.pm_GetDocument function TatJournalBookmark.pm_GetPara: TParaId; //#UC START# *4FC8EE000329_4FC8EC8900FEget_var* //#UC END# *4FC8EE000329_4FC8EC8900FEget_var* begin //#UC START# *4FC8EE000329_4FC8EC8900FEget_impl* Result := f_Entity.GetParaId; //#UC END# *4FC8EE000329_4FC8EC8900FEget_impl* end;//TatJournalBookmark.pm_GetPara function TatJournalBookmark.pm_GetFullName: AnsiString; //#UC START# *4FC8EE480371_4FC8EC8900FEget_var* var l_Str : IString; //#UC END# *4FC8EE480371_4FC8EC8900FEget_var* begin //#UC START# *4FC8EE480371_4FC8EC8900FEget_impl* f_Entity.GetFullName(l_Str); if Assigned(l_Str) then Result := l_Str.GetData; //#UC END# *4FC8EE480371_4FC8EC8900FEget_impl* end;//TatJournalBookmark.pm_GetFullName constructor TatJournalBookmark.Create(const anEntityBase: IEntityBase); //#UC START# *4FC8E5780345_4FC8EC8900FE_var* //#UC END# *4FC8E5780345_4FC8EC8900FE_var* begin //#UC START# *4FC8E5780345_4FC8EC8900FE_impl* inherited; Name; FullName; //#UC END# *4FC8E5780345_4FC8EC8900FE_impl* end;//TatJournalBookmark.Create class procedure TatUserJournalHelper.AddBookmark(const aBookmark: IJournalBookmark); //#UC START# *4D0A078B002B_4D0A033202D2_var* //#UC END# *4D0A078B002B_4D0A033202D2_var* begin //#UC START# *4D0A078B002B_4D0A033202D2_impl* UserJournal.Save(aBookmark, JOT_BOOKMARK); //#UC END# *4D0A078B002B_4D0A033202D2_impl* end;//TatUserJournalHelper.AddBookmark class procedure TatUserJournalHelper.AddQuery(const aQuery: IQuery); //#UC START# *4D0A07A7007E_4D0A033202D2_var* //#UC END# *4D0A07A7007E_4D0A033202D2_var* begin //#UC START# *4D0A07A7007E_4D0A033202D2_impl* UserJournal.Save(aQuery, JOT_QUERY); //#UC END# *4D0A07A7007E_4D0A033202D2_impl* end;//TatUserJournalHelper.AddQuery class procedure TatUserJournalHelper.Clear; //#UC START# *4D0A07C00107_4D0A033202D2_var* var l_Root : INodeBase; //#UC END# *4D0A07C00107_4D0A033202D2_var* begin //#UC START# *4D0A07C00107_4D0A033202D2_impl* with UserJournal do begin GetUserJornalTree(l_Root); Clear; end //#UC END# *4D0A07C00107_4D0A033202D2_impl* end;//TatUserJournalHelper.Clear class procedure TatUserJournalHelper.ReadAll; //#UC START# *4D0A07D1012C_4D0A033202D2_var* var l_Root : INodeBase; //#UC END# *4D0A07D1012C_4D0A033202D2_var* begin //#UC START# *4D0A07D1012C_4D0A033202D2_impl* UserJournal.GetUserJornalTree(l_Root); if (l_Root <> nil) then TatNodeHelper.LoadNodes(l_Root, High(Word), High(Cardinal), ReadJournalNode); //#UC END# *4D0A07D1012C_4D0A033202D2_impl* end;//TatUserJournalHelper.ReadAll class procedure TatUserJournalHelper.ReadHistory(aMaxItems: Integer); //#UC START# *4D0A07EB0282_4D0A033202D2_var* var l_JBL : IJournalBookmarkList; l_JB : IJournalBookmark; i : Integer; //#UC END# *4D0A07EB0282_4D0A033202D2_var* begin //#UC START# *4D0A07EB0282_4D0A033202D2_impl* try UserJournal.GetBookmarkHistory(BJT_BOOKMARK, aMaxItems, l_JBL); except on ECanNotFindData do ; end; if (l_JBL <> nil) then for i := 0 to l_JBL.Count-1 do begin l_JBL.pm_GetItem(i, l_JB); ReadJournalBookmark(l_JB); end; //#UC END# *4D0A07EB0282_4D0A033202D2_impl* end;//TatUserJournalHelper.ReadHistory class procedure TatUserJournalHelper.ReadJournalNode(const aNode: INodeBase); //#UC START# *4D0A100E0332_4D0A033202D2_var* var l_JournalBookmark : IJournalBookmark; l_Query : IQuery; l_Entity : IEntityBase; l_NodeType : TJournalObjectType; //#UC END# *4D0A100E0332_4D0A033202D2_var* begin //#UC START# *4D0A100E0332_4D0A033202D2_impl* l_NodeType := TJournalObjectType(aNode.GetType); // if l_NodeType = JOT_FOLDER then TatNodeHelper.GetCaption(aNode) else begin try aNode.GetEntity(l_Entity); except on ENoEntity do ; end; // if (l_Entity <> nil) then case l_NodeType of JOT_BOOKMARK : if Supports(l_Entity, IJournalBookmark, l_JournalBookmark) then ReadJournalBookmark(l_JournalBookmark); JOT_QUERY : if Supports(l_Entity, IQuery, l_Query) then ReadJournalQuery(l_Query); end; end; //#UC END# *4D0A100E0332_4D0A033202D2_impl* end;//TatUserJournalHelper.ReadJournalNode class procedure TatUserJournalHelper.ReadJournalBookmark(const aJournalBookmark: IJournalBookmark); //#UC START# *4D0A10510060_4D0A033202D2_var* var l_String : IString; //#UC END# *4D0A10510060_4D0A033202D2_var* begin //#UC START# *4D0A10510060_4D0A033202D2_impl* aJournalBookmark.GetName(l_String); if l_String <> nil then l_String.GetData; //#UC END# *4D0A10510060_4D0A033202D2_impl* end;//TatUserJournalHelper.ReadJournalBookmark class procedure TatUserJournalHelper.ReadJournalQuery(const aQuery: IQuery); //#UC START# *4D0A107B033E_4D0A033202D2_var* var l_String : IString; l_Date : TDate; //#UC END# *4D0A107B033E_4D0A033202D2_var* begin //#UC START# *4D0A107B033E_4D0A033202D2_impl* aQuery.GetName(l_String); if l_String <> nil then l_String.GetData; //#UC END# *4D0A107B033E_4D0A033202D2_impl* end;//TatUserJournalHelper.ReadJournalQuery class function TatUserJournalHelper.UserJournal: IUserJournal; //#UC START# *4D0A18D900B0_4D0A033202D2_var* //#UC END# *4D0A18D900B0_4D0A033202D2_var* begin //#UC START# *4D0A18D900B0_4D0A033202D2_impl* Result := TatGblAdapterWorker.Instance.GblAdapterDll.MakeUserJournal; //#UC END# *4D0A18D900B0_4D0A033202D2_impl* end;//TatUserJournalHelper.UserJournal class function TatUserJournalHelper.GetElements(aDate: Double = 0): TObjectList; //#UC START# *4FC8C0CF0161_4D0A033202D2_var* var l_Entity : IEntityBase; l_Root, l_Node, l_TempNode : INodeBase; l_Query : IQuery; //#UC END# *4FC8C0CF0161_4D0A033202D2_var* begin //#UC START# *4FC8C0CF0161_4D0A033202D2_impl* Result := TObjectList.Create(true); // UserJournal.GetUserJornalTree(l_Root); l_Node := l_Root; while true do begin // переходим на следующую ноду if l_Node.HasChildren then begin l_TempNode := l_Node; l_TempNode.GetFirstChild(l_Node); l_TempNode := nil; end else begin while l_Node.IsLast do begin l_TempNode := l_Node; l_TempNode.GetParent(l_Node); l_TempNode := nil; if l_Node = nil then Exit; end; // l_TempNode := l_Node; l_TempNode.GetNext(l_Node); l_TempNode := nil; end; // пропускаем папки, дата которых раньше чем заданная while (aDate <> 0) AND (l_Node.GetLevel = 1) AND (TJournalObjectType(l_Node.GetType) = JOT_FOLDER) AND (StrToDate(TatNodeHelper.GetCaption(l_Node)) < aDate) do if NOT l_Node.IsLast then begin l_TempNode := l_Node; l_TempNode.GetNext(l_Node); l_TempNode := nil; end else Exit; // пропускаем папки if TJournalObjectType(l_Node.GetType) = JOT_FOLDER then continue; try l_Node.GetEntity(l_Entity); except on ENoEntity do ; end; if l_Entity <> nil then if TatJournalBookmark.IsItMe(l_Entity) then Result.Add(TatJournalBookmark.Create(l_Entity)) else if TatQuery.IsItMe(l_Entity) then begin (l_Entity as IQuery).Clone(l_Query); Result.Add(TatQuery.Create(l_Query)); end else Raise Exception.Create('Неизвестная Entity!'); end; //#UC END# *4FC8C0CF0161_4D0A033202D2_impl* end;//TatUserJournalHelper.GetElements class function TatUserJournalHelper.GetQueryHistory(aType: TQueryType; aMaxCount: Integer): TObjectList; //#UC START# *500D90A4007E_4D0A033202D2_var* var l_QL : IQueryList; l_Query : IQuery; i : Integer; //#UC END# *500D90A4007E_4D0A033202D2_var* begin //#UC START# *500D90A4007E_4D0A033202D2_impl* Result := nil; try UserJournal.GetQueryHistory(aType, aMaxCount, l_QL); except on ECanNotFindData do Exit; end; if Assigned(l_QL) AND (l_QL.Count > 0) then begin Result := TObjectList.Create; Result.OwnsObjects := true; for i := 0 to l_QL.Count-1 do begin l_QL.pm_GetItem(i, l_Query); Result.Add( TatQuery.Create(l_Query) ); end; end; //#UC END# *500D90A4007E_4D0A033202D2_impl* end;//TatUserJournalHelper.GetQueryHistory end.
unit IngGrid07; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Grids, DBGrids, ComCtrls, ExtCtrls, AdoDb, DBActns, ActnList, DbClient, Menus, ImgList, ToolWin, StdActns, Db, JvExDBGrids, JvDBGrid, JvComponentBase, JvBalloonHint, JvBaseDlg, JvProgressDialog, JvFormPlacement, JvAppStorage, JvAppIniStorage, StdCtrls, Buttons, Mask, JvExMask, JvToolEdit, JvMaskEdit, JvDBFindEdit, JvExStdCtrls, JvEdit, JvDBSearchEdit, JvCombobox; type TFIngGrid07 = class(TForm) MainMenu1: TMainMenu; imgLst: TImageList; sctlst: TActionList; Ventana1: TMenuItem; Salir1: TMenuItem; Cancel1: TDataSetCancel; Delete1: TDataSetDelete; Edit1: TDataSetEdit; First1: TDataSetFirst; Insert1: TDataSetInsert; Last1: TDataSetLast; Next1: TDataSetNext; Post1: TDataSetPost; Prior1: TDataSetPrior; Refresh1: TDataSetRefresh; Ds: TDataSource; pnlMain: TPanel; StatusBar1: TStatusBar; Editar1: TMenuItem; Primero1: TMenuItem; Anterior1: TMenuItem; Siguiente1: TMenuItem; Ultimo1: TMenuItem; N1: TMenuItem; Agregar1: TMenuItem; Borrar1: TMenuItem; Grabar1: TMenuItem; Anular3: TMenuItem; Ayuda1: TMenuItem; Informacion1: TMenuItem; Salir: TAction; Buscar: TAction; Editar2: TMenuItem; EditCopy1: TEditCopy; EditCut1: TEditCut; EditDelete1: TEditDelete; EditPaste1: TEditPaste; EditUndo1: TEditUndo; Copiar1: TMenuItem; Cortar1: TMenuItem; Pegar1: TMenuItem; N2: TMenuItem; Eliminar1: TMenuItem; Deshacer1: TMenuItem; N3: TMenuItem; BuscarRegistro1: TMenuItem; Grilla: TJvDBGrid; jvHint: TJvBalloonHint; jvIni: TJvAppIniFileStorage; jvForm: TJvFormStorage; PopupMenu: TPopupMenu; Primero2: TMenuItem; CambiodeFechas2: TMenuItem; prgBar: TJvProgressDialog; GrabarDlg: TSaveDialog; mBorrarFiltro: TAction; cBar: TCoolBar; ToolBar1: TToolBar; ToolButton7: TToolButton; ToolButton12: TToolButton; ToolButton1: TToolButton; ToolButton2: TToolButton; ToolButton3: TToolButton; ToolButton4: TToolButton; ToolButton11: TToolButton; ToolButton5: TToolButton; ToolButton9: TToolButton; ToolButton10: TToolButton; ToolButton8: TToolButton; ToolButton6: TToolButton; cbSearch: TJvComboBox; sEdit: TJvDBSearchEdit; jvFiltrar: TJvDBFindEdit; BitBtn1: TBitBtn; procedure Salir1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure SalirExecute(Sender: TObject); procedure DsUpdateData(Sender: TObject); procedure BuscarExecute(Sender: TObject); procedure GrillaTitleClick(Column: TColumn); procedure cbSearchChange(Sender: TObject); procedure mBorrarFiltroExecute(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private { Private declarations } Ascending: boolean; FVieProc: TNotifyEvent; FAsc: boolean; FNoCerrar: boolean; procedure OnNuevoRegistro( DataSet: TDataSet ); procedure Reordenar( Campo: string ); public { Public declarations } procedure Inicializar( Data: TDataSet; FBus: string = '' ); procedure EnHint( Sender: TObject ); end; var FIngGrid07: TFIngGrid07; implementation uses BusVal2; {$R *.DFM} procedure TFIngGrid07.Salir1Click(Sender: TObject); begin Close; end; procedure TFIngGrid07.FormClose(Sender: TObject; var Action: TCloseAction); begin jvFiltrar.DataField := ''; jvFiltrar.DataSource := nil; end; procedure TFIngGrid07.FormCreate(Sender: TObject); begin FAsc := true; FVieProc := Application.OnHint; Application.OnHint := EnHint; if ( Assigned( Ds.DataSet )) and not (( Ds.DataSet ).Active ) then begin ( Ds.DataSet ).OnNewRecord := OnNuevoRegistro; ( Ds.DataSet ).Open; end else FNoCerrar := true; end; procedure TFIngGrid07.FormDestroy(Sender: TObject); begin Application.OnHint := FVieProc; if not FNoCerrar then begin ( Ds.DataSet ).OnNewRecord := nil; ( Ds.DataSet ).Close; end; end; procedure TFIngGrid07.GrillaTitleClick(Column: TColumn); begin if Grilla.SortedField = Column.FieldName then Ascending := not Ascending else Ascending := false; Reordenar( Column.FieldName ); Grilla.SortedField := Column.FieldName; end; procedure TFIngGrid07.Inicializar( Data: TDataSet; FBus: string = '' ); var x: integer; begin Ds.DataSet := Data; for x:= 0 to ( Ds.dataset ).FieldCount - 1 do cbSearch.Items.Add( Ds.dataset.Fields[x].fieldName ); if ( FBus = '' ) then cbSearch.ItemIndex := 0 else cbSearch.ItemIndex := cbSearch.Items.IndexOf( FBus ); sEdit.DataField := Ds.dataset.Fields[cbSearch.ItemIndex ].FieldName; jvFiltrar.DataField := Ds.dataset.Fields[ cbSearch.ItemIndex ].FieldName; jvFiltrar.ResetFilter; end; procedure TFIngGrid07.EnHint(Sender: TObject); begin StatusBar1.SimpleText := Application.Hint; end; procedure TFIngGrid07.SalirExecute(Sender: TObject); begin close; end; procedure TFIngGrid07.cbSearchChange(Sender: TObject); begin if cbSearch.ItemIndex >= 0 then begin sEdit.DataField := Ds.Dataset.Fields[ cbSearch.ItemIndex ].FieldName; jvFiltrar.DataField := Ds.Dataset.Fields[ cbSearch.ItemIndex ].FieldName; if Ds.Dataset.Fields[ cbSearch.ItemIndex ] is TDateField then jvFiltrar.EditMask := '!99/99/9999;1;_' else jvFiltrar.EditMask := ''; end; end; procedure TFIngGrid07.DsUpdateData(Sender: TObject); begin // tomar valores de campos para ser insertados en nuevo registro // como ultimo valor grabado. end; procedure TFIngGrid07.OnNuevoRegistro(DataSet: TDataSet); begin // asignar valores de inicio al nuevo registro end; procedure TFIngGrid07.mBorrarFiltroExecute(Sender: TObject); begin jvFiltrar.ResetFilter; end; procedure TFIngGrid07.BuscarExecute(Sender: TObject); begin BusValDlg2 := TBusValDlg2.create( self ); BusValDlg2.DataSet := TClientDataSet( Ds.DataSet ); BusValDlg2.Select( Grilla.SelectedField.FieldName ); BusValDlg2.ShowModal; BusValDlg2.free; end; procedure TFIngGrid07.Reordenar( Campo: string ); var hBook: TBookmark; begin Screen.Cursor := crHourGlass; try ( Ds.DataSet ).DisableControls; hBook := ( Ds.DataSet ).GetBookmark; if ( Ds.Dataset is TAdoDataSet ) then TAdoDataSet( Ds.DataSet ).IndexFieldNames := Campo else if (Ds.DataSet is TClientDataSet ) then TClientDataSet( Ds.DataSet ).IndexFieldNames := Campo; ( Ds.DataSet ).GotoBookmark( hBook ); finally ( Ds.DataSet ).FreeBookmark( hBook ); ( Ds.DataSet ).EnableControls; Screen.Cursor := crDefault; end; end; end.
unit volfied_hw; //{$DEFINE MCU=1} interface uses {$IFDEF WINDOWS}windows,{$ENDIF} m68000,main_engine,controls_engine,gfx_engine,ym_2203,taitosnd,rom_engine, pal_engine,sound_engine{$IFDEF MCU},taito_cchip{$ELSE IF},volfied_cchip{$ENDIF}; function iniciar_volfied:boolean; implementation const volfied_rom:array[0..3] of tipo_roms=( (n:'c04-12-1.30';l:$10000;p:0;crc:$afb6a058),(n:'c04-08-1.10';l:$10000;p:$1;crc:$19f7e66b), (n:'c04-11-1.29';l:$10000;p:$20000;crc:$1aaf6e9b),(n:'c04-25-1.9';l:$10000;p:$20001;crc:$b39e04f9)); volfied_rom2:array[0..3] of tipo_roms=( (n:'c04-20.7';l:$20000;p:$0;crc:$0aea651f),(n:'c04-22.9';l:$20000;p:$1;crc:$f405d465), (n:'c04-19.6';l:$20000;p:$40000;crc:$231493ae),(n:'c04-21.8';l:$20000;p:$40001;crc:$8598d38e)); volfied_sound:tipo_roms=(n:'c04-06.71';l:$8000;p:0;crc:$b70106b2); volfied_sprites:array[0..7] of tipo_roms=( (n:'c04-16.2';l:$20000;p:$0;crc:$8c2476ef),(n:'c04-18.4';l:$20000;p:$1;crc:$7665212c), (n:'c04-15.1';l:$20000;p:$40000;crc:$7c50b978),(n:'c04-17.3';l:$20000;p:$40001;crc:$c62fdeb8), (n:'c04-10.15';l:$10000;p:$80000;crc:$429b6b49),(n:'c04-09.14';l:$10000;p:$80001;crc:$c78cf057), (n:'c04-10.15';l:$10000;p:$a0000;crc:$429b6b49),(n:'c04-09.14';l:$10000;p:$a0001;crc:$c78cf057)); {$IFDEF MCU}cchip_eeprom:tipo_roms=(n:'cchip_c04-23';l:$2000;p:0;crc:$46b0b479);{$ENDIF} //DIP volfied_dip1:array [0..5] of def_dip=( (mask:$1;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$1;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$2;name:'Flip_Screen';number:2;dip:((dip_val:$2;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$8;name:'Demo_Sounds';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$8;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Coin A';number:4;dip:((dip_val:$00;dip_name:'4C-1C'),(dip_val:$10;dip_name:'3C-1C'),(dip_val:$20;dip_name:'2C-1C'),(dip_val:$30;dip_name:'1C-1C'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c0;name:'Coin B';number:4;dip:((dip_val:$c0;dip_name:'1C-2C'),(dip_val:$80;dip_name:'1C-3C'),(dip_val:$40;dip_name:'1C-4C'),(dip_val:$00;dip_name:'1C-6C'),(),(),(),(),(),(),(),(),(),(),(),())),()); volfied_dip2:array [0..4] of def_dip=( (mask:$3;name:'Bonus Life';number:4;dip:((dip_val:$2;dip_name:'20k 40k 120k 480k 2400k'),(dip_val:$3;dip_name:'50k 150k 600k 3000k'),(dip_val:$1;dip_name:'70k 280k 1400k'),(dip_val:$0;dip_name:'100k 500k'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$c;name:'Difficulty';number:4;dip:((dip_val:$8;dip_name:'Easy'),(dip_val:$c;dip_name:'Medium'),(dip_val:$4;dip_name:'Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$70;name:'Lives';number:4;dip:((dip_val:$70;dip_name:'3'),(dip_val:$60;dip_name:'4'),(dip_val:$50;dip_name:'5'),(dip_val:$40;dip_name:'6'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Languaje';number:2;dip:((dip_val:$0;dip_name:'English'),(dip_val:$80;dip_name:'Japanese'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); CPU_SYNC=4; var video_mask,video_ctrl:word; rom:array[0..$1ffff] of word; rom2,ram2:array[0..$3ffff] of word; ram1,ram3:array[0..$1fff] of word; spritebank:byte; procedure update_video_volfied; var x,y,nchar,atrib,color:word; p:dword; f:byte; begin p:=0; if (video_ctrl and 1)<>0 then p:=p+$20000; for y:=0 to 247 do begin for x:=1 to 336 do begin // Hmm, 1 pixel offset is needed to align properly with sprites atrib:=ram2[p+x]; color:=(atrib shl 2) and $700; if (atrib and $8000)<>0 then begin color:=color or $800 or ((atrib shr 9) and $f); if (atrib and $2000)<>0 then color:=color and not($f); // hack */ end else begin color:=color or (atrib and $f); end; putpixel(y,(336-x-1) and $1ff,1,@paleta[color],1); end; p:=p+512; end; actualiza_trozo(0,0,248,336,1,0,0,248,336,2); //Sprites for f:=$ff downto 0 do begin nchar:=(ram3[$2+(f*4)]) mod $1800; atrib:=ram3[f*4]; color:=((atrib and $f) or spritebank) shl 4; put_gfx_sprite(nchar,color+$1000,(atrib and $8000)<>0,(atrib and $4000)<>0,0); y:=320-ram3[$3+(f*4)]; x:=ram3[$1+(f*4)]; actualiza_gfx_sprite(x and $1ff,y and $1ff,2,0); end; actualiza_trozo_final(8,16,240,320,2); end; procedure eventos_volfied; begin if event.arcade then begin //F00007 if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $df) else marcade.in0:=(marcade.in0 or $20); if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $bf) else marcade.in0:=(marcade.in0 or $40); //F00009 if arcade_input.coin[0] then marcade.in1:=(marcade.in1 or $1) else marcade.in1:=(marcade.in1 and $fe); if arcade_input.coin[1] then marcade.in1:=(marcade.in1 or $2) else marcade.in1:=(marcade.in1 and $fd); //F0000B if arcade_input.up[0] then marcade.in2:=(marcade.in2 and $fb) else marcade.in2:=(marcade.in2 or $4); if arcade_input.down[0] then marcade.in2:=(marcade.in2 and $f7) else marcade.in2:=(marcade.in2 or $8); if arcade_input.left[0] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10); if arcade_input.right[0] then marcade.in2:=(marcade.in2 and $df) else marcade.in2:=(marcade.in2 or $20); if arcade_input.but0[0] then marcade.in2:=(marcade.in2 and $bf) else marcade.in2:=(marcade.in2 or $40); //F0000D if arcade_input.up[1] then marcade.in3:=(marcade.in3 and $fd) else marcade.in3:=(marcade.in3 or $2); if arcade_input.down[1] then marcade.in3:=(marcade.in3 and $fb) else marcade.in3:=(marcade.in3 or $4); if arcade_input.right[1] then marcade.in3:=(marcade.in3 and $ef) else marcade.in3:=(marcade.in3 or $10); if arcade_input.but0[1] then marcade.in3:=(marcade.in3 and $df) else marcade.in3:=(marcade.in3 or $20); if arcade_input.left[1] then marcade.in3:=(marcade.in3 and $7f) else marcade.in3:=(marcade.in3 or $80); end; end; procedure volfied_principal; var frame_m,frame_s{$IFDEF MCU},frame_mcu{$ENDIF}:single; f,h:byte; begin init_controls(false,false,false,true); frame_m:=m68000_0.tframes; frame_s:=tc0140syt_0.z80.tframes; {$IFDEF MCU}frame_mcu:=cchip_0.upd7810.tframes;{$ENDIF} while EmuStatus=EsRuning do begin for f:=0 to $ff do begin for h:=1 to CPU_SYNC do begin //Main CPU m68000_0.run(frame_m); frame_m:=frame_m+m68000_0.tframes-m68000_0.contador; //Sound CPU tc0140syt_0.z80.run(frame_s); frame_s:=frame_s+tc0140syt_0.z80.tframes-tc0140syt_0.z80.contador; //MCU {$IFDEF MCU} cchip_0.upd7810.run(frame_mcu); frame_mcu:=frame_mcu+cchip_0.upd7810.tframes-cchip_0.upd7810.contador; {$ENDIF} end; if f=247 then begin update_video_volfied; m68000_0.irq[4]:=HOLD_LINE; {$IFDEF MCU}cchip_0.set_int;{$ENDIF} end; end; eventos_volfied; video_sync; end; end; function volfied_getword(direccion:dword):word; begin case direccion of 0..$3ffff:volfied_getword:=rom[direccion shr 1]; $80000..$fffff:volfied_getword:=rom2[(direccion and $7ffff) shr 1]; $100000..$103fff:volfied_getword:=ram1[(direccion and $3fff) shr 1]; $200000..$203fff:volfied_getword:=ram3[(direccion and $3fff) shr 1]; $400000..$47ffff:volfied_getword:=ram2[(direccion and $7ffff) shr 1]; $500000..$503fff:volfied_getword:=buffer_paleta[(direccion and $3fff) shr 1]; $d00000:volfied_getword:=$60; $e00002:if m68000_0.read_8bits_hi_dir then volfied_getword:=tc0140syt_0.comm_r; {$IFDEF MCU} $f00000..$f007ff:volfied_getword:=cchip_0.mem_r((direccion and $7ff) shr 1); $f00800..$f00fff:volfied_getword:=cchip_0.asic_r((direccion and $7ff) shr 1); {$ELSE IF} $f00000..$f007ff:volfied_getword:=volfied_cchip_ram_r(direccion and $7ff); $f00802:volfied_getword:=volfied_cchip_ctrl_r; {$ENDIF} end; end; procedure volfied_putword(direccion:dword;valor:word); procedure cambiar_color(tmp_color,numero:word); var color:tcolor; begin color.b:=pal5bit(tmp_color shr 10); color.g:=pal5bit(tmp_color shr 5); color.r:=pal5bit(tmp_color); set_pal_color(color,numero); end; begin case direccion of 0..$fffff:; //ROM $100000..$103fff:ram1[(direccion and $3fff) shr 1]:=valor; $200000..$203fff:ram3[(direccion and $3fff) shr 1]:=valor; $400000..$47ffff:ram2[(direccion and $7ffff) shr 1]:=(ram2[(direccion and $7ffff) shr 1] and not(video_mask)) or (valor and video_mask); $500000..$503fff:if buffer_paleta[(direccion and $3fff) shr 1]<>valor then begin buffer_paleta[(direccion and $3fff) shr 1]:=valor; cambiar_color(valor,(direccion and $3fff) shr 1); end; $600000:video_mask:=valor; $700000:spritebank:=(valor and $3c) shl 2; $d00000:video_ctrl:=valor; $e00000:tc0140syt_0.port_w(valor and $ff); $e00002:tc0140syt_0.comm_w(valor and $ff); {$IFDEF MCU} $f00000..$f007ff:cchip_0.mem_w((direccion and $7ff) shr 1,valor and $ff); $f00800..$f00fff:cchip_0.asic_w((direccion and $7ff) shr 1,valor and $ff); {$ELSE IF} $f00000..$f007ff:volfied_cchip_ram_w(direccion and $7ff,valor); $f00802:volfied_cchip_ctrl_w(valor); $f00c00:volfied_cchip_bank_w(valor); {$ENDIF} end; end; function volfied_snd_getbyte(direccion:word):byte; begin case direccion of $0..$87ff:volfied_snd_getbyte:=mem_snd[direccion]; $8801:volfied_snd_getbyte:=tc0140syt_0.slave_comm_r; $9000:volfied_snd_getbyte:=ym2203_0.status; $9001:volfied_snd_getbyte:=ym2203_0.read; end; end; procedure volfied_snd_putbyte(direccion:word;valor:byte); begin case direccion of 0..$7fff:; //ROM $8000..$87ff:mem_snd[direccion]:=valor; $8800:tc0140syt_0.slave_port_w(valor); $8801:tc0140syt_0.slave_comm_w(valor); $9000:ym2203_0.Control(valor); $9001:ym2203_0.Write(valor); end; end; procedure volfied_update_sound; begin ym2203_0.Update; end; function volfied_dipa:byte; begin volfied_dipa:=marcade.dswa; end; function volfied_dipb:byte; begin volfied_dipb:=marcade.dswb; end; function volfied_f00007:byte; begin volfied_f00007:=marcade.in0; end; function volfied_f00009:byte; begin volfied_f00009:=marcade.in1; end; function volfied_f0000c:byte; begin volfied_f0000c:=marcade.in2; end; function volfied_f0000d:byte; begin volfied_f0000d:=marcade.in3; end; procedure snd_irq(irqstate:byte); begin tc0140syt_0.z80.change_irq(irqstate); end; //Main procedure reset_volfied; begin m68000_0.reset; tc0140syt_0.reset; ym2203_0.reset; {$IFDEF MCU} cchip_0.reset; {$ELSE IF} volfied_cchip_reset; {$ENDIF} reset_audio; marcade.in0:=$ff; marcade.in1:=$fc; marcade.in2:=$ff; marcade.in3:=$ff; video_mask:=0; video_ctrl:=0; spritebank:=0; end; function iniciar_volfied:boolean; const ps_x:array[0..15] of dword=(0*4, 1*4, 2*4, 3*4, 4*4, 5*4, 6*4, 7*4, 8*4, 9*4, 10*4, 11*4, 12*4, 13*4, 14*4, 15*4); ps_y:array[0..15] of dword=(0*64, 1*64, 2*64, 3*64, 4*64, 5*64, 6*64, 7*64, 8*64, 9*64, 10*64, 11*64, 12*64, 13*64, 14*64, 15*64); var memoria_temp:pbyte; begin iniciar_volfied:=false; llamadas_maquina.bucle_general:=volfied_principal; llamadas_maquina.reset:=reset_volfied; iniciar_audio(false); screen_init(1,248,512); screen_init(2,512,512,false,true); iniciar_video(240,320); //Main CPU m68000_0:=cpu_m68000.create(8000000,256*CPU_SYNC); m68000_0.change_ram16_calls(volfied_getword,volfied_putword); //Sound CPU tc0140syt_0:=tc0140syt_chip.create(4000000,256*CPU_SYNC); tc0140syt_0.z80.change_ram_calls(volfied_snd_getbyte,volfied_snd_putbyte); tc0140syt_0.z80.init_sound(volfied_update_sound); //Sound Chips ym2203_0:=ym2203_chip.create(4000000,4); ym2203_0.change_io_calls(volfied_dipa,volfied_dipb,nil,nil); ym2203_0.change_irq_calls(snd_irq); //MCU {$IFDEF MCU} //?????????? Tengo que poner 4Mhz mas... En teoria son 10Mhz, pero si lo pongo hae cosas raras... cchip_0:=cchip_chip.create(10000000,256); cchip_0.change_ad(volfied_f0000d); cchip_0.change_in(volfied_f00007,volfied_f00009,volfied_f0000c,nil,nil); if not(roms_load(cchip_0.get_eeprom_dir,cchip_eeprom)) then exit; {$ELSE IF} volfied_init_cchip(m68000_0.numero_cpu); {$ENDIF} //ROMS if not(roms_load16w(@rom,volfied_rom)) then exit; if not(roms_load16w(@rom2,volfied_rom2)) then exit; //cargar sonido+ponerlas en su banco if not(roms_load(@mem_snd,volfied_sound)) then exit; //convertir sprites getmem(memoria_temp,$100000); if not(roms_load16b(memoria_temp,volfied_sprites)) then exit; init_gfx(0,16,16,$1800); gfx[0].trans[0]:=true; gfx_set_desc_data(4,0,128*8,0,1,2,3); convert_gfx(0,0,memoria_temp,@ps_x,@ps_y,false,true); freemem(memoria_temp); //DIP marcade.dswa:=$fe; marcade.dswa_val:=@volfied_dip1; marcade.dswb:=$7f; marcade.dswb_val:=@volfied_dip2; //final reset_volfied; iniciar_volfied:=true; end; end.
unit uTimeVars; interface uses Classes, // Own units UCommon; type TTimeVars = class(THODObject) private FList: TStringList; function GetText: string; procedure SetText(const AValue: string); public //** Конструктор. constructor Create; //** Деструктор. destructor Destroy; override; function Count: Integer; function Name(I: Integer): string; function Value(I: Integer): Integer; overload; function Value(I: string): Integer; overload; function IsMove: Boolean; function IsVar(I: string): Boolean; property Text: string read GetText write SetText; procedure Add(AName: string; AValue: Integer); procedure Clear; procedure Move; end; var TV: TTimeVars; implementation { TTimeVars } uses SysUtils; const LS = '%s=%d'; procedure TTimeVars.Clear; begin FList.Clear; end; function TTimeVars.Count: Integer; begin Result := FList.Count; end; constructor TTimeVars.Create; begin FList := TStringList.Create; end; destructor TTimeVars.Destroy; begin FList.Free; inherited; end; function TTimeVars.IsMove: Boolean; begin Result := (FList.Count > 0); end; function TTimeVars.Name(I: Integer): string; begin Result := FList.Names[I]; end; procedure TTimeVars.Move; var I, V: Integer; begin if IsMove then with FList do for I := Count - 1 downto 0 do begin V := Value(I); System.Dec(V); if (V > 0) then FList[I] := Format(LS, [Name(I), V]) else Delete(I); end; end; function TTimeVars.Value(I: Integer): Integer; begin Result := StrToIntDef(FList.ValueFromIndex[I], 0); end; function TTimeVars.Value(I: string): Integer; begin Result := StrToIntDef(FList.Values[I], 0); end; function TTimeVars.IsVar(I: string): Boolean; begin Result := (Value(I) > 0); end; procedure TTimeVars.Add(AName: string; AValue: Integer); var I, V: Integer; begin if (Trim(AName) = '') or (AValue <= 0) or (AValue > 10000) then Exit; if IsMove then with FList do for I := 0 to Count - 1 do begin if (AName = Name(I)) then begin V := Value(I); if (AValue > V) then V := AValue; FList[I] := Format(LS, [Name(I), V]); Exit; end; end; FList.Append(Format(LS, [AName, AValue])); end; procedure TTimeVars.SetText(const AValue: string); begin FList.Text := AValue; end; function TTimeVars.GetText: string; begin Result := FList.Text; end; initialization TV := TTimeVars.Create; finalization TV.Free; end.
{ CoreGraphics - CGGeometry.h * Copyright (c) 1998-2003 Apple Computer, Inc. * All rights reserved. } { Pascal Translation Updated: Peter N Lewis, <peter@stairways.com.au>, August 2005 } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit CGGeometry; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} uses MacTypes,CFBase,CGBase; {$ALIGN POWER} { Points. } type CGPointPtr = ^CGPoint; CGPoint = record x: Float32; y: Float32; end; { Sizes. } type CGSizePtr = ^CGSize; CGSize = record width: Float32; height: Float32; end; { Rectangles. } type CGRectPtr = ^CGRect; CGRect = record origin: CGPoint; size: CGSize; end; { Rectangle edges. } type CGRectEdge = SInt32; const CGRectMinXEdge = 0; CGRectMinYEdge = 1; CGRectMaxXEdge = 2; CGRectMaxYEdge = 3; { The "zero" point -- equivalent to CGPointMake(0, 0). } var CGPointZero: CGPoint; external name '_CGPointZero'; (* attribute const *) { The "zero" size -- equivalent to CGSizeMake(0, 0). } var CGSizeZero: CGSize; external name '_CGSizeZero'; (* attribute const *) { The "zero" rectangle -- equivalent to CGRectMake(0, 0, 0, 0). } var CGRectZero: CGRect; external name '_CGRectZero'; (* attribute const *) { The "empty" rect. This is the rectangle returned when, for example, we * intersect two disjoint rectangles. Note that the null rect is not the * same as the zero rect. } var CGRectNull: CGRect; external name '_CGRectNull'; (* attribute const *) { The infinite rectangle. } var CGRectInfinite: CGRect; external name '_CGRectInfinite'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { Make a point from `(x, y)'. } // CG_INLINE CGPoint CGPointMake(float x, float y); { Make a size from `(width, height)'. } // CG_INLINE CGSize CGSizeMake(float width, float height); { Make a rect from `(x, y; width, height)'. } // CG_INLINE CGRect CGRectMake(float x, float y, float width, float height); { Return the leftmost x-value of `rect'. } function CGRectGetMinX( rect: CGRect ): Float32; external name '_CGRectGetMinX'; { Return the midpoint x-value of `rect'. } function CGRectGetMidX( rect: CGRect ): Float32; external name '_CGRectGetMidX'; { Return the rightmost x-value of `rect'. } function CGRectGetMaxX( rect: CGRect ): Float32; external name '_CGRectGetMaxX'; { Return the bottommost y-value of `rect'. } function CGRectGetMinY( rect: CGRect ): Float32; external name '_CGRectGetMinY'; { Return the midpoint y-value of `rect'. } function CGRectGetMidY( rect: CGRect ): Float32; external name '_CGRectGetMidY'; { Return the topmost y-value of `rect'. } function CGRectGetMaxY( rect: CGRect ): Float32; external name '_CGRectGetMaxY'; { Return the width of `rect'. } function CGRectGetWidth( rect: CGRect ): Float32; external name '_CGRectGetWidth'; { Return the height of `rect'. } function CGRectGetHeight( rect: CGRect ): Float32; external name '_CGRectGetHeight'; { Return 1 if `point1' and `point2' are the same, 0 otherwise. } function CGPointEqualToPoint( point1: CGPoint; point2: CGPoint ): SInt32; external name '_CGPointEqualToPoint'; { Return 1 if `size1' and `size2' are the same, 0 otherwise. } function CGSizeEqualToSize( size1: CGSize; size2: CGSize ): SInt32; external name '_CGSizeEqualToSize'; { Return 1 if `rect1' and `rect2' are the same, 0 otherwise. } function CGRectEqualToRect( rect1: CGRect; rect2: CGRect ): SInt32; external name '_CGRectEqualToRect'; { Standardize `rect' -- i.e., convert it to an equivalent rect which has * positive width and height. } function CGRectStandardize( rect: CGRect ): CGRect; external name '_CGRectStandardize'; { Return 1 if `rect' is empty -- i.e., if it has zero width or height. A * null rect is defined to be empty. } function CGRectIsEmpty( rect: CGRect ): SInt32; external name '_CGRectIsEmpty'; { Return 1 if `rect' is null -- e.g., the result of intersecting two * disjoint rectangles is a null rect. } function CGRectIsNull( rect: CGRect ): SInt32; external name '_CGRectIsNull'; { Return true if `rect' is the infinite rectangle, false otherwise. } function CGRectIsInfinite( rect: CGRect ): CBool; external name '_CGRectIsInfinite'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) { Inset `rect' by `(dx, dy)' -- i.e., offset its origin by `(dx, dy)', and * decrease its size by `(2*dx, 2*dy)'. } function CGRectInset( rect: CGRect; dx: Float32; dy: Float32 ): CGRect; external name '_CGRectInset'; { Expand `rect' to the smallest rect containing it with integral origin * and size. } function CGRectIntegral( rect: CGRect ): CGRect; external name '_CGRectIntegral'; { Return the union of `r1' and `r2'. } function CGRectUnion( r1: CGRect; r2: CGRect ): CGRect; external name '_CGRectUnion'; { Return the intersection of `r1' and `r2'. This may return a null * rect. } function CGRectIntersection( r1: CGRect; r2: CGRect ): CGRect; external name '_CGRectIntersection'; { Offset `rect' by `(dx, dy)'. } function CGRectOffset( rect: CGRect; dx: Float32; dy: Float32 ): CGRect; external name '_CGRectOffset'; { Make two new rectangles, `slice' and `remainder', by dividing `rect' * with a line that's parallel to one of its sides, specified by `edge' -- * either `CGRectMinXEdge', `CGRectMinYEdge', `CGRectMaxXEdge', or * `CGRectMaxYEdge'. The size of `slice' is determined by `amount', which * measures the distance from the specified edge. } procedure CGRectDivide( rect: CGRect; var slice: CGRect; var remainder: CGRect; amount: Float32; edge: CGRectEdge ); external name '_CGRectDivide'; { Return 1 if `point' is contained in `rect', 0 otherwise. } function CGRectContainsPoint( rect: CGRect; point: CGPoint ): SInt32; external name '_CGRectContainsPoint'; { Return 1 if `rect2' is contained in `rect1', 0 otherwise. `rect2' is * contained in `rect1' if the union of `rect1' and `rect2' is equal to * `rect1'. } function CGRectContainsRect( rect1: CGRect; rect2: CGRect ): SInt32; external name '_CGRectContainsRect'; { Return 1 if `rect1' intersects `rect2', 0 otherwise. `rect1' intersects * `rect2' if the intersection of `rect1' and `rect2' is not the null * rect. } function CGRectIntersectsRect( rect1: CGRect; rect2: CGRect ): SInt32; external name '_CGRectIntersectsRect'; (* {** Definitions of inline functions. **} // CG_INLINE CGPoint CGPointMake(float x, float y) { CGPoint p; p.x = x; p.y = y; return p; } // CG_INLINE CGSize CGSizeMake(float width, float height) { CGSize size; size.width = width; size.height = height; return size; } // CG_INLINE CGRect CGRectMake(float x, float y, float width, float height) { CGRect rect; rect.origin.x = x; rect.origin.y = y; rect.size.width = width; rect.size.height = height; return rect; } *) end.
[assembly: FlitBit.Wireup.Meta.WireupDependency(typeof(FlitBit.Represent.AssemblyWireup))]
{******************************************************************************* 作者: dmzn@163.com 2011-11-21 描述: 查看产品库存 *******************************************************************************} unit UFrameProductView; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UFrameBase, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, Menus, StdCtrls, cxButtons, cxLabel, cxRadioGroup, Grids, UGridPainter, UGridExPainter, ExtCtrls; type TfFrameProductView = class(TfFrameBase) PanelR: TPanel; PanelL: TPanel; LabelHint: TLabel; GridDetail: TDrawGridEx; Label2: TLabel; GridProduct: TDrawGridEx; Splitter1: TSplitter; procedure BtnExitClick(Sender: TObject); private { Private declarations } FPainter: TGridPainter; FPainterEx: TGridExPainter; //绘图对象 FData: TList; //数据列表 procedure ClearData(const nFree: Boolean); //清理数据 procedure LoadProductData; procedure LoadProductList; //产品列表 function CountNumber(const nID: string): Integer; //统计数量 procedure OnBtnClick(Sender: TObject); //点击按钮 public { Public declarations } procedure OnCreateFrame; override; procedure OnDestroyFrame; override; class function FrameID: integer; override; end; implementation {$R *.dfm} uses IniFiles, ULibFun, UDataModule, DB, UMgrControl, USysConst, USysDB, USysFun, UFormProductPrice; type PDataItem = ^TDataItem; TDataItem = record FStyle: string; FName: string; FColor: string; FSize: string; FNumber: Integer; FTime: string; end; class function TfFrameProductView.FrameID: integer; begin Result := cFI_FrameProductView; end; procedure TfFrameProductView.OnCreateFrame; var nIni: TIniFile; begin Name := MakeFrameName(FrameID); FData := TList.Create; FPainter := TGridPainter.Create(GridProduct); FPainterEx := TGridExPainter.Create(GridDetail); with FPainter do begin HeaderFont.Style := HeaderFont.Style + [fsBold]; //粗体 AddHeader('序号', 50); AddHeader('款式名称', 50); AddHeader('总库存量', 50); AddHeader('操作', 50); end; with FPainterEx do begin HeaderFont.Style := HeaderFont.Style + [fsBold]; //粗体 AddHeader('颜色', 50, True); AddHeader('尺码', 50); AddHeader('现有存量', 50); AddHeader('上次入库时间', 50); end; nIni := TIniFile.Create(gPath + sFormConfig); try LoadDrawGridConfig(Name, GridProduct, nIni); LoadDrawGridConfig(Name, GridDetail, nIni); PanelL.Width := nIni.ReadInteger(Name, 'PanelL', 120); Width := PanelL.Width + GetGridHeaderWidth(GridDetail); LoadProductData; finally nIni.Free; end; end; procedure TfFrameProductView.OnDestroyFrame; var nIni: TIniFile; begin nIni := TIniFile.Create(gPath + sFormConfig); try SaveDrawGridConfig(Name, GridProduct, nIni); SaveDrawGridConfig(Name, GridDetail, nIni); nIni.WriteInteger(Name, 'PanelL', PanelL.Width); finally nIni.Free; end; FPainter.Free; FPainterEx.Free; ClearData(True); end; procedure TfFrameProductView.BtnExitClick(Sender: TObject); begin Close; end; //Desc: 清理数据 procedure TfFrameProductView.ClearData(const nFree: Boolean); var nIdx: Integer; begin for nIdx:=FData.Count - 1 downto 0 do begin Dispose(PDataItem(FData[nIdx])); FData.Delete(nIdx); end; if nFree then FData.Free; end; //Desc: 载入产品列表 procedure TfFrameProductView.LoadProductData; var nStr,nHint: string; nDS: TDataSet; nItem: PDataItem; begin nStr := 'Select pt.*,p.StyleID,StyleName,ColorName,SizeName From $PT pt' + ' Left Join (Select ProductID,StyleName,dpt.StyleID From $DPT dpt' + ' Left Join $ST st On st.StyleID=dpt.StyleID' + ' ) p On ProductID=pt.P_ID' + ' Left Join $CR cr On cr.ColorID=P_Color ' + ' Left Join $SZ sz on sz.SizeID=P_Size ' + 'Where P_TerminalID=''$ID'' ' + 'Order By p.StyleID,ColorName,SizeName'; //xxxxx nStr := MacroValue(nStr, [MI('$PT', sTable_Product), MI('$DPT', sTable_DL_Product), MI('$ST', sTable_DL_Style), MI('$CR', sTable_DL_Color), MI('$SZ', sTable_DL_Size), MI('$ID', gSysParam.FTerminalID)]); //xxxxx nDS := FDM.LockDataSet(nStr, nHint); try if not Assigned(nDS) then begin ShowDlg(nHint, sWarn); Exit; end; FPainter.ClearData; if nDS.RecordCount < 1 then Exit; with nDS do begin First; while not Eof do begin New(nItem); FData.Add(nItem); with nItem^ do begin FStyle := FieldByName('StyleID').AsString; FName := FieldByName('StyleName').AsString; FColor := FieldByName('ColorName').AsString; FSize := FieldByName('SizeName').AsString; FNumber := FieldByName('P_Number').AsInteger; FTime := DateTime2Str(FieldByName('P_LastIn').AsDateTime); end; Next; end; end; finally FDM.ReleaseDataSet(nDS); end; LoadProductList; end; //Desc: 载入产品列表到界面 procedure TfFrameProductView.LoadProductList; var i,nIdx,nInt: Integer; nList: TStrings; nBtn: TcxButton; nData: TGridDataArray; begin nList := TStringList.Create; try nInt := 1; for nIdx:=0 to FData.Count - 1 do with PDataItem(FData[nIdx])^ do if nList.IndexOf(FStyle) < 0 then begin nList.Add(FStyle); SetLength(nData, 5); for i:=Low(nData) to High(nData) do begin nData[i].FText := ''; nData[i].FCtrls := nil; nData[i].FAlign := taCenter; end; nData[0].FText := IntToStr(nInt); Inc(nInt); nData[4].FText := FStyle; nData[1].FText := FName; nData[2].FText := IntToStr(CountNumber(FStyle)); with nData[3] do begin FText := ''; FAlign := taCenter; FCtrls := TList.Create; nBtn := TcxButton.Create(Self); FCtrls.Add(nBtn); with nBtn do begin Caption := '调价'; Width := 35; Height := 18; Enabled := gSysParam.FIsAdmin; OnClick := OnBtnClick; Tag := FPainter.DataCount; end; nBtn := TcxButton.Create(Self); FCtrls.Add(nBtn); with nBtn do begin Caption := '详细'; Width := 35; Height := 18; Parent := Self; OnClick := OnBtnClick; Tag := FPainter.DataCount; end; end; FPainter.AddData(nData); end; finally nList.Free; end; end; //Desc: 统计指定款式的库存总量 function TfFrameProductView.CountNumber(const nID: string): Integer; var nIdx: Integer; begin Result := 0; for nIdx:=FData.Count - 1 downto 0 do with PDataItem(FData[nIdx])^ do if FStyle = nID then Result := Result + FNumber; //xxxxx end; //Desc: 查看详情 procedure TfFrameProductView.OnBtnClick(Sender: TObject); var nStr,nID: string; nIdx,nNum,nInt: Integer; nRow: TGridExDataArray; nCol: TGridExColDataArray; begin nNum := TComponent(Sender).Tag; if Sender = FPainter.Data[nNum][3].FCtrls[0] then begin ShowProductPriceForm(FPainter.Data[nNum][4].FText); Exit; end; //调价 nID := FPainter.Data[nNum][4].FText; LabelHint.Caption := FPainter.Data[nNum][1].FText + '详细信息'; nInt := AdjustLabelCaption(LabelHint, GridDetail); if nInt > LabelHint.Width then Width := PanelL.Width + nInt + 32; //标题超长自适应 nNum := 0; nStr := ''; FPainterEx.ClearData; for nIdx:=0 to FData.Count - 1 do with PDataItem(FData[nIdx])^ do if FStyle = nID then begin SetLength(nRow, 3); for nInt:=Low(nRow) to High(nRow) do begin nRow[nInt].FCtrls := nil; nRow[nInt].FAlign := taCenter; end; nRow[0].FText := FSize; nRow[1].FText := IntToStr(FNumber); nRow[2].FText := FTime; FPainterEx.AddRowData(nRow); //添加行数据 if nStr = '' then nStr := FColor; //xxxxx if nStr = FColor then begin Inc(nNum); Continue; end; SetLength(nCol, 1); with nCol[0] do begin FCol := 0; FRows := nNum; FAlign := taCenter; FText := nStr; nNum := 1; nStr := FColor; end; FPainterEx.AddColData(nCol); end; //color if nNum > 0 then begin SetLength(nCol, 1); with nCol[0] do begin FCol := 0; FRows := nNum; FAlign := taCenter; FText := nStr; end; FPainterEx.AddColData(nCol); end; end; initialization gControlManager.RegCtrl(TfFrameProductView, TfFrameProductView.FrameID); end.
unit DataContainers.TField; interface uses System.SysUtils, System.Variants, Utils.TArrayUtil, Framework.Interfaces, ValidationRules.TIsEmptyValidationRule, ValidationRules.TDataTypeValidationRule, ValidationRules.TMaxLengthValidationRule; type TField = class(TInterfacedObject, IField) private FDestinationFieldName: String; FValidationRules: TArray<IValidationRule>; FIsValid: Boolean; FName: String; FValue: Variant; function GetName: String; procedure SetName(const AName: String); procedure SetDestinationFieldName(const ADestinationFieldName: String); function GetValue: Variant; procedure SetValue(const AValue: Variant); procedure SetValidationRules(const AAcceptEmpty: Boolean; const ADataType: String; const ADateFormat: String; const ADateSeparator: Char; const AMaxLength: Integer); public constructor Create(const AAcceptEmpty: Boolean; const ADataType: String; const ADateFormat: String; const ADateSeparator: Char; const AMaxLength: Integer); destructor Destroy; override; function Parse(var AReasonForRejection: String): Boolean; property DestinationFieldName: String read FDestinationFieldName write SetDestinationFieldName; property IsValid: Boolean read FIsValid; property Name: String read GetName write SetName; property Value: Variant read GetValue write SetValue; end; implementation { TField } constructor TField.Create(const AAcceptEmpty: Boolean; const ADataType: String; const ADateFormat: String; const ADateSeparator: Char; const AMaxLength: Integer); begin inherited Create; SetValidationRules(AAcceptEmpty, ADataType, ADateFormat, ADateSeparator, AMaxLength); end; destructor TField.Destroy; begin inherited; end; function TField.GetName: String; begin Result := FName; end; function TField.GetValue: Variant; begin Result := FValue; end; function TField.Parse(var AReasonForRejection: String): Boolean; var Index: Integer; begin Result := False; for Index := 0 to Length(FValidationRules) -1 do begin Result := FValidationRules[Index].Parse(FValue, AReasonForRejection); if not Result then Break; end; end; procedure TField.SetDestinationFieldName(const ADestinationFieldName: String); begin if FDestinationFieldName <> ADestinationFieldName then FDestinationFieldName := ADestinationFieldName; end; procedure TField.SetName(const AName: String); begin if FName <> AName then FName := AName; end; procedure TField.SetValidationRules(const AAcceptEmpty: Boolean; const ADataType, ADateFormat: String; const ADateSeparator: Char; const AMaxLength: Integer); var AuxValidationRule: IValidationRule; begin AuxValidationRule := TIsEmptyValidationRule.Create(AAcceptEmpty); TArrayUtil<IValidationRule>.Append(FValidationRules, AuxValidationRule); AuxValidationRule := TDataTypeValidationRule.Create(AAcceptEmpty, ADataType, ADateFormat, ADateSeparator); TArrayUtil<IValidationRule>.Append(FValidationRules, AuxValidationRule); if AMaxLength > 0 then begin AuxValidationRule := TMaxLengthValidationRule.Create(AMaxLength); TArrayUtil<IValidationRule>.Append(FValidationRules, AuxValidationRule); end; end; procedure TField.SetValue(const AValue: Variant); begin if FValue <> AValue then FValue := AValue; end; end.
unit uRunUtils; {$mode objfpc}{$H+} interface uses Classes, SysUtils, process, FileUtil, AsyncProcess; type { TRunUtils } TRunUtils = class(TDataModule) // TODO - odstranit třídu runSyncProcess: TProcess; runAsyncProcess: TAsyncProcess; // TODO - na lokální proměnnou private { private declarations } public procedure RunAsync(const aCmd, aParams, aDir, aPath, aName: string); // TODO - na běžnou proceduru procedure RunSync(const aCmd, aParams, aDir, aPath, aName: string); end; var RunUtils: TRunUtils; implementation Const BEGIN_SL = 0; {$R *.lfm} { TRunUtils } Procedure TRunUtils.RunAsync(Const aCmd, aParams, aDir, aPath, aName: string); var sl, slCmd: TStringList; lParams, lCmd: string; begin // replace macros if aDir <> '' then lParams := StringReplace(aParams, '%d', '"' + aDir + '"', [rfReplaceAll]); if aPath <> '' then lParams := StringReplace(lParams, '%p', '"' + aPath + '"', [rfReplaceAll]); if aName <> '' then lParams := StringReplace(lParams, '%f', '"' + aName + '"', [rfReplaceAll]); sl := TStringList.Create; try slCmd := tStringList.Create; slCmd.Delimiter := ' '; slCmd.DelimitedText := aCmd; lCmd := slCmd[BEGIN_SL]; slCmd.Delete(BEGIN_SL); //sl.StrictDelimiter := true; sl.Delimiter := ' '; sl.DelimitedText := lParams; slCmd.AddStrings(sl); // execute process if aDir <> '' then runAsyncProcess.CurrentDirectory := aDir; runAsyncProcess.Executable := lCmd; runAsyncProcess.Parameters.Clear; runAsyncProcess.Parameters.AddStrings(slCmd); runAsyncProcess.Execute; finally FreeAndNil(slCmd); sl.Free; end; end; Procedure TRunUtils.RunSync(Const aCmd, aParams, aDir, aPath, aName: string); var sl: TStringList; lParams: string; begin // replace macros if aDir <> '' then lParams := StringReplace(aParams, '%d', '''' + aDir + '''', [rfReplaceAll]); if aPath <> '' then lParams := StringReplace(lParams, '%p', '''' + aPath + '''', [rfReplaceAll]); if aPath <> '' then lParams := StringReplace(lParams, '%f', '''' + ExtractFileName(aPath) + '''', [rfReplaceAll]); if aName <> '' then lParams := StringReplace(lParams, '%n', '''' + aName + '''', [rfReplaceAll]); sl := TStringList.Create; try //sl.StrictDelimiter := true; sl.Delimiter := ' '; sl.DelimitedText := lParams; // execute process if aDir <> '' then runSyncProcess.CurrentDirectory := aDir; runSyncProcess.Executable := aCmd; runSyncProcess.Parameters.Clear; runSyncProcess.Parameters.AddStrings(sl); runSyncProcess.Execute; WriteLn(runSyncProcess.ExitCode); //sl.Clear; //sl.LoadFromStream(runSyncProcess.Output); //for i := 0 to sl.Count - 1 do // WriteLn(sl[i]); finally sl.Free; end; End; end.
unit uAtualizacaoCampoMSSQL; interface uses System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Dialogs, ZAbstractConnection, ZConnection, ZAbstractRODataset, ZAbstractDataset, ZDataset, System.SysUtils, uAtualizacaoBancoDeDados; type TAtualizacaoCampoMSSQL = class(TAtualizabancoDeDados) private function CampoExisteNaTabela(aNomeTabela, aCampo: String): Boolean; procedure Versao1; protected public constructor Create(aConexao:TZConnection); destructor Destroy; override; end; implementation { TAtualizacaoTableMSSQ8L } constructor TAtualizacaoCampoMSSQL.Create(aConexao: TZConnection); begin ConexaoDB := aConexao; Versao1; end; destructor TAtualizacaoCampoMSSQL.Destroy; begin inherited; end; function TAtualizacaoCampoMSSQL.CampoExisteNaTabela(aNomeTabela: String; aCampo:String): Boolean; Var Qry:TZQuery; Begin Try Result:=False; Qry:=TZQuery.Create(nil); Qry.Connection:=ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add(' SELECT COUNT(COLUMN_NAME) AS Qtde '); Qry.SQL.Add(' FROM INFORMATION_SCHEMA.COLUMNS '); Qry.SQL.Add(' WHERE TABLE_NAME =:Tabela '); Qry.SQL.Add(' AND COLUMN_NAME=:Campo '); Qry.ParamByName('Tabela').AsString:=aNomeTabela; Qry.ParamByName('Campo').AsString :=aCampo; Qry.Open; if Qry.FieldByName('Qtde').AsInteger>0 then Result:=True; Finally Qry.Close; if Assigned(Qry) then FreeAndNil(Qry); End; end; procedure TAtualizacaoCampoMSSQL.Versao1; begin if not CampoExisteNaTabela('fornecedor','Forn_email') then begin ExecutaDiretoBancoDeDados('ALTER TABLE fornecedor ADD Forn_email varchar(50) NULL '); end; if not CampoExisteNaTabela('empresa','Emp_Contato') then begin ExecutaDiretoBancoDeDados('ALTER TABLE empresa ADD Emp_Contato varchar(50) NULL '); end; end; end.
unit helpers; interface uses Vcl.Forms, xn.list, xn.list.index; {$M+} type TMyRecord = record private fCod: integer; procedure CodSet(aCod: integer); function CodGet: integer; public constructor Create(aCod: integer); property Cod: integer read CodGet write CodSet; end; IMyObject = interface ['{D7BA6D54-E2D9-492B-81B3-84B737AC4859}'] procedure CodSet(aCod: integer); function CodGet: integer; property Cod: integer read CodGet write CodSet; end; TMyObject = class(TInterfacedObject, IMyObject) private fCod: integer; procedure CodSet(aCod: integer); function CodGet: integer; published constructor Create(aCod: integer); property Cod: integer read CodGet write CodSet; end; var t0: TDateTime; t1: TDateTime; procedure TimerStart; procedure TimerStop(aForm: TForm; aCaption: string); function IntegerComparison(const aLeft, aRight: integer): integer; function MyRecordComparison(const aLeft, aRight: TMyRecord): integer; function MyObjectComparison(const aLeft, aRight: IMyObject): integer; function AsDebug(aList: IxnList<integer>): string; overload; function AsDebug(aList: IxnList<TMyRecord>): string; overload; function AsDebug(aList: IxnList<IMyObject>): string; overload; function AsDebug(aList: IxnListIndex<integer>): string; overload; function AsDebug(aList: IxnListIndex<TMyRecord>): string; overload; function AsDebug(aList: IxnListIndex<IMyObject>): string; overload; implementation uses System.SysUtils; // ***************************************************************************** // ***************************************************************************** { TMyRecord } function TMyRecord.CodGet: integer; begin Result := fCod end; procedure TMyRecord.CodSet(aCod: integer); begin fCod := aCod; end; constructor TMyRecord.Create(aCod: integer); begin fCod := aCod; end; { TMyObject } constructor TMyObject.Create(aCod: integer); begin fCod := aCod; end; function TMyObject.CodGet: integer; begin Result := fCod end; procedure TMyObject.CodSet(aCod: integer); begin fCod := aCod; end; // ***************************************************************************** // ***************************************************************************** procedure TimerStart; begin t0 := Now; Application.ProcessMessages; end; procedure TimerStop(aForm: TForm; aCaption: string); begin Application.ProcessMessages; t1 := Now; Application.ProcessMessages; aForm.Caption := aCaption + ' elapsed time ' + FormatDateTime('ss:zzz', t1 - t0); end; // ***************************************************************************** // ***************************************************************************** function IntegerComparison(const aLeft, aRight: integer): integer; begin Result := aLeft - aRight; end; function MyRecordComparison(const aLeft, aRight: TMyRecord): integer; begin Result := aLeft.Cod - aRight.Cod; end; function MyObjectComparison(const aLeft, aRight: IMyObject): integer; begin // if aLeft.Cod.ToString = aRight.Cod.ToString then // Result := 0 // else if aLeft.Cod.ToString < aRight.Cod.ToString then // Result := -1 // else // Result := +1; Result := aLeft.Cod - aRight.Cod; end; // ***************************************************************************** // ***************************************************************************** function AsDebug(aList: IxnList<integer>): string; overload; var i: integer; begin Result := ''; for i in aList do Result := Result + i.ToString() + ' '; end; function AsDebug(aList: IxnList<TMyRecord>): string; overload; var i: TMyRecord; begin Result := ''; for i in aList do Result := Result + i.Cod.ToString() + ' '; end; function AsDebug(aList: IxnList<IMyObject>): string; overload; var i: IMyObject; begin Result := ''; for i in aList do Result := Result + i.Cod.ToString() + ' '; end; function AsDebug(aList: IxnListIndex<integer>): string; overload; var i: integer; begin Result := ''; for i in aList do Result := Result + i.ToString() + ' '; end; function AsDebug(aList: IxnListIndex<TMyRecord>): string; overload; var i: TMyRecord; begin Result := ''; for i in aList do Result := Result + i.Cod.ToString() + ' '; end; function AsDebug(aList: IxnListIndex<IMyObject>): string; overload; var i: IMyObject; begin Result := ''; for i in aList do Result := Result + i.Cod.ToString() + ' '; end; end.
unit UAccessContainer; interface uses Classes, UAccessBase; type TVersionString = string[30]; TSAVAccessContainer = class(TObject) private FCaption: string; FDescription: string; FSID: string; FVersion: TVersionString; FID: Integer; FWorkDir: string; FFilepath: string; FContainerType:Char; FIniPath: string; FBases: TSAVAccessBase; procedure SetBases(const Value: TSAVAccessBase); procedure SetCaption(const Value: string); procedure SetDescription(const Value: string); procedure SetFilePath(const Value: string); procedure SetIniPath(const Value: string); procedure SetSID(const Value: string); procedure SetID(const Value: Integer); procedure SetVersion(const Value: TVersionString); procedure SetWorkDir(const Value: string); procedure SetContainerType(const Value: Char); public property Caption: string read FCaption write SetCaption; property Description: string read FDescription write SetDescription; property WorkDir: string read FWorkDir write SetWorkDir; property ID: Integer read FID write SetID; property SID: string read FSID write SetSID; property ContainerType:Char read FContainerType write SetContainerType; property FilePath: string read FFilePath write SetFilePath; property IniPath: string read FIniPath write SetIniPath; property Version: TVersionString read FVersion write SetVersion; property Bases: TSAVAccessBase read FBases write SetBases; constructor Create; overload; procedure Save; virtual; abstract; function Load(aSID: string = ''): Boolean; virtual; abstract; procedure GetImportantList(List: TStrings); virtual; procedure GetIndependentList(List: TStrings); virtual; procedure Clear; virtual; procedure Open(aBase: TSAVAccessBase; const aCaption, aSID: string; const aDescription: string = ''; const aParam: string = ''; const aVersion: TVersionString = ''); virtual; function GetNewVersion: string; function WriteVersion(const aFileName: string = ''): Boolean; function ReadVersion(const aFileName: string = ''): Boolean; procedure UpdateVersion; virtual; end; implementation uses Sysutils, IniFiles, UAccessConstant; { TSAVAccessContainer } constructor TSAVAccessContainer.Create; begin end; procedure TSAVAccessContainer.SetBases(const Value: TSAVAccessBase); begin FBases := Value end; procedure TSAVAccessContainer.SetCaption(const Value: string); begin end; procedure TSAVAccessContainer.SetDescription(const Value: string); begin FDescription := Value; end; procedure TSAVAccessContainer.SetFilePath(const Value: string); begin FFilepath := Value; end; procedure TSAVAccessContainer.SetIniPath(const Value: string); begin FIniPath := Value end; procedure TSAVAccessContainer.SetID(const Value: Integer); begin FID := Value end; procedure TSAVAccessContainer.SetSID(const Value: string); begin FSID := Value end; procedure TSAVAccessContainer.Clear; begin FCaption := ''; FDescription := ''; FSID := ''; FID := 0; FFilepath := ''; FIniPath := ''; FBases := nil; FVersion := ''; FWorkDir := ''; end; procedure TSAVAccessContainer.GetImportantList(List: TStrings); begin end; procedure TSAVAccessContainer.GetIndependentList(List: TStrings); begin end; procedure TSAVAccessContainer.SetVersion(const Value: TVersionString); begin FVersion := Value; end; function TSAVAccessContainer.GetNewVersion: string; begin DateTimeToString(Result, 'yymmddhhnnss', Now); end; procedure TSAVAccessContainer.Open(aBase: TSAVAccessBase; const aCaption, aSID, aDescription, aParam: string; const aVersion: TVersionString); begin FBases := aBase; FCaption := aCaption; FSID := aSID; FDescription := aDescription; if aVersion = '' then begin ReadVersion; if FVersion = '' then FVersion := GetNewVersion end else FVersion := aVersion; end; function TSAVAccessContainer.ReadVersion(const aFileName: string): Boolean; var Ini01: TIniFile; sF: string; begin Result := True; if aFileName = '' then sF := IncludeTrailingPathDelimiter(WorkDir) + csContainerCfg else sF := aFileName; Ini01 := TIniFile.Create(sF); try FVersion := Ini01.ReadString('main', 'version', ''); except Result := False; FVersion := ''; end; FreeAndNil(Ini01); end; function TSAVAccessContainer.WriteVersion( const aFileName: string): Boolean; var Ini01: TMemIniFile; sF: string; begin Result := True; if aFileName = '' then sF := IncludeTrailingPathDelimiter(WorkDir) + csContainerCfg else sF := aFileName; Ini01 := TMemIniFile.Create(sF); try Ini01.WriteString('main', 'version', FVersion); Ini01.WriteString('main', 'type', FContainerType); Ini01.UpdateFile; except Result := False; end; FreeAndNil(Ini01); end; procedure TSAVAccessContainer.SetWorkDir(const Value: string); begin FWorkDir := Value; end; procedure TSAVAccessContainer.SetContainerType(const Value: Char); begin FContainerType := Value; end; procedure TSAVAccessContainer.UpdateVersion; begin FVersion:=GetNewVersion; WriteVersion; end; end.
unit LUX.GPU.Vulkan.root; interface //#################################################################### ■ uses SYstem.Generics.Collections; type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】 TVkDeviceObject<TVkDevice_,TVkParent_:class> = class; TVkDeviceLister<TVkDevice_,TVkParent_,TVkChildr_:class> = class; TVkDeviceLister<TVkDevice_,TVkChildr_:class> = class; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkDeviceObject<TVkDevice_,TVkParent_> TVkDeviceObject<TVkDevice_,TVkParent_:class> = class private protected _Parent :TVkParent_; ///// アクセス function GetDevice :TVkDevice_; virtual; abstract; function GetParent :TVkParent_; { TODO : virtual; にすると「F2084 内部エラー: URW1302」が生じる。 } public constructor Create; overload; virtual; constructor Create( const Parent_:TVkParent_ ); overload; virtual; ///// プロパティ property Device :TVkDevice_ read GetDevice; property Parent :TVkParent_ read GetParent; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkDeviceLister<TVkDevice_,TVkParent_,TVkChildr_> TVkDeviceLister<TVkDevice_,TVkParent_,TVkChildr_:class> = class( TObjectList<TVkChildr_> ) private protected _Parent :TVkParent_; ///// アクセス function GetDevice :TVkDevice_; virtual; abstract; function GetParent :TVkParent_; virtual; public constructor Create; overload; virtual; constructor Create( const Parent_:TVkParent_ ); overload; virtual; ///// プロパティ property Device :TVkDevice_ read GetDevice; property Parent :TVkParent_ read GetParent; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkDeviceLister<TVkDevice_,TVkChildr_> TVkDeviceLister<TVkDevice_,TVkChildr_:class> = class( TVkDeviceLister<TVkDevice_,TVkDevice_,TVkChildr_> ) private protected ///// アクセス function GetDevice :TVkDevice_; override; public end; //const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】 //var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 implementation //############################################################### ■ //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkDeviceObject<TVkDevice_,TVkParent_> //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected function TVkDeviceObject<TVkDevice_,TVkParent_>.GetParent :TVkParent_; begin Result := _Parent; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TVkDeviceObject<TVkDevice_,TVkParent_>.Create; begin inherited; end; constructor TVkDeviceObject<TVkDevice_,TVkParent_>.Create( const Parent_:TVkParent_ ); begin Create; _Parent := Parent_; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkDeviceLister<TVkDevice_,TVkParent_,TVkChildr_> //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected function TVkDeviceLister<TVkDevice_,TVkParent_,TVkChildr_>.GetParent :TVkParent_; begin Result := _Parent; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TVkDeviceLister<TVkDevice_,TVkParent_,TVkChildr_>.Create; begin inherited; end; constructor TVkDeviceLister<TVkDevice_,TVkParent_,TVkChildr_>.Create( const Parent_:TVkParent_ ); begin Create; _Parent := Parent_; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkDeviceLister<TVkDevice_,TVkChildr_> //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TVkDeviceLister<TVkDevice_,TVkChildr_>.GetDevice :TVkDevice_; begin Result := _Parent; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 end. //######################################################################### ■
unit ScanDocs; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, EnScan, EnImgScr, StdCtrls, sComboBox, sEdit, sSpinEdit, Buttons, sBitBtn, sLabel, ExtCtrls, sPanel, {, for, TScanner, } EnDiGrph, {, for, TDibGraphic, } EnDcxGr, EnPrint, {, for, TEnvisionPrintMode, TDibGraphicPrinter, } EnMisc, {, for, MinFloat, } EnTransf, {, for, TImageTransform, } EnTifGr, {, for, TTifGraphic, } EnBmpGr, {, for, TBitmapGraphic, } EnIcoGr, {, for, TIconGraphic, } EnWmfGr, {, for, TMetaFileGraphic, } EnReg, {, for, image, format, registration, } Spin; type TfrmScanDocs = class(TForm) Panel1: TsPanel; btnScan: TsBitBtn; btnOk: TsBitBtn; Image: TImageScrollBox; btnCancel: TsBitBtn; btnClear: TsBitBtn; Label1: TsLabel; PageNum: TsSpinEdit; Label2: TsLabel; PageCount: TsLabel; Label3: TsLabel; cbScale: TsComboBox; procedure btnScanClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnClearClick(Sender: TObject); procedure PageNumChange(Sender: TObject); procedure cbScaleChange(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormActivate(Sender: TObject); private { Private declarations } FScanner : TScanner; procedure OnAcquire(const DibHandle: THandle; const XDpi, YDpi: Word; const CallBackData: Integer); public { Public declarations } ms : TMemoryStream; end; implementation {$R *.DFM} type TpScanInfo = ^TScanInfo; TScanInfo = record MultiPage : Boolean; { supplementary info when MultiPage is True } Graphic : TTiffGraphic; Stream : TMemoryStream; ImageCount : LongInt; end; procedure TfrmScanDocs.btnScanClick(Sender: TObject); var ScanInfo : TScanInfo; begin if not FScanner.IsConfigured then begin ShowMessage('A scanner is not configured on your computer'); Exit; end; FillChar(ScanInfo, SizeOf(ScanInfo), 0); ScanInfo.Stream := ms; ScanInfo.MultiPage := true; ScanInfo.Graphic := TTiffGraphic.Create; Self.Enabled := False; try { to hide the user interface and set parameters FScanner.ShowUI := False; FScanner.RequestedXDpi := 200; FScanner.RequestedYDpi := 200; FScanner.RequestedImageFormat := ifTrueColor; } FScanner.Acquire(OnAcquire, LongInt(@ScanInfo)); finally Self.Enabled := True; // if ScanInfo.ImageCount > 0 then Image.LoadFromStream(ms,'TIF',PageNum.value); end; cbScaleChange(nil); if ScanInfo.ImageCount > 0 then begin btnOk.Enabled := true; btnScan.Enabled := false; btnClear.Enabled := true; end; end; procedure TfrmScanDocs.OnAcquire( const DibHandle : THandle; const XDpi : Word; const YDpi : Word; const CallBackData : LongInt ); var pScanInfo : TpScanInfo; begin pScanInfo := TpScanInfo(CallBackData); if pScanInfo^.MultiPage then begin pScanInfo^.Graphic.AssignFromDibHandle(DibHandle); pScanInfo^.Graphic.XDotsPerInch := XDpi; pScanInfo^.Graphic.YDotsPerInch := YDpi; pScanInfo^.Graphic.Compression := tcGroup4; pScanInfo^.Stream.Seek(0, soFromBeginning); if pScanInfo^.ImageCount = 0 then pScanInfo^.Graphic.SaveToStream(pScanInfo^.Stream) else pScanInfo^.Graphic.AppendToStream(pScanInfo^.Stream); { display some visual feedback by displaying each image scanned one by one. } Image.Graphic := pScanInfo^.Graphic; Application.ProcessMessages; Inc(pScanInfo^.ImageCount); end; end; procedure TfrmScanDocs.FormCreate(Sender: TObject); begin FScanner := TScanner.Create; ms := TMemoryStream.Create; end; procedure TfrmScanDocs.FormDestroy(Sender: TObject); begin ms.free; FScanner.Free; end; procedure TfrmScanDocs.btnClearClick(Sender: TObject); begin ms.Clear; Image.Clear; pageNum.MaxValue := 0; btnOk.Enabled := false; btnScan.Enabled := true; btnClear.Enabled := false; end; procedure TfrmScanDocs.PageNumChange(Sender: TObject); begin if PageNum.maxValue > 0 then begin ms.Seek(0, soFromBeginning); Image.LoadFromStream(ms,'TIF',PageNum.value); cbScaleChange(nil); end; end; procedure TfrmScanDocs.cbScaleChange(Sender: TObject); begin case cbScale.ItemIndex of 0 : image.ZoomPercent := 100; 1 : image.ZoomPercent := 50; 2 : image.ZoomPercent := 25; end; end; procedure TfrmScanDocs.FormShow(Sender: TObject); begin cbScaleChange(nil); end; procedure TfrmScanDocs.FormActivate(Sender: TObject); begin btnScan.Click; end; end.
unit nsPrimCachedEventsProcessor; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Data" // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/Data/nsPrimCachedEventsProcessor.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> F1 Базовые определения предметной области::LegalDomain::Data::Logging::TnsPrimCachedEventsProcessor // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface uses l3SimpleObject, LoggingInterfaces, InsDefferedEventList ; type TnsPrimCachedEventsProcessor = class(Tl3SimpleObject, InsCachedEventsProcessor) private // private fields f_List : TInsDefferedEventList; f_CacheWasWritten : TDateTime; private // private methods procedure Notify; protected // realized methods procedure RegisterEvent(const aEvent: InsDefferedEvent); procedure RequestWriteCache; protected // overridden protected methods procedure Cleanup; override; {* Функция очистки полей объекта. } protected // protected methods constructor Create; reintroduce; public // public methods class function Make: InsCachedEventsProcessor; reintroduce; end;//TnsPrimCachedEventsProcessor implementation uses DateUtils, SysUtils ; // start class TnsPrimCachedEventsProcessor procedure TnsPrimCachedEventsProcessor.Notify; //#UC START# *4B139F9D008C_4B139F5C025B_var* var l_IDX: Integer; //#UC END# *4B139F9D008C_4B139F5C025B_var* begin //#UC START# *4B139F9D008C_4B139F5C025B_impl* for l_IDX := 0 to f_List.Count - 1 do f_List[l_IDX].FireLog; //#UC END# *4B139F9D008C_4B139F5C025B_impl* end;//TnsPrimCachedEventsProcessor.Notify constructor TnsPrimCachedEventsProcessor.Create; //#UC START# *4B139FDA0182_4B139F5C025B_var* //#UC END# *4B139FDA0182_4B139F5C025B_var* begin //#UC START# *4B139FDA0182_4B139F5C025B_impl* inherited Create; f_List := TInsDefferedEventList.MakeSorted; //#UC END# *4B139FDA0182_4B139F5C025B_impl* end;//TnsPrimCachedEventsProcessor.Create class function TnsPrimCachedEventsProcessor.Make: InsCachedEventsProcessor; var l_Inst : TnsPrimCachedEventsProcessor; begin l_Inst := Create; try Result := l_Inst; finally l_Inst.Free; end;//try..finally end; procedure TnsPrimCachedEventsProcessor.RegisterEvent(const aEvent: InsDefferedEvent); //#UC START# *4B139E6B00C1_4B139F5C025B_var* //#UC END# *4B139E6B00C1_4B139F5C025B_var* begin //#UC START# *4B139E6B00C1_4B139F5C025B_impl* f_List.Add(aEvent); //#UC END# *4B139E6B00C1_4B139F5C025B_impl* end;//TnsPrimCachedEventsProcessor.RegisterEvent procedure TnsPrimCachedEventsProcessor.RequestWriteCache; //#UC START# *4B139E860009_4B139F5C025B_var* const c_emFreqWriteInHours = 1; //#UC END# *4B139E860009_4B139F5C025B_var* begin //#UC START# *4B139E860009_4B139F5C025B_impl* if HoursBetween(f_CacheWasWritten, Now) >= c_emFreqWriteInHours then begin Notify; f_CacheWasWritten := Now; end; //#UC END# *4B139E860009_4B139F5C025B_impl* end;//TnsPrimCachedEventsProcessor.RequestWriteCache procedure TnsPrimCachedEventsProcessor.Cleanup; //#UC START# *479731C50290_4B139F5C025B_var* //#UC END# *479731C50290_4B139F5C025B_var* begin //#UC START# *479731C50290_4B139F5C025B_impl* Notify; FreeAndNil(f_List); inherited Cleanup; //#UC END# *479731C50290_4B139F5C025B_impl* end;//TnsPrimCachedEventsProcessor.Cleanup end.
unit NLDNotifier; interface uses Windows, Controls, Messages, SysUtils, Classes, Forms, StdCtrls, ExtCtrls, Contnrs, Graphics; type TNLDNotifier = class; TNotifyForm = class; TNotifyLabel = class(TLabel) private FForm: TNotifyForm; protected procedure Click; override; property Form: TNotifyForm read FForm; constructor Create(AOwner: TNotifyForm); reintroduce; procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER; procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X: Integer; Y: Integer); override; end; { Formulier voor [TNLDNotifier] } TNotifyForm = class(TCustomForm) private FLabel: TNotifyLabel; FTimer: TTimer; FNotifier: TNLDNotifier; FURL: string; procedure TimerDone(Sender: TObject); function GetText: string; procedure SetText(const Value: string); procedure Remove; function GetTimeout: Integer; procedure SetTimeout(const Value: Integer); protected procedure CreateParams(var Params: TCreateParams); override; public property Text: string read GetText Write SetText; property URL: string read FURL write FURL; property Timeout: Integer read GetTimeout write SetTimeout; property Notifier: TNLDNotifier read FNotifier; constructor CreateNew(AOwner: TComponent; Dummy: Integer = 0); override; end; { Component om een een textbox by de traybar tekst(en) te tonen } TNLDNotifier = class(TComponent) private FFormList: TComponentList; FColor: TColor; FTimeout: Integer; FEnabled: Boolean; FOnClick: TNotifyEvent; FLinkColor: TColor; FTextColor: TColor; public procedure Execute(const NotifyText: string; URL: string = ''; Tag: integer = -1); constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure DeleteForm(Form: TNotifyForm); published property Color: TColor read FColor write FColor; property TextColor: TColor read FTextColor write FTextColor; property LinkColor: TColor read FLinkColor write FLinkColor; property Timeout: Integer read FTimeout write FTimeout; property Enabled: Boolean read FEnabled write FEnabled; property OnClick: TNotifyEvent read FOnClick write FOnClick; end; procedure Register; implementation uses ShellAPI; const FormHeight = 20; FormWidth = 400; procedure Register; begin RegisterComponents('NLDelphi', [TNLDNotifier]); end; { TNLDNotifier } constructor TNLDNotifier.Create(AOwner: TComponent); begin inherited; FFormList := TComponentList.Create; FFormList.OwnsObjects := False; end; { Formulier wordt uit de lijst gehaald en vrijgegeven } procedure TNLDNotifier.DeleteForm(Form: TNotifyForm); begin FFormList.Remove(Form); { Moet in dit geval een release zijn omdat free regelmatig AV's abstract errors geeft } Form.Release; end; destructor TNLDNotifier.Destroy; begin FFormList.Free; inherited; end; { Nieuw formulier wordt aangemaakt en onder eventueel eerdere formulieren geplaatst } procedure TNLDNotifier.Execute(const NotifyText: string; URL: string = ''; Tag: Integer = -1); var Form: TNotifyForm; i: Integer; begin if not FEnabled then Exit; { De overige forms omhoogschuiven } for i := 0 to FFormList.Count -1 do TNotifyForm(FFormList[i]).Top := TNotifyForm(FFormList[i]).Top - FormHeight; Form := TNotifyForm.CreateNew(Self); Form.URL := URL; Form.Tag := Tag; FFormList.Add(Form); Form.Color := FColor; Form.Text := NotifyText; Form.Timeout := FTimeout; ShowWindow(Form.Handle, SW_SHOWNOACTIVATE); Form.Visible := True; Form.Update; end; { TNotifyForm } { Wordt aangeroepen door de timer. Roept FNotifier.[DeleteForm] aan. } procedure TNotifyForm.TimerDone(Sender: TObject); begin Remove; end; procedure TNotifyForm.Remove; begin FNotifier.DeleteForm(Self); end; constructor TNotifyForm.CreateNew(AOwner: TComponent; Dummy: Integer); var r: TRect; begin inherited; FNotifier := TNLDNotifier(AOwner); FormStyle := fsStayOnTop; Color := clInfoBk; Height := FormHeight; Width := FormWidth; BorderIcons := []; BorderStyle := bsNone; { Desktopomvang ophalen } SystemParametersInfo(SPI_GETWORKAREA, 0, @r, 0); Left := r.Right - Width; Top := r.Bottom - Height; FTimer := TTimer.Create(self); FTimer.Interval := 0; FTimer.Enabled := False; FTimer.OnTimer := TimerDone; FLabel := TNotifyLabel.Create(self); FLabel.Parent := self; FLabel.Left := 3; FLabel.Top := 3; FLabel.Font.Color := Notifier.FTextColor; end; procedure TNotifyForm.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); Params.WndParent := GetDesktopWindow; Params.Style := Params.Style and not WS_CAPTION or WS_POPUP; Params.ExStyle := Params.ExStyle or WS_EX_TOOLWINDOW; { TODO : Testen of alles nu goed gaat Params.ExStyle := Params.ExStyle or WS_EX_TOOLWINDOW or WS_EX_NOACTIVATE; maar dat gaf DrWatson meldingen op NT } end; function TNotifyForm.GetText: string; begin Result := FLabel.Caption; end; procedure TNotifyForm.SetText(const Value: string); begin FLabel.Caption := Value; FLabel.ShowHint := True; FLabel.Hint := Value; end; function TNotifyForm.GetTimeout: Integer; begin Result := FTimer.Interval div 1000; end; procedure TNotifyForm.SetTimeout(const Value: Integer); begin FTimer.Interval := Value * 1000; FTimer.Enabled := FTimer.Interval > 0; end; { TNotifyLabel } procedure TNotifyLabel.Click; begin inherited; Form.FTimer.Enabled := False; if Form.URL <> '' then ShellExecute(0, 'open', PChar(Form.URL), nil, nil, SW_SHOW); if Assigned(Form.Notifier.OnClick) then Form.Notifier.OnClick(Form); Form.Remove; end; procedure TNotifyLabel.CMMouseEnter(var Message: TMessage); begin Font.Color := Form.Notifier.LinkColor; Font.Style := Font.Style + [fsUnderline]; end; procedure TNotifyLabel.CMMouseLeave(var Message: TMessage); begin Font.Color := Form.Notifier.TextColor; Font.Style := Font.Style - [fsUnderline]; end; constructor TNotifyLabel.Create(AOwner: TNotifyForm); begin inherited Create(AOwner); FForm := AOwner; Cursor := crHandPoint; end; procedure TNotifyLabel.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin inherited; if Button = mbRight then Form.Remove; end; end.
{ DBAExplorer - Oracle Admin Management Tool Copyright (C) 2008 Alpaslan KILICKAYA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit frmDBMSOutput; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, QDialogs, dxBar, dxBarExtItems, cxControls, cxContainer, cxEdit, cxTextEdit, cxMemo, cxRichEdit, ExtCtrls, DB, MemDS, DBAccess, Ora, GenelDM, OraBarConn, cxGraphics, dxStatusBar; type TDBMSOutputFrm = class(TForm) dxBarManager1: TdxBarManager; btnTurnOutputOn: TdxBarButton; btnClearWindows: TdxBarButton; btnSetBufferSize: TdxBarButton; btnSaveToFile: TdxBarButton; lblSeconds: TdxBarStatic; btnFrequency: TdxBarSpinEdit; tDbMS_output: TTimer; redtDBMS_output: TcxRichEdit; sdDBMS: TSaveDialog; spDbms_output: TOraStoredProc; statusBar: TdxStatusBar; btnClose: TdxBarButton; procedure btnTurnOutputOnClick(Sender: TObject); procedure btnClearWindowsClick(Sender: TObject); procedure btnSetBufferSizeClick(Sender: TObject); procedure btnSaveToFileClick(Sender: TObject); procedure tDbMS_outputTimer(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnCloseClick(Sender: TObject); private { Private declarations } DBMS_OUTPUT_BufferSize: integer; public { Public declarations } procedure Init(ABarConnection : TBarConnection); end; var DBMSOutputFrm: TDBMSOutputFrm; implementation {$R *.dfm} uses frmMain, VisualOptions, DBQuery; procedure TDBMSOutputFrm.Init(ABarConnection : TBarConnection); begin DMGenel.ChangeLanguage(self); ChangeVisualGUI(self); DBMS_OUTPUT_BufferSize := 20000; spDbms_output.Session := ABarConnection.Session; Caption := ABarConnection.Session.Server+'/'+ABarConnection.Session.UserName+' - '+'DBMS Output'; statusBar.Panels[0].Text := ABarConnection.Session.Server+'/'+ABarConnection.Session.UserName; MainFrm.dxBarListWindows.Items.AddObject(Caption, Self); end; procedure TDBMSOutputFrm.btnTurnOutputOnClick(Sender: TObject); begin if btnTurnOutputOn.Down then begin ExecSQL('Begin ' +' DBMS_OUTPUT.enable('+IntToStr(DBMS_OUTPUT_BufferSize)+'); ' +'end; ', '', spDbms_output.Session); tDbMS_output.Interval := (btnFrequency.IntValue * 1000); tDbMS_output.Enabled := true; end else begin ExecSQL('Begin ' +' DBMS_OUTPUT.disable; ' +'end; ', '', spDbms_output.Session); tDbMS_output.Enabled := false; end; end; procedure TDBMSOutputFrm.btnClearWindowsClick(Sender: TObject); begin redtDBMS_output.Clear; end; procedure TDBMSOutputFrm.btnSetBufferSizeClick(Sender: TObject); begin DBMS_OUTPUT_BufferSize := InputBox('Set DBMS Output Buffer', 'Size', DBMS_OUTPUT_BufferSize, 1, 1000000); end; procedure TDBMSOutputFrm.btnSaveToFileClick(Sender: TObject); begin if sdDBMS.Execute then redtDBMS_output.Lines.SaveToFile(sdDBMS.FileName); end; procedure TDBMSOutputFrm.tDbMS_outputTimer(Sender: TObject); begin spDbms_output.ExecProc; if spDbms_output.Params[1].AsString = '0' then redtDBMS_output.Lines.Add(spDbms_output.Params[0].AsString); end; procedure TDBMSOutputFrm.FormClose(Sender: TObject; var Action: TCloseAction); begin spDbms_output.close; with MainFrm.dxBarListWindows.Items do Delete(IndexOfObject(Self)); action := caFree; end; procedure TDBMSOutputFrm.btnCloseClick(Sender: TObject); begin ExecSQL('Begin ' +' DBMS_OUTPUT.disable; ' +'end; ', '', spDbms_output.Session); close; end; end.
{$IFDEF WIN32} {$H+} {$ENDIF} unit csProp; { //-------------------------------------------------------------------- // Property access routines. // Contributed to public domain by Ken Revak Catalyst Systems. // // some minor modifications and 2 additional routines by Timo Hartmann //-------------------------------------------------------------------- } interface uses Classes, Graphics; function PropertyExists(Component : TComponent; const PropName : string) : boolean; procedure SetPointerProperty(Component : TComponent;const PropName : String; ptr : Pointer); function GetPointerProperty(Component : TComponent;const PropName :String) : Pointer; procedure SetBooleanProperty(Component : TComponent;const PropName : String; B : Boolean); function GetBooleanProperty(Component : TComponent;const PropName :String) : Boolean; procedure SetStringProperty(Component : TComponent;const PropName : String; Value : String); function GetStringProperty(Component : TComponent;const PropName :String) : string; procedure SetMethodProperty(Component : TComponent;const PropName : string; Code, Data : Pointer); function GetFontProperty(Component : TComponent) : TFont; function GetIntegerProperty(Component : TComponent; const PropName :String) : Longint; procedure SetIntegerProperty(Component : TComponent; const PropName : String; L: Longint); function GetFloatProperty(Component : TComponent; const PropName :String) : Extended; procedure SetFloatProperty(Component : TComponent; const PropName : String; Value: Extended); implementation uses TypInfo, SysUtils; function PropertyExists(Component : TComponent; const PropName : string) : boolean; begin Result:=GetPropInfo(Component.ClassInfo, PropName) <> nil; end; procedure SetPointerProperty(Component : TComponent; const PropName : String; ptr : Pointer); var ptrPropInfo : PPropInfo; begin ptrPropInfo := GetPropInfo(Component.ClassInfo, PropName); if ptrPropInfo <> nil then SetOrdProp(Component, ptrPropInfo, LongInt(ptr)); end; function GetPointerProperty(Component : TComponent; const PropName :String) : Pointer; var ptrPropInfo : PPropInfo; begin ptrPropInfo := GetPropInfo(Component.ClassInfo, PropName); if ptrPropInfo = nil then Result := nil else Result := Pointer(GetOrdProp(Component, ptrPropInfo)); end; procedure SetBooleanProperty(Component : TComponent; const PropName : String; B : Boolean); var ptrPropInfo : PPropInfo; begin ptrPropInfo := GetPropInfo(Component.ClassInfo, PropName); if ptrPropInfo <> nil then SetOrdProp(Component, ptrPropInfo, LongInt(B)); end; function GetBooleanProperty(Component : TComponent; const PropName :String) : Boolean; var ptrPropInfo : PPropInfo; begin ptrPropInfo := GetPropInfo(Component.ClassInfo, PropName); if ptrPropInfo = nil then Result := False else Result := GetOrdProp(Component, ptrPropInfo) = 1; end; procedure SetIntegerProperty(Component : TComponent; const PropName : String; L: Longint); var ptrPropInfo : PPropInfo; begin ptrPropInfo := GetPropInfo(Component.ClassInfo, PropName); if ptrPropInfo <> nil then SetOrdProp(Component, ptrPropInfo, L); end; function GetIntegerProperty(Component : TComponent; const PropName :String) : Longint; var ptrPropInfo : PPropInfo; begin ptrPropInfo := GetPropInfo(Component.ClassInfo, PropName); if ptrPropInfo = nil then Result := 0 else Result := GetOrdProp(Component, ptrPropInfo); end; procedure SetFloatProperty(Component : TComponent; const PropName : String; Value : Extended); var ptrPropInfo : PPropInfo; begin ptrPropInfo := GetPropInfo(Component.ClassInfo, PropName); if ptrPropInfo <> nil then SetFloatProp(Component, ptrPropInfo, Value); end; function GetFloatProperty(Component : TComponent;const PropName :String) : Extended; var ptrPropInfo : PPropInfo; begin ptrPropInfo := GetPropInfo(Component.ClassInfo, PropName); if ptrPropInfo = nil then Result := 0 else Result := GetFloatProp(Component, ptrPropInfo); end; procedure SetStringProperty(Component : TComponent; const PropName : String; Value : string); var ptrPropInfo : PPropInfo; begin ptrPropInfo := GetPropInfo(Component.ClassInfo, PropName); if ptrPropInfo <> nil then SetStrProp(Component, ptrPropInfo, Value); end; function GetStringProperty(Component : TComponent;const PropName :String) : string; var ptrPropInfo : PPropInfo; begin ptrPropInfo := GetPropInfo(Component.ClassInfo, PropName); if ptrPropInfo = nil then Result := '' else Result := GetStrProp(Component, ptrPropInfo); end; procedure SetMethodProperty(Component : TComponent;const PropName : string; Code, Data : Pointer); var Method : TMethod; ptrPropInfo : PPropInfo; begin ptrPropInfo := GetPropInfo(Component.ClassInfo, PropName); if ptrPropInfo <> nil then begin Method.Code := Code; Method.Data := Data; SetMethodProp(Component, ptrPropInfo, Method); end; end; function GetFontProperty(Component : TComponent) : TFont; begin Result := TFont(GetPointerProperty(Component, 'Font')); end; end.
unit Figure; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Graphics, Transformation, Math, ExtCtrls; type { TFigure } TFigure = class(TPersistent) private FPenColor: TColor; FMinPoint, FMaxPoint: MegaPoint; FSelected: boolean; public FWorldPoints: array of MegaPoint; property Minpoint: MegaPoint read FMinPoint; property Maxpoint: MegaPoint read FMaxPoint; procedure EditPoint (Pt: MegaPoint; Ind: integer); virtual; abstract; procedure CreateAncor (ACanvas: TCanvas); virtual; procedure MovingFrame (Pt1, Pt2, Pt3: MegaPoint; ind: integer); virtual; property Selected: boolean read FSelected write FSelected; procedure Draw (ACanvas: TCanvas); virtual; function Check (X, Y: double): TAnchorMoving; virtual; published property PenColor: TColor read FPenColor write FPenColor; end; { TSprey } TSprey = class(TFigure) private FFreq, FSize, FFirstElem: integer; FTimes: string; published property FirstElem: integer read FFirstElem write FFirstElem; property Size: integer read FSize write FSize; property Freq: integer read FFreq write FFreq; property Times: string read FTimes write FTimes; procedure Draw (ACanvas: TCanvas); override; procedure EditPoint (Pt: MegaPoint; Ind: integer); override; procedure CreateAncor (ACanvas: TCanvas); override; function Check (X, Y: double): TAnchorMoving; override; end; TGeometryFigure = class(TFigure) private FPenStyle, FPenWidth: integer; public procedure Draw (ACanvas: TCanvas); override; procedure EditPoint (Pt: MegaPoint; Ind: integer); override; published property PenStyle: integer read FPenStyle write FPenStyle; property PenWidth: integer read FPenWidth write FPenWidth; end; TFigureClass = class of TFigure; TFillFigure = class(TGeometryFigure) private FBrushColor: TColor; FBrushStyle: integer; public procedure Draw (ACanvas: TCanvas); override; procedure EditPoint (Pt: MegaPoint; Ind: integer); override; published property BrushColor: TColor read FBrushColor write FBrushColor; property BrushStyle: integer read FBrushStyle write FBrushStyle; end; TText = class(TFigure) private FTexts: string; FTextStyle: TFontStyles; FTextSize: integer; public RectPoints: array of TPoint; TTextSyles: TTextStyle; TextSeting: string; procedure Draw (ACanvas: TCanvas); override; procedure EditPoint (Pt: MegaPoint; Ind: integer); override; published property Texts: string read FTexts write FTexts; property TextStyle: TFontStyles read FTextStyle write FTextStyle; property TextSize: integer read FTextSize write FTextSize; end; TRoundRectangl = class(TFillFigure) private FRoundX, FRoundY: integer; public procedure Draw (ACanvas: TCanvas); override; published property RoundX: integer read FRoundX write FRoundX; property RoundY: integer read FRoundY write FRoundY; end; TEllipse = class(TFillFigure) public procedure Draw (ACanvas: TCanvas); override; procedure EditPoint (Pt: MegaPoint; Ind: integer); override; end; TPolygon = class(TFillFigure) public procedure Draw (ACanvas: TCanvas); override; end; TRegularPolygon = class(TFillFigure) private FAngles: integer; public procedure Draw (ACanvas: TCanvas); override; procedure EditPoint (Pt: MegaPoint; Ind: integer); override; procedure CreateAncor (ACanvas: TCanvas); override; function Check (X, Y: double): TAnchorMoving; override; published property Tops: integer read FAngles write FAngles; end; TRectangl = class(TFillFigure) procedure Draw (ACanvas: TCanvas); override; procedure EditPoint (Pt: MegaPoint; Ind: integer); override; end; TPencil = class(TGeometryFigure) public procedure Draw (ACanvas: TCanvas) override; end; function CreateRightFigure (Point1, Point2: MegaPoint; Angels: integer): PointArray; var ArrayFigureClass: array of TFigureClass; Figures: array of TFigure; Maxp,Minp : TPoint; implementation function CreateRightFigure (Point1, Point2: MegaPoint; Angels: integer): PointArray; var Center: TPoint; i: integer; x0, y0, r, angle: double; begin SetLength (Result, Angels); Center := WorldToScreen (Point1); x0 := WorldToScreen (Point2).X - Center.X; y0 := WorldToScreen (Point2).Y - Center.Y; angle := arctan2(y0, x0); r := sqrt (x0 * x0 + y0 * y0); if r = 0 then Exit; angle := arccos (x0 / r); if y0 < 0 then angle *= -1; for i := 0 to Angels - 1 do begin angle += 2 * pi / Angels; Result[i].X := Round (r * cos (angle) + Center.X); Result[i].Y := Round (r * sin (angle) + Center.Y); MaxMin (ScreenToWorld (Result[i])); end; Minp:=Result[0]; Maxp:=Result[0]; for i :=1 to High(Result) do begin if Maxp.x < Result[i].x then Maxp.x := Result[i].x; if Maxp.y < Result[i].y then Maxp.y := Result[i].y; if Minp.x > Result[i].x then Minp.x := Result[i].x; if Minp.y > Result[i].y then Minp.y := Result[i].y; end; end; { TSprey } function MyRandom (Elem : integer) : Integer; var r,a,b : Integer; begin r := 714025; a := 4096; b := 150889; Result := ((Elem * a) + b) mod r; end; procedure TSprey.Draw (ACanvas: TCanvas); var i, Digit, x, y, Angle, Time: integer; Counter: double; TimesStr: string; begin FMinpoint := PointW (FWorldPoints[0].X - Size, FWorldPoints[0].Y - Size); FMaxpoint := PointW (FWorldPoints[0].X + Size, FWorldPoints[0].Y + Size); for i := 1 to High (FWorldPoints) do begin if (FWorldPoints[i].x + FSize) > FMaxPoint.X then FMaxPoint.X := FWorldPoints[i].x + FSize; if (FWorldPoints[i].x - FSize) < FMinPoint.X then FMinPoint.X := FWorldPoints[i].x - FSize; if (FWorldPoints[i].y + FSize) > FMaxPoint.y then FMaxPoint.y := FWorldPoints[i].y + FSize; if (FWorldPoints[i].y - FSize) < FMinPoint.y then FMinPoint.y := FWorldPoints[i].y - FSize; end; Counter := 1; Digit := FirstElem; Angle := 1; TimesStr := Times; for i := 0 to High (FWorldPoints) do begin TimesStr := Copy (TimesStr, Pos (':', TimesStr) + 1, Length (TimesStr) - Pos (':', TimesStr)); Time := StrToInt (Copy (TimesStr, 1, Pos (';', TimesStr) - 1)); while Counter <= Time do begin Digit := MyRandom(Digit); Angle := MyRandom(Angle); x := round ((Digit mod Size) * cos (Angle)) + WorldToScreen (FWorldPoints[i]).X; y := round ((Digit mod Size) * sin (Angle)) + WorldToScreen (FWorldPoints[i]).Y; ACanvas.Pixels[x,y] := FPenColor; Counter += 10 / Freq; end; end; end; procedure TSprey.EditPoint (Pt: MegaPoint; Ind: integer); begin end; procedure TSprey.CreateAncor (ACanvas: TCanvas); begin inherited CreateAncor (ACanvas); end; function TSprey.Check (X, Y: double): TAnchorMoving; begin Result.Selected := False; end; // Classes Figures procedure TFigure.Draw (ACanvas: TCanvas); var i: integer; begin FMinpoint := FWorldPoints[0]; FMaxpoint := FWorldPoints[0]; for i := 1 to High (FWorldPoints) do begin if (FWorldPoints[i].x) > FMaxPoint.X then FMaxPoint.X := FWorldPoints[i].x; if (FWorldPoints[i].x) < FMinPoint.X then FMinPoint.X := FWorldPoints[i].x; if (FWorldPoints[i].y) > FMaxPoint.y then FMaxPoint.y := FWorldPoints[i].y; if (FWorldPoints[i].y) < FMinPoint.y then FMinPoint.y := FWorldPoints[i].y; end; end; function TFigure.Check (X, Y: double): TAnchorMoving; var i: integer; begin for i := 0 to High (FWorldPoints) do begin Result.Selected := (Abs(WorldToScreenX (FWorldPoints[i].X) - WorldToScreenX (X)) < AnchorsSize) and (Abs(WorldToScreenY (FWorldPoints[i].Y) - WorldToScreenY (Y)) < AnchorsSize); if Result.Selected then begin Result.Action := @EditPoint; Result.ind := i; Break; end; end; end; procedure TFigure.CreateAncor (ACanvas: TCanvas); var i: integer; begin for i := 0 to High (FWorldPoints) do begin ACanvas.Brush.Style := bsClear; ACanvas.Pen.Style := psSolid; ACanvas.Pen.Color := $ff4400; ACanvas.Pen.Width := 1; ACanvas.Rectangle ( WorldToScreenX (FWorldPoints[i].X) - AnchorsSize, WorldToScreenY (FWorldPoints[i].Y) - AnchorsSize, WorldToScreenX (FWorldPoints[i].X) + AnchorsSize, WorldToScreenY (FWorldPoints[i].Y) + AnchorsSize); end; end; procedure TFigure.MovingFrame (Pt1, Pt2, Pt3: MegaPoint; ind: integer); var cofx, cofy: double; i,inset: integer; begin inset:=Round(1/scale); case ind of 1: begin if ((Pt2.X - Pt3.X) <= inset) or ((Pt2.y - Pt3.y) <= inset) or ((Pt2.X - Pt1.X)=0) or ((Pt2.y - Pt1.y)=0) then Exit; cofx := (Pt2.X - Pt3.X) / (Pt2.X - Pt1.X); cofy := (Pt2.y - Pt3.y) / (Pt2.y - Pt1.y); for i := 0 to High (FWorldPoints) do begin FWorldPoints[i].x := Pt2.X - (Pt2.X - FWorldPoints[i].x) * cofx; FWorldPoints[i].y := Pt2.y - (Pt2.y - FWorldPoints[i].y) * cofy; end; end; 2: begin if ((Pt3.X - Pt1.X) <= inset) or (Pt2.y - Pt3.y <= inset) or ((Pt2.X - Pt1.X)=0) or ((Pt2.y - Pt1.y)=0) then Exit; cofx := (Pt3.X - Pt1.X) / (Pt2.X - Pt1.X); cofy := (Pt2.y - Pt3.y) / (Pt2.y - Pt1.y); for i := 0 to High (FWorldPoints) do begin FWorldPoints[i].x := Pt1.X + (FWorldPoints[i].x - Pt1.X) * cofx; FWorldPoints[i].y := Pt2.y - (Pt2.y - FWorldPoints[i].y) * cofy; end; end; 3: begin if (Pt3.X - Pt1.X <= inset) or (Pt3.Y - Pt1.Y <= inset) or ((Pt2.X - Pt1.X)=0) or ((Pt2.y - Pt1.y)=0) then Exit; cofy := (Pt3.Y - Pt1.Y) / (Pt2.Y - Pt1.Y); cofx := (Pt3.X - Pt1.X) / (Pt2.X - Pt1.X); for i := 0 to High (FWorldPoints) do begin FWorldPoints[i].x := Pt1.X + (FWorldPoints[i].x - Pt1.X) * cofx; FWorldPoints[i].y := Pt1.y + (FWorldPoints[i].y - Pt1.y) * cofy; end; end; 4: begin if (Pt2.X - Pt3.X <= inset) or (Pt3.Y - Pt1.Y <= inset) or ((Pt2.X - Pt1.X)=0) or ((Pt2.y - Pt1.y)=0) then Exit; cofx := (Pt2.X - Pt3.X) / (Pt2.X - Pt1.X); cofy := (Pt3.Y - Pt1.Y) / (Pt2.Y - Pt1.Y); for i := 0 to High (FWorldPoints) do begin FWorldPoints[i].x := Pt2.X - (Pt2.X - FWorldPoints[i].x) * cofx; FWorldPoints[i].y := Pt1.y + (FWorldPoints[i].y - Pt1.y) * cofy; end; end; end; end; //ClassGeometryFigure procedure TGeometryFigure.Draw (ACanvas: TCanvas); begin inherited; ACanvas.Pen.Color := PenColor; ACanvas.Pen.Width := PenWidth; ACanvas.Pen.Style := TPenStyle (PenStyle); end; procedure TGeometryFigure.EditPoint (Pt: MegaPoint; Ind: integer); begin FWorldPoints[Ind] := Pt; end; //Class FillFigure procedure TFillFigure.Draw (ACanvas: TCanvas); begin inherited; ACanvas.Brush.Color := BrushColor; ACanvas.Brush.Style := TBrushStyle (BrushStyle); end; procedure TFillFigure.EditPoint (Pt: MegaPoint; Ind: integer); begin FWorldPoints[Ind] := Pt; end; //Class Pensil procedure TPencil.Draw (ACanvas: TCanvas); begin inherited; //DestroyAncor (); ACanvas.PolyLine (WorldToScreen (FWorldPoints)); if Selected then CreateAncor (ACanvas); end; // Class Text procedure TText.Draw (ACanvas: TCanvas); var FScreenPoints: PointArray; begin inherited; SetLength (FScreenPoints, Length (FWorldPoints)); FScreenPoints := WorldToScreen (FWorldPoints); ACanvas.Font.Size := round (TextSize * scale); ACanvas.Font.Color := FPenColor; ACanvas.Font.Style := TextStyle; TTextSyles.Wordbreak := True; TTextSyles.Clipping := True; TTextSyles.SingleLine := False; ACanvas.Brush.Style := bsClear; ACanvas.Pen.Style := psDash; ACanvas.Pen.Width := 1; ACanvas.Pen.Color := clBlack; ACanvas.Font.Name := TextSeting; if not DownPress then SetLength (RectPoints, 0); if Length (RectPoints) <> 0 then ACanvas.Rectangle ( RectPoints[0].X, RectPoints[0].Y, RectPoints[1].X, RectPoints[1].Y); ACanvas.TextRect (Rect ( min (FScreenPoints[0].x, FScreenPoints[1].x), min (FScreenPoints[0].y, FScreenPoints[1].y), max (FScreenPoints[0].x, FScreenPoints[1].x), max (FScreenPoints[0].y, FScreenPoints[1].y)), min (FScreenPoints[0].x, FScreenPoints[1].x), min (FScreenPoints[0].y, FScreenPoints[1].y), InNormText (Texts), TTextSyles); if Selected then begin with ACanvas do begin Pen.Color := clBlack; Pen.Style := psDash; Pen.Width := 1; Brush.Style := bsClear; end; CreateAncor (ACanvas); end; end; procedure TText.EditPoint (Pt: MegaPoint; Ind: integer); begin FWorldPoints[Ind] := Pt; end; //ClassEllips procedure TEllipse.Draw (ACanvas: TCanvas); begin inherited; ACanvas.Ellipse ( WorldToScreen (FWorldPoints[0]).x, WorldToScreen (FWorldPoints[0]).y, WorldToScreen (FWorldPoints[1]).x, WorldToScreen (FWorldPoints[1]).y); if Selected then CreateAncor (ACanvas); end; procedure TEllipse.EditPoint (Pt: MegaPoint; Ind: integer); begin FWorldPoints[Ind] := Pt; end; //RoundRectangl procedure TRoundRectangl.Draw (ACanvas: TCanvas); begin inherited; ACanvas.RoundRect ( WorldToScreen (FWorldPoints[0]).x, WorldToScreen (FWorldPoints[0]).y, WorldToScreen (FWorldPoints[1]).x, WorldToScreen (FWorldPoints[1]).y, RoundX, RoundY); if Selected then CreateAncor (ACanvas); end; // TRectangl procedure TRectangl.Draw (ACanvas: TCanvas); begin inherited; ACanvas.Polygon (WorldToScreen (FWorldPoints)); if Selected then CreateAncor (ACanvas); end; procedure TRectangl.EditPoint (Pt: MegaPoint; Ind: integer); begin case ind of 0: begin FWorldPoints[0] := Pt; FWorldPoints[1].Y := Pt.Y; FWorldPoints[3].X := Pt.X; end; 1: begin FWorldPoints[1] := Pt; FWorldPoints[0].Y := Pt.Y; FWorldPoints[2].X := Pt.X; end; 2: begin FWorldPoints[2] := Pt; FWorldPoints[3].Y := Pt.Y; FWorldPoints[1].X := Pt.X; end; 3: begin FWorldPoints[3] := Pt; FWorldPoints[2].Y := Pt.Y; FWorldPoints[0].X := Pt.X; end; end; end; //TRegularPolygon procedure TRegularPolygon.Draw (Acanvas: TCanvas); var Points: PointArray; x0,y0,r : Double; //WPoints: MegaArray; begin inherited; SetLength (Points, Tops); Points := CreateRightFigure (FWorldPoints[0], FWorldPoints[1], Tops); FMinPoint:=ScreenToWorld(minp); FMaxPoint:=ScreenToWorld(maxp); ACanvas.Polygon (Points); if Selected then CreateAncor (Acanvas); end; function TRegularPolygon.Check (X, Y: double): TAnchorMoving; var i: integer; pt: TPoint; begin pt := WorldToScreen (PointW (X, Y)); for i := 0 to 1 do begin if (pt.x < WorldToScreenX (FWorldPoints[i].X) + AnchorsSize) and (pt.x > WorldToScreenX (FWorldPoints[i].X) - AnchorsSize) and (pt.y < WorldToScreenY (FWorldPoints[i].Y) + AnchorsSize) and (pt.y > WorldToScreenY (FWorldPoints[i].Y) - AnchorsSize) then begin Result.Selected := True; Result.Action := @EditPoint; Result.ind := i; Break; end else Result.Selected := False; end; end; procedure TRegularPolygon.EditPoint (Pt: MegaPoint; Ind: integer); begin FWorldPoints[Ind] := Pt; end; procedure TRegularPolygon.CreateAncor (ACanvas: TCanvas); var i: integer; begin for i := 0 to 1 do begin ACanvas.Brush.Style := bsClear; ACanvas.Pen.Style := psSolid; ACanvas.Pen.Color := $ff4400; ACanvas.Pen.Width := 1; ACanvas.Rectangle ( WorldToScreenX (FWorldPoints[i].X) - AnchorsSize, WorldToScreenY (FWorldPoints[i].Y) - AnchorsSize, WorldToScreenX (FWorldPoints[i].X) + AnchorsSize, WorldToScreenY (FWorldPoints[i].Y) + AnchorsSize); end; end; //ClassPoligone procedure TPolygon.Draw (ACanvas: TCanvas); begin inherited; ACanvas.Polygon (WorldToScreen (FWorldPoints)); if Selected then CreateAncor (ACanvas); end; procedure RegistrateFigure (AClass: TFigureClass); begin SetLength (ArrayFigureClass, Length (ArrayFigureClass) + 1); ArrayFigureClass[High (ArrayFigureClass)] := AClass; RegisterClass (AClass); end; initialization RegistrateFigure (TSprey); RegistrateFigure (TRegularPolygon); RegistrateFigure (TRectangl); RegistrateFigure (TRoundRectangl); RegistrateFigure (TPencil); RegistrateFigure (TEllipse); RegistrateFigure (TPolygon); RegistrateFigure (TText); end.
unit testfile_Complex; interface uses uDataObject, Data.dbxJsonReflect, System.SysUtils, System.Classes; type // COMPLEX OBJECT - Contains TStringList as property. TMyComplexClass = class(TMyClass) private aStringList: TStringList; public class procedure RegisterConverters(aMar: TJsonMarshal); override; class procedure RegisterReverters(aUnMar: TJSONUnMarshal); override; constructor Create; override; destructor Destroy; override; procedure Assign(aSource: TMyClass); override; procedure SetupData; override; property pStringList: TStringList read aStringList write aStringList; end; TMyComplexClassList<T: TMyComplexClass, constructor> = class(TMyClassList<T>) private public constructor Create; override; procedure Assign(aSource: TMyClassList<T>); override; end; var initComplexList: TMyComplexClassList<TMyComplexClass>; implementation { TMyComplexClass } procedure TMyComplexClass.Assign(aSource: TMyClass); var aStr: string; aCC: TMyComplexClass; begin inherited Assign(aSource); aStringList.Clear; aCC := aSource as TMyComplexClass; for aStr in aCC.aStringList do aStringList.Add(aStr); end; constructor TMyComplexClass.Create; begin inherited Create; aStringList := TStringList.Create; end; destructor TMyComplexClass.Destroy; begin aStringList.Free; inherited; end; class procedure TMyComplexClass.RegisterConverters(aMar: TJsonMarshal); begin inherited; // register class specifik converters here. aMar.RegisterConverter(TStringList, function(Data: TObject): TListOfStrings var i, Count: integer; begin Count := TStringList(Data).Count; SetLength(Result, Count); for i := 0 to Count - 1 do Result[i] := TStringList(Data)[i]; end); end; class procedure TMyComplexClass.RegisterReverters(aUnMar: TJSONUnMarshal); begin inherited; // register class specific reverters here aUnMar.RegisterReverter(TStringList, function(Data: TListOfStrings): TObject var StrList: TStringList; Str: string; begin StrList := TStringList.Create; for Str in Data do StrList.Add(Str); Result := StrList; end); end; procedure TMyComplexClass.SetupData; var i: integer; begin inherited SetupData; for i := 0 to pInteger do aStringList.Add(IntToStr(pInteger) + ' - Text - ' + IntToStr(i)); end; { TMyComplexClassList<T> } procedure TMyComplexClassList<T>.Assign(aSource: TMyClassList<T>); begin inherited Assign(aSource); end; constructor TMyComplexClassList<T>.Create; begin inherited Create; end; initialization initComplexList := TMyComplexClassList<TMyComplexClass>.Create; finalization initComplexList.Free; end.
unit UFactory; interface uses System.SysUtils, Data.DBXJSON, UDaoConfiguracaoClient, UDaoPermissaoTelaClient, UDaoImagemClient, UDaoFormularioClient, UDaoUsuario, UDaoGrupoPessoa, UDaoImagemDSClient, UDaoImgCli, UDaoCliente, UDaoPadrao; type IFactory = interface ['{584046D2-0333-40A1-9318-237B20BF5D03}'] function Config: TDaoConfiguracaoClient; function PermissaoTela: TDaoPermissaoTelaClient; function ImagemRest: TDaoImagemClient; function Formulario: TDaoFormularioClient; function Usuario: TDaoUsuarioClient; function GrupoPessoa: TDaoGrupoPessoaClient; function ImagemDS: TdaoImagemDSClient; function ImgCli: TdaoImgCliClient; function Cliente: TdaoClienteClient; function ClassDaoPadrao: TDaoPadrao; end; TFactoryClas = class(TInterfacedObject, IFactory) private FConfig: TDaoConfiguracaoClient; FPermissaoTela: TDaoPermissaoTelaClient; FImagemRest: TDaoImagemClient; FFormulario: TDaoFormularioClient; FUsuario: TDaoUsuarioClient; FGrupoPessoa: TDaoGrupoPessoaClient; FImagemDS: TdaoImagemDSClient; FImgCli: TdaoImgCliClient; FCliente: TdaoClienteClient; FClassDaoPadrao: TDaoPadrao; public class function New: IFactory; destructor Destroy; override; function Config: TDaoConfiguracaoClient; function PermissaoTela: TDaoPermissaoTelaClient; function ImagemRest: TDaoImagemClient; function Formulario: TDaoFormularioClient; function Usuario: TDaoUsuarioClient; function GrupoPessoa: TDaoGrupoPessoaClient; function ImagemDS: TdaoImagemDSClient; function ImgCli: TdaoImgCliClient; function Cliente: TdaoClienteClient; function ClassDaoPadrao: TDaoPadrao; end; implementation uses UDmConexao; { TFactoryClas } function TFactoryClas.ClassDaoPadrao: TDaoPadrao; begin if not Assigned(Self.FClassDaoPadrao) then Self.FClassDaoPadrao := TDaoPadrao.Create(DmConexao.conDS.DBXConnection); Result := Self.FClassDaoPadrao; end; function TFactoryClas.Cliente: TdaoClienteClient; begin if not Assigned(Self.FCliente) then Self.FCliente := TdaoClienteClient.Create(DmConexao.conDS.DBXConnection); Result := Self.FCliente; end; function TFactoryClas.Config: TDaoConfiguracaoClient; begin if not Assigned(Self.FConfig) then Self.FConfig := TDaoConfiguracaoClient.Create(DmConexao.conDS.DBXConnection); Result := Self.FConfig; end; destructor TFactoryClas.Destroy; begin FreeAndNil(self.FConfig); FreeAndNil(self.FPermissaoTela); FreeAndNil(self.FImagemRest); FreeAndNil(self.FFormulario); FreeAndNil(self.FUsuario); FreeAndNil(self.FGrupoPessoa); FreeAndNil(self.FImgCli); FreeAndNil(self.FClassDaoPadrao); FreeAndNil(self.FImagemDS); FreeAndNil(self.FCliente); inherited; end; function TFactoryClas.Formulario: TDaoFormularioClient; begin if not Assigned(Self.FFormulario) then Self.FFormulario := TDaoFormularioClient.Create(DmConexao.conDS.DBXConnection); Result := Self.FFormulario; end; function TFactoryClas.GrupoPessoa: TDaoGrupoPessoaClient; begin if not Assigned(Self.FGrupoPessoa) then Self.FGrupoPessoa := TDaoGrupoPessoaClient.Create(DmConexao.conDS.DBXConnection); Result := Self.FGrupoPessoa; end; function TFactoryClas.ImagemDS: TdaoImagemDSClient; begin if not Assigned(Self.FImagemDS) then Self.FImagemDS := TdaoImagemDSClient.Create(DmConexao.conDS.DBXConnection); Result := Self.FImagemDS; end; function TFactoryClas.ImagemRest: TDaoImagemClient; begin if not Assigned(Self.FImagemRest) then Self.FImagemRest := TDaoImagemClient.Create; Result := Self.FImagemRest; end; function TFactoryClas.ImgCli: TdaoImgCliClient; begin if not Assigned(Self.FImgCli) then Self.FImgCli := TdaoImgCliClient.Create(DmConexao.conDS.DBXConnection); Result := Self.FImgCli; end; class function TFactoryClas.New: IFactory; begin Result := Self.Create; end; function TFactoryClas.PermissaoTela: TDaoPermissaoTelaClient; begin if not Assigned(Self.FPermissaoTela) then Self.FPermissaoTela := TDaoPermissaoTelaClient.Create(DmConexao.conDS.DBXConnection); Result := Self.FPermissaoTela; end; function TFactoryClas.Usuario: TDaoUsuarioClient; begin if not Assigned(Self.FUsuario) then Self.FUsuario := TDaoUsuarioClient.Create(DmConexao.conDS.DBXConnection); Result := Self.FUsuario; end; end.
unit TestImpl; interface uses Test, Test_int, orbtypes, orb_int, poa, mtdebug, SysUtils; type TTestIntfFactory_impl = class(TTestIntfFactory_serv) protected function create_test_intf: ITestIntf; override; end; TTestIntf_impl = class(TTestIntf_serv) protected function check_short(const value_in: short; var value_inout: short; out value_out: short): short; override; function check_long(const value_in: long; var value_inout: long; out value_out: long): long; override; function check_unsigned_short(const value_in: _ushort; var value_inout: _ushort; out value_out: _ushort): _ushort; override; function check_unsigned_long(const value_in: _ulong; var value_inout: _ulong; out value_out: _ulong): _ulong; override; function check_float(const value_in: float; var value_inout: float; out value_out: float): float; override; function check_double(const value_in: double; var value_inout: double; out value_out: double): double; override; function check_boolean(const value_in: boolean; var value_inout: boolean; out value_out: boolean): boolean; override; function check_char(const value_in: AnsiChar; var value_inout: AnsiChar; out value_out: AnsiChar): AnsiChar; override; function check_octet(const value_in: octet; var value_inout: octet; out value_out: octet): octet; override; function check_string(const value_in: AnsiString; var value_inout: AnsiString; out value_out: AnsiString): AnsiString; override; function check_longlong(const value_in: longlong; var value_inout: longlong; out value_out: longlong): longlong; override; function check_unsigned_longlong(const value_in: _ulonglong; var value_inout: _ulonglong; out value_out: _ulonglong): _ulonglong; override; function check_wchar(const value_in: widechar; var value_inout: widechar; out value_out: widechar): widechar; override; function check_wstring(const value_in: widestring; var value_inout: widestring; out value_out: widestring): widestring; override; function check_octet_seq(const value_in: TTestOctetSeq; var value_inout: TTestOctetSeq; out value_out: TTestOctetSeq): TTestOctetSeq; override; function check_struct(const value_in: TTestStruct; var value_inout: TTestStruct; out value_out: TTestStruct): TTestStruct; override; function check_enum(const value_in: TTestEnum; var value_inout: TTestEnum; out value_out: TTestEnum): TTestEnum; override; function check_obj(const value_in: ITestIntf; var value_inout: ITestIntf; out value_out: ITestIntf): ITestIntf; override; procedure check_exception(const mes: AnsiString); override; procedure deactivate; override; //public //constructor Create(const ); end; implementation procedure CheckTestIntf(const ATest: ITestIntf); var i: Integer; shortValIn, shortValInOut, shortValOut, shortValResult: short; longValIn, longValInOut, longValOut, longValResult: long; ushortValIn, ushortValInOut, ushortValOut, ushortValResult: _ushort; octetSeqValIn, octetSeqValInOut, octetSeqValOut, octetSeqValResult: TTestOctetSeq; {ulongValIn, ulongValInOut, ulongValOut, ulongValResult: _ulong; {booleanValIn, booleanValInOut, booleanValOut, booleanValResult: boolean; shortValIn, shortValInOut, shortValOut, shortValResult: short; shortValIn, shortValInOut, shortValOut, shortValResult: short; shortValIn, shortValInOut, shortValOut, shortValResult: short; shortValIn, shortValInOut, shortValOut, shortValResult: short; shortValIn, shortValInOut, shortValOut, shortValResult: short; shortValIn, shortValInOut, shortValOut, shortValResult: short; shortValIn, shortValInOut, shortValOut, shortValResult: short; shortValIn, shortValInOut, shortValOut, shortValResult: short; shortValIn, shortValInOut, shortValOut, shortValResult: short;} begin shortValIn := Trunc(Random(High(short))); shortValInOut := shortValIn; shortValResult := ATest.check_short(shortValIn, shortValInOut, shortValOut); if shortValIn <> shortValResult then MTDORBLogger.Error('Client callback. Mismatch short value.'); longValIn := Trunc(Random(High(long))); longValInOut := longValIn; longValResult := ATest.check_long(longValIn, longValInOut, longValOut); if longValIn <> longValResult then MTDORBLogger.Error('Client callback. Mismatch long value.'); ushortValIn := Trunc(Random(High(_ushort))); ushortValInOut := ushortValIn; ushortValResult := ATest.check_unsigned_short(ushortValIn, ushortValInOut, ushortValOut); if ushortValIn <> ushortValResult then MTDORBLogger.Error('Client callback. Mismatch unsigned short value.'); SetLength(octetSeqValIn, 1024{*1024*5}); for i := 0 to Length(octetSeqValIn) - 1 do octetSeqValIn[i] := octet(Trunc(Random(Ord(High(octet))))); octetSeqValInOut := Copy(octetSeqValIn, 0, Length(octetSeqValIn)); octetSeqValResult := ATest.check_octet_seq(octetSeqValIn, octetSeqValInOut, octetSeqValOut); if not CompareMem(octetSeqValIn, octetSeqValResult, Length(octetSeqValInOut)) then MTDORBLogger.Error('Client callback. Mismatch octet sequence value.'); {ulongValIn := Trunc(Random(High(_ulong))); ulongValResult := ATest.check_unsigned_long(ulongValIn, ulongValInOut, ulongValOut); if ulongValIn <> ulongValResult then MTDORBLogger.Error('Client callback. Mismatch unsigned long value.'); booleanValIn := Trunc(Random(High(boolean))); booleanValResult := ATest.check_short(shortValIn, shortValInOut, shortValOut); if shortValIn <> shortValResult then MTDORBLogger.Error('Client callback. Mismatch short value.'); shortValIn := Trunc(Random(High(short))); shortValResult := ATest.check_short(shortValIn, shortValInOut, shortValOut); if shortValIn <> shortValResult then MTDORBLogger.Error('Client callback. Mismatch short value.'); shortValIn := Trunc(Random(High(short))); shortValResult := ATest.check_short(shortValIn, shortValInOut, shortValOut); if shortValIn <> shortValResult then MTDORBLogger.Error('Client callback. Mismatch short value.'); shortValIn := Trunc(Random(High(short))); shortValResult := ATest.check_short(shortValIn, shortValInOut, shortValOut); if shortValIn <> shortValResult then MTDORBLogger.Error('Client callback. Mismatch short value.'); shortValIn := Trunc(Random(High(short))); shortValResult := ATest.check_short(shortValIn, shortValInOut, shortValOut); if shortValIn <> shortValResult then MTDORBLogger.Error('Client callback. Mismatch short value.'); shortValIn := Trunc(Random(High(short))); shortValResult := ATest.check_short(shortValIn, shortValInOut, shortValOut); if shortValIn <> shortValResult then MTDORBLogger.Error('Client callback. Mismatch short value.'); shortValIn := Trunc(Random(High(short))); shortValResult := ATest.check_short(shortValIn, shortValInOut, shortValOut); if shortValIn <> shortValResult then MTDORBLogger.Error('Client callback. Mismatch short value.');} end; { TTestIntfFactory_impl } function TTestIntfFactory_impl.create_test_intf: ITestIntf; var ref: IORBObject; begin ref := FPoa.servant_to_reference(TTestIntf_impl.Create); Result := TTestIntf._narrow(ref); end; { TTestIntf_impl } function TTestIntf_impl.check_boolean(const value_in: boolean; var value_inout: boolean; out value_out: boolean): boolean; begin if value_in <> value_inout then MTDORBLogger.Error(AnsiString(Format('Mismatch boolean value. %d <> %d', [Ord(value_in), Ord(value_inout)]))); Result := value_in; value_inout := value_in; value_out := value_in; end; function TTestIntf_impl.check_char(const value_in: AnsiChar; var value_inout: AnsiChar; out value_out: AnsiChar): AnsiChar; begin if value_in <> value_inout then MTDORBLogger.Error(AnsiString(Format('Mismatch char value. %s <> %s', [value_in, value_inout]))); Result := value_in; value_inout := value_in; value_out := value_in; end; function TTestIntf_impl.check_double(const value_in: double; var value_inout: double; out value_out: double): double; begin if value_in <> value_inout then MTDORBLogger.Error(AnsiString(Format('Mismatch double value. %n <> %n', [value_in, value_inout]))); Result := value_in; value_inout := value_in; value_out := value_in; end; function TTestIntf_impl.check_enum(const value_in: TTestEnum; var value_inout: TTestEnum; out value_out: TTestEnum): TTestEnum; begin if value_in <> value_inout then MTDORBLogger.Error(AnsiString(Format('Mismatch enum value. %d <> %d', [Ord(value_in), Ord(value_inout)]))); Result := value_in; value_inout := value_in; value_out := value_in; end; procedure TTestIntf_impl.check_exception(const mes: AnsiString); begin raise TTestException.Create(mes); end; function TTestIntf_impl.check_float(const value_in: float; var value_inout: float; out value_out: float): float; begin if value_in <> value_inout then MTDORBLogger.Error(AnsiString(Format('Mismatch float value. %n <> %n', [value_in, value_inout]))); Result := value_in; value_inout := value_in; value_out := value_in; end; function TTestIntf_impl.check_long(const value_in: long; var value_inout: long; out value_out: long): long; begin if value_in <> value_inout then MTDORBLogger.Error(AnsiString(Format('Mismatch long value. %d <> %d', [value_in, value_inout]))); Result := value_in; value_inout := value_in; value_out := value_in; end; function TTestIntf_impl.check_longlong(const value_in: longlong; var value_inout: longlong; out value_out: longlong): longlong; begin if value_in <> value_inout then MTDORBLogger.Error(AnsiString(Format('Mismatch longlong value. %d <> %d', [value_in, value_inout]))); Result := value_in; value_inout := value_in; value_out := value_in; end; function TTestIntf_impl.check_obj(const value_in: ITestIntf; var value_inout: ITestIntf; out value_out: ITestIntf): ITestIntf; begin Result := value_in; value_out := value_in; CheckTestIntf(value_in); end; function TTestIntf_impl.check_octet(const value_in: octet; var value_inout: octet; out value_out: octet): octet; begin if value_in <> value_inout then MTDORBLogger.Error(AnsiString(Format('Mismatch octet value. %d <> %d', [Ord(value_in), Ord(value_inout)]))); Result := value_in; value_inout := value_in; value_out := value_in; end; function TTestIntf_impl.check_octet_seq(const value_in: TTestOctetSeq; var value_inout: TTestOctetSeq; out value_out: TTestOctetSeq): TTestOctetSeq; begin if not CompareMem(value_in, value_inout, Length(value_in)) then MTDORBLogger.Error('Mismatch octet sequence value'); Result := Copy(value_in, 0, Length(value_in)); value_inout := Copy(value_in, 0, Length(value_in)); value_out := Copy(value_in, 0, Length(value_in)); end; function TTestIntf_impl.check_short(const value_in: short; var value_inout: short; out value_out: short): short; begin if value_in <> value_inout then MTDORBLogger.Error(AnsiString(Format('Mismatch short value. %d <> %d', [value_in, value_inout]))); Result := value_in; value_inout := value_in; value_out := value_in; end; function TTestIntf_impl.check_string(const value_in: AnsiString; var value_inout: AnsiString; out value_out: AnsiString): AnsiString; begin if value_in <> value_inout then MTDORBLogger.Error(AnsiString(Format('Mismatch string value. %s <> %s', [value_in, value_inout]))); Result := value_in; value_inout := value_in; value_out := value_in; end; function TTestIntf_impl.check_struct(const value_in: TTestStruct; var value_inout: TTestStruct; out value_out: TTestStruct): TTestStruct; begin if (value_in.value_long <> value_inout.value_long) or (value_in.value_string <> value_inout.value_string) then MTDORBLogger.Error('Mismatch struct value'); Result := value_in; value_inout := value_in; value_out := value_in; end; function TTestIntf_impl.check_unsigned_long(const value_in: _ulong; var value_inout: _ulong; out value_out: _ulong): _ulong; begin if value_in <> value_inout then MTDORBLogger.Error(AnsiString(Format('Mismatch unsigned long value. %d <> %d', [value_in, value_inout]))); Result := value_in; value_inout := value_in; value_out := value_in; end; function TTestIntf_impl.check_unsigned_longlong(const value_in: _ulonglong; var value_inout: _ulonglong; out value_out: _ulonglong): _ulonglong; begin if value_in <> value_inout then MTDORBLogger.Error(AnsiString(Format('Mismatch unsigned longlong value. %d <> %d', [value_in, value_inout]))); Result := value_in; value_inout := value_in; value_out := value_in; end; function TTestIntf_impl.check_unsigned_short(const value_in: _ushort; var value_inout: _ushort; out value_out: _ushort): _ushort; begin if value_in <> value_inout then MTDORBLogger.Error(AnsiString(Format('Mismatch unsigned short value. %d <> %d', [value_in, value_inout]))); Result := value_in; value_inout := value_in; value_out := value_in; end; function TTestIntf_impl.check_wchar(const value_in: widechar; var value_inout: widechar; out value_out: widechar): widechar; begin if value_in <> value_inout then MTDORBLogger.Error(AnsiString(Format('Mismatch widechar value. %d <> %d', [Ord(value_in), Ord(value_inout)]))); Result := value_in; value_inout := value_in; value_out := value_in; end; function TTestIntf_impl.check_wstring(const value_in: widestring; var value_inout: widestring; out value_out: widestring): widestring; begin if value_in <> value_inout then MTDORBLogger.Error(AnsiString(Format('Mismatch widestring value. %s <> %s', [value_in, value_inout]))); Result := value_in; value_inout := value_in; value_out := value_in; end; procedure TTestIntf_impl.deactivate; begin if POA_Current.iscurrent then FPOA.deactivate_object(POA_Current.get_object_id()); end; end.
unit UAccessFile; interface uses Classes, UAccessContainer, DB, md5; type TMD5 = string[32]; TSAVAccessFiles = class(TObject) private FContainer: TSAVAccessContainer; FDataSource: TDataSet; FRDataSource: TDataSet; FFileDir: string; procedure SetContainer(const Value: TSAVAccessContainer); procedure SetDataSource(const Value: TDataSet); procedure SetRDataSource(const Value: TDataSet); public property Container: TSAVAccessContainer read FContainer write SetContainer; property DataSource: TDataSet read FDataSource write SetDataSource; property RDataSource: TDataSet read FRDataSource write SetRDataSource; property FileDir: string read FFileDir; function GetMD5(const aFileName: string): string; function AppendFile(aDS:TDataSet; const aFileName: string): Boolean; virtual; function AppendAndCopyFile(aDS:TDataSet; const aFileName: string; const aNewFileName: string = ''): Boolean; virtual; function UpdateFile(aDS:TDataSet): Boolean; virtual; function DeleteFile(aDS:TDataSet): Boolean; virtual; constructor Create(aContainer: TSAVAccessContainer); overload; end; TSAVAccessFile = class(TObject) private FFileName: string; FFileType: Integer; FExtension: string; FServerPath: string; FClientPath: string; FMD5: TMD5; FFileAction: Integer; procedure SetClientPath(const Value: string); procedure SetExtension(const Value: string); procedure SetFileAction(const Value: Integer); procedure SetFileName(const Value: string); procedure SetFileType(const Value: Integer); procedure SetMD5(const Value: TMD5); procedure SetServerPath(const Value: string); protected property FileName: string read FFileName write SetFileName; property FileType: Integer read FFileType write SetFileType; property Extension: string read FExtension write SetExtension; property ServerPath: string read FServerPath write SetServerPath; property ClientPath: string read FClientPath write SetClientPath; property MD5: TMD5 read FMD5 write SetMD5; property FileAction: Integer read FFileAction write SetFileAction; public end; implementation uses StrUtils, SysUtils, SAVLib, UAccessConstant, KoaUtils; { TSAVAccessFile } procedure TSAVAccessFile.SetClientPath(const Value: string); begin FClientPath := Value; end; procedure TSAVAccessFile.SetExtension(const Value: string); begin FExtension := Value; end; procedure TSAVAccessFile.SetFileAction(const Value: Integer); begin FFileAction := Value; end; procedure TSAVAccessFile.SetFileName(const Value: string); begin FFileName := Value; end; procedure TSAVAccessFile.SetFileType(const Value: Integer); begin FFileType := Value; end; procedure TSAVAccessFile.SetMD5(const Value: TMD5); begin FMD5 := Value; end; procedure TSAVAccessFile.SetServerPath(const Value: string); begin FServerPath := Value; end; { TSAVAccessFiles } function TSAVAccessFiles.AppendAndCopyFile(aDS:TDataSet; const aFileName, aNewFileName: string): Boolean; var s: string; begin if aNewFileName = '' then s := ExtractFileName(aFileName) else s := aNewFileName; Result := True; try fCopyFile(aFileName, FFileDir + s); except Result := False; end; if Result then Result := AppendFile(aDS, FFileDir + s); end; function TSAVAccessFiles.AppendFile(aDS:TDataSet; const aFileName: string): Boolean; begin try Result := True; aDS.Append; ads.FieldByName(csFieldPrority).AsInteger:=100; aDS.FieldByName(csFieldSrvrFile).AsString := AnsiLowerCase(ExtractFileName(aFileName)); aDS.FieldByName(csFieldExt).AsString := ExtractFileExt(aDS.FieldByName(csFieldSrvrFile).AsString); aDS.FieldByName(csFieldMD5).AsString := GetMD5(aFileName); aDS.FieldByName(csFieldVersion).AsString := Container.GetNewVersion; aDS.Post; except Result := False; end; end; constructor TSAVAccessFiles.Create(aContainer: TSAVAccessContainer); begin inherited Create; FContainer := aContainer; FFileDir := IncludeTrailingPathDelimiter(FContainer.WorkDir) + 'f\'; end; function TSAVAccessFiles.DeleteFile(aDS:TDataSet): Boolean; begin Result := True; try fDeleteFile(FFileDir + aDS.FieldByName(csFieldSrvrFile).AsString); except Result := False; end; if Result then aDS.Delete; end; function TSAVAccessFiles.GetMD5(const aFileName: string): string; begin try Result := MD5DigestToStr(MD5File(aFileName)); except Result := ''; end; end; procedure TSAVAccessFiles.SetContainer(const Value: TSAVAccessContainer); begin FContainer := Value; end; procedure TSAVAccessFiles.SetDataSource(const Value: TDataSet); begin FDataSource := Value; end; procedure TSAVAccessFiles.SetRDataSource(const Value: TDataSet); begin FRDataSource := Value; end; function TSAVAccessFiles.UpdateFile(aDS:TDataSet): Boolean; var s: string; begin Result := False; if aDS.FieldByName(csFieldSrvrFile).AsString <> '' then begin s := GetMD5(FFileDir + aDS.FieldByName(csFieldSrvrFile).AsString); if s <> aDS.FieldByName(csFieldMD5).AsString then begin aDS.Edit; aDS.FieldByName(csFieldMD5).AsString := s; aDS.FieldByName(csFieldVersion).AsString := Container.GetNewVersion; aDS.Post; end; Result := True; end; end; end.
unit fmSplash; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, ADC.Types, ADC.Common, ADC.GlobalVar, ADC.ADObject, Vcl.Imaging.pngimage; type TForm_Splash = class(TForm) Label_AppVersion: TLabel; Label_AppName: TLabel; Label_Copyright: TLabel; Label_Department: TLabel; Image_Splash: TImage; Label_Info: TLabel; Label_API: TLabel; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private const csProgressInfo = 'Поиск объектов в домене %s... %s'; csJoker = 'klever'; private FBitMap: TBitMap; FRect: TRect; function GetJokeAppTitle: string; function GetJokeAppVersion: string; function GetCurrentUserName: string; public procedure OnEnumProgress(AItem: TObject; AProgress: Integer); procedure OnEnumException(AMsg: string; ACode: ULONG); procedure OnEnumComplete(Sender: TObject); procedure DrawInfoText(AText: string); end; var Form_Splash: TForm_Splash; implementation {$R *.dfm} procedure TForm_Splash.DrawInfoText(AText: string); var c: TCanvas; r: TRect; begin try c := Label_Info.Canvas; c.Brush.Style := bsClear; c.Font.Color := clWhite; r := c.ClipRect; c.CopyRect(r, FBitMap.Canvas, FRect); c.TextOut(0, 0, AText); // c.TextRect(r, AText, [tfEndEllipsis, tfSingleLine, tfVerticalCenter]); except end; Label_Info.Update; end; procedure TForm_Splash.FormCreate(Sender: TObject); const CopyrightStr: string = 'Copyright © 2017-%d, JSC Mozyr Oil Refinery'; begin Label_API.Caption := ''; Label_AppName.Caption := GetJokeAppTitle; Label_AppVersion.Caption := GetJokeAppVersion; Label_Info.Caption := ''; Label_Copyright.Caption := Format(CopyrightStr, [CurrentYear]); Position := poDesigned; Top := (Screen.PrimaryMonitor.Height - Height) div 2; Left := (Screen.PrimaryMonitor.Width - Width) div 2; FBitMap := TBitmap.Create; try FBitMap.Assign(Image_Splash.Picture); FRect.TopLeft := Point(Label_Info.Left, Label_Info.Top); FRect.Width := Label_Info.Width; FRect.Height := Label_Info.Height; except end; end; procedure TForm_Splash.FormDestroy(Sender: TObject); begin if FBitMap <> nil then FBitMap.Free; end; function TForm_Splash.GetCurrentUserName: string; const NameSamCompatible = 2; UNLEN = 256; var BuffSize: Cardinal; Buff: PWideChar; begin BuffSize := UNLEN + 1; GetMem(Buff, BuffSize); // if GetUserNameEx(NameSamCompatible, Buff, BuffSize) if GetUserName(Buff, BuffSize) then Result := string(Buff); FreeMem(Buff); end; function TForm_Splash.GetJokeAppTitle: string; const UNLEN = 256; var BuffSize: Cardinal; n: PWideChar; begin BuffSize := UNLEN + 1; GetMem(n, BuffSize); GetUserName(n, BuffSize); if CompareText(string(n), csJoker) = 0 then Result := APP_TITLE_JOKE else Result := APP_TITLE; FreeMem(n); end; function TForm_Splash.GetJokeAppVersion: string; const UNLEN = 256; var BuffSize: Cardinal; n: PWideChar; begin Result := 'Версия: ' + GetFileInfo(Application.ExeName, 'ProductVersion'); {$IFDEF WIN64} Result := Result + ' (x64)'; {$ENDIF} BuffSize := UNLEN + 1; GetMem(n, BuffSize); GetUserName(n, BuffSize); if CompareText(string(n), csJoker) = 0 then Result := Result + ' - Kalashnikoff''s Edition'; FreeMem(n); end; procedure TForm_Splash.OnEnumComplete(Sender: TObject); begin DrawInfoText(Format(csProgressInfo, [SelectedDC.DomainDnsName, FormatFloat('#,##0', List_ObjFull.Count)])); Sleep(50); List_ObjFull.SortObjects; List_ObjFull.Filter.Apply; end; procedure TForm_Splash.OnEnumException(AMsg: string; ACode: ULONG); var s: string; begin if ACode = 0 then s := AMsg else s := AMsg + Format(' Error code: ', [ACode]); DrawInfoText(s); end; procedure TForm_Splash.OnEnumProgress(AItem: TObject; AProgress: Integer); var s: string; begin if AItem <> nil then if AItem is TADObject then begin if apEventsStorage = CTRL_EVENT_STORAGE_DISK then TADObject(AItem).LoadEventsFromFile(apEventsDir); end; if AProgress mod 25 = 0 then begin if AProgress = 0 then s := Format(csProgressInfo, [SelectedDC.DomainDnsName, '']) else s := Format(csProgressInfo, [SelectedDC.DomainDnsName, FormatFloat('#,##0', AProgress)]); DrawInfoText(s); end; end; end.
{ RxHistoryNavigator unit Copyright (C) 2005-2011 Lagunov Aleksey alexs@hotbox.ru and Lazarus team original conception from rx library for Delphi (c) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } unit RxHistoryNavigator; {$I rx.inc} interface uses Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, rxtoolbar, Menus; type PNavigateRec = ^TNavigateRec; TNavigateRec = record Name:string; Cond:string; Next:PNavigateRec; end; type TRxHistoryNavigator = class; THistoryNavigateEvent = procedure(Sender:TRxHistoryNavigator; AInfo:string; AProcessed:boolean) of object; { TRxHistoryNavigator } TRxHistoryNavigator = class(TComponent) private FForwardBtnItem:TToolbarItem; FForwardBtn: string; FBackBtnItem:TToolbarItem; FBackBtn: string; First:PNavigateRec; Curr:PNavigateRec; FMaxPopupItems: integer; FOnHistoryNavigate: THistoryNavigateEvent; FToolPanel: TToolPanel; PMBack:TPopupMenu; PMForw:TPopupMenu; function GetBackBtn: string; function GetForwardBtn: string; procedure SetBackBtn(AValue: string); procedure SetForwardBtn(AValue: string); procedure SetToolPanel(AValue: TToolPanel); procedure ClearFromCurrent(var C:PNavigateRec); procedure CreateBackMenu; procedure CreateRetrMenu; function Last:PNavigateRec; function Prior(R:PNavigateRec):PNavigateRec; procedure CheckTop; procedure CheckBottom; procedure EnableAction(ActName:byte; Enable:boolean); procedure BackProc(Sender: TObject); procedure ForwardProc(Sender: TObject); procedure DoSetItems; protected function Navigate(ToTop:boolean; Count:integer):boolean; procedure Loaded; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure ClearHistory; procedure AddToHistory(AHistoryCaption, AInfo:string); published property ToolPanel: TToolPanel read FToolPanel write SetToolPanel; property BackBtn:string read GetBackBtn write SetBackBtn; property ForwardBtn:string read GetForwardBtn write SetForwardBtn; property OnHistoryNavigate:THistoryNavigateEvent read FOnHistoryNavigate write FOnHistoryNavigate; property MaxPopupItems:integer read FMaxPopupItems write FMaxPopupItems default 10; end; implementation uses ActnList, rxconst; { TRxHistoryNavigator } procedure TRxHistoryNavigator.SetToolPanel(AValue: TToolPanel); begin if FToolPanel=AValue then Exit; FToolPanel:=AValue; end; procedure TRxHistoryNavigator.ClearFromCurrent(var C: PNavigateRec); var R:PNavigateRec; begin while C<>nil do begin R:=C; C:=C^.Next; Dispose(R); end; end; procedure TRxHistoryNavigator.CreateRetrMenu; var i:integer; S:PNavigateRec; Item:TMenuItem; begin if Curr=nil then exit; PMForw.Items.Clear; i:=0; S:=Curr^.Next; while (i<FMaxPopupItems) and (S<>nil) do begin Item := TMenuItem.Create(Self); Item.Caption := S^.Name; Item.OnClick := @ForwardProc; Item.Hint:=Format(sHistoryDesc, [S^.Cond]); Item.Tag:=i; PMForw.Items.Add(Item); inc(i); S:=S^.Next; end; end; function TRxHistoryNavigator.Last: PNavigateRec; begin if First=nil then Result:=nil else begin Result:=First; while Result^.Next<>nil do Result:=Result^.Next; end; end; function TRxHistoryNavigator.Prior(R: PNavigateRec): PNavigateRec; var L:PNavigateRec; begin if First=nil then Result:=nil else begin L:=First; while (L^.Next<>nil) and (L^.Next<>R) do begin L:=L^.Next; end; if L^.Next=nil then Result:=nil else Result:=l; end; end; procedure TRxHistoryNavigator.CheckTop; begin EnableAction(0, (Curr<>nil) and (Curr<>First)); end; procedure TRxHistoryNavigator.CheckBottom; begin EnableAction(1, (Curr<>nil) and (Curr^.Next<>nil)); end; procedure TRxHistoryNavigator.EnableAction(ActName: byte; Enable: boolean); begin if First=nil then Enable:=false; if ActName = 0 then begin if Assigned(FBackBtnItem) then (FBackBtnItem.Action as TAction).Enabled:=Enable end else if Assigned(FForwardBtnItem) then (FForwardBtnItem.Action as TAction).Enabled:=Enable end; procedure TRxHistoryNavigator.BackProc(Sender: TObject); begin Navigate(true, (Sender as TComponent).Tag); end; procedure TRxHistoryNavigator.ForwardProc(Sender: TObject); begin Navigate(false, (Sender as TComponent).Tag); end; procedure TRxHistoryNavigator.DoSetItems; begin if Assigned(FToolPanel) then begin FForwardBtnItem:=FToolPanel.Items.ByActionName[FForwardBtn]; if Assigned(FForwardBtnItem) then begin FForwardBtnItem.DropDownMenu:=PMForw; FForwardBtnItem.Action.OnExecute:=@ForwardProc; end; FBackBtnItem:=FToolPanel.Items.ByActionName[FBackBtn]; if Assigned(FBackBtnItem) then begin FBackBtnItem.DropDownMenu:=PMBack; FBackBtnItem.Action.OnExecute:=@BackProc; end; end; end; function TRxHistoryNavigator.Navigate(ToTop: boolean; Count: integer): boolean; var F:boolean; Condit: string; begin Result:=false; if First=nil then exit; if ToTop then begin inc(Count); repeat Curr:=Prior(Curr); if Curr=nil then Curr:=First; Dec(Count); until (Count=0) or (Curr=First); Result:=true; Condit:=Curr^.Cond; CreateBackMenu; CreateRetrMenu; end else begin inc(Count); repeat if Curr^.Next<>nil then Curr:=Curr^.Next; Dec(Count); until (Count=0) or (Curr^.Next=nil); Result:=true; Condit:=Curr^.Cond; CreateRetrMenu; CreateBackMenu; end; CheckTop; CheckBottom; F:=true; if Assigned(FOnHistoryNavigate) and Assigned(Curr) then FOnHistoryNavigate(Self, Condit, F); end; procedure TRxHistoryNavigator.Loaded; begin inherited Loaded; DoSetItems; CheckTop; CheckBottom; end; procedure TRxHistoryNavigator.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if Operation = opRemove then begin if AComponent = FToolPanel then begin if Assigned(FForwardBtnItem) then begin FForwardBtnItem.Action.OnExecute:=nil; FForwardBtnItem:=nil; end; if Assigned(FBackBtnItem) then begin FBackBtnItem.Action.OnExecute:=nil; FBackBtnItem:=nil; end; end else if AComponent = Self then begin if Assigned(FForwardBtnItem) then begin FForwardBtnItem.Action.OnExecute:=nil; FForwardBtnItem.DropDownMenu:=nil; FForwardBtnItem:=nil; end; if Assigned(FBackBtnItem) then begin FBackBtnItem.Action.OnExecute:=nil; FBackBtnItem.DropDownMenu:=nil; FBackBtnItem:=nil; end; end; end; end; procedure TRxHistoryNavigator.CreateBackMenu; var i:integer; S:PNavigateRec; Item:TMenuItem; begin if Curr=nil then exit; PMBack.Items.Clear; i:=0; S:=Curr; while (i<FMaxPopupItems) and (S<>First) do begin Item := TMenuItem.Create(Self); Item.Caption := S^.Name; Item.OnClick := @BackProc; Item.Hint:=Format(sHistoryDesc, [S^.Cond]); Item.Tag:=i; PMBack.Items.Add(Item); inc(i); S:=Prior(S); end; end; constructor TRxHistoryNavigator.Create(AOwner: TComponent); begin inherited Create(AOwner); PMBack:=TPopupMenu.Create(Self); PMBack.Parent:=Self; PMForw:=TPopupMenu.Create(Self); PMForw.Parent:=Self; FMaxPopupItems:=10; end; destructor TRxHistoryNavigator.Destroy; begin Curr:=nil; ClearFromCurrent(First); inherited Destroy; end; procedure TRxHistoryNavigator.ClearHistory; begin end; procedure TRxHistoryNavigator.AddToHistory(AHistoryCaption, AInfo: string); var R, L:PNavigateRec; begin New(R); FillChar(R^, SizeOf(TNavigateRec), 0); R^.Name:=AHistoryCaption; R^.Cond:=AInfo; if First<>nil then begin L:=Last; if Curr<>L then ClearFromCurrent(Curr^.Next); Curr^.Next:=R; Curr:=R; end else begin First:=R; Curr:=R; end; CreateBackMenu; CreateRetrMenu; CheckTop; CheckBottom; end; procedure TRxHistoryNavigator.SetBackBtn(AValue: string); begin if FBackBtn=AValue then Exit; if ForwardBtn = AValue then ForwardBtn:=''; FBackBtn:=AValue; if Assigned(FBackBtnItem) then begin FBackBtnItem.DropDownMenu:=nil; FBackBtnItem.Action.OnExecute:=nil; end; if Assigned(FToolPanel) and (FBackBtn<>'') then begin FBackBtnItem:=FToolPanel.Items.ByActionName[FBackBtn]; if Assigned(FBackBtnItem) then begin FBackBtnItem.DropDownMenu:=PMBack; FBackBtnItem.Action.OnExecute:=@BackProc; end; end else FBackBtnItem:=nil; end; function TRxHistoryNavigator.GetBackBtn: string; begin if Assigned(FBackBtnItem) then Result:=FBackBtnItem.Action.Name else Result:=FBackBtn; end; function TRxHistoryNavigator.GetForwardBtn: string; begin if Assigned(FForwardBtnItem) then Result:=FForwardBtnItem.Action.Name else Result:=FForwardBtn; end; procedure TRxHistoryNavigator.SetForwardBtn(AValue: string); begin if FForwardBtn=AValue then Exit; if BackBtn = AValue then BackBtn:=''; FForwardBtn:=AValue; if Assigned(FForwardBtnItem) then begin FForwardBtnItem.DropDownMenu:=nil; FForwardBtnItem.Action.OnExecute:=nil; end; if Assigned(FToolPanel) and (AValue <>'') then begin FForwardBtnItem:=FToolPanel.Items.ByActionName[FForwardBtn]; if Assigned(FForwardBtnItem) then begin FForwardBtnItem.DropDownMenu:=PMForw; FForwardBtnItem.Action.OnExecute:=@ForwardProc; end; end else FForwardBtnItem:=nil; end; end.
unit evExtSearch; { Библиотека "Эверест" } { Автор: Люлин А.В. © } { Модуль: evExtSearch - } { Начат: 14.09.2001 10:18 } { $Id: evExtSearch.pas,v 1.4 2005/03/02 09:08:36 lulin Exp $ } // $Log: evExtSearch.pas,v $ // Revision 1.4 2005/03/02 09:08:36 lulin // - bug fix: не компилировалось. // // Revision 1.3 2003/03/05 13:20:05 law // - bug fix. // // Revision 1.2 2001/09/14 12:50:22 law // - new behavior: добавлено значение текста по умолчанию. // // Revision 1.1 2001/09/14 12:30:34 law // - new behavior: добавлена возможность поиска. // {$I evDefine.inc } interface uses Classes, Dialogs, l3Types, l3Base, l3InterfacedComponent, evCustomEditor, evEditor, evSearch ; type TSearcher = class(TDataModule) FindDialog: TFindDialog; TextSearcher: TevBMTextSearcher; procedure FindDialogFind(Sender: TObject); private f_Editor : TevCustomEditor; { Private declarations } public { Public declarations } procedure Search(anEditor: TevCustomEditor); {-} end; function Search(anEditor : TevCustomEditor): Bool; {-} function SearchAgain(anEditor : TevCustomEditor): Bool; {-} implementation uses Forms, evTypes, evExcept ; {$R *.dfm} var l_Searcher : TSearcher; function Search(anEditor : TevCustomEditor): Bool; begin Result := true; if (l_Searcher = nil) then l_Searcher := TSearcher.Create(Application); l_Searcher.Search(anEditor); end; function SearchAgain(anEditor : TevCustomEditor): Bool; begin Result := true; if (l_Searcher = nil) then Result := false else begin Result := true; with l_Searcher do begin f_Editor := anEditor; FindDialogFind(FindDialog) end;//with l_Searcher end;// end; // start class TSearcher procedure TSearcher.Search(anEditor: TevCustomEditor); {-} begin f_Editor := anEditor; FindDialog.FindText := f_Editor.Range.AsString; FindDialog.Execute; end; procedure TSearcher.FindDialogFind(Sender: TObject); begin if (frMatchCase in FindDialog.Options) then TextSearcher.Options := [ev_soMatchCase] else TextSearcher.Options := []; TextSearcher.Text := FindDialog.FindText; try f_Editor.Find(TextSearcher, nil, []); except on EevSearchFailed do begin MessageDlg(TextSearcher.NotFoundMessage, mtWarning, [mbOK], 0); end;//on EevSearchFailed end;//try..except end; end.
unit caTableQueryFactory; // Модуль: "w:\common\components\rtl\Garant\ComboAccess\caTableQueryFactory.pas" // Стереотип: "SimpleClass" // Элемент модели: "TcaTableQueryFactory" MUID: (56C4594703CF) {$Include w:\common\components\rtl\Garant\ComboAccess\caDefine.inc} interface {$If Defined(UsePostgres) AND Defined(TestComboAccess)} uses l3IntfUses , l3ProtoObject , daInterfaces , caInterfaces , daTypes ; type TcaTableQueryFactory = class(Tl3ProtoObject, IdaTableQueryFactory) private f_HTFactory: IdaTableQueryFactory; f_PGFactory: IdaTableQueryFactory; f_DataConverter: IcaDataConverter; protected function MakeTabledQuery(const aFromClause: IdaFromClause): IdaTabledQuery; function MakeSelectField(const aTableAlias: AnsiString; const aField: IdaFieldDescription; const anAlias: AnsiString = ''): IdaSelectField; function MakeParamsCondition(const aTableAlias: AnsiString; const aField: IdaFieldDescription; anOperation: TdaCompareOperation; const aParamName: AnsiString): IdaCondition; function Get_DataConverter: IdaDataConverter; function MakeLogicCondition(const aLeft: IdaCondition; anOperation: TdaLogicOperation; const aRight: IdaCondition): IdaCondition; function MakeSubQueryCondition(const aTableAlias: AnsiString; const aField: IdaFieldDescription; const aQuery: IdaTabledQuery): IdaCondition; function MakeSortField(const aSelectField: IdaSelectField; aSortOrder: TdaSortOrder = daTypes.da_soAscending): IdaSortField; function MakeJoin(const aLeft: IdaFromClause; const aRight: IdaFromClause; aKind: TdaJoinKind): IdaJoin; function MakeJoinCondition(const aLeftTableAlias: AnsiString; const aLeftField: IdaFieldDescription; const aRightTableAlias: AnsiString; const aRightField: IdaFieldDescription): IdaCondition; function MakeSimpleFromClause(const aTable: IdaTableDescription; const anAlias: AnsiString = ''): IdaFromClause; function MakeAggregateField(anOperation: TdaAggregateOperation; const aField: IdaSelectField; const anAlias: AnsiString): IdaSelectField; function MakeBitwiseCondition(const aTableAlias: AnsiString; const aField: IdaFieldDescription; anOperation: TdaBitwiseOperator; aValue: Int64): IdaCondition; procedure Cleanup; override; {* Функция очистки полей объекта. } public constructor Create(const aDataConverter: IcaDataConverter; const aHTFactory: IdaTableQueryFactory; const aPGFactory: IdaTableQueryFactory); reintroduce; class function Make(const aDataConverter: IcaDataConverter; const aHTFactory: IdaTableQueryFactory; const aPGFactory: IdaTableQueryFactory): IdaTableQueryFactory; reintroduce; end;//TcaTableQueryFactory {$IfEnd} // Defined(UsePostgres) AND Defined(TestComboAccess) implementation {$If Defined(UsePostgres) AND Defined(TestComboAccess)} uses l3ImplUses , caTabledQuery , daLogicCondition , daParamsCondition , daSortField , daSelectField , daSubQueryCondition , daJoin , daJoinCondition , caFromClause , daAggregateField , daBitwiseCondition //#UC START# *56C4594703CFimpl_uses* //#UC END# *56C4594703CFimpl_uses* ; constructor TcaTableQueryFactory.Create(const aDataConverter: IcaDataConverter; const aHTFactory: IdaTableQueryFactory; const aPGFactory: IdaTableQueryFactory); //#UC START# *56C45EE801FB_56C4594703CF_var* //#UC END# *56C45EE801FB_56C4594703CF_var* begin //#UC START# *56C45EE801FB_56C4594703CF_impl* inherited Create; f_DataConverter := aDataConverter; f_HTFactory := aHTFactory; f_PGFactory := aPGFactory; //#UC END# *56C45EE801FB_56C4594703CF_impl* end;//TcaTableQueryFactory.Create class function TcaTableQueryFactory.Make(const aDataConverter: IcaDataConverter; const aHTFactory: IdaTableQueryFactory; const aPGFactory: IdaTableQueryFactory): IdaTableQueryFactory; var l_Inst : TcaTableQueryFactory; begin l_Inst := Create(aDataConverter, aHTFactory, aPGFactory); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TcaTableQueryFactory.Make function TcaTableQueryFactory.MakeTabledQuery(const aFromClause: IdaFromClause): IdaTabledQuery; //#UC START# *5549C65D038D_56C4594703CF_var* //#UC END# *5549C65D038D_56C4594703CF_var* begin //#UC START# *5549C65D038D_56C4594703CF_impl* Result := TcaTabledQuery.Make(Self, f_DataConverter, aFromClause, f_HTFactory.MakeTabledQuery((aFromClause as IdaComboAccessFromClauseHelper).HTClause), f_PGFactory.MakeTabledQuery((aFromClause as IdaComboAccessFromClauseHelper).PGClause)); //#UC END# *5549C65D038D_56C4594703CF_impl* end;//TcaTableQueryFactory.MakeTabledQuery function TcaTableQueryFactory.MakeSelectField(const aTableAlias: AnsiString; const aField: IdaFieldDescription; const anAlias: AnsiString = ''): IdaSelectField; //#UC START# *559B80BD00A8_56C4594703CF_var* //#UC END# *559B80BD00A8_56C4594703CF_var* begin //#UC START# *559B80BD00A8_56C4594703CF_impl* Result := TdaSelectField.Make(aTableAlias, aField, anAlias); //#UC END# *559B80BD00A8_56C4594703CF_impl* end;//TcaTableQueryFactory.MakeSelectField function TcaTableQueryFactory.MakeParamsCondition(const aTableAlias: AnsiString; const aField: IdaFieldDescription; anOperation: TdaCompareOperation; const aParamName: AnsiString): IdaCondition; //#UC START# *559B810003CF_56C4594703CF_var* //#UC END# *559B810003CF_56C4594703CF_var* begin //#UC START# *559B810003CF_56C4594703CF_impl* Result := TdaParamsCondition.Make(aTableAlias, aField, anOperation, aParamName); //#UC END# *559B810003CF_56C4594703CF_impl* end;//TcaTableQueryFactory.MakeParamsCondition function TcaTableQueryFactory.Get_DataConverter: IdaDataConverter; //#UC START# *55C1BFA402E3_56C4594703CFget_var* //#UC END# *55C1BFA402E3_56C4594703CFget_var* begin //#UC START# *55C1BFA402E3_56C4594703CFget_impl* Result := f_DataConverter; //#UC END# *55C1BFA402E3_56C4594703CFget_impl* end;//TcaTableQueryFactory.Get_DataConverter function TcaTableQueryFactory.MakeLogicCondition(const aLeft: IdaCondition; anOperation: TdaLogicOperation; const aRight: IdaCondition): IdaCondition; //#UC START# *56405475021D_56C4594703CF_var* //#UC END# *56405475021D_56C4594703CF_var* begin //#UC START# *56405475021D_56C4594703CF_impl* Result := TdaLogicCondition.Make(aLeft, anOperation, aRight); //#UC END# *56405475021D_56C4594703CF_impl* end;//TcaTableQueryFactory.MakeLogicCondition function TcaTableQueryFactory.MakeSubQueryCondition(const aTableAlias: AnsiString; const aField: IdaFieldDescription; const aQuery: IdaTabledQuery): IdaCondition; //#UC START# *5641E5DB02C3_56C4594703CF_var* //#UC END# *5641E5DB02C3_56C4594703CF_var* begin //#UC START# *5641E5DB02C3_56C4594703CF_impl* Result := TdaSubQueryCondition.Make(aTableALias, aField, aQuery); //#UC END# *5641E5DB02C3_56C4594703CF_impl* end;//TcaTableQueryFactory.MakeSubQueryCondition function TcaTableQueryFactory.MakeSortField(const aSelectField: IdaSelectField; aSortOrder: TdaSortOrder = daTypes.da_soAscending): IdaSortField; //#UC START# *56811844032C_56C4594703CF_var* //#UC END# *56811844032C_56C4594703CF_var* begin //#UC START# *56811844032C_56C4594703CF_impl* Result := TdaSortField.Make(aSelectField, aSortOrder); //#UC END# *56811844032C_56C4594703CF_impl* end;//TcaTableQueryFactory.MakeSortField function TcaTableQueryFactory.MakeJoin(const aLeft: IdaFromClause; const aRight: IdaFromClause; aKind: TdaJoinKind): IdaJoin; //#UC START# *574584D802F6_56C4594703CF_var* //#UC END# *574584D802F6_56C4594703CF_var* begin //#UC START# *574584D802F6_56C4594703CF_impl* Result := TcaFromClause.Make(Self, f_HTFactory.MakeJoin((aLeft as IdaComboAccessFromClauseHelper).HTClause, (aRight as IdaComboAccessFromClauseHelper).HTClause, aKind) as IdaFromClause, f_PGFactory.MakeJoin((aLeft as IdaComboAccessFromClauseHelper).PGClause, (aRight as IdaComboAccessFromClauseHelper).PGClause, aKind) as IdaFromClause); //#UC END# *574584D802F6_56C4594703CF_impl* end;//TcaTableQueryFactory.MakeJoin function TcaTableQueryFactory.MakeJoinCondition(const aLeftTableAlias: AnsiString; const aLeftField: IdaFieldDescription; const aRightTableAlias: AnsiString; const aRightField: IdaFieldDescription): IdaCondition; //#UC START# *574BF2B20123_56C4594703CF_var* //#UC END# *574BF2B20123_56C4594703CF_var* begin //#UC START# *574BF2B20123_56C4594703CF_impl* Result := TdaJoinCondition.Make(aLeftTableAlias, aLeftField, aRightTableAlias, aRightField); //#UC END# *574BF2B20123_56C4594703CF_impl* end;//TcaTableQueryFactory.MakeJoinCondition function TcaTableQueryFactory.MakeSimpleFromClause(const aTable: IdaTableDescription; const anAlias: AnsiString = ''): IdaFromClause; //#UC START# *574C32760314_56C4594703CF_var* //#UC END# *574C32760314_56C4594703CF_var* begin //#UC START# *574C32760314_56C4594703CF_impl* Result := TcaFromClause.Make(Self, f_HTFactory.MakeSimpleFromClause(aTable, anAlias), f_PGFactory.MakeSimpleFromClause(aTable, anAlias)) as IdaFromClause; //#UC END# *574C32760314_56C4594703CF_impl* end;//TcaTableQueryFactory.MakeSimpleFromClause function TcaTableQueryFactory.MakeAggregateField(anOperation: TdaAggregateOperation; const aField: IdaSelectField; const anAlias: AnsiString): IdaSelectField; //#UC START# *5755313E0083_56C4594703CF_var* //#UC END# *5755313E0083_56C4594703CF_var* begin //#UC START# *5755313E0083_56C4594703CF_impl* Result := TdaAggregateField.Make(anOperation, aField, anAlias); //#UC END# *5755313E0083_56C4594703CF_impl* end;//TcaTableQueryFactory.MakeAggregateField function TcaTableQueryFactory.MakeBitwiseCondition(const aTableAlias: AnsiString; const aField: IdaFieldDescription; anOperation: TdaBitwiseOperator; aValue: Int64): IdaCondition; //#UC START# *57A9A66C00A7_56C4594703CF_var* //#UC END# *57A9A66C00A7_56C4594703CF_var* begin //#UC START# *57A9A66C00A7_56C4594703CF_impl* Result := TdaBitwiseCondition.Make(aTableAlias, aField, anOperation, aValue); //#UC END# *57A9A66C00A7_56C4594703CF_impl* end;//TcaTableQueryFactory.MakeBitwiseCondition procedure TcaTableQueryFactory.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_56C4594703CF_var* //#UC END# *479731C50290_56C4594703CF_var* begin //#UC START# *479731C50290_56C4594703CF_impl* f_DataConverter := nil; f_HTFactory := nil; f_PGFactory := nil; inherited; //#UC END# *479731C50290_56C4594703CF_impl* end;//TcaTableQueryFactory.Cleanup {$IfEnd} // Defined(UsePostgres) AND Defined(TestComboAccess) end.
object EncWarn: TEncWarn Left = 287 Top = 140 BorderStyle = bsDialog Caption = 'Warning!' ClientHeight = 88 ClientWidth = 376 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'MS Sans Serif' Font.Style = [] FormStyle = fsStayOnTop OldCreateOrder = False Position = poScreenCenter PixelsPerInch = 120 TextHeight = 16 object Label1: TLabel Left = 8 Top = 8 Width = 323 Height = 16 Caption = 'Some characters are missing from the target encoding.' end object Label2: TLabel Left = 8 Top = 24 Width = 246 Height = 16 Caption = 'Part of a text may look like '#39'????? ??? ???'#39 end object Button1: TButton Left = 296 Top = 56 Width = 75 Height = 25 Caption = 'Ok' ModalResult = 1 TabOrder = 0 OnClick = Button1Click end object CheckBox1: TCheckBox Left = 8 Top = 64 Width = 225 Height = 17 Caption = 'Never show this message again' TabOrder = 1 end end
unit GX_FeedbackWizard; // Original Authors: // Stig Jørgensen <stig.joergensen@clearsky.dk> and // Erik Berry <eberry@gexperts.org> interface {$I GX_CondDefine.inc} {$WARN SYMBOL_PLATFORM OFF} uses Classes, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, ActnList, GX_BaseForm, Actions; type TFeedbackType = (fbBug, fbFeature); TfmFeedbackWizard = class(TfmBaseForm) pnlTop: TPanel; pnlHeader: TPanel; lblFeeedback: TLabel; pgeMain: TPageControl; lblDescription: TLabel; tshType: TTabSheet; rgpFeedbackType: TRadioGroup; pnlContent: TPanel; pnlButtons: TPanel; btnCancel: TButton; btnPrev: TButton; btnNext: TButton; pgeInfo: TPageControl; tshInfoHelp: TTabSheet; tshInfoExample: TTabSheet; Splitter: TSplitter; tshDescription: TTabSheet; mmoDescription: TMemo; mmoInfoHelp: TMemo; mmoInfoExample: TMemo; pnlButtonsCenter: TPanel; tshBugDetails: TTabSheet; tshBugSteps: TTabSheet; mmoBugSteps: TMemo; tshReport: TTabSheet; mmoReport: TMemo; pnlReportButtons: TPanel; btnCopy: TButton; btnEmail: TButton; btnSave: TButton; tshConfiguration: TTabSheet; gbxConfigurationData: TGroupBox; chkOS: TCheckBox; chkExperts: TCheckBox; chkIdeVer: TCheckBox; chkPackages: TCheckBox; chkLocaleKeyboard: TCheckBox; chkCpu: TCheckBox; chkGExpertsVer: TCheckBox; gbxBugDetails: TGroupBox; chkProjectSpecific: TCheckBox; chkMultipleMachines: TCheckBox; lblPercent: TLabel; edtPercent: TEdit; chkReproducible: TCheckBox; Actions: TActionList; actPrev: TAction; actNext: TAction; dlgSaveReport: TSaveDialog; pnlDescription: TPanel; pnlMain: TPanel; chkGExpertsSettings: TCheckBox; procedure actPrevUpdate(Sender: TObject); procedure actNextUpdate(Sender: TObject); procedure actPrevExecute(Sender: TObject); procedure actNextExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure chkReproducibleClick(Sender: TObject); procedure rgpFeedbackTypeClick(Sender: TObject); procedure btnEmailClick(Sender: TObject); procedure btnCopyClick(Sender: TObject); procedure btnSaveClick(Sender: TObject); procedure btnCancelClick(Sender: TObject); procedure pgeMainResize(Sender: TObject); procedure pnlButtonsResize(Sender: TObject); procedure edtPercentKeyPress(Sender: TObject; var Key: Char); procedure InfoMemoEnter(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); private FActiveTab: TTabSheet; FActiveTabNumber: Integer; TabsNotForBugs: TList; TabsNotForFeatures: TList; FIDEName: string; FBugEmail: string; FFeatureEmail: string; procedure SetDescriptionCaption; function GetFeedbackType: TFeedbackType; procedure SetDescriptionInfo; procedure SetExampleInfo; procedure UpdateInfo; property FeedbackType: TFeedbackType read GetFeedbackType; procedure UpdateForNewTab; procedure SetTabCaptions; procedure SetDefaultConfigurationData; function GetNextTab: TTabSheet; function GetPrevTab: TTabSheet; function OnLastPage: Boolean; function OnFirstPage: Boolean; function CanProceed: Boolean; procedure SetTabFocusControl; function IsValidTab(const Tab: TTabSheet): Boolean; procedure CenterTabContents; procedure CenterInParent(Control: TControl); procedure InitializeTabControls; procedure GenerateReport; function GetDestinationEmail: string; function GetFeedbackTypeString: string; function GetTabReportText(Tab: TTabSheet): string; function GetBugDetailsString: string; function GetSystemConfigurationString: string; public class procedure Execute(AOwner: TComponent; const ABugEmail, AFeatureEmail: string); end; implementation uses Windows, SysUtils, ShellAPI, TypInfo, Clipbrd, Registry, GX_GenericUtils, GX_ConfigurationInfo, GX_OtaUtils, GX_GetIdeVersion, GX_IdeUtils, Menus, Math; {$R *.dfm} const SkipLine = sLineBreak + sLineBreak; CRLF = sLineBreak; const SItemOfItem = ' (%d of %d)'; function GetLocaleChar(Locale, LocaleType: Integer; Default: Char): Char; begin Result := SysUtils.GetLocaleChar(Locale, LocaleType, Default); end; function GetLocaleStr(Locale, LocaleType: Integer; const Default: string): string; begin Result := SysUtils.GetLocaleStr(Locale, LocaleType, Default); end; { TfmFeedbackWizard } class procedure TfmFeedbackWizard.Execute(AOwner: TComponent; const ABugEmail, AFeatureEmail: string); var Form: TfmFeedbackWizard; begin Form := TfmFeedbackWizard.Create(AOwner); Form.FBugEmail := ABugEmail; Form.FFeatureEmail := AFeatureEmail; Form.Show; // Non-modal, this frees itself using caFree Action end; procedure TfmFeedbackWizard.SetDescriptionCaption; begin if FActiveTab = nil then lblDescription.Caption := '' else if FActiveTab = tshType then lblDescription.Caption := FActiveTab.Caption else if FeedbackType = fbFeature then lblDescription.Caption := FActiveTab.Caption + Format(SItemOfItem, [FActiveTabNumber, pgeMain.PageCount - TabsNotForFeatures.Count]) else lblDescription.Caption := FActiveTab.Caption + Format(SItemOfItem, [FActiveTabNumber, pgeMain.PageCount - TabsNotForBugs.Count]); end; function TfmFeedbackWizard.GetFeedbackType: TFeedbackType; begin if rgpFeedbackType.ItemIndex = 0 then Result := fbBug else Result := fbFeature; end; procedure TfmFeedbackWizard.SetDescriptionInfo; const TypeDescription = ' Bug reports include access violations, crashes, ' + 'non-working features, and other failures. ' + sLineBreak + sLineBreak + ' Feature requests are suggestions for future development ' + 'of GExperts.' + sLineBreak + sLineBreak + ' Please verify you are using the latest GExperts release before ' + 'sending in feedback. See: http://www.gexperts.org/'; BugDescriptionDescription = ' Please enter a detailed description of the bug. Include any unique ' + 'data about your system setup that you think might assist us in ' + 'duplicating the bug.' + sLineBreak + sLineBreak + ' The exact steps necessary to duplicate the bug and general data such ' + 'as the version of your IDE and operating system will be collected later.'; FeatureDescriptionDescription = ' Please enter a detailed description of the feature you are proposing. ' + 'Be sure to state why/when the feature would be useful to you.'; DetailsDescription = ' It is important to try to find repeatable steps that can reproduce ' + 'a bug before reporting it. Please indicate if you have been able to ' + 'find reproducible steps and how regularly the bug is seen using those ' + 'steps. Also indicate if you have verified that the problem happens ' + 'on other machines or only happens with specific projects.'; StepsDescription = ' It is critical to enter a detailed list of steps to help us ' + 'duplicate the problem. Your steps should begin with a fresh startup ' + 'of the IDE and be as specific as possible. Include mouse clicks, ' + 'keypresses, windows currently visible/active, and exact error messages ' + 'where appropriate.' + sLineBreak + sLineBreak + ' If possible, try to duplicate problems with the default (empty) project, ' + 'a simple project, or one of the IDE''s included demo projects.'; ConfigurationDescription1 = ' All the items you check here will be sent with your report to help us '; ConfigurationDescription2 = ' To ensure an effective report, we strongly recommend you leave the ' + 'default items checked. You may edit or remove any of the configuration ' + 'information in a moment (before reporting anything to us).'; BugConfigurationDescription = ConfigurationDescription1 + 'duplicate the bug and determine the cause.' + ConfigurationDescription2; FeatureConfigurationDescription = ConfigurationDescription1 + 'determine when the requested feature would be helpful.' + ConfigurationDescription2; ReportDescription = ' Click Finish to copy the generated report to the clipboard and ' + 'create an email (using your default email client) where you can then ' + 'paste the report into the email.' + sLineBreak + sLineBreak + ' You may also save the generated report to a file and send it at a ' + 'later date to %s.' + sLineBreak + sLineBreak + ' This wizard does not transmit any information to us unless ' + 'you manually send an email with the generated report included.'; var Lines: TStrings; begin Lines := mmoInfoHelp.Lines; Lines.Text := ''; if FActiveTab = tshType then Lines.Text := TypeDescription else if FActiveTab = tshDescription then begin if FeedbackType = fbBug then Lines.Text := BugDescriptionDescription else Lines.Text := FeatureDescriptionDescription; end else if FActiveTab = tshBugDetails then Lines.Text := DetailsDescription else if FActiveTab = tshBugSteps then Lines.Text := StepsDescription else if FActiveTab = tshConfiguration then begin if FeedbackType = fbBug then Lines.Text := BugConfigurationDescription else Lines.Text := FeatureConfigurationDescription; end else if FActiveTab = tshReport then Lines.Text := Format(ReportDescription, [GetDestinationEmail]); end; procedure TfmFeedbackWizard.SetExampleInfo; const TypeExample = ' Some examples of features we do NOT have any plans to ' + 'implement include method folding, custom painting inside the editor, support for ' + 'Visual C++ and Java, etc.'; BugDescriptionExample = 'The editor toolbar is shown without the separators when the toolbar ' + 'is aligned to the left or right of the editor window. The ' + 'separators appear fine when the toolbar is aligned to the ' + 'top or bottom. I have about 15 toolbar buttons and 4 separators ' + 'in my editor toolbar.'; FeatureDescriptionExample = 'I would love to see a new editor expert that translates my code from %s ' + 'to Visual Basic so I can write Outlook email viruses. I would '+ 'also like to offer you a job that includes a huge salary and lots of ' + 'paid vacation time.'; StepsExample = '1. Open %s from the start menu' + sLineBreak + '2. Turn on the GExperts editor toolbar from the GExperts Configuration dialog' + sLineBreak + '3. Align the toolbar to the left' + sLineBreak + '4. Click the Customize Toolbar button' + sLineBreak + '5. Add 20 toolbar actions of any type with separators every 5 actions' + sLineBreak + '6. Save the GExperts settings and look at the editor window' + sLineBreak + '7. The separators are missing from the toolbar' + sLineBreak + '8. Re-align the toolbar to the Top, and the separators appear again'; var Lines: TStrings; begin Lines := mmoInfoExample.Lines; Lines.Text := ''; if FActiveTab = tshType then Lines.Text := TypeExample else if FActiveTab = tshDescription then begin if FeedbackType = fbBug then Lines.Text := BugDescriptionExample else Lines.Text := Format(FeatureDescriptionExample, [FIDEName]); end else if FActiveTab = tshBugSteps then Lines.Text := Format(StepsExample, [FIDEName]); end; procedure TfmFeedbackWizard.actPrevUpdate(Sender: TObject); begin actPrev.Enabled := not OnFirstPage; end; procedure TfmFeedbackWizard.actNextUpdate(Sender: TObject); const SFinish = '&Finish'; SNext = '&Next >'; begin actNext.Enabled := CanProceed; if OnLastPage then actNext.Caption := SFinish else actNext.Caption := SNext; end; procedure TfmFeedbackWizard.actPrevExecute(Sender: TObject); begin FActiveTab := GetPrevTab; UpdateForNewTab; pgeMain.ActivePage := FActiveTab; SetTabFocusControl; end; procedure TfmFeedbackWizard.actNextExecute(Sender: TObject); begin if OnLastPage then begin Clipboard.AsText := mmoReport.Lines.Text; btnEmail.Click; Close; end else begin FActiveTab := GetNextTab; UpdateForNewTab; pgeMain.ActivePage := FActiveTab; SetTabFocusControl; end; end; procedure TfmFeedbackWizard.FormCreate(Sender: TObject); var i: Integer; begin for i := 0 to pgeMain.PageCount - 1 do pgeMain.Pages[i].TabVisible := False; pgeMain.ActivePage := pgeMain.Pages[0]; FActiveTab := pgeMain.Pages[0]; TabsNotForBugs := TList.Create; TabsNotForFeatures := TList.Create; TabsNotForFeatures.Add(tshBugDetails); TabsNotForFeatures.Add(tshBugSteps); SetTabFocusControl; FActiveTabNumber := 1; UpdateInfo; pgeMain.Style := tsButtons; FIDEName := GxOtaGetIDEProductIdentifier; SetParentBackgroundValue(pnlHeader, False); end; procedure TfmFeedbackWizard.chkReproducibleClick(Sender: TObject); begin edtPercent.Enabled := chkReproducible.Checked; lblPercent.Enabled := chkReproducible.Checked; end; procedure TfmFeedbackWizard.UpdateForNewTab; begin UpdateInfo; SetDescriptionCaption; CenterTabContents; InitializeTabControls; end; procedure TfmFeedbackWizard.rgpFeedbackTypeClick(Sender: TObject); begin SetTabCaptions; SetDefaultConfigurationData; end; procedure TfmFeedbackWizard.SetTabCaptions; const SFeedbackDescription = '%s Description'; SFeedbackCompleted = 'Completed %s'; begin tshDescription.Caption := Format(SFeedbackDescription, [GetFeedbackTypeString]); tshReport.Caption := Format(SFeedbackCompleted, [GetFeedbackTypeString]); end; procedure TfmFeedbackWizard.SetDefaultConfigurationData; var i: Integer; CheckBox: TCheckBox; begin {$IFNDEF GX_VER310_up} CheckBox := nil; {$ENDIF} for i := 0 to gbxConfigurationData.ControlCount - 1 do begin if gbxConfigurationData.Controls[i] is TCheckBox then CheckBox := gbxConfigurationData.Controls[i] as TCheckBox else Continue; if FeedbackType = fbBug then CheckBox.Checked := True else CheckBox.Checked := not CheckBox.Enabled; end; end; function TfmFeedbackWizard.GetNextTab: TTabSheet; var CurrentIndex: Integer; begin Assert(not OnLastPage); CurrentIndex := pgeMain.ActivePageIndex; Inc(CurrentIndex); Result := pgeMain.Pages[CurrentIndex]; while not IsValidTab(Result) do begin Inc(CurrentIndex); Result := pgeMain.Pages[CurrentIndex]; end; Inc(FActiveTabNumber); end; function TfmFeedbackWizard.GetPrevTab: TTabSheet; var CurrentIndex: Integer; begin Assert(not OnFirstPage); CurrentIndex := pgeMain.ActivePageIndex; Dec(CurrentIndex); Result := pgeMain.Pages[CurrentIndex]; if FeedbackType = fbFeature then if (Result = tshBugDetails) or (Result = tshBugSteps) then Result := tshDescription; Dec(FActiveTabNumber); end; function TfmFeedbackWizard.CanProceed: Boolean; begin Result := True; if FActiveTab = tshDescription then Result := Length(Trim(mmoDescription.Text)) > 0 else if FActiveTab = tshBugSteps then Result := mmoBugSteps.Modified; end; function TfmFeedbackWizard.OnFirstPage: Boolean; begin Result := pgeMain.ActivePage = pgeMain.Pages[0]; end; function TfmFeedbackWizard.OnLastPage: Boolean; begin Result := pgeMain.ActivePage = pgeMain.Pages[pgeMain.PageCount - 1]; end; type TTabSheetCracker = class(TTabSheet); procedure TfmFeedbackWizard.SetTabFocusControl; begin TTabSheetCracker(FActiveTab).SelectFirst; end; procedure TfmFeedbackWizard.btnEmailClick(Sender: TObject); var ExecFilename: string; Address: string; Subject: string; Body: string; const SFillInReminder = 'Please remember to paste the generated report here'; SFillInReminderPaste = SFillInReminder; SFillInReminderAttach = SFillInReminder + ' or attach %s'; begin Subject := 'GExperts ' + GetFeedbackTypeString; // Do not localize. Address := GetDestinationEmail; if dlgSaveReport.FileName <> '' then Body := Format(SFillInReminderAttach, [dlgSaveReport.FileName]) else Body := SFillInReminderPaste; // Do not localize the lines below. ExecFilename := Format('mailto:%s?Subject=%s&Body=%s', [Address, Subject, Body]); ExecFilename := StringReplace(ExecFilename, ' ', '%20', [rfReplaceAll]); ShellExecute(Self.Handle, 'open', PChar(ExecFilename), nil, PChar(ExtractFilePath(application.ExeName)), SW_SHOWNORMAL); end; procedure TfmFeedbackWizard.btnCopyClick(Sender: TObject); begin Clipboard.AsText := mmoReport.Lines.Text; end; procedure TfmFeedbackWizard.btnSaveClick(Sender: TObject); begin if GetOpenSaveDialogExecute(dlgSaveReport) then mmoReport.Lines.SaveToFile(dlgSaveReport.FileName); end; procedure TfmFeedbackWizard.btnCancelClick(Sender: TObject); begin Close; end; function TfmFeedbackWizard.IsValidTab(const Tab: TTabSheet): Boolean; begin Result := False; case FeedbackType of fbBug: Result := TabsNotForBugs.IndexOf(Tab) = -1; fbFeature: Result := TabsNotForFeatures.IndexOf(Tab) = -1; end; end; procedure TfmFeedbackWizard.CenterTabContents; begin if not Assigned(FActiveTab) then Exit; if (FActiveTab.ControlCount = 1) then CenterInParent(FActiveTab.Controls[0]); end; procedure TfmFeedbackWizard.pgeMainResize(Sender: TObject); begin CenterTabContents; end; procedure TfmFeedbackWizard.CenterInParent(Control: TControl); var Parent: TControl; begin Parent := Control.Parent; Assert(Assigned(Parent)); Control.Top := (Parent.ClientHeight - Control.Height) div 2; Control.Left := (Parent.ClientWidth - Control.Width) div 2; end; procedure TfmFeedbackWizard.pnlButtonsResize(Sender: TObject); begin CenterInParent(pnlButtonsCenter); end; procedure TfmFeedbackWizard.InitializeTabControls; const Steps = '1. Start %s from the start menu' + CRLF + '2. The default (empty) project is open' + CRLF + '3. On the main menu, select ...' + CRLF + '4.' + CRLF + '5.'; begin if FActiveTab = tshReport then GenerateReport; // Do not localize the lines below. if (FActiveTab = tshBugSteps) and (not mmoBugSteps.Modified) then mmoBugSteps.Lines.Text := Format(Steps, [FIDEName]); end; procedure TfmFeedbackWizard.GenerateReport; var Report: string; i: Integer; begin Report := ''; for i := 0 to pgeMain.PageCount - 1 do if IsValidTab(pgeMain.Pages[i]) then Report := Report + GetTabReportText(pgeMain.Pages[i]); mmoReport.Lines.Text := Report; end; procedure TfmFeedbackWizard.edtPercentKeyPress(Sender: TObject; var Key: Char); begin if not CharInSet(Key, ['0'..'9', #8]) then Key := #0; end; procedure TfmFeedbackWizard.UpdateInfo; var IsVisible: Boolean; begin SetDescriptionInfo; SetExampleInfo; IsVisible := mmoInfoHelp.Lines.Text <> ''; tshInfoHelp.TabVisible := IsVisible; IsVisible := mmoInfoExample.Lines.Text <> ''; tshInfoExample.TabVisible := IsVisible; IsVisible := tshInfoHelp.TabVisible or tshInfoExample.TabVisible; pgeInfo.Visible := IsVisible; Splitter.Visible := IsVisible; end; procedure TfmFeedbackWizard.InfoMemoEnter(Sender: TObject); begin pgeMain.SetFocus; end; function TfmFeedbackWizard.GetDestinationEmail: string; begin if FeedbackType = fbBug then Result := FBugEmail else Result := FFeatureEmail; end; function TfmFeedbackWizard.GetTabReportText(Tab: TTabSheet): string; const SDescription = 'Description:'; SSteps = 'Steps:'; begin Result := ''; if Tab = tshType then Result := 'GExperts ' + GetFeedbackTypeString + SkipLine // Do not localize. else if Tab = tshDescription then Result := SDescription + CRLF + mmoDescription.Lines.Text + SkipLine else if Tab = tshBugDetails then Result := GetBugDetailsString else if Tab = tshBugSteps then Result := SSteps + CRLF + mmoBugSteps.Lines.Text + SkipLine else if Tab = tshConfiguration then Result := GetSystemConfigurationString; end; function TfmFeedbackWizard.GetFeedbackTypeString: string; const SBugReport = 'Bug Report'; SFeatureRequest = 'Feature Request'; begin if FeedbackType = fbBug then Result := SBugReport else Result := SFeatureRequest; end; function TfmFeedbackWizard.GetBugDetailsString: string; const SBugDetails = 'Bug Details:'; SBugIsReproducible = ' The bug is reproducible %s%% of the time'; SBugIsNotReproducible = ' The bug is not reproducible'; begin Result := SBugDetails + CRLF; if chkReproducible.Checked then Result := Result + Format(SBugIsReproducible + CRLF, [edtPercent.Text]) else Result := Result + SBugIsNotReproducible + CRLF; if chkMultipleMachines.Checked then Result := Result + ' ' + StripHotkey(chkMultipleMachines.Caption) + CRLF; if chkProjectSpecific.Checked then Result := Result + ' ' + StripHotkey(chkProjectSpecific.Caption) + CRLF; Result := Result + CRLF; end; function GetGExpertsVersionString: string; begin Result := ExtractFileName(ThisDllName); Result := Result + ' ' + GetFileVersionString(ThisDllName, True, False); Result := Result + ' from ' + DateTimeToStr(GetFileDate(ThisDllName)); Result := Result + CRLF; end; // Do not localize any of the strings below. const cKeyNamePath = '\SYSTEM\CurrentControlSet\Control\Keyboard Layouts\'; cKeyCodePath = '\SYSTEM\CurrentControlSet\Control\Keyboard Layout\DosKeybCodes'; cKeySubCodes: array[0..7] of string = ('Unknown', 'IBM PC/XT or compatible (83-key) keyboard', 'Olivetti "ICO" (102-key) keyboard', 'IBM PC/AT (84-key) or similar keyboard', 'IBM enhanced (101 or 102-key) keyboard', 'Nokia 1050 and similar keyboards', 'Nokia 9140 and similar keyboards', 'Japanese keyboard'); cKeyNumFKeys: array[0..7] of string = ('Unknown', '10', '12 (18)', '10', '12', '10', '24', 'OEM'); cSysInfoProcessorText: array[0..4] of string = ('Intel', 'MIPS', 'ALPHA', 'PPC', 'UNKNOWN'); function GetKeyboardLayoutNameFromReg: string; var Reg: TRegistry; Name, Code, Dll: string; Layout: string; begin Result := '<unknown>'; SetLength(Layout, KL_NAMELENGTH); if not GetKeyboardLayoutName(PChar(Layout)) then Exit; Reg := TRegistry.Create(KEY_READ); try Reg.RootKey := HKEY_LOCAL_MACHINE; if Reg.OpenKey(cKeyNamePath + Layout, False) then begin Name := Reg.ReadString('Layout Text'); Dll := Reg.ReadString('Layout File'); end; Reg.CloseKey; if Reg.OpenKey(cKeyCodePath, False) then Code := Reg.ReadString(Layout); Reg.CloseKey; Result := Format('%s (%s) in %s', [Name, Code, Dll]); finally FreeAndNil(Reg); end; end; function GetLocaleKeyboardString: string; var Data: TStrings; begin Data := TStringList.Create; try Data.Add('Keyboard:'); Data.Add(Format(' Type %d: %s with %s FKeys', [GetKeyboardType(1), cKeySubCodes[Min(GetKeyboardType(0), 7)], cKeyNumFKeys[Min(GetKeyboardType(2), 7)]])); Data.Add(Format(' Layout: %s', [GetKeyboardLayoutNameFromReg])); Data.Add(''); Data.Add('Locale Info:'); Data.Add(Format(' Number of Digits: ''%s''', [GetLocaleChar(0, LOCALE_IDIGITS, '.')])); Data.Add(Format(' Leading Zero: ''%s''', [GetLocaleStr(0, LOCALE_ITLZERO, '0')])); Data.Add(Format(' List Separators: ''%s''', [GetLocaleStr(0, LOCALE_SLIST, '0')])); Data.Add(Format(' Grouping: ''%s''', [GetLocaleStr(0, LOCALE_SGROUPING, '0')])); Data.Add(Format(' Decimal Separator: ''%s''', [GetLocaleStr(0, LOCALE_SDECIMAL, '.')])); Data.Add(Format(' Group Separator: ''%s''', [GetLocaleStr(0, LOCALE_STHOUSAND, ',')])); Data.Add(Format(' Monetary Grouping: ''%s''', [GetLocaleStr(0, LOCALE_SMONGROUPING, '0')])); Data.Add(Format(' Monetary Decimal Separator: ''%s''', [GetLocaleStr(0, LOCALE_SMONDECIMALSEP, '0')])); Data.Add(Format(' Monetary Group Separator: ''%s''', [GetLocaleStr(0, LOCALE_SMONTHOUSANDSEP, '0')])); finally Result := Data.Text + CRLF; FreeAndNil(Data); end; end; function GetCPUSpeed: Extended; const DelayTime = 250; var TimerHi, TimerLo: DWORD; PriorityClass, Priority: Integer; begin try PriorityClass := GetPriorityClass(GetCurrentProcess()); Priority := GetThreadPriority(GetCurrentThread()); SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS); SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL); Sleep(10); asm dw 310Fh // rdtsc mov TimerLo, eax mov TimerHi, edx end; Sleep(DelayTime); asm dw 310Fh // rdtsc sub eax, TimerLo sbb edx, TimerHi mov TimerLo, eax mov TimerHi, edx end; SetThreadPriority(GetCurrentThread(), Priority); SetPriorityClass(GetCurrentProcess(), PriorityClass); Result := (TimerLo / DelayTime) * 999.1; // Inaccuracy in sleep except Result := 0; end; end; function GetCpuInfoString: string; var Data: TStringList; SysInfo: TSystemInfo; begin GetSystemInfo(SysInfo); Data := TStringList.Create; try Data.Add('CPU:'); Data.Add(Format(' # Processors: %d', [SysInfo.dwNumberOfProcessors])); Data.Add(Format(' Type: %s %d model %d Stepping %d', [cSysInfoProcessorText[SysInfo.wProcessorArchitecture], SysInfo.dwProcessorType, Integer(SysInfo.wProcessorRevision shr 8), Integer(SysInfo.wProcessorRevision and $00FF)])); Data.Add(Format(' Speed: %.2f MHz', [GetCPUSpeed / 1000000])); finally Result := Data.Text + CRLF; FreeAndNil(Data); end; end; function ReportItemsInRegistryKey(const Header, Key: string): string; var Reg: TRegistry; Names: TStringList; i: Integer; Value: string; begin Reg := TRegistry.Create(KEY_READ); try if Reg.OpenKey(Key, False) then begin Names := TStringList.Create; try Reg.GetValueNames(Names); Result := Result + Header + CRLF; for i := 0 to Names.Count - 1 do begin Value := Reg.ReadString(Names[i]); Result := Result + Format(' %s = %s', [Value, Names[i]]) + CRLF; end; finally FreeAndNil(Names); end; end else Result := 'No data for ' + Key + SkipLine; finally FreeAndNil(Reg); end; end; function GetInstalledExpertsString: string; begin Result := ReportItemsInRegistryKey('Installed Experts:', GxOtaGetIdeBaseRegistryKey + '\Experts') + CRLF; end; function GetInstalledPackagesString: string; begin Result := ReportItemsInRegistryKey('Installed Packages:', GxOtaGetIdeBaseRegistryKey + '\Known Packages') + CRLF; Result := Result + ReportItemsInRegistryKey('Installed IDE Packages:', GxOtaGetIdeBaseRegistryKey + '\Known IDE Packages') + CRLF; end; function GetGExpertsSettingsString: string; begin Result := ReportItemsInRegistryKey('GExperts Experts:', ConfigInfo.GExpertsIdeRootRegistryKey + '\EnabledExperts') + CRLF; end; function TfmFeedbackWizard.GetSystemConfigurationString: string; begin Result := 'Configuration:' + CRLF; Result := Result + ' OS: ' + GetOSString + CRLF; Result := Result + ' GExperts: ' + GetGExpertsVersionString; Result := Result + ' IDE: ' + TypInfo.GetEnumName(TypeInfo(TBorlandIdeVersion), Ord(GetBorlandIdeVersion)) + ' ' + GetIdeEdition + CRLF; Result := Result + ' ComCtl32: ' + GetFileVersionString('comctl32.dll', False) + SkipLine; if chkExperts.Checked then Result := Result + GetInstalledExpertsString; if chkPackages.Checked then Result := Result + GetInstalledPackagesString; if chkGExpertsSettings.Checked then Result := Result + GetGExpertsSettingsString; if chkCpu.Checked then Result := Result + GetCpuInfoString; if chkLocaleKeyboard.Checked then Result := Result + GetLocaleKeyboardString; end; procedure TfmFeedbackWizard.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; end; end.
unit hashed_command; interface THashedCommand=class(TAbstractTreeCommand) private fHash: T4x4LongWordRecord; procedure WriteHash(stream: TStream); procedure ReadHash(stream: TStream); function HashNotEmpty: boolean; protected procedure DefineProperties(Filer: TFiler); override; public function HashIsEqual(value: T4x4LongWordRecord): Boolean; function EqualsByAnyOtherName(what: TStreamingClass): boolean; override; //'old' command may compute hash and 'new' one not yet, but they still could //be equal constructor Create(owner: TComponent); override; property Hash: T4x4LongWordRecord read fHash; end; THashedDocument = class(TAbstractDocument) protected procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override; end; THashingThread=class(TThread) private fcommand: THashedCommand; fIsUndo: boolean; fErrorString: string; procedure ShowError; protected procedure Execute; override; public constructor Create(command: THashedCommand;isUndo: Boolean); end; implementation function THashedCommand.EqualsByAnyOtherName(what: TStreamingClass): boolean; begin end; (* THashedCommand *) constructor THashedCommand.Create(owner: TComponent); var i: Integer; begin inherited Create(owner); for i:=0 to 3 do fHash[i]:=0; end; procedure THashedCommand.DefineProperties(Filer: TFiler); begin Filer.DefineBinaryProperty('Hash',ReadHash,WriteHash,HashNotEmpty); end; function THashedCommand.HashNotEmpty: boolean; begin Result:=(fHash[0]<>0) and (fHash[1]<>0) and (fHash[2]<>0) and (fHash[3]<>0); end; procedure THashedCommand.WriteHash(stream: TStream); begin stream.Write(fHash[0],SizeOf(fHash)); end; procedure THashedCommand.ReadHash(stream: TStream); begin stream.Read(fHash[0],SizeOf(fHash)); end; function THashedCommand.HashIsEqual(value: T4x4LongWordRecord): boolean; var i: Integer; begin Result:=true; for i:=0 to 3 do if value[i]<>fHash[i] then Result:=false; end; (* THashingThread *) constructor THashingThread.Create(command: THashedCommand;isUndo: Boolean); begin inherited Create(true); priority:=tpIdle; fcommand:=command; fIsUndo:=isUndo; FreeOnTerminate:=true; Resume; end; procedure THashingThread.ShowError; begin application.MessageBox(PChar(fErrorString),'HashedCommand'); end; procedure THashingThread.Execute; var tmpHash: T4x4LongWordRecord; begin (fcommand.FindOwner as TAbstractDocument).fCriticalSection.Acquire; BeginHashEvent.SetEvent; tmpHash:=(fcommand.FindOwner as TAbstractDocument).Hash; if (fcommand.HashNotEmpty) and not (fcommand.HashIsEqual(tmpHash)) then begin if fIsUndo then fErrorString:='отмене' else fErrorString:='повторе'; // fErrorString:='Несовпадение хэша при '+fErrorString+' команды '+fcommand.Name+' ('+fcommand.ClassName+')'; fErrorString:='Несовпадение хэша при '+fErrorString+' команды '+ fcommand.ClassName+',было '+TIDHash128.AsHex(fcommand.Hash)+', стало '+ TIDHash128.AsHex(TmpHash); end else fcommand.fHash:=tmpHash; (fcommand.FindOwner as TAbstractDocument).fCriticalSection.Release; if fErrorString<>'' then Synchronize(ShowError); end; function TAbstractDocument.Hash: T4x4LongWordRecord; var buSaveWithUndo: boolean; buSaveFormat: TstreamingClassSaveFormat; str: TMemoryStream; // filestr: TFileStream; begin // fCriticalSection.Acquire; buSaveWithUndo:=SaveWithUndo; //потом вернем buSaveFormat:=SaveFormat; SaveWithUndo:=false; //чтобы найти хэш SaveFormat:=sfCyr; str:=TMemoryStream.Create; str.WriteComponent(self); str.Seek(0,soFromBeginning); with TIdHashMessageDigest5.Create do begin try Result:=HashValue(str); finally Free; end; end; //debug (* filestr:=TFileStream.Create(TIDHash128.AsHex(Result)+'.txt',fmCreate); str.Seek(0,soFromBeginning); filestr.CopyFrom(str,str.Size); filestr.Free; *) //end of debug str.Free; // self.saveFormat:=fCyr; // self.SaveToFile(TIDHash128.AsHex(Result)+'.txt'); SaveFormat:=buSaveFormat; SaveWithUndo:=buSaveWithUndo; // fCriticalSection.Leave; end; procedure THashedDocument.GetChildren(Proc: TGetChildProc; Root: TComponent); var i : Integer; fList: TStringList; begin fList:=TStringList.Create; try for i := 0 to ComponentCount-1 do if not (csSubComponent in Components[i].ComponentStyle) and (((Components[i]<>UndoContainer) and (Components[i]<>Tool)) or SaveWithUndo) then fList.AddObject(Components[i].Name,Components[i]); fList.Sort; //тем самым объекты расположатся в алфавитном порядке а не в порядке создания //поскольку разные манипуляции могут изменить порядок и не совпадет хэш //нам этого не надо! for i:=0 to fList.Count-1 do Proc( TComponent(fList.Objects[i]) ); finally fList.Free; end; end; end.
unit mgLngLst; (* // // module: mglnglst.pas // author: Mickael P. Golovin // // Copyright (c) 1997-2000 by Archivarius Team, free for non commercial use. // // $Id: mglnglst.pas,v 1.7 2013/04/05 12:04:42 lulin Exp $ // *) {$I m0Define.inc} interface uses Windows, Messages, SysUtils, Consts, Classes, l3Types, l3Base, m0Const, m0AddTyp, m0MEMLib, m0IDPLib, mgConst, mgBasLst ; type TmgLangFormHandle = class(TmgBaseHandle) private FStatus: longint; FValue: string; protected // internal methods class function IsCacheable: Bool; override; {-} public property Status: longint Read FStatus Write FStatus; property Value: string Read FValue Write FValue; procedure AssignHandle(AItem: TmgBaseHandle); override; end; PmgLangFormHandleKey = ^TmgLangFormHandleKey; TmgLangFormHandleKey = packed record RBuff: PAnsiChar; RSize: longint; end; TmgLangFormHandleList = class(TmgBaseHandleList) private function pm_GetHandle(AIndex: longint): TmgLangFormHandle; reintroduce; (* procedure pm_SetHandle(AIndex: longint; AHandle: TmgLangFormHandle); reintroduce;*) protected procedure AllocItem(var AItem: Pointer); override; function CompareKeyByItem(AKey: Pointer; AItem: Pointer): integer; override; public property Handles[AIndex: longint]: TmgLangFormHandle Read pm_GetHandle(* Write pm_SetHandle*); function BinSearchByKey(ABuff: PAnsiChar; ASize: longint; var AIndex: longint): longbool; end; (* TmgLangTokenHandle = class(TmgBaseHandle) private FPrefix: string; FSource: string; FSuffix: string; FSents: longint; FChars: longint; FBegPos: longint; FEndPos: longint; FLangFormList: TmgLangFormHandleList; function ClaInitProc0001(ADoneProc: Tm0IDPLibDoneProc): Tm0IDPLibDoneProc; procedure ClaDoneProc0001(); procedure pm_SetFormList(AFormList: TmgLangFormHandleList); public property Prefix: string Read FPrefix Write FPrefix; property Source: string Read FSource Write FSource; property Suffix: string Read FSuffix Write FSuffix; property Sents: longint Read FSents Write FSents; property Chars: longint Read FChars Write FChars; property BegPos: longint Read FBegPos Write FBegPos; property EndPos: longint Read FEndPos Write FEndPos; property LangFormList: TmgLangFormHandleList Read FLangFormList Write pm_SetFormList; constructor Create(); procedure AssignHandle(AItem: TmgBaseHandle); override; end;*) (* TmgLangTokenHandleList = class(TmgBaseHandleList) private function pm_GetHandle(AIndex: longint): TmgLangTokenHandle; reintroduce; procedure pm_SetHandle(AIndex: longint; AHandle: TmgLangTokenHandle); reintroduce; protected procedure AllocItem(var AItem: Pointer); override; public property Handles[AIndex: longint]: TmgLangTokenHandle Read pm_GetHandle Write pm_SetHandle; end;*) (* TmgDMYNTokenHandle = class(TmgBaseHandle) private FDay: longint; FMonth: longint; FYear: longint; FNumber: PAnsiChar; FNumberLength: longint; FSents: longint; FChars: longint; FBegPos: longint; FEndPos: longint; protected public property Day: longint Read FDay Write FDay; property Month: longint Read FMonth Write FMonth; property Year: longint Read FYear Write FYear; property Number: PAnsiChar Read FNumber Write FNumber; property NumberLength: longint Read FNumberLength Write FNumberLength; property Sents: longint Read FSents Write FSents; property Chars: longint Read FChars Write FChars; property BegPos: longint Read FBegPos Write FBegPos; property EndPos: longint Read FEndPos Write FEndPos; constructor Create(); procedure AssignHandle(AItem: TmgBaseHandle); override; end; TmgDMYNTokenHandleList = class(TmgBaseHandleList) private function pm_GetHandle(AIndex: longint): TmgDMYNTokenHandle; reintroduce; procedure pm_SetHandle(AIndex: longint; AHandle: TmgDMYNTokenHandle); reintroduce; protected procedure AllocItem(var AItem: Pointer); override; public property Handles[AIndex: longint]: TmgDMYNTokenHandle Read pm_GetHandle Write pm_SetHandle; end;*) implementation // start class TmgLangFormHandle class function TmgLangFormHandle.IsCacheable: Bool; //override; {-} begin Result := True; end; procedure TmgLangFormHandle.AssignHandle(AItem: TmgBaseHandle); var LItem: TmgLangFormHandle absolute AItem; begin Status := LItem.Status; Value := LItem.Value; end; { -- TmgLangFormHandleList.private -- } function TmgLangFormHandleList.pm_GetHandle(AIndex: longint): TmgLangFormHandle; begin Result := TmgLangFormHandle(GetItem(AIndex)); end; (*procedure TmgLangFormHandleList.pm_SetHandle(AIndex: longint; AHandle: TmgLangFormHandle); begin DoSetItem(AIndex, AHandle); end;*) { -- TmgLangFormHandleList.protected -- } procedure TmgLangFormHandleList.AllocItem(var AItem: Pointer); var LItem: TmgLangFormHandle absolute AItem; begin LItem := TmgLangFormHandle.Create(); end; function TmgLangFormHandleList.CompareKeyByItem(AKey: Pointer; AItem: Pointer): integer; var LItem: TmgLangFormHandle absolute AItem; LKey: PmgLangFormHandleKey absolute AKey; begin with LKey^ do begin with LItem do begin Result := m0MEMCompareEx(Pointer(RBuff), RSize, Pointer(Value), Length(Value)); end; end; end; { -- TmgLangFormHandleList.public -- } function TmgLangFormHandleList.BinSearchByKey(ABuff: PAnsiChar; ASize: longint; var AIndex: longint): longbool; var LKey: TmgLangFormHandleKey; begin with LKey do begin RBuff := ABuff; RSize := ASize; end; Result := FindItemByKey( @LKey, AIndex); end; (* { -- TmgLangTokenHandle.private -- } function TmgLangTokenHandle.ClaInitProc0001(ADoneProc: Tm0IDPLibDoneProc): Tm0IDPLibDoneProc; begin Result := ADoneProc; end; procedure TmgLangTokenHandle.ClaDoneProc0001(); begin l3Free(FLangFormList); end; procedure TmgLangTokenHandle.pm_SetFormList(AFormList: TmgLangFormHandleList); begin l3Set(FLangFormList, AFormList); end; { -- TmgLangTokenHandle.protected -- } { -- TmgLangTokenHandle.public -- } constructor TmgLangTokenHandle.Create(); begin inherited Create(); m0IDPAddDoneProc(FClaDoneProcHandle, ClaInitProc0001(ClaDoneProc0001)); end; procedure TmgLangTokenHandle.AssignHandle(AItem: TmgBaseHandle); var LItem: TmgLangTokenHandle absolute AItem; begin Prefix := LItem.Prefix; Source := LItem.Source; Suffix := LItem.Suffix; Sents := LItem.Sents; Chars := LItem.Chars; BegPos := LItem.BegPos; EndPos := LItem.EndPos; LangFormList := LItem.LangFormList; end;*) (* { -- TmgLangTokenHandleList.private -- } function TmgLangTokenHandleList.pm_GetHandle(AIndex: longint): TmgLangTokenHandle; begin Result := TmgLangTokenHandle(GetItem(AIndex)); end; procedure TmgLangTokenHandleList.pm_SetHandle(AIndex: longint; AHandle: TmgLangTokenHandle); begin DoSetItem(AIndex, AHandle); end; { -- TmgLangTokenHandleList.protected -- } procedure TmgLangTokenHandleList.AllocItem(var AItem: Pointer); var LItem: TmgLangTokenHandle absolute AItem; begin LItem := TmgLangTokenHandle.Create(); end;*) (*{ -- TmgDMYNTokenHandle.public -- } constructor TmgDMYNTokenHandle.Create(); begin inherited Create(); FDay := -1; FMonth := -1; FYear := -1; end; procedure TmgDMYNTokenHandle.AssignHandle(AItem: TmgBaseHandle); var LItem: TmgDMYNTokenHandle absolute AItem; begin Day := LItem.Day; Month := LItem.Month; Year := LItem.Year; Number := LItem.Number; NumberLength := LItem.NumberLength; Sents := LItem.Sents; Chars := LItem.Chars; BegPos := LItem.BegPos; EndPos := LItem.EndPos; end; { -- TmgDMYNTokenHandleList.private -- } function TmgDMYNTokenHandleList.pm_GetHandle(AIndex: longint): TmgDMYNTokenHandle; begin Result := TmgDMYNTokenHandle(GetItem(AIndex)); end; procedure TmgDMYNTokenHandleList.pm_SetHandle(AIndex: longint; AHandle: TmgDMYNTokenHandle); begin DoSetItem(AIndex, AHandle); end; { -- TmgDMYNTokenHandleList.protected -- } procedure TmgDMYNTokenHandleList.AllocItem(var AItem: Pointer); var LItem: TmgDMYNTokenHandle absolute AItem; begin LItem := TmgDMYNTokenHandle.Create(); end;*) end.
//Exercicio 20: Faça um algoritmo que verifique a validade de uma senha fornecida pelo usuário para ter acesso a //um terminal de consulta. A senha é um conjunto de caracteres que são: "fatecbt". O algoritmo deve imprimir //mensagem de permissão ou negação de acesso. { Solução em Portugol Algoritmo Exercicio 20; Var senha: caracter; Inicio exiba("Tela de acesso."); exiba("Digite a senha:"); leia(senha); se(senha = "fatecbt") então exiba("Acesso permitido.") senão exiba("Acesso negado."); fimse; Fim. } // Solução em Pascal Program Exercicio20; uses crt; var senha: string; begin clrscr; writeln('Tela de acesso'); writeln('Digite a senha:'); readln(senha); if(senha ='fatecbt') then writeln('Acesso permitido.') else writeln('Acesso negado.'); repeat until keypressed; end.
unit mod_tappywords; {$mode objfpc}{$H+} interface uses Classes, SysUtils, // FileUtil, // fpSound, // LCL ExtCtrls, IntfGraphics, LCLType, Forms, Controls, Graphics, Dialogs, StdCtrls, // TappyTux tappyconfig, tappydrawer, tappymodules; type { TTappyWords } TTappyWords = class(TTappyModule) private gameScore : Integer; gameLives : Integer; gameLevel : Integer; gameSLevel : Integer; gameSndFX : Boolean; gameMusic : Boolean; gameQuestionList : TStringList; count : Integer; timerWords: TTimer; NewQuestionFrequency: Integer; procedure HandleOnTimer(Sender: TObject); public constructor Create; override; destructor Destroy; override; procedure TranslateTextsToEnglish; override; procedure TranslateTextsToPortuguese; override; procedure StartNewGame(SndFX: Integer; Music: Integer; Level: Integer; QuestionList: Integer); override; procedure createQuestion(); override; function GetFallingDurationFromLevel: Integer; function GetTextFileFromLanguageId(AID: Integer): string; procedure Answered(AText: string); override; procedure EndGame(); override; procedure GameWon(); override; procedure GameLost(); override; procedure ProcessFallingTextEnd(); override; procedure ProcessSpriteEnd(AUserData: TObject; APosition: TPoint); override; end; var backgroundMusic: TSoundDocument; startupSound: TSoundDocument; implementation { TTappyWords } procedure TTappyWords.HandleOnTimer(Sender: TObject); var i: Integer; j: Integer; snowmanWrong: TFallingText; begin // Periodically create new questions count := count + timerWords.Interval; if count >= NewQuestionFrequency then begin count := 0; CreateQuestion(); end; vTappyTuxDrawer.HandleAnimationOnTimer(timerWords.Interval); end; constructor TTappyWords.Create; begin inherited Create; timerWords := TTimer.Create(nil); timerWords.Enabled := False; timerWords.Interval := 100; timerWords.OnTimer := @HandleOnTimer; NewQuestionFrequency := 5000; ConfigItems := 'English' + LineEnding + 'Portuguese' + LineEnding + 'French' + LineEnding + 'German' + LineEnding + 'Italian' + LineEnding + 'Afrikaans' + LineEnding; end; destructor TTappyWords.Destroy; begin timerWords.Free; inherited Destroy; end; procedure TTappyWords.TranslateTextsToEnglish; begin ShortDescription := 'TappyWords'; LongDescription := 'A game to learn typing and ortography.'; // Hint: Try to keep looking at the screen instead of the keyboard! ConfigCaption := 'Select a list of words'; end; procedure TTappyWords.TranslateTextsToPortuguese; begin ShortDescription := 'TappyWords'; LongDescription := 'Um jogo para aprender a digitar e ortografia'; ConfigCaption := 'Selecione uma lista de palavras'; end; procedure TTappyWords.StartNewGame(SndFX: Integer; Music: Integer; Level: Integer; QuestionList: Integer); var i: Integer; lTuxAnimation: TTappySpriteAnimation; begin count := 5; timerWords.Enabled := True; timerWords.Interval := 100; gameScore := 0; gameLives := 5; gameLevel := Level+1; if (Level < 0) then gameLevel := 1; if (SndFX <= 0) then gameSndFX := true; if (SndFX = 1) then gameSndFX := false; if (Music <= 0) then gameMusic := true; if (Music = 1) then gameMusic := false; gameSLevel := gameLevel; // Loads the list of questions if QuestionList < 0 then QuestionList := 0; gameQuestionList := TStringList.Create; gameQuestionList.LoadFromFile(vTappyTuxConfig.GetResourcesDir() + 'images' + PathDelim + 'modules' + PathDelim + 'tappywords' + PathDelim + GetTextFileFromLanguageId(QuestionList)); //gameQuestionList.LoadFromFile('C:/'+IntToStr(QuestionList)+'.txt'); UpdateLevel(gameLevel); UpdateScore(gameScore); UpdateLives(gameLives); // Animations Creation lTuxAnimation := TTappySpriteAnimation.Create; lTuxAnimation.IsInfinite := True; lTuxAnimation.StartPoint := Point(250, 328); lTuxAnimation.EndPoint := lTuxAnimation.StartPoint; SetLength(lTuxAnimation.Images, 6); lTuxAnimation.LoadImageFromPng(0, vTappyTuxConfig.GetResourcesDir() + 'images' + PathDelim + 'sprites' + PathDelim + 'tux_1.png'); lTuxAnimation.LoadImageFromPng(1, vTappyTuxConfig.GetResourcesDir() + 'images' + PathDelim + 'sprites' + PathDelim + 'tux_2.png'); lTuxAnimation.LoadImageFromPng(2, vTappyTuxConfig.GetResourcesDir() + 'images' + PathDelim + 'sprites' + PathDelim + 'tux_3.png'); lTuxAnimation.LoadImageFromPng(3, vTappyTuxConfig.GetResourcesDir() + 'images' + PathDelim + 'sprites' + PathDelim + 'tux_4.png'); lTuxAnimation.LoadImageFromPng(4, vTappyTuxConfig.GetResourcesDir() + 'images' + PathDelim + 'sprites' + PathDelim + 'tux_3.png'); lTuxAnimation.LoadImageFromPng(5, vTappyTuxConfig.GetResourcesDir() + 'images' + PathDelim + 'sprites' + PathDelim + 'tux_2.png'); vTappyTuxDrawer.AddAnimation(lTuxAnimation); //Sound Creation //backgroundMusic := TSoundDocument.Create; //backgroundMusic.LoadFromFile(vTappyTuxConfig.GetResourcesDir() + 'images' + PathDelim + 'music' + PathDelim + 'tux_1.png'); //startupSound := TSoundDocument.Create; //startupSound.LoadFromFile(vTappyTuxConfig.GetResourcesDir() + 'images' + PathDelim + 'sounds' + PathDelim + 'startup.wav'); for i:= 1 to 3 do begin CreateQuestion; end; startupSound.Play; end; procedure TTappyWords.CreateQuestion(); var i: Integer; j: Integer; xAux: Integer; yAux: Integer; heightAux: array [0..4] of integer; existenceAux: array [0..4] of boolean; snowmanAnimation: TFallingText; begin for i:= 0 to 4 do begin existenceAux[i]:= False; heightAux[i] := 500; end; xAux:=5; yAux:=5; snowmanAnimation := TFallingText.Create; for i:= 0 to vTappyTuxDrawer.GetAnimationCount - 1 do begin if vTappyTuxDrawer.GetAnimation(i).InheritsFrom(TFallingText) then begin for j:= 0 to 4 do begin if vTappyTuxDrawer.GetAnimation(i).StartPoint.X = 5+(103*j) then begin existenceAux[j] := True; if vTappyTuxDrawer.GetAnimation(i).Position.Y < heightAux[j] then heightAux[j] := vTappyTuxDrawer.GetAnimation(i).Position.Y; end; end; end; end; for i:= 0 to 4 do begin if heightAux[i] > yAux then begin yAux := heightAux[i]; xAux := 5 + i*103; end; end; if existenceAux[0] = false then xAux := 5 else begin if existenceAux[1] = false then xAux := 108 else begin if existenceAux[2] = false then xAux := 211 else begin if existenceAux[3] = false then xAux := 314 else begin if existenceAux[4] = false then xAux := 417 end; end; end; end; snowmanAnimation.StartPoint := Point(xAux, -100); snowmanAnimation.EndPoint := Point(xAux, 270); snowmanAnimation.IsInfinite := false; snowmanAnimation.StepCount := GetFallingDurationFromLevel(); snowmanAnimation.LoadImageFromPng(vTappyTuxConfig.GetResourcesDir() + 'images' + PathDelim + 'sprites' + PathDelim + 'snowman.png'); snowmanAnimation.caption:= gameQuestionList[random(gameQuestionList.Count - 1)]; vTappyTuxDrawer.AddAnimation(snowmanAnimation); end; function TTappyWords.GetFallingDurationFromLevel: Integer; begin case gameLevel of 1: Result := 25000; 2: Result := 20000; 3: Result := 15000; 4: Result := 10000; else Result := 7000; end; end; function TTappyWords.GetTextFileFromLanguageId(AID: Integer): string; begin case AID of 1: Result := 'wordlist.Portuguese'; 2: Result := 'wordlist.French'; 3: Result := 'wordlist.German'; 4: Result := 'wordlist.Italian'; 5: Result := 'wordlist.Afrikaans'; else Result := 'wordlist.English'; end; end; procedure TTappyWords.Answered(AText: string); var i: Integer; j: Integer; lAnimation: TTappyTuxAnimation; hammer: TTappySpriteAnimation; begin i:= 0; j:= vTappyTuxDrawer.GetAnimationCount - 1; while (i<= j) do begin lAnimation := vTappyTuxDrawer.GetAnimation(i); if lAnimation is TFallingText then begin if TFallingText(lAnimation).Caption = AText then begin gameScore := gameScore +1; gameLevel := (gameScore div 20) + gameSLevel; UpdateScore(gameScore); UpdateLevel(gameLevel); lAnimation.Stopped := True; hammer := TTappySpriteAnimation.Create; hammer.IsInfinite := False; hammer.StartPoint := Point(250, 328); hammer.EndPoint := lAnimation.Position; hammer.StepCount := 1000; hammer.SpriteChangeInterval := 200; SetLength(hammer.Images, 4); hammer.LoadImageFromPng(0, vTappyTuxConfig.GetResourcesDir() + 'images' + PathDelim + 'sprites' + PathDelim + 'hammer_1.png'); hammer.LoadImageFromPng(1, vTappyTuxConfig.GetResourcesDir() + 'images' + PathDelim + 'sprites' + PathDelim + 'hammer_2.png'); hammer.LoadImageFromPng(2, vTappyTuxConfig.GetResourcesDir() + 'images' + PathDelim + 'sprites' + PathDelim + 'hammer_3.png'); hammer.LoadImageFromPng(3, vTappyTuxConfig.GetResourcesDir() + 'images' + PathDelim + 'sprites' + PathDelim + 'hammer_4.png'); hammer.UserData := lAnimation; hammer.UserPosition := lAnimation.Position; vTappyTuxDrawer.AddAnimation(hammer); end; end; i := i + 1; j := vTappyTuxDrawer.GetAnimationCount - 1; end; end; procedure TTappyWords.EndGame; var i : Integer; j : Integer; gameOverScreen: TTappySpriteAnimation; continueBtn: TButton; exitBtn: TButton; begin timerWords.Enabled := False; // Delete all animations i:= 0; j:= vTappyTuxDrawer.GetAnimationCount - 1; while (i<= j) do begin vTappyTuxDrawer.RemoveAnimation(i); j := vTappyTuxDrawer.GetAnimationCount - 1; end; GoToConfigForm(); end; procedure TTappyWords.GameWon; var lRes: Integer; begin timerWords.Enabled := False; // Now check what the user desires to do lRes := Application.MessageBox( 'Congratulations, you have won the game =D Would you like to play again?', '', MB_YESNO); if lRes = ID_YES then RestartGame() else EndGame(); end; procedure TTappyWords.GameLost; var lRes: Integer; begin timerWords.Enabled := False; // Now check what the user desires to do lRes := Application.MessageBox( 'Unfortunately you have lost =P Would you like to play again?', '', MB_YESNO); if lRes = ID_YES then RestartGame() else EndGame(); end; procedure TTappyWords.ProcessFallingTextEnd; begin gameLives := gameLives - 1; UpdateLives(gameLives); if gameLives <= 0 then GameLost(); end; procedure TTappyWords.ProcessSpriteEnd(AUserData: TObject; APosition: TPoint); var snowmanRight: TFallingText; lIndex: Integer; begin snowmanRight := TFallingText.Create; snowmanRight.IsInfinite := False; snowmanRight.StartPoint := APosition; snowmanRight.EndPoint := APosition; snowmanRight.Position := APosition; snowmanRight.StepCount := 2000; snowmanRight.LoadImageFromPng(vTappyTuxConfig.GetResourcesDir() + 'images' + PathDelim + 'sprites' + PathDelim + 'snowmanright.png'); snowmanRight.caption:= 'OK!'; snowmanRight.ProcessOnEnd := False; vTappyTuxDrawer.AddAnimation(snowmanRight); lIndex := vTappyTuxDrawer.GetAnimationIndex(TTappyTuxAnimation(AUserData)); if lIndex >= 0 then vTappyTuxDrawer.RemoveAnimation(lIndex); end; initialization AddModule(TTappyWords.Create); end.
unit lazeyes2painter; {$mode objfpc}{$H+} interface uses Classes, Math, SysUtils, Graphics, Forms, LResources, StdCtrls, ExtCtrls, Controls, LCLType, LCLIntf; const // Sizes for the basic eye ellipse INT_EYE_WIDTH = 60; INT_EYE_HALFWIDTH = (INT_EYE_WIDTH div 2); INT_EYE_HALFWIDTH_SQR = INT_EYE_HALFWIDTH * INT_EYE_HALFWIDTH; INT_EYE_HEIGHT = 60; INT_EYE_HALFHEIGHT = (INT_EYE_HEIGHT div 2); INT_EYE_HALFHEIGHT_SQR = INT_EYE_HALFHEIGHT * INT_EYE_HALFHEIGHT; // This extra border width is the size of the pen, // and is also used to make the outer ellipse larger // then the puppil ellipse, to create a better // visual effect INT_BORDER_WIDTH = 15; INT_OUTER_EYE_WIDTH = INT_EYE_WIDTH + 2*INT_BORDER_WIDTH; INT_OUTER_EYE_HEIGHT = INT_EYE_HEIGHT+2*INT_BORDER_WIDTH; INT_INTEREYE_SPACE = 20; INT_WINDOW_WIDTH = 2*INT_OUTER_EYE_WIDTH + INT_OUTER_EYE_HEIGHT; type { TLazEye2Painter } TLazEye2Painter = class(TCustomControl) public procedure EraseBackground(DC: HDC); override; procedure Paint; override; procedure DrawToCanvas(ACanvas: TCanvas); property OnMouseDown; property OnMouseMove; property OnMouseUp; end; var MousePos, LeftEyePos, RightEyePos: TPoint; implementation procedure TLazEye2Painter.EraseBackground(DC: HDC); begin // Uncomment this to enable default background erasing //inherited EraseBackground(DC); end; procedure TLazEye2Painter.Paint; var Bitmap: TBitmap; begin Bitmap := TBitmap.Create; try // Initializes the Bitmap Size Bitmap.Height := Height; Bitmap.Width := Width; DrawToCanvas(Bitmap.Canvas); Canvas.Draw(0, 0, Bitmap); finally Bitmap.Free; end; inherited Paint; end; procedure TLazEye2Painter.DrawToCanvas(ACanvas: TCanvas); begin // Background ACanvas.Brush.Color := clWhite; ACanvas.Pen.Color := clWhite; ACanvas.FillRect(0, 0, Width, Height); // Eyes form ACanvas.Pen.Color := clBlack; ACanvas.Pen.Width := 5; ACanvas.Ellipse( 0, 0, INT_OUTER_EYE_WIDTH, INT_OUTER_EYE_HEIGHT); ACanvas.Ellipse( INT_OUTER_EYE_WIDTH + INT_INTEREYE_SPACE, 0, 2* INT_OUTER_EYE_WIDTH + INT_INTEREYE_SPACE, INT_OUTER_EYE_HEIGHT); // Eyes pupils ACanvas.Brush.Color := clBlack; ACanvas.Pen.Width := 10; ACanvas.Ellipse( LeftEyePos.X - 2, LeftEyePos.Y - 2, LeftEyePos.X + 2, LeftEyePos.Y + 2); ACanvas.Ellipse( RightEyePos.X - 2, RightEyePos.Y - 2, RightEyePos.X + 2, RightEyePos.Y + 2); end; end.
unit sim_hid_io; { ################################################################################ Author: Ulrich Hornung Date: März 2008 Funktion: Simulieren von Benutzereingaben über die "Standart"-Delphi Möglichkeiten -> Steuerung von Metin2 (nur Tastatureingaben) Funktioniert leider nicht so toll -> Aushilfe: Synergy (siehe synergy_server_sim) ################################################################################ } interface uses Controls, Types, Windows; procedure sim_io_MouseMove(x, y: Integer); procedure sim_io_MouseDown(mousebutton: TMouseButton = mbleft); procedure sim_io_MouseUp(mousebutton: TMouseButton = mbleft); procedure sim_io_KeyDown(C: Char); procedure sim_io_KeyUp(C: Char); procedure sim_io_TypeString(S: string); procedure sim_io_MouseClick(p: TPoint; mousebutton: TMouseButton); implementation procedure sim_io_MouseMove(x, y: Integer); begin Mouse.CursorPos := Point((x),(y)); end; procedure sim_io_MouseDown(mousebutton: TMouseButton = mbleft); begin case mousebutton of mbLeft: mouse_event(MOUSEEVENTF_LEFTDOWN,0,0,0,0); mbRight: mouse_event(MOUSEEVENTF_RIGHTDOWN,0,0,0,0); mbMiddle: mouse_event(MOUSEEVENTF_MIDDLEDOWN,0,0,0,0); end; end; procedure sim_io_MouseUp(mousebutton: TMouseButton = mbleft); begin case mousebutton of mbLeft: mouse_event(MOUSEEVENTF_LEFTUP,0,0,0,0); mbRight: mouse_event(MOUSEEVENTF_RIGHTUP,0,0,0,0); mbMiddle: mouse_event(MOUSEEVENTF_MIDDLEUP,0,0,0,0); end; end; procedure sim_io_KeyDown(C: Char); begin keybd_event(Byte(C),0,0,0); end; procedure sim_io_KeyUp(C: Char); begin keybd_event(Byte(C),0,KEYEVENTF_KEYUP,0); end; procedure sim_io_TypeString(S: string); var i: integer; c: char; w: word; begin for i := 1 to length(s) do begin w := Word(VkKeyScan(s[i])); c := char(w); if (w and $0100 > 0) then sim_io_KeyDown(char(VK_SHIFT)); //SHIFT if (w and $0200 > 0) then sim_io_KeyDown(char(VK_CONTROL)); //CTRL if (w and $0400 > 0) then sim_io_KeyDown(char(VK_MENU)); //ALT sim_io_KeyDown(c); sim_io_KeyUp(c); if (w and $0100 > 0) then sim_io_KeyUp(char(VK_SHIFT)); if (w and $0200 > 0) then sim_io_KeyUp(char(VK_CONTROL)); if (w and $0400 > 0) then sim_io_KeyUp(char(VK_MENU)); end; end; procedure sim_io_MouseClick(p: Tpoint; mousebutton: TMouseButton); begin sim_io_MouseMove(p.X, p.Y); sim_io_MouseDown(mousebutton); sim_io_MouseUp(mousebutton); end; end.
unit creaturesStrUtils; interface function ReplaceStr(const str: String; const find, replace: string): string; implementation uses StrUtils, Classes, SysUtils; function ReplaceStr(const str: String; const find, replace: string): string; var pstart, pfind: integer; begin Result := ''; pstart := 1; pfind := PosEx(find, str, pstart); while pfind > 0 do begin Result := Result + copy(str,pstart,pfind-pstart); pstart := pfind + length(find); pfind := PosEx(find, str, pstart); end; end; end.
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Program: NsLookup Description: Demo for DnsQuery ICS component. Author: François Piette Creation: January 29, 1999 Version: 6.00 EMail: francois.piette@overbyte.be http://www.overbyte.be Support: Use the mailing list twsocket@elists.org Follow "support" link at http://www.overbyte.be for subscription. Legal issues: Copyright (C) 1999-2006 by François PIETTE Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56 <francois.piette@overbyte.be> This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. History: Feb 27, 1999 V1.01 Added PTR lookup (reverse DNS lookup) Mar 07, 1999 V1.02 Adapted for Delphi 1 May 29, 2005 V1.03 Added TCP/UDP protocol selection. Added version infos. Mar 26, 2006 V6.00 New version 6 started * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} unit OverbyteIcsNsLookup1; interface uses WinTypes, WinProcs, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, IniFiles, StdCtrls, ExtCtrls, Buttons, OverbyteIcsWinSock, OverbyteIcsWSocket, OverbyteIcsDnsQuery; const NsLookVersion = 600; CopyRight : String = ' NsLookup (c) 1999-2006 F. Piette V6.00 '; type TNsLookupForm = class(TForm) DisplayMemo: TMemo; Panel1: TPanel; DnsEdit: TEdit; NameEdit: TEdit; MXLookupButton: TButton; DnsQuery1: TDnsQuery; ClearDisplayBitBtn: TBitBtn; ALookupButton: TButton; PTRLookupButton: TButton; TcpRadioButton: TRadioButton; UdpRadioButton: TRadioButton; procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure MXLookupButtonClick(Sender: TObject); procedure DnsQuery1RequestDone(Sender: TObject; Error: Word); procedure ClearDisplayBitBtnClick(Sender: TObject); procedure ALookupButtonClick(Sender: TObject); procedure PTRLookupButtonClick(Sender: TObject); private FIniFileName : String; FInitialized : Boolean; FRequestID : Integer; procedure Display(Msg : String); procedure DumpDnsResponse; public property IniFileName : String read FIniFileName write FIniFileName; end; var NsLookupForm: TNsLookupForm; implementation {$R *.DFM} const SectionWindow = 'Window'; KeyTop = 'Top'; KeyLeft = 'Left'; KeyWidth = 'Width'; KeyHeight = 'Height'; SectionData = 'Data'; KeyName = 'Name'; KeyDns = 'Dns'; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNsLookupForm.FormCreate(Sender: TObject); begin FIniFileName := LowerCase(ExtractFileName(Application.ExeName)); FIniFileName := Copy(FIniFileName, 1, Length(FIniFileName) - 3) + 'ini'; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNsLookupForm.FormShow(Sender: TObject); var IniFile : TIniFile; begin if not FInitialized then begin FInitialized := TRUE; IniFile := TIniFile.Create(FIniFileName); Width := IniFile.ReadInteger(SectionWindow, KeyWidth, Width); Height := IniFile.ReadInteger(SectionWindow, KeyHeight, Height); Top := IniFile.ReadInteger(SectionWindow, KeyTop, (Screen.Height - Height) div 2); Left := IniFile.ReadInteger(SectionWindow, KeyLeft, (Screen.Width - Width) div 2); NameEdit.Text := IniFile.ReadString(SectionData, KeyName, 'borland.com'); DnsEdit.Text := IniFile.ReadString(SectionData, KeyDns, '193.121.171.135'); DisplayMemo.Clear; Display(Trim(CopyRight)); IniFile.Destroy; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNsLookupForm.FormClose(Sender: TObject; var Action: TCloseAction); var IniFile : TIniFile; begin IniFile := TIniFile.Create(FIniFileName); IniFile.WriteInteger(SectionWindow, KeyTop, Top); IniFile.WriteInteger(SectionWindow, KeyLeft, Left); IniFile.WriteInteger(SectionWindow, KeyWidth, Width); IniFile.WriteInteger(SectionWindow, KeyHeight, Height); IniFile.WriteString(SectionData, KeyName, NameEdit.Text); IniFile.WriteString(SectionData, KeyDns, DnsEdit.Text); IniFile.Destroy; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNsLookupForm.Display(Msg : String); begin if DisplayMemo.Lines.Count > 200 then DisplayMemo.Lines.Delete(0); DisplayMemo.Lines.Add(Msg); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNsLookupForm.DumpDnsResponse; var P : PChar; I : Integer; Len : Integer; Buf : String; begin Display('Response dump (' + IntToStr(DnsQuery1.ResponseLen) + ' bytes):'); P := DnsQuery1.ResponseBuf; Len := DnsQuery1.ResponseLen; Buf := ''; I := 0; while I < Len do begin if P^ in [' '..'~'] then Buf := Buf + P^ else Buf := Buf + '<' + IntToStr(Ord(P^)) + '>'; Inc(I); Inc(P); if (I mod 16) = 0 then begin Display(' ' + Buf); Buf := ''; end; end; if Length(Buf) > 0 then Display(' ' + Buf); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNsLookupForm.DnsQuery1RequestDone(Sender: TObject; Error: Word); var I : Integer; nIndex : Integer; begin if Error <> 0 then begin Display('Error #' + IntToStr(Error)); Exit; end; Display('ID : ' + IntToStr(DnsQuery1.ResponseID)); Display('ResponseCode : ' + IntToStr(DnsQuery1.ResponseCode)); Display('OpCode : ' + IntToStr(DnsQuery1.ResponseOpCode)); Display('Authoritative : ' + IntToStr(Ord(DnsQuery1.ResponseAuthoritative))); Display('Truncation : ' + IntToStr(Ord(DnsQuery1.ResponseTruncation))); Display('RecursionAvailable : ' + IntToStr(Ord(DnsQuery1.ResponseRecursionAvailable))); Display('QDCount : ' + IntToStr(DnsQuery1.ResponseQDCount)); Display('ANCount : ' + IntToStr(DnsQuery1.ResponseANCount)); Display('NSCount : ' + IntToStr(DnsQuery1.ResponseNSCount)); Display('ARCount : ' + IntToStr(DnsQuery1.ResponseARCount)); Display('ResponseLen : ' + IntToStr(DnsQuery1.ResponseLen)); Display('QuestionName : ' + DnsQuery1.QuestionName); Display('QuestionType : ' + IntToStr(DnsQuery1.QuestionType)); Display('QuestionClass : ' + IntToStr(DnsQuery1.QuestionClass)); for I := 0 to DnsQuery1.ResponseANCount - 1 do begin Display('Answer #' + IntToStr(I + 1)); Display(' AnswerName : ' + DnsQuery1.AnswerName[I]); Display(' AnswerType : ' + IntToStr(DnsQuery1.AnswerType[I])); Display(' AnswerClass : ' + IntToStr(DnsQuery1.AnswerClass[I])); Display(' AnswerTTL : ' + IntToStr(DnsQuery1.AnswerTTL[I])); nIndex := DnsQuery1.AnswerTag[I]; if nIndex >= 0 then begin case DnsQuery1.AnswerType[I] of DnsQueryMX: begin Display(' MXPreference : ' + IntToStr(DnsQuery1.MXPreference[nIndex])); Display(' MXExchange : ' + DnsQuery1.MXExchange[nIndex]); end; DnsQueryA: begin Display(' Address : ' + WSocket_inet_ntoa(DnsQuery1.Address[nIndex])); end; DnsQueryPTR: begin Display(' Hostname : ' + DnsQuery1.Hostname[nIndex]); end; end; end; end; { Dump complete response } DumpDnsResponse; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNsLookupForm.ClearDisplayBitBtnClick(Sender: TObject); begin DisplayMemo.Clear; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNsLookupForm.MXLookupButtonClick(Sender: TObject); begin if UdpRadioButton.Checked then DnsQuery1.Proto := 'udp' else DnsQuery1.Proto := 'tcp'; DnsQuery1.Addr := DnsEdit.Text; FRequestID := DnsQuery1.MXLookup(NameEdit.Text); Display('Request ID : ' + IntToStr(FRequestID)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNsLookupForm.ALookupButtonClick(Sender: TObject); begin if UdpRadioButton.Checked then DnsQuery1.Proto := 'udp' else DnsQuery1.Proto := 'tcp'; DnsQuery1.Addr := DnsEdit.Text; FRequestID := DnsQuery1.ALookup(NameEdit.Text); Display('Request ID : ' + IntToStr(FRequestID)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TNsLookupForm.PTRLookupButtonClick(Sender: TObject); begin if UdpRadioButton.Checked then DnsQuery1.Proto := 'udp' else DnsQuery1.Proto := 'tcp'; DnsQuery1.Addr := DnsEdit.Text; FRequestID := DnsQuery1.PTRLookup(NameEdit.Text); Display('Request ID : ' + IntToStr(FRequestID)); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} end.
unit evCopyTableCellWidth; {* Интсрумент для копирования ширин колонок из одной таблицы в другую. } // Модуль: "w:\common\components\gui\Garant\Everest\evCopyTableCellWidth.pas" // Стереотип: "SimpleClass" // Элемент модели: "TevCopyTableCellWidth" MUID: (4F28F7160399) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface uses l3IntfUses , l3ProtoObject , evCellsOffsetsList , l3Variant , evEditorInterfaces , l3Interfaces ; type TevCopyTableCellWidth = {final} class(Tl3ProtoObject) {* Интсрумент для копирования ширин колонок из одной таблицы в другую. } private f_TemplatesArray: TevCellsOffsetsList; f_TableTag: Tl3Tag; private procedure RememberRowWidth(const anIterator: IedCellsIterator); protected procedure Cleanup; override; {* Функция очистки полей объекта. } public procedure RememberWidths(const aRange: IedRange); virtual; procedure ApplyWidths(const aRange: IedRange; const aProgress: Il3Progress = nil); virtual; function CanApply: Boolean; virtual; procedure Clear; virtual; class function Instance: TevCopyTableCellWidth; {* Метод получения экземпляра синглетона TevCopyTableCellWidth } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } end;//TevCopyTableCellWidth implementation uses l3ImplUses , nevBase , evCellsWidthCorrecter , SysUtils , l3Base //#UC START# *4F28F7160399impl_uses* //#UC END# *4F28F7160399impl_uses* ; var g_TevCopyTableCellWidth: TevCopyTableCellWidth = nil; {* Экземпляр синглетона TevCopyTableCellWidth } procedure TevCopyTableCellWidthFree; {* Метод освобождения экземпляра синглетона TevCopyTableCellWidth } begin l3Free(g_TevCopyTableCellWidth); end;//TevCopyTableCellWidthFree procedure TevCopyTableCellWidth.RememberRowWidth(const anIterator: IedCellsIterator); //#UC START# *4F29052701FB_4F28F7160399_var* //#UC END# *4F29052701FB_4F28F7160399_var* begin //#UC START# *4F29052701FB_4F28F7160399_impl* f_TemplatesArray.Try2RemeberWidths(anIterator); //#UC END# *4F29052701FB_4F28F7160399_impl* end;//TevCopyTableCellWidth.RememberRowWidth procedure TevCopyTableCellWidth.RememberWidths(const aRange: IedRange); //#UC START# *4F28FC7702ED_4F28F7160399_var* var l_Row : IedRow; l_Table : IedTable; l_RowsIterator : IedRowsIterator; l_CellIterator : IedCellsIterator; //#UC END# *4F28FC7702ED_4F28F7160399_var* begin //#UC START# *4F28FC7702ED_4F28F7160399_impl* if (aRange <> nil) then begin l_Table := aRange.Table; if (l_Table <> nil) then begin l_RowsIterator := l_Table.RowsIterator; if (l_RowsIterator <> nil) then begin l_Row := l_RowsIterator.First; if f_TemplatesArray = nil then f_TemplatesArray := TevCellsOffsetsList.Create else f_TemplatesArray.Clear; while (l_Row <> nil) do begin l_CellIterator := l_Row.CellsIterator; if l_CellIterator <> nil then RememberRowWidth(l_CellIterator); l_Row := l_RowsIterator.Next; end; // while (l_Row <> nil) do l_Table.GetTag.SetRef(f_TableTag); end; // if (l_RowsIterator <> nil) then end; // if (l_Table <> nil) then end; // if (aRange <> nil) then //#UC END# *4F28FC7702ED_4F28F7160399_impl* end;//TevCopyTableCellWidth.RememberWidths procedure TevCopyTableCellWidth.ApplyWidths(const aRange: IedRange; const aProgress: Il3Progress = nil); //#UC START# *4F28FC900076_4F28F7160399_var* var l_Table: IedTable; //#UC END# *4F28FC900076_4F28F7160399_var* begin //#UC START# *4F28FC900076_4F28F7160399_impl* if (aRange <> nil) then begin l_Table := aRange.Table; if (l_Table <> nil) and (f_TemplatesArray <> nil) and (f_TemplatesArray.Count > 0) then begin if l_Table.GetTag.IsSame(f_TableTag) then TevCellsWidthCorrecter.DoCorrection(l_Table, nil, True, aProgress) else TevCellsWidthCorrecter.DoCorrection(l_Table, f_TemplatesArray, True, aProgress); end; // if (l_Table <> nil) and (f_TemplatesArray <> nil) and (f_TemplatesArray.Count > 0) then end; // if (aRange <> nil) then //#UC END# *4F28FC900076_4F28F7160399_impl* end;//TevCopyTableCellWidth.ApplyWidths function TevCopyTableCellWidth.CanApply: Boolean; //#UC START# *4F28FCC703E7_4F28F7160399_var* //#UC END# *4F28FCC703E7_4F28F7160399_var* begin //#UC START# *4F28FCC703E7_4F28F7160399_impl* Result := (f_TemplatesArray <> nil) and (f_TemplatesArray.Count > 0); //#UC END# *4F28FCC703E7_4F28F7160399_impl* end;//TevCopyTableCellWidth.CanApply procedure TevCopyTableCellWidth.Clear; //#UC START# *4F28FCDD00F8_4F28F7160399_var* //#UC END# *4F28FCDD00F8_4F28F7160399_var* begin //#UC START# *4F28FCDD00F8_4F28F7160399_impl* l3Free(f_TemplatesArray); FreeAndNil(f_TableTag); inherited; //#UC END# *4F28FCDD00F8_4F28F7160399_impl* end;//TevCopyTableCellWidth.Clear class function TevCopyTableCellWidth.Instance: TevCopyTableCellWidth; {* Метод получения экземпляра синглетона TevCopyTableCellWidth } begin if (g_TevCopyTableCellWidth = nil) then begin l3System.AddExitProc(TevCopyTableCellWidthFree); g_TevCopyTableCellWidth := Create; end; Result := g_TevCopyTableCellWidth; end;//TevCopyTableCellWidth.Instance class function TevCopyTableCellWidth.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_TevCopyTableCellWidth <> nil; end;//TevCopyTableCellWidth.Exists procedure TevCopyTableCellWidth.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_4F28F7160399_var* //#UC END# *479731C50290_4F28F7160399_var* begin //#UC START# *479731C50290_4F28F7160399_impl* l3Free(f_TemplatesArray); FreeAndNil(f_TableTag); inherited; //#UC END# *479731C50290_4F28F7160399_impl* end;//TevCopyTableCellWidth.Cleanup end.
unit Validator; interface procedure ValidateFilename(const FileName: string); implementation uses System.IOUtils, System.SysUtils; procedure ValidateFilename(const FileName: string); var ADirectory: string; begin if not TPath.HasValidPathChars(FileName, False) then raise Exception.CreateFmt('Invalid file path "%s"', [FileName]); if not TPath.HasValidFileNameChars(TPath.GetFileName(FileName), False) then raise Exception.CreateFmt('Invalid file name "%s"', [FileName]); ADirectory := TPath.GetDirectoryName(FileName); if (ADirectory <> '') and not TDirectory.Exists(ADirectory) then raise Exception.CreateFmt('Directory "%s" is not exist', [ADirectory]); end; end.
unit add_account; interface uses account; type {$M+} IAddAccountModel = interface ['{F54BD6F9-0516-4DB6-A564-2224F5748874}'] function name: String; overload; function name(const AValue: String): IAddAccountModel; overload; function email: String; overload; function email(const AValue: String): IAddAccountModel; overload; function password: String; overload; function password(const AValue: String): IAddAccountModel; overload; end; IAddAccount = interface ['{3212DFB8-7B72-4406-895A-290E85CA7001}'] function add(const account: IAddAccountModel): IAccountModel; end; TAddAccountModel = class(TInterfacedObject, IAddAccountModel) private FName: String; FEmail: String; FPassword: String; function name: String; overload; function name(const AValue: String): IAddAccountModel; overload; function email: String; overload; function email(const AValue: String): IAddAccountModel; overload; function password: String; overload; function password(const AValue: String): IAddAccountModel; overload; public class function New: IAddAccountModel; end; {$M-} implementation function TAddAccountModel.email: String; begin result := FEmail; end; function TAddAccountModel.email(const AValue: String): IAddAccountModel; begin FEmail := AValue; result := self; end; function TAddAccountModel.name(const AValue: String): IAddAccountModel; begin FName := AValue; result := self; end; function TAddAccountModel.name: String; begin result := FName; end; class function TAddAccountModel.New: IAddAccountModel; begin result := self.Create; end; function TAddAccountModel.password: String; begin result := FPassword; end; function TAddAccountModel.password(const AValue: String): IAddAccountModel; begin FPassword := AValue; result := self; end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpDerGeneralString; {$I ..\Include\CryptoLib.inc} interface uses Classes, SysUtils, ClpDerStringBase, ClpAsn1Tags, ClpAsn1OctetString, ClpAsn1Object, ClpIProxiedInterface, ClpDerOutputStream, ClpCryptoLibTypes, ClpIAsn1TaggedObject, ClpIDerGeneralString, ClpConverters; resourcestring SIllegalObject = 'Illegal Object in GetInstance: %s'; SStrNil = '"str"'; type TDerGeneralString = class(TDerStringBase, IDerGeneralString) strict private var FStr: String; function GetStr: String; inline; property Str: String read GetStr; strict protected function Asn1Equals(const asn1Object: IAsn1Object): Boolean; override; public constructor Create(const Str: TCryptoLibByteArray); overload; constructor Create(const Str: String); overload; function GetString(): String; override; function GetOctets(): TCryptoLibByteArray; inline; procedure Encode(const derOut: TStream); override; class function GetInstance(const obj: TObject): IDerGeneralString; overload; static; inline; class function GetInstance(const obj: IAsn1TaggedObject; isExplicit: Boolean): IDerGeneralString; overload; static; inline; end; implementation { TDerGeneralString } function TDerGeneralString.GetStr: String; begin result := FStr; end; function TDerGeneralString.GetOctets: TCryptoLibByteArray; begin result := TConverters.ConvertStringToBytes(Str, TEncoding.ASCII); end; function TDerGeneralString.Asn1Equals(const asn1Object: IAsn1Object): Boolean; var other: IDerGeneralString; begin if (not Supports(asn1Object, IDerGeneralString, other)) then begin result := false; Exit; end; result := Str = other.Str; end; constructor TDerGeneralString.Create(const Str: TCryptoLibByteArray); begin Create(TConverters.ConvertBytesToString(Str, TEncoding.ASCII)); end; constructor TDerGeneralString.Create(const Str: String); begin Inherited Create(); if (Str = '') then begin raise EArgumentNilCryptoLibException.CreateRes(@SStrNil); end; FStr := Str; end; procedure TDerGeneralString.Encode(const derOut: TStream); begin (derOut as TDerOutputStream).WriteEncoded(TAsn1Tags.GeneralString, GetOctets()); end; class function TDerGeneralString.GetInstance(const obj: TObject) : IDerGeneralString; begin if ((obj = Nil) or (obj is TDerGeneralString)) then begin result := obj as TDerGeneralString; Exit; end; raise EArgumentCryptoLibException.CreateResFmt(@SIllegalObject, [obj.ClassName]); end; class function TDerGeneralString.GetInstance(const obj: IAsn1TaggedObject; isExplicit: Boolean): IDerGeneralString; var o: IAsn1Object; begin o := obj.GetObject(); if ((isExplicit) or (Supports(o, IDerGeneralString))) then begin result := GetInstance(o as TAsn1Object); Exit; end; result := TDerGeneralString.Create (TAsn1OctetString.GetInstance(o as TAsn1Object).GetOctets()); end; function TDerGeneralString.GetString: String; begin result := Str; end; end.
unit cCadCongregacao; interface uses System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Dialogs, FireDAC.Comp.Client, System.SysUtils; // LISTA DE UNITS type TCongregacao = class private // VARIAVEIS PRIVADA SOMENTE DENTRO DA CLASSE ConexaoDB: TFDConnection; F_cod_congregacao: Integer; F_cod_central: Integer; F_congregacao: string; F_setor: string; F_polo: string; F_situacao: string; F_telefone: string; F_cnpj: string; F_siteblog: string; F_endereco: string; F_complemento: string; F_bairro: string; F_cep: string; F_cidade: string; F_diasculto: string; F_diacoa: string; F_diacom: string; F_diacoi: string; F_diacv: string; F_data_aber_sub: TDateTime; F_data_aber_cong: TDateTime; F_data_fun_coa: TDateTime; F_data_fun_com: TDateTime; F_data_fun_coi: TDateTime; F_data_fun_cv: TDateTime; F_data_cadastro: TDateTime; F_usuario_cadastro: string; F_cong_principal: string; F_dirigente: string; F_cod_setor: string; F_cod_igreja: string; F_cod_cc: Integer; F_sigla: string; F_cod_dirigente: Integer; F_percentual_central:string; F_percentual_valor:Double; F_meta_central:string; F_meta_valor:Double; public constructor Create(aConexao: TFDConnection); // CONSTRUTOR DA CLASSE destructor Destroy; override; // DESTROI A CLASSE USAR OVERRIDE POR CAUSA function Inserir: Boolean; function Atualizar: Boolean; function Apagar: Boolean; function Selecionar(id: Integer): Boolean; published // VARIAVEIS PUBLICAS UTILAIZADAS PARA PROPRIEDADES DA CLASSE // PARA FORNECER INFORMAÇÕESD EM RUMTIME property cod_congregacao: Integer read F_cod_congregacao write F_cod_congregacao; property cod_central: Integer read F_cod_central write F_cod_central; property congregacao: string read F_congregacao write F_congregacao; property setor: string read F_setor write F_setor; property polo: string read F_polo write F_polo; property situacao: string read F_situacao write F_situacao; property telefone: string read F_telefone write F_telefone; property cnpj: string read F_cnpj write F_cnpj; property siteblog: string read F_siteblog write F_siteblog; property endereco: string read F_endereco write F_endereco; property complemento: string read F_complemento write F_complemento; property bairro: string read F_bairro write F_bairro; property cep: string read F_cep write F_cep; property cidade: string read F_cidade write F_cidade; property diasculto: string read F_diasculto write F_diasculto; property diacoa: string read F_diacoa write F_diacoa; property diacom: string read F_diacom write F_diacom; property diacoi: string read F_diacoi write F_diacoi; property diacv: string read F_diacv write F_diacv; property data_aber_sub: TDateTime read F_data_aber_sub write F_data_aber_sub; property data_aber_cong: TDateTime read F_data_aber_cong write F_data_aber_cong; property data_fun_coa: TDateTime read F_data_fun_coa write F_data_fun_coa; property data_fun_com: TDateTime read F_data_fun_com write F_data_fun_com; property data_fun_coi: TDateTime read F_data_fun_coi write F_data_fun_coi; property data_fun_cv: TDateTime read F_data_fun_cv write F_data_fun_cv; property data_cadastro: TDateTime read F_data_cadastro write F_data_cadastro; property usuario_cadastro: string read F_usuario_cadastro write F_usuario_cadastro; property cong_principal: string read F_cong_principal write F_cong_principal; property dirigente: string read F_dirigente write F_dirigente; property cod_setor: string read F_cod_setor write F_cod_setor; property cod_igreja: string read F_cod_igreja write F_cod_igreja; property cod_cc: Integer read F_cod_cc write F_cod_cc; property sigla: string read F_sigla write F_sigla; property cod_dirigente: Integer read F_cod_dirigente write F_cod_dirigente; property percentual_central: string read F_percentual_central write F_percentual_central; property meta_central: string read F_meta_central write F_meta_central; property percentual_valor: double read F_percentual_valor write F_percentual_valor; property meta_valor: double read F_meta_valor write F_meta_valor; end; implementation {$REGION 'Constructor and Destructor'} constructor TCongregacao.Create; begin ConexaoDB := aConexao; end; destructor TCongregacao.Destroy; begin inherited; end; {$ENDREGION} {$REGION 'CRUD'} function TCongregacao.Apagar: Boolean; var Qry: TFDQuery; begin if MessageDlg('Apagar o Registro: ' + #13 + #13 + 'Código: ' + IntToStr(F_cod_congregacao) + #13 + 'Descrição: ' + F_congregacao, mtConfirmation, [mbYes, mbNo], 0) = mrNO then begin Result := false; Abort; end; Try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add ('DELETE FROM tb_congregacao WHERE cod_congregacao=:cod_congregacao '); Qry.ParamByName('cod_congregacao').AsInteger := F_cod_congregacao; try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; except ConexaoDB.Rollback; Result:=false; end; Finally if Assigned(Qry) then FreeAndNil(Qry) End; end; function TCongregacao.Atualizar: Boolean; var Qry: TFDQuery; begin try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('UPDATE tb_congregacao ' + ' SET cod_central=:cod_central, congregacao=:congregacao, setor=:setor, polo=:polo, ' + 'situacao=:situacao, telefone=:telefone, cnpj=:cnpj, siteblog=:siteblog, endereco=:endereco, ' + 'complemento=:complemento, bairro=:bairro, cep=:cep, cidade=:cidade, diasculto=:diasculto, ' + 'diacoa=:diacoa, diacom=:diacom, diacoi=:diacoi, diacv=:diacv, data_aber_sub=:data_aber_sub, ' + 'data_aber_cong=:data_aber_cong, data_fun_coa=:data_fun_coa, data_fun_com=:data_fun_com, data_fun_coi=:data_fun_coi, ' + 'data_fun_cv=:data_fun_cv, cong_principal=:cong_principal, ' + 'dirigente=:dirigente, cod_setor=:cod_setor, cod_igreja=:cod_igreja, '+ ' cod_cc=:cod_cc, sigla=:sigla,cod_dirigente=:cod_dirigente, ' + ' percentual_central=:percentual_central, percentual_valor=:percentual_valor, '+ ' meta_central=:meta_central, meta_valor=:meta_valor '+ ' WHERE cod_congregacao=:cod_congregacao'); Qry.ParamByName('cod_congregacao').AsInteger := F_cod_congregacao; Qry.ParamByName('cod_central').AsInteger := F_cod_central; Qry.ParamByName('congregacao').AsString := F_congregacao; Qry.ParamByName('setor').AsString := F_setor; Qry.ParamByName('polo').AsString := F_polo; Qry.ParamByName('situacao').AsString := F_situacao; Qry.ParamByName('telefone').AsString := F_telefone; Qry.ParamByName('cnpj').AsString := F_cnpj; Qry.ParamByName('siteblog').AsString := F_siteblog; Qry.ParamByName('endereco').AsString := F_endereco; Qry.ParamByName('complemento').AsString := F_complemento; Qry.ParamByName('bairro').AsString := F_bairro; Qry.ParamByName('cep').AsString := F_cep; Qry.ParamByName('cidade').AsString := F_cidade; Qry.ParamByName('diasculto').AsString := F_diasculto; Qry.ParamByName('diacoa').AsString := F_diacoa; Qry.ParamByName('diacom').AsString := F_diacom; Qry.ParamByName('diacoi').AsString := F_diacoi; Qry.ParamByName('diacv').AsString := F_diacv; Qry.ParamByName('data_aber_sub').AsDate := F_data_aber_sub; Qry.ParamByName('data_aber_cong').AsDate := F_data_aber_cong; Qry.ParamByName('data_fun_coa').AsDate := F_data_fun_coa; Qry.ParamByName('data_fun_com').AsDate := F_data_fun_com; Qry.ParamByName('data_fun_coi').AsDate := F_data_fun_coi; Qry.ParamByName('data_fun_cv').AsDate := F_data_fun_cv; Qry.ParamByName('cong_principal').AsString := F_cong_principal; Qry.ParamByName('dirigente').AsString := F_dirigente; Qry.ParamByName('cod_setor').AsString := F_cod_setor; Qry.ParamByName('cod_igreja').AsString := F_cod_igreja; Qry.ParamByName('cod_cc').AsInteger := F_cod_cc; Qry.ParamByName('sigla').AsString := F_sigla; Qry.ParamByName('cod_dirigente').AsInteger := F_cod_dirigente; Qry.ParamByName('percentual_central').AsString := F_percentual_central; Qry.ParamByName('meta_central').AsString := F_meta_central; Qry.ParamByName('meta_valor').AsFloat := F_meta_valor; Qry.ParamByName('percentual_valor').AsFloat := F_percentual_valor; try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; except ConexaoDB.Rollback; Result:=false; end; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; function TCongregacao.Inserir: Boolean; var Qry: TFDQuery; begin try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('INSERT INTO tb_congregacao(cod_central, congregacao, '+ ' setor, polo, situacao, telefone, cnpj, siteblog, endereco, complemento, '+ ' bairro, cep, cidade, diasculto, diacoa, diacom, diacoi, diacv, '+ ' data_aber_sub, data_aber_cong, data_fun_coa, data_fun_com, data_fun_coi, '+ ' data_fun_cv, data_cadastro, usuario_cadastro, cong_principal, dirigente, '+ ' cod_setor, cod_igreja, cod_cc, sigla,cod_dirigente '+ ' ,percentual_central,percentual_valor, meta_central,meta_valor )VALUES(:cod_central, :congregacao, '+ ' :setor, :polo, :situacao, :telefone, :cnpj, :siteblog, :endereco, '+ ' :complemento, :bairro, :cep, :cidade, :diasculto, :diacoa, :diacom, '+ ' :diacoi, :diacv, :data_aber_sub, :data_aber_cong, :data_fun_coa, '+ ' :data_fun_com, :data_fun_coi, :data_fun_cv, :data_cadastro, '+ ' :usuario_cadastro, :cong_principal, :dirigente, :cod_setor, '+ ' :cod_igreja, :cod_cc, :sigla,:cod_dirigente,:percentual_central,:percentual_valor, :meta_central,:meta_valor)'); //Qry.ParamByName('cod_congregacao').AsInteger := Self.F_cod_congregacao; Qry.ParamByName('cod_central').AsInteger := Self.F_cod_central; Qry.ParamByName('congregacao').Asstring := Self.F_congregacao; Qry.ParamByName('setor').Asstring := Self.F_setor; Qry.ParamByName('polo').Asstring := Self.F_polo; Qry.ParamByName('situacao').Asstring := Self.F_situacao; Qry.ParamByName('telefone').Asstring := Self.F_telefone; Qry.ParamByName('cnpj').Asstring := Self.F_cnpj; Qry.ParamByName('siteblog').Asstring := Self.F_siteblog; Qry.ParamByName('endereco').Asstring := Self.F_endereco; Qry.ParamByName('complemento').Asstring := Self.F_complemento; Qry.ParamByName('bairro').Asstring := Self.F_bairro; Qry.ParamByName('cep').Asstring := Self.F_cep; Qry.ParamByName('cidade').Asstring := Self.F_cidade; Qry.ParamByName('diasculto').Asstring := Self.F_diasculto; Qry.ParamByName('diacoa').Asstring := Self.F_diacoa; Qry.ParamByName('diacom').Asstring := Self.F_diacom; Qry.ParamByName('diacoi').Asstring := Self.F_diacoi; Qry.ParamByName('diacv').Asstring := Self.F_diacv; Qry.ParamByName('data_aber_sub').AsDate := Self.F_data_aber_sub; Qry.ParamByName('data_aber_cong').AsDate := Self.F_data_aber_cong; Qry.ParamByName('data_fun_coa').AsDate := Self.F_data_fun_coa; Qry.ParamByName('data_fun_com').AsDate := Self.F_data_fun_com; Qry.ParamByName('data_fun_coi').AsDate := Self.F_data_fun_coi; Qry.ParamByName('data_fun_cv').AsDate := Self.F_data_fun_cv; Qry.ParamByName('data_cadastro').AsDate := Self.F_data_cadastro; Qry.ParamByName('usuario_cadastro').Asstring := Self.F_usuario_cadastro; Qry.ParamByName('cong_principal').Asstring := Self.F_cong_principal; Qry.ParamByName('dirigente').Asstring := Self.F_dirigente; Qry.ParamByName('cod_setor').Asstring := Self.F_cod_setor; Qry.ParamByName('cod_igreja').Asstring := Self.F_cod_igreja; Qry.ParamByName('cod_cc').AsInteger := Self.F_cod_cc; Qry.ParamByName('sigla').Asstring := Self.F_sigla; Qry.ParamByName('cod_dirigente').AsInteger := Self.F_cod_dirigente; Qry.ParamByName('percentual_central').AsString := Self.F_percentual_central; Qry.ParamByName('percentual_valor').AsFloat := Self.F_percentual_valor; Qry.ParamByName('meta_central').AsString := Self.F_meta_central; Qry.ParamByName('meta_valor').AsFloat := Self.F_meta_valor; try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; except ConexaoDB.Rollback; Result:=false; end; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; function TCongregacao.Selecionar(id: Integer): Boolean; var Qry: TFDQuery; begin try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add ('SELECT cod_congregacao, cod_central, congregacao, setor, polo, situacao, ' + 'telefone, cnpj, siteblog, endereco, complemento, bairro, cep, cidade, diasculto, ' + ' diacoa, diacom, diacoi, diacv, data_aber_sub, data_aber_cong, data_fun_coa, ' + ' data_fun_com, data_fun_coi, data_fun_cv, data_cadastro, usuario_cadastro, ' + ' cong_principal, dirigente, cod_setor, cod_igreja, cod_cc, sigla,cod_dirigente ' + ',percentual_central,percentual_valor,meta_central,meta_valor FROM tb_congregacao WHERE cod_congregacao=:cod_congregacao '); Qry.ParamByName('cod_congregacao').AsInteger := id; try Qry.Open; Self.F_cod_congregacao := Qry.FieldByName('cod_congregacao') .AsInteger; Self.F_cod_central := Qry.FieldByName('cod_central').AsInteger; Self.F_congregacao := Qry.FieldByName('congregacao').AsString; Self.F_setor := Qry.FieldByName('setor').AsString; Self.F_polo := Qry.FieldByName('polo').AsString; Self.F_situacao := Qry.FieldByName('situacao').AsString; Self.F_telefone := Qry.FieldByName('telefone').AsString; Self.F_cnpj := Qry.FieldByName('cnpj').AsString; Self.F_siteblog := Qry.FieldByName('siteblog').AsString; Self.F_endereco := Qry.FieldByName('endereco').AsString; Self.F_complemento := Qry.FieldByName('complemento').AsString; Self.F_bairro := Qry.FieldByName('bairro').AsString; Self.F_cep := Qry.FieldByName('cep').AsString; Self.F_cidade := Qry.FieldByName('cidade').AsString; Self.F_diasculto := Qry.FieldByName('diasculto').AsString; Self.F_diacoa := Qry.FieldByName('diacoa').AsString; Self.F_diacom := Qry.FieldByName('diacom').AsString; Self.F_diacoi := Qry.FieldByName('diacoi').AsString; Self.F_diacv := Qry.FieldByName('diacv').AsString; Self.F_data_aber_sub := Qry.FieldByName('data_aber_sub').AsDateTime; Self.F_data_aber_cong := Qry.FieldByName('data_aber_cong').AsDateTime; Self.F_data_fun_coa := Qry.FieldByName('data_fun_coa').AsDateTime; Self.F_data_fun_com := Qry.FieldByName('data_fun_com').AsDateTime; Self.F_data_fun_coi := Qry.FieldByName('data_fun_coi').AsDateTime; Self.F_data_fun_cv := Qry.FieldByName('data_fun_cv').AsDateTime; Self.F_data_cadastro := Qry.FieldByName('data_cadastro').AsDateTime; Self.F_usuario_cadastro := Qry.FieldByName('usuario_cadastro').AsString; Self.F_cong_principal := Qry.FieldByName('cong_principal').AsString; Self.F_dirigente := Qry.FieldByName('dirigente').AsString; Self.F_cod_setor := Qry.FieldByName('cod_setor').AsString; Self.F_cod_igreja := Qry.FieldByName('cod_igreja').AsString; Self.F_cod_cc := Qry.FieldByName('cod_cc').AsInteger; Self.F_sigla := Qry.FieldByName('sigla').AsString; Self.F_cod_dirigente := Qry.FieldByName('cod_dirigente').AsInteger; Self.F_percentual_central := Qry.FieldByName('percentual_central').AsString; Self.F_percentual_valor := Qry.FieldByName('percentual_valor').AsFloat; Self.F_meta_central := Qry.FieldByName('meta_central').AsString; Self.F_meta_valor := Qry.FieldByName('meta_valor').AsFloat; Except Result := false; end; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; {$ENDREGION} end.
unit USelectPrices; interface uses System.SysUtils, System.Types, System.UITypes, System.Rtti, System.Classes, System.Generics.Collections, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, UDialog, FMX.ListBox, FMX.Layouts, FMX.Objects, UModel; type TPriceSelectDialog = class(TDialogFrame) Label1: TLabel; Button1: TButton; Button2: TButton; Button3: TButton; Button4: TButton; // procedure Price1Click(Sender: TObject); procedure ButtonClick(Sender: TObject); private { Private declarations } public { Public declarations } pricelist: TList<TButton>; CurrentMenuItem: TMenuItem; SelectedIndex: integer; procedure InitialPrices(MenuItem: TMenuItem); end; implementation {$R *.fmx} procedure TPriceSelectDialog.ButtonClick(Sender: TObject); begin inherited; if (Sender as TButton).Text <> '' then begin SelectedIndex := (Sender as TButton).Tag; DialogResult := mrOK; FProcessDialogResult.ProcessDialogResult; end; end; procedure TPriceSelectDialog.InitialPrices(MenuItem: TMenuItem); var i: integer; s: string; begin pricelist := TList<TButton>.Create; pricelist.Add(Button1); pricelist.Add(Button2); pricelist.Add(Button3); pricelist.Add(Button4); CurrentMenuItem := MenuItem; for i := 0 to 3 do begin if i < CurrentMenuItem.pricelist.Count then begin // Str(CurrentMenuItem.PriceList.Items[i].Value:52:2,s); s := Format('%12s %24.2m', [CurrentMenuItem.pricelist.Items[i].Key, CurrentMenuItem.pricelist.Items[i].Value]); pricelist.Items[i].Text := s end else begin pricelist.Items[i].Text := ''; end; end; end; end.
unit BufferClipbrd; interface uses Windows, Clipbrd, Buffer, SpeedBmp; procedure BitmapSaveToClipboard( Source : TBuffer ); procedure BitmapLoadFromClipboard( Dest : TBuffer ); implementation procedure BitmapSaveToClipboard( Source : TBuffer ); var Data : THandle; Format : word; Palette : HPALETTE; begin with Clipboard do begin Open; try Clear; Palette := 0; Source.SaveToClipboardFormat( Format, Data, Palette ); SetClipboardData( Format, Data ); if Palette <> 0 then SetClipboardData( CF_PALETTE, Palette ); finally Close; end; end; end; procedure BitmapLoadFromClipboard( Dest : TBuffer ); begin with Clipboard do begin Open; try Dest.LoadFromClipboardFormat( CF_DIB, GetClipboardData( CF_DIB ), 0 ); finally Close; end; end; end; end.
unit l3DataObject; {* Базовый класс для работы с IDataObject. } // Модуль: "w:\common\components\rtl\Garant\L3\l3DataObject.pas" // Стереотип: "SimpleClass" // Элемент модели: "Tl3DataObject" MUID: (4680F5AA0274) {$Include w:\common\components\rtl\Garant\L3\l3Define.inc} interface uses l3IntfUses , l3SimpleObject , l3Interfaces , l3InternalInterfaces , l3LongintList , l3StringList , ActiveX , Windows ; type Tl3DataObject = class(Tl3SimpleObject, IDataObject, Il3DragImageSource) {* Базовый класс для работы с IDataObject. } private f_DragBitmap: Il3Bitmap; f_FilesNames: Tl3StringList; f_Formats: Tl3LongintList; protected function DoGetData(const aFormatEtcIn: TFormatEtc; var medium: Tl3StoragePlace): HResult; virtual; function DoGetDataHere(const aFormatEtcIn: TFormatEtc; const medium: Tl3StoragePlace): HResult; virtual; procedure WriteFilesAndSetNames(aNames: Tl3StringList); virtual; function Bitmap: Il3Bitmap; virtual; procedure CheckFormats; function DoQueryGetData(const aFormatEtc: TFormatEtc): HResult; virtual; procedure SetDragBitmap(const aBitmap: Il3Bitmap); function Image: Il3Bitmap; function GetData(const formatetcIn: TFormatEtc; out medium: TStgMedium): HResult; stdcall; function GetDataHere(const formatetc: TFormatEtc; out medium: TStgMedium): HResult; stdcall; function QueryGetData(const formatetc: TFormatEtc): HResult; stdcall; function GetCanonicalFormatEtc(const formatetc: TFormatEtc; out formatetcOut: TFormatEtc): HResult; stdcall; function SetData(const formatetc: TFormatEtc; var medium: TStgMedium; fRelease: BOOL): HResult; stdcall; function EnumFormatEtc(dwDirection: Integer; out enumFormatEtc: IEnumFormatEtc): HResult; stdcall; function DAdvise(const formatetc: TFormatEtc; advf: Integer; const advSink: IAdviseSink; out dwConnection: Integer): HResult; stdcall; function DUnadvise(dwConnection: Integer): HResult; stdcall; function EnumDAdvise(out enumAdvise: IEnumStatData): HResult; stdcall; procedure Cleanup; override; {* Функция очистки полей объекта. } procedure InitFields; override; public constructor Create(const aFormats: Tl3ClipboardFormats); reintroduce; function AcceptableTymed: Integer; virtual; public property Formats: Tl3LongintList read f_Formats; end;//Tl3DataObject implementation uses l3ImplUses , l3DataObjectEnum , l3Base , SysUtils , ShlObj //#UC START# *4680F5AA0274impl_uses* //#UC END# *4680F5AA0274impl_uses* ; constructor Tl3DataObject.Create(const aFormats: Tl3ClipboardFormats); //#UC START# *48F340C901DE_4680F5AA0274_var* var l_Index : Integer; //#UC END# *48F340C901DE_4680F5AA0274_var* begin //#UC START# *48F340C901DE_4680F5AA0274_impl* inherited Create; f_Formats := Tl3LongintList.Make; for l_Index := Low(aFormats) to High(aFormats) do f_Formats.Add(aFormats[l_Index]); if (Win32Platform <> VER_PLATFORM_WIN32_NT) AND (f_Formats.Count > 0) AND (f_Formats.IndexOf(CF_Locale) < 0) then f_Formats.Add(CF_Locale); //#UC END# *48F340C901DE_4680F5AA0274_impl* end;//Tl3DataObject.Create function Tl3DataObject.DoGetData(const aFormatEtcIn: TFormatEtc; var medium: Tl3StoragePlace): HResult; //#UC START# *48F3495D0398_4680F5AA0274_var* const c_Inch = 2540; var l_HObject : HGLOBAL; l_Index : Integer; l_Size : Integer; l_pChar : PAnsiChar; l_pDropFiles : PDropFiles; l_Format : Word; l_Data : THandle; l_Palette : HPALETTE; l_HMetafile : HMETAFILE; l_Canvas : Il3Canvas; l_Bmp : Il3Bitmap; l_DC : hDC; //#UC END# *48F3495D0398_4680F5AA0274_var* begin //#UC START# *48F3495D0398_4680F5AA0274_impl* Result := S_Ok; with aFormatEtcIn do if (cfFormat = CF_HDROP) and ((tymed and TYMED_HGLOBAL) <> 0) then begin medium.tymed := TYMED_HGLOBAL; if (f_FilesNames = nil) then begin f_FilesNames := Tl3StringList.Make; WriteFilesAndSetNames(f_FilesNames); end;//f_FilesNames = nil if (f_FilesNames.Count > 0) then begin l_Size := sizeof(TDropFiles) + 1;//+завершающий байт for l_Index := 0 to f_FilesNames.Count - 1 do l_Size := l_Size + f_FilesNames[l_Index].AsWStr.SLen + 1;//длина каждой строки, плюс 1 байт l_HObject := GlobalAlloc(GMEM_SHARE or GMEM_MOVEABLE or GMEM_ZEROINIT, l_Size); try if (l_HObject <> 0) then begin l_pDropFiles := GlobalLock(l_HObject); try l_pDropFiles.pFiles := sizeof(TDropFiles); GetCursorPos(l_pDropFiles.pt); l_pDropFiles.fNC := true; l_pDropFiles.fWide := false; l_pChar := PAnsiChar(l_pDropFiles) + l_pDropFiles.pFiles; for l_Index := 0 to f_FilesNames.Count - 1 do begin StrCopy(l_pChar, f_FilesNames[l_Index].AsWStr.S); l_pChar := l_pChar + (f_FilesNames[l_Index].AsWStr.SLen + 1); end;//for l_Index finally GlobalUnlock(l_HObject); end;//try..finally medium.hGlobal := l_HObject; end;//l_HObject <> 0 except GlobalFree(l_HObject); Result := E_OutOfMemory; end;//try..except end;//f_FilesNames.Count > 0 if medium.hGlobal = 0 then Result := DV_E_FORMATETC; end//cfFormat = CF_HDROP.. else begin l_Bmp := Bitmap; if (l_Bmp <> nil) then begin if (cfFormat = CF_BITMAP) and ((tymed and (TYMED_HGLOBAL or TYMED_GDI)) <> 0) then begin medium.tymed := TYMED_GDI; l_Format := cfFormat; l_Bmp.SaveToClipboardFormat(l_Format, l_Data, l_Palette); medium.hGlobal := l_Data; end//cfFormat = CF_BITMAP.. (* else if (cfFormat = CF_METAFILEPICT) and ((tymed and (TYMED_HGLOBAL or TYMED_MFPICT)) <> 0) then begin //medium.tymed := TYMED_HGLOBAL; medium.tymed := TYMED_MFPICT; l_DC := CreateMetafile(nil); try l_Canvas := Tl3OldMFCanvas.Make; try SetMapMode(l_DC, MM_ANISOTROPIC); SetWindowOrgEx(l_DC, 0, 0, nil); SetWindowExtEx(l_DC, l_Bmp.Width, l_Bmp.Height, nil); l_Canvas.DC := l_DC; l_Canvas.BeginPaint; try l_Canvas.DrawEnabled := true; //l_Canvas.ClipRect := l_Canvas.DR2LR(l3SRect(0, 0, l_Bmp.Width, l_Bmp.Height)); l_Bmp.StretchDraw(l3Rect(0,0, l_Bmp.InchWidth, l_Bmp.InchHeight), l_Canvas); //l_Canvas.TextOut(l3Point0, l3PCharLen('Test')); finally l_Canvas.EndPaint; end;//try..finally finally l_Canvas := nil; end;//try..finally finally l_HMetafile := CloseMetafile(l_DC); end;//try..finally l_HObject := GlobalAlloc(GMEM_MOVEABLE, sizeof(METAFILEPICT)); try with PMetafilePict(GlobalLock(l_HObject))^ do begin mm := MM_ANISOTROPIC; //mm := MM_ISOTROPIC; hMF := l_HMetafile; xExt := l_Bmp.Width * c_Inch div Screen.PixelsPerInch;//mm*100 yExt := l_Bmp.Height * c_Inch div Screen.PixelsPerInch; end;//PMetafilePict(GlobalLock(l_HObject))^ GlobalUnlock(l_HObject); medium.hGlobal := l_HObject; except GlobalFree(l_HObject); Result := E_OutOfMemory; end;//try..except end///cfFormat = CF_METAFILEPICT*) else if ((cfFormat = CF_ENHMETAFILE)) and ((tymed and (TYMED_HGLOBAL or TYMED_MFPICT)) <> 0) then begin medium.tymed := TYMED_MFPICT; l_Format := cfFormat; l_Bmp.SaveToClipboardFormat(l_Format, l_Data, l_Palette); medium.hGlobal := l_Data; end//cfFormat = CF_ENHMETAFILE else Result := DV_E_FORMATETC; end//l_Bmp <> nil else Result := DV_E_FORMATETC; end;//cfFormat = CF_HDROP.. //#UC END# *48F3495D0398_4680F5AA0274_impl* end;//Tl3DataObject.DoGetData function Tl3DataObject.DoGetDataHere(const aFormatEtcIn: TFormatEtc; const medium: Tl3StoragePlace): HResult; //#UC START# *48F349AE00F1_4680F5AA0274_var* //#UC END# *48F349AE00F1_4680F5AA0274_var* begin //#UC START# *48F349AE00F1_4680F5AA0274_impl* Result := DV_E_FORMATETC; //#UC END# *48F349AE00F1_4680F5AA0274_impl* end;//Tl3DataObject.DoGetDataHere procedure Tl3DataObject.WriteFilesAndSetNames(aNames: Tl3StringList); //#UC START# *48F3504301B7_4680F5AA0274_var* //#UC END# *48F3504301B7_4680F5AA0274_var* begin //#UC START# *48F3504301B7_4680F5AA0274_impl* //#UC END# *48F3504301B7_4680F5AA0274_impl* end;//Tl3DataObject.WriteFilesAndSetNames function Tl3DataObject.Bitmap: Il3Bitmap; //#UC START# *48F350F802F7_4680F5AA0274_var* //#UC END# *48F350F802F7_4680F5AA0274_var* begin //#UC START# *48F350F802F7_4680F5AA0274_impl* Result := f_DragBitmap; //#UC END# *48F350F802F7_4680F5AA0274_impl* end;//Tl3DataObject.Bitmap function Tl3DataObject.AcceptableTymed: Integer; //#UC START# *48F351BE0015_4680F5AA0274_var* //#UC END# *48F351BE0015_4680F5AA0274_var* begin //#UC START# *48F351BE0015_4680F5AA0274_impl* Result := TYMED_NULL; if (Bitmap <> nil) then Result := Result or TYMED_HGLOBAL or TYMED_GDI or TYMED_MFPICT //#UC END# *48F351BE0015_4680F5AA0274_impl* end;//Tl3DataObject.AcceptableTymed procedure Tl3DataObject.CheckFormats; //#UC START# *48F351EB00E1_4680F5AA0274_var* //#UC END# *48F351EB00E1_4680F5AA0274_var* begin //#UC START# *48F351EB00E1_4680F5AA0274_impl* if (Bitmap = nil) then begin f_Formats.Remove(CF_BITMAP); f_Formats.Remove(CF_METAFILEPICT); f_Formats.Remove(CF_ENHMETAFILE); end//Bitmap = nil else begin if (f_Formats.IndexOf(CF_BITMAP) < 0) then f_Formats.Add(CF_BITMAP); (* if (f_Formats.IndexOf(CF_METAFILEPICT) < 0) then f_Formats.Add(CF_METAFILEPICT);*) if (f_Formats.IndexOf(CF_ENHMETAFILE) < 0) then f_Formats.Add(CF_ENHMETAFILE); end;//Bitmap <> nil //#UC END# *48F351EB00E1_4680F5AA0274_impl* end;//Tl3DataObject.CheckFormats function Tl3DataObject.DoQueryGetData(const aFormatEtc: TFormatEtc): HResult; //#UC START# *48F359680368_4680F5AA0274_var* var l_Index : Integer; //#UC END# *48F359680368_4680F5AA0274_var* begin //#UC START# *48F359680368_4680F5AA0274_impl* with aFormatEtc do begin if (dwAspect <> DVASPECT_CONTENT) then Result := DV_E_DVAspect else if (lIndex <> -1) then Result := DV_E_LINDEX else begin if (tymed AND AcceptableTymed <> TYMED_NULL) then begin Result := DV_E_FormatEtc; for l_Index := f_Formats.Lo to f_Formats.Hi do if (f_Formats[l_Index] = cfFormat) then begin Result := S_Ok; break; end;//f_Formats[l_Index] = cfFormat end//if (tymed AND AcceptableTymed <> TYMED_NULL) then else Result := DV_E_FormatEtc; end;//lIndex <> -1 end;//with aFormatEtc do //#UC END# *48F359680368_4680F5AA0274_impl* end;//Tl3DataObject.DoQueryGetData procedure Tl3DataObject.SetDragBitmap(const aBitmap: Il3Bitmap); //#UC START# *48F35AEC0254_4680F5AA0274_var* //#UC END# *48F35AEC0254_4680F5AA0274_var* begin //#UC START# *48F35AEC0254_4680F5AA0274_impl* f_DragBitmap := aBitmap; CheckFormats; //#UC END# *48F35AEC0254_4680F5AA0274_impl* end;//Tl3DataObject.SetDragBitmap function Tl3DataObject.Image: Il3Bitmap; //#UC START# *476F77AA034A_4680F5AA0274_var* //#UC END# *476F77AA034A_4680F5AA0274_var* begin //#UC START# *476F77AA034A_4680F5AA0274_impl* Result := f_DragBitmap; //#UC END# *476F77AA034A_4680F5AA0274_impl* end;//Tl3DataObject.Image function Tl3DataObject.GetData(const formatetcIn: TFormatEtc; out medium: TStgMedium): HResult; //#UC START# *48F32DD50284_4680F5AA0274_var* var l_HObject : hGlobal; l_P : PInteger; //#UC END# *48F32DD50284_4680F5AA0274_var* begin //#UC START# *48F32DD50284_4680F5AA0274_impl* Result := QueryGetData(formatetcIn); if (Result = S_Ok) then begin with formatetcIn do if (cfFormat = CF_Locale) then begin if ((tymed and TYMED_HGLOBAL) <> 0) then begin l_HObject := GlobalAlloc(GMEM_SHARE or GMEM_MOVEABLE or GMEM_ZEROINIT, SizeOf(Integer)); try l_P := GlobalLock(l_HObject); try l_P^ := LANG_RUSSIAN; finally GlobalUnlock(l_HObject); end;//try..finally medium.tymed := TYMED_HGLOBAL; medium.hGlobal := l_HObject; except GlobalFree(l_HObject); Result := E_OutOfMemory; end;//try..except (* medium.tymed := TYMED_HGLOBAL; medium.hGlobal := LANG_RUSSIAN;*) end//(tymed and TYMED_HGLOBAL) <> 0.. else Result := DV_E_FORMATETC; end//cfFormat = CF_Locale.. else begin l3FillChar(medium, sizeof(medium), 0); Result := DoGetData(formatetcIn, medium); end;//cfFormat = CF_Locale.. end;//Result = S_Ok //#UC END# *48F32DD50284_4680F5AA0274_impl* end;//Tl3DataObject.GetData function Tl3DataObject.GetDataHere(const formatetc: TFormatEtc; out medium: TStgMedium): HResult; //#UC START# *48F32E0200AF_4680F5AA0274_var* var l_P : PInteger; //#UC END# *48F32E0200AF_4680F5AA0274_var* begin //#UC START# *48F32E0200AF_4680F5AA0274_impl* Result := QueryGetData(formatetc); if (Result = S_Ok) then begin with formatetc do if (cfFormat = CF_Locale) then begin if ((tymed and TYMED_HGLOBAL) <> 0) AND (medium.tymed = TYMED_HGLOBAL) then begin l_P := GlobalLock(medium.hGlobal); try l_P^ := LANG_RUSSIAN; finally GlobalUnlock(medium.hGlobal); end;//try..finally (* medium.hGlobal := LANG_RUSSIAN;*) end//tymed and TYMED_HGLOBAL) <> 0 else Result := DV_E_FORMATETC; end//cfFormat = CF_Locale.. else Result := DoGetDataHere(formatetc, medium); end;//Result = S_Ok //#UC END# *48F32E0200AF_4680F5AA0274_impl* end;//Tl3DataObject.GetDataHere function Tl3DataObject.QueryGetData(const formatetc: TFormatEtc): HResult; //#UC START# *48F32E20007F_4680F5AA0274_var* //#UC END# *48F32E20007F_4680F5AA0274_var* begin //#UC START# *48F32E20007F_4680F5AA0274_impl* Result := DoQueryGetData(formatetc); //#UC END# *48F32E20007F_4680F5AA0274_impl* end;//Tl3DataObject.QueryGetData function Tl3DataObject.GetCanonicalFormatEtc(const formatetc: TFormatEtc; out formatetcOut: TFormatEtc): HResult; //#UC START# *48F32E330154_4680F5AA0274_var* //#UC END# *48F32E330154_4680F5AA0274_var* begin //#UC START# *48F32E330154_4680F5AA0274_impl* Result := DATA_S_SAMEFORMATETC; FormatEtcOut := FormatEtc; FormatEtcOut.ptd := nil; //#UC END# *48F32E330154_4680F5AA0274_impl* end;//Tl3DataObject.GetCanonicalFormatEtc function Tl3DataObject.SetData(const formatetc: TFormatEtc; var medium: TStgMedium; fRelease: BOOL): HResult; //#UC START# *48F32E4D0179_4680F5AA0274_var* //#UC END# *48F32E4D0179_4680F5AA0274_var* begin //#UC START# *48F32E4D0179_4680F5AA0274_impl* Result := E_NOTIMPL; //#UC END# *48F32E4D0179_4680F5AA0274_impl* end;//Tl3DataObject.SetData function Tl3DataObject.EnumFormatEtc(dwDirection: Integer; out enumFormatEtc: IEnumFormatEtc): HResult; //#UC START# *48F330A10257_4680F5AA0274_var* //#UC END# *48F330A10257_4680F5AA0274_var* begin //#UC START# *48F330A10257_4680F5AA0274_impl* if (dwDirection = DATADIR_GET) then begin Result := S_Ok; enumFormatEtc := Tl3DataObjectEnum.Make(Self); end//if (dwDirection = DATADIR_GET) then else Result := E_NotImpl; //#UC END# *48F330A10257_4680F5AA0274_impl* end;//Tl3DataObject.EnumFormatEtc function Tl3DataObject.DAdvise(const formatetc: TFormatEtc; advf: Integer; const advSink: IAdviseSink; out dwConnection: Integer): HResult; //#UC START# *48F330C40367_4680F5AA0274_var* //#UC END# *48F330C40367_4680F5AA0274_var* begin //#UC START# *48F330C40367_4680F5AA0274_impl* Result := OLE_E_AdviseNotSupported; //#UC END# *48F330C40367_4680F5AA0274_impl* end;//Tl3DataObject.DAdvise function Tl3DataObject.DUnadvise(dwConnection: Integer): HResult; //#UC START# *48F3312B0381_4680F5AA0274_var* //#UC END# *48F3312B0381_4680F5AA0274_var* begin //#UC START# *48F3312B0381_4680F5AA0274_impl* Result := OLE_E_AdviseNotSupported; //#UC END# *48F3312B0381_4680F5AA0274_impl* end;//Tl3DataObject.DUnadvise function Tl3DataObject.EnumDAdvise(out enumAdvise: IEnumStatData): HResult; //#UC START# *48F3313E0339_4680F5AA0274_var* //#UC END# *48F3313E0339_4680F5AA0274_var* begin //#UC START# *48F3313E0339_4680F5AA0274_impl* Result := OLE_E_AdviseNotSupported; //#UC END# *48F3313E0339_4680F5AA0274_impl* end;//Tl3DataObject.EnumDAdvise procedure Tl3DataObject.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_4680F5AA0274_var* //#UC END# *479731C50290_4680F5AA0274_var* begin //#UC START# *479731C50290_4680F5AA0274_impl* l3Free(f_Formats); f_DragBitmap := nil; l3Free(f_FilesNames); inherited; //#UC END# *479731C50290_4680F5AA0274_impl* end;//Tl3DataObject.Cleanup procedure Tl3DataObject.InitFields; //#UC START# *47A042E100E2_4680F5AA0274_var* //#UC END# *47A042E100E2_4680F5AA0274_var* begin //#UC START# *47A042E100E2_4680F5AA0274_impl* inherited; CheckFormats; //#UC END# *47A042E100E2_4680F5AA0274_impl* end;//Tl3DataObject.InitFields end.
unit fbkREQTYPETable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TfbkREQTYPERecord = record PType: String[4]; PDescription: String[30]; End; TfbkREQTYPEBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TfbkREQTYPERecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIfbkREQTYPE = (fbkREQTYPEPrimaryKey); TfbkREQTYPETable = class( TDBISAMTableAU ) private FDFType: TStringField; FDFDescription: TStringField; procedure SetPType(const Value: String); function GetPType:String; procedure SetPDescription(const Value: String); function GetPDescription:String; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEIfbkREQTYPE); function GetEnumIndex: TEIfbkREQTYPE; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TfbkREQTYPERecord; procedure StoreDataBuffer(ABuffer:TfbkREQTYPERecord); property DFType: TStringField read FDFType; property DFDescription: TStringField read FDFDescription; property PType: String read GetPType write SetPType; property PDescription: String read GetPDescription write SetPDescription; published property Active write SetActive; property EnumIndex: TEIfbkREQTYPE read GetEnumIndex write SetEnumIndex; end; { TfbkREQTYPETable } procedure Register; implementation function TfbkREQTYPETable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TfbkREQTYPETable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TfbkREQTYPETable.GenerateNewFieldName } function TfbkREQTYPETable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TfbkREQTYPETable.CreateField } procedure TfbkREQTYPETable.CreateFields; begin FDFType := CreateField( 'Type' ) as TStringField; FDFDescription := CreateField( 'Description' ) as TStringField; end; { TfbkREQTYPETable.CreateFields } procedure TfbkREQTYPETable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TfbkREQTYPETable.SetActive } procedure TfbkREQTYPETable.SetPType(const Value: String); begin DFType.Value := Value; end; function TfbkREQTYPETable.GetPType:String; begin result := DFType.Value; end; procedure TfbkREQTYPETable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TfbkREQTYPETable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TfbkREQTYPETable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Type, String, 4, N'); Add('Description, String, 30, N'); end; end; procedure TfbkREQTYPETable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, Type, Y, Y, N, N'); end; end; procedure TfbkREQTYPETable.SetEnumIndex(Value: TEIfbkREQTYPE); begin case Value of fbkREQTYPEPrimaryKey : IndexName := ''; end; end; function TfbkREQTYPETable.GetDataBuffer:TfbkREQTYPERecord; var buf: TfbkREQTYPERecord; begin fillchar(buf, sizeof(buf), 0); buf.PType := DFType.Value; buf.PDescription := DFDescription.Value; result := buf; end; procedure TfbkREQTYPETable.StoreDataBuffer(ABuffer:TfbkREQTYPERecord); begin DFType.Value := ABuffer.PType; DFDescription.Value := ABuffer.PDescription; end; function TfbkREQTYPETable.GetEnumIndex: TEIfbkREQTYPE; var iname : string; begin iname := uppercase(indexname); if iname = '' then result := fbkREQTYPEPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Feedback Tables', [ TfbkREQTYPETable, TfbkREQTYPEBuffer ] ); end; { Register } function TfbkREQTYPEBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..2] of string = ('TYPE','DESCRIPTION' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 2) and (flist[x] <> s) do inc(x); if x <= 2 then result := x else result := 0; end; function TfbkREQTYPEBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; end; end; function TfbkREQTYPEBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PType; 2 : result := @Data.PDescription; end; end; end.
unit InfoVenta; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Db, TeeProcs, TeEngine, Chart, DBChart, ExtCtrls, Menus, ComCtrls, ToolWin, Series, Grids, DBGrids, ActnList, ImgList, printers, DateUtils, DBClient, System.Actions; type TFInfoVenta = class(TForm) CoolBar1: TCoolBar; StatusBar1: TStatusBar; ToolBar1: TToolBar; MainMenu1: TMainMenu; Panel1: TPanel; Graf: TDBChart; Series1: TBarSeries; DataSource1: TDataSource; Ventana1: TMenuItem; Salir1: TMenuItem; Seleccion1: TMenuItem; ActionList1: TActionList; SelFec: TAction; SeleccionarFechas1: TMenuItem; ToolButton1: TToolButton; ToolButton2: TToolButton; ImageList1: TImageList; Salir: TAction; ToolButton3: TToolButton; ToolButton4: TToolButton; ToolButton5: TToolButton; ToolButton6: TToolButton; ProxPag: TAction; AntPag: TAction; N1: TMenuItem; PaginaAnterior1: TMenuItem; PaginaSiguiente1: TMenuItem; Imprimir: TAction; Imprimir1: TMenuItem; N2: TMenuItem; ToolButton7: TToolButton; ToolButton8: TToolButton; PrintDialog1: TPrintDialog; ItemsPorPag: TAction; Ayuda: TMenuItem; Indice: TMenuItem; N3: TMenuItem; ItemsporPagina1: TMenuItem; Cds: TClientDataSet; CdsTOTAL: TFloatField; CdsMES: TStringField; procedure FormCreate(Sender: TObject); procedure Salir1Click(Sender: TObject); procedure SelFecExecute(Sender: TObject); procedure ProxPagExecute(Sender: TObject); procedure AntPagExecute(Sender: TObject); procedure ImprimirExecute(Sender: TObject); procedure SalirExecute(Sender: TObject); procedure ItemsPorPagExecute(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure CdsMESGetText(Sender: TField; var Text: String; DisplayText: Boolean); private { Private declarations } FIni, FFin: TDateTime; procedure AbrirQuery; procedure ArmarGrafico; procedure SetearGrafico; procedure Procesar; procedure AgregarRegistro(const Fecha: string); public { Public declarations } procedure EnHint( Sender: TObject ); end; var FInfoVenta: TFInfoVenta; implementation uses DmIng, SelFechas; {$R *.DFM} procedure TFInfoVenta.FormCreate(Sender: TObject); begin TDMIng.TDatos.Open; FIni := date-180; FIni := StartOfTheMonth( FIni ); FFin := date; Cds.CreateDataSet; ArmarGrafico; AbrirQuery; Application.OnHint := EnHint; end; procedure TFInfoVenta.Salir1Click(Sender: TObject); begin Close; end; procedure TFInfoVenta.SelFecExecute(Sender: TObject); begin with TSelFechasDlg.create( application ) do try FecIni.date := FIni; FecFin.date := FFin; ShowModal; Screen.Cursor := crHourGlass; Application.ProcessMessages; if ModalResult = mrOK then begin FIni := FecIni.date; FFin := FecFin.date; AbrirQuery; end; finally free; Screen.Cursor := crDefault; end; end; procedure TFInfoVenta.ProxPagExecute(Sender: TObject); begin Graf.NextPage; if Graf.Page > 1 then AntPag.enabled := true; if Graf.Page = Graf.NumPages then ProxPag.Enabled := false; end; procedure TFInfoVenta.AntPagExecute(Sender: TObject); begin Graf.PreviousPage; if Graf.Page <= 1 then AntPag.enabled := false; if Graf.Page < Graf.NumPages then ProxPag.Enabled := true; end; procedure TFInfoVenta.ImprimirExecute(Sender: TObject); begin if PrintDialog1.execute then begin Graf.PrintOrientation( poLandscape ); Graf.PrintProportional := true; // Graf.PrintLandscape; end; end; procedure TFInfoVenta.SalirExecute(Sender: TObject); begin Close; end; procedure TFInfoVenta.AbrirQuery; begin LockWindowUpdate( Handle ); TDmIng.AdoResVtas.Close; TDmIng.AdoResVtas.Parameters[0].value := FIni; TDmIng.AdoResVtas.Parameters[1].value := FFin; TDmIng.AdoResVtas.Open; Procesar; Graf.Title.Text[ 1 ] := 'De: ' + DateToStr( FIni ) + ' a ' + DateToStr( FFin ); SetearGrafico; LockWindowUpdate( HWnd(nil) ); end; procedure TFInfoVenta.ItemsPorPagExecute(Sender: TObject); var AItems: string; begin AItems := InputBox( 'Items', 'Items por Pagina: ', IntToStr( Graf.MaxPointsPerPage )); try Graf.MaxPointsPerPage := StrToInt( AItems ); SetearGrafico; except ShowMessage( 'Por favor, ingrese un numero valido' ); end; end; procedure TFInfoVenta.FormClose(Sender: TObject; var Action: TCloseAction); begin TDMIng.TDatos.Open; Application.OnHint := nil; end; procedure TFInfoVenta.ArmarGrafico; begin With graf do begin Title.Text[ 1 ] := 'De: ' + DateToStr( FIni ) + ' a ' + DateToStr( FFin ); Foot.Text.Add( TDMIng.TDatosDENOMINA.value ); end; end; procedure TFInfoVenta.EnHint(Sender: TObject); begin StatusBar1.Panels[ 0 ].Text := Application.Hint; end; procedure TFInfoVenta.SetearGrafico; begin AntPag.Enabled := false; if Graf.Numpages = 1 then begin Graf.MaxPointsPerPage := 0; ProxPag.enabled := false; end else ProxPag.Enabled := true; end; procedure TFInfoVenta.Procesar; var FVieFec, Fecha: string; FMonto: double; Anio, Mes, Dia: word; begin with Cds, TDMIng do try Cds.EmptyDataSet; FMonto := 0; DecodeDate( AdoResVtasFECHA.AsDateTime, Anio, Mes, Dia ); FVieFec := format( '%4.4d%2.2d', [ Anio, Mes ]); AgregarRegistro( FVieFec ); while not AdoResVtas.eof do begin DecodeDate( AdoResVtasFECHA.Value, Anio, Mes, Dia ); Fecha := format( '%4.4d%2.2d', [ Anio, Mes ]); if ( Fecha <> FVieFec ) then begin CdsTOTAL.value := FMonto; Cds.Post; FVieFec := Fecha; AgregarRegistro( FVieFec ); FMonto := 0; end; FMonto := FMonto + AdoResVtasVTA.Value; AdoResVtas.next; end; CdsTOTAL.value := FMonto; Cds.Post; AdoResVtas.close; except on e:exception do showmessage( e.Message ); end; end; procedure TFInfoVenta.AgregarRegistro( const Fecha: string ); begin with TDMIng do begin Cds.Append; CdsMES.Value := Fecha; end; end; procedure TFInfoVenta.CdsMESGetText(Sender: TField; var Text: String; DisplayText: Boolean); begin Text := Copy( Sender.value, 5, 2 ) + '-' + Copy( Sender.value, 3, 2 ); end; end.
unit vg_ani; {$I vg_define.inc} interface uses Classes, SysUtils, vg_scene, //vgNonModelTypes, vgTypes, vgBounds, vgBitmap, vgVisualObject ; type TvgColorAnimation = class(TvgAnimation) private FStartColor: TvgColor; FStopColor: TvgColor; FPath, FPropertyName: AnsiString; FInstance: TObject; FStartFromCurrent: boolean; function GetStartColor: string; function GetStopColor: string; procedure SetStartColor(const Value: string); procedure SetStopColor(const Value: string); protected procedure ProcessAnimation; override; public constructor Create(AOwner: TComponent); override; procedure Cleanup; override; procedure Start; override; published property StartValue: string read GetStartColor write SetStartColor; property StartFromCurrent: boolean read FStartFromCurrent write FStartFromCurrent default false; property StopValue: string read GetStopColor write SetStopColor; property PropertyName: AnsiString read FPropertyName write FPropertyName; end; TvgGradientAnimation = class(TvgAnimation) private FStartGradient: TvgGradient; FStopGradient: TvgGradient; FPath, FPropertyName: AnsiString; FInstance: TObject; FStartFromCurrent: boolean; procedure SetStartGradient(const Value: TvgGradient); procedure SetStopGradient(const Value: TvgGradient); protected procedure ProcessAnimation; override; public constructor Create(AOwner: TComponent); override; procedure Cleanup; override; procedure Start; override; published property StartValue: TvgGradient read FStartGradient write SetStartGradient; property StartFromCurrent: boolean read FStartFromCurrent write FStartFromCurrent default false; property StopValue: TvgGradient read FStopGradient write SetStopGradient; property PropertyName: AnsiString read FPropertyName write FPropertyName; end; TvgFloatAnimation = class(TvgAnimation) private FStartFloat: single; FStopFloat: single; FPath, FPropertyName: AnsiString; FInstance: TObject; FStartFromCurrent: boolean; protected procedure ProcessAnimation; override; public constructor Create(AOwner: TComponent); override; procedure Cleanup; override; procedure Start; override; procedure Stop; override; published property StartValue: single read FStartFloat write FStartFloat stored true; property StartFromCurrent: boolean read FStartFromCurrent write FStartFromCurrent default false; property StopValue: single read FStopFloat write FStopFloat stored true; property PropertyName: AnsiString read FPropertyName write FPropertyName; end; TvgRectAnimation = class(TvgAnimation) private FStartRect: TvgBounds; FCurrent: TvgBounds; FStopRect: TvgBounds; FPath, FPropertyName: AnsiString; FInstance: TObject; FStartFromCurrent: boolean; protected procedure ProcessAnimation; override; public constructor Create(AOwner: TComponent); override; procedure Cleanup; override; procedure Start; override; published property StartValue: TvgBounds read FStartRect write FStartRect; property StartFromCurrent: boolean read FStartFromCurrent write FStartFromCurrent default false; property StopValue: TvgBounds read FStopRect write FStopRect; property PropertyName: AnsiString read FPropertyName write FPropertyName; end; TvgBitmapAnimation = class(TvgAnimation) private FPropertyName: AnsiString; FInstance: TObject; FStartBitmap: TvgBitmap; FStopBitmap: TvgBitmap; FCurrent: TvgBitmap; protected procedure ProcessAnimation; override; public constructor Create(AOwner: TComponent); override; procedure Cleanup; override; published property StartValue: TvgBitmap read FStartBitmap write FStartBitmap; property StopValue: TvgBitmap read FStopBitmap write FStopBitmap; property PropertyName: AnsiString read FPropertyName write FPropertyName; end; TvgBitmapListAnimation = class(TvgAnimation) private FPropertyName: AnsiString; FInstance: TObject; FCurrent: TvgBitmap; FAnimationCount: Integer; FAnimationBitmap: TvgBitmap; FLastAnimationStep: Integer; protected procedure ProcessAnimation; override; public constructor Create(AOwner: TComponent); override; procedure Cleanup; override; published property PropertyName: AnsiString read FPropertyName write FPropertyName; property AnimationBitmap: TvgBitmap read FAnimationBitmap write FAnimationBitmap; property AnimationCount: Integer read FAnimationCount write FAnimationCount; end; { Key Animations } TvgKey = class(TCollectionItem) private FKey: single; procedure SetKey(const Value: single); public published property Key: single read FKey write SetKey; end; TvgKeys = class(TCollection) private public function FindKeys(const Time: single; var Key1, Key2: TvgKey): boolean; published end; TvgColorKey = class(TvgKey) private FValue: string; public published property Value: string read FValue write FValue; end; TvgColorKeyAnimation = class(TvgAnimation) private FPropertyName: AnsiString; FInstance: TObject; FKeys: TvgKeys; FPath: AnsiString; FStartFromCurrent: boolean; protected procedure ProcessAnimation; override; public constructor Create(AOwner: TComponent); override; procedure Cleanup; override; procedure Start; override; published property PropertyName: AnsiString read FPropertyName write FPropertyName; property Keys: TvgKeys read FKeys write FKeys; property StartFromCurrent: boolean read FStartFromCurrent write FStartFromCurrent; end; TvgFloatKey = class(TvgKey) private FValue: single; public published property Value: single read FValue write FValue; end; TvgFloatKeyAnimation = class(TvgAnimation) private FPropertyName: AnsiString; FInstance: TObject; FKeys: TvgKeys; FPath: AnsiString; FStartFromCurrent: boolean; protected procedure ProcessAnimation; override; public constructor Create(AOwner: TComponent); override; procedure Cleanup; override; procedure Start; override; published property PropertyName: AnsiString read FPropertyName write FPropertyName; property Keys: TvgKeys read FKeys write FKeys; property StartFromCurrent: boolean read FStartFromCurrent write FStartFromCurrent; end; { Path Animation } TvgPathAnimation = class(TvgAnimation) private FPath: TvgPathData; FPolygon: TvgPolygon; FObj: TvgVisualObject; FStart: TvgPoint; FRotate: boolean; FSpline: TvgSpline; procedure SetPath(const Value: TvgPathData); protected procedure ProcessAnimation; override; public constructor Create(AOwner: TComponent); override; procedure Cleanup; override; procedure Start; override; published property Path: TvgPathData read FPath write SetPath; property Rotate: boolean read FRotate write FRotate default false; end; { Switch Animations } TvgPathSwitcher = class(TvgAnimation) private FPath, FPropertyName: AnsiString; FInstance: TObject; FPathTrue: string; FPathFalse: string; procedure SetPathFalse(const Value: string); procedure SetPathTrue(const Value: string); protected procedure ProcessAnimation; override; public constructor Create(AOwner: TComponent); override; procedure Cleanup; override; procedure Start; override; published property PathTrue: string read FPathTrue write SetPathTrue; property PathFalse: string read FPathFalse write SetPathFalse; property PropertyName: AnsiString read FPropertyName write FPropertyName; end; implementation {===============================================================} uses vg_objects, math, typinfo; { TvgAnimation ===================================================================} constructor TvgColorAnimation.Create(AOwner: TComponent); begin inherited; Duration := 0.2; FStartColor := $FFFFFFFF; FStartColor := $FFFFFFFF; end; procedure TvgColorAnimation.Cleanup; begin inherited; end; procedure TvgColorAnimation.Start; var Persistent: string; begin if (Parent <> nil) and (FPropertyName <> '') then begin if FInstance = nil then begin FInstance := Parent; FPath := FPropertyName; while Pos('.', FPath) > 0 do begin Persistent := vgGetToken(FPath, '.'); if GetPropInfo(FInstance.ClassInfo, Persistent, [tkClass]) <> nil then FInstance := GetObjectProp(FInstance, Persistent); end; end; end; if (FInstance <> nil) and StartFromCurrent then begin { is string prop } if GetPropInfo(FInstance.ClassInfo, FPath, [tkString, tkLString, tkWString{$IFDEF FPC},tkAString{$ENDIF}{$IFDEF KS_COMPILER11_UP}, tkUString{$ENDIF}]) <> nil then StartValue := GetStrProp(FInstance, FPath); { is int prop } if GetPropInfo(FInstance.ClassInfo, FPath, [tkInteger]) <> nil then StartValue := vgColorToStr(GetOrdProp(FInstance, FPath)); end; inherited; end; procedure TvgColorAnimation.ProcessAnimation; begin if FInstance <> nil then begin { is string prop } if GetPropInfo(FInstance.ClassInfo, FPath, [tkString, tkLString, tkWString{$IFDEF FPC},tkAString{$ENDIF}{$IFDEF KS_COMPILER11_UP}, tkUString{$ENDIF}]) <> nil then SetStrProp(FInstance, FPath, vgColorToStr(vgInterpolateColor(FStartColor, FStopColor, NormalizedTime))); { is int prop } if GetPropInfo(FInstance.ClassInfo, FPath, [tkInteger]) <> nil then SetOrdProp(FInstance, FPath, vgInterpolateColor(FStartColor, FStopColor, NormalizedTime)); end; end; function TvgColorAnimation.GetStartColor: string; begin Result := vgColorToStr(FStartColor); end; function TvgColorAnimation.GetStopColor: string; begin Result := vgColorToStr(FStopColor); end; procedure TvgColorAnimation.SetStartColor(const Value: string); begin FStartColor := vgStrToColor(Value); end; procedure TvgColorAnimation.SetStopColor(const Value: string); begin FStopColor := vgStrToColor(Value); end; { TvgAnimation ===================================================================} constructor TvgGradientAnimation.Create(AOwner: TComponent); begin inherited; Duration := 0.2; FStartGradient := TvgGradient.Create; FStopGradient := TvgGradient.Create; end; procedure TvgGradientAnimation.Cleanup; begin FreeAndNil(FStartGradient); FreeAndNil(FStopGradient); inherited; end; procedure TvgGradientAnimation.Start; var Persistent: string; begin if (Parent <> nil) and (FPropertyName <> '') then begin if FInstance = nil then begin FInstance := Parent; FPath := FPropertyName; while Pos('.', FPath) > 0 do begin Persistent := vgGetToken(FPath, '.'); if GetPropInfo(FInstance.ClassInfo, Persistent, [tkClass]) <> nil then FInstance := GetObjectProp(FInstance, Persistent); end; end; end; if (FInstance <> nil) and StartFromCurrent then begin if GetPropInfo(FInstance.ClassInfo, FPath, [tkClass]) <> nil then begin StartValue := TvgGradient(GetObjectProp(FInstance, FPath, TvgGradient)); end; end; inherited; end; procedure TvgGradientAnimation.ProcessAnimation; var i: integer; G: TvgGradient; begin if FInstance <> nil then begin if GetPropInfo(FInstance.ClassInfo, FPath, [tkClass]) <> nil then begin with TvgGradient(GetObjectProp(FInstance, FPath, TvgGradient)) do begin for i := 0 to Points.Count - 1 do begin if (i < FStopGradient.Points.Count) or (i < FStartGradient.Points.Count) then Points[i].Color := vgColorToStr(vgInterpolateColor(vgStrToColor(FStartGradient.Points[i].Color), vgStrToColor(FStopGradient.Points[i].Color), NormalizedTime)); end; Change; end; end; end; end; procedure TvgGradientAnimation.SetStartGradient(const Value: TvgGradient); begin FStartGradient.Assign(Value); end; procedure TvgGradientAnimation.SetStopGradient(const Value: TvgGradient); begin FStopGradient.Assign(Value); end; { TvgAnimation ===================================================================} constructor TvgFloatAnimation.Create(AOwner: TComponent); begin inherited; Duration := 0.2; FStartFloat := 0; FStopFloat := 0; end; procedure TvgFloatAnimation.Cleanup; begin inherited; end; procedure TvgFloatAnimation.Start; var Persistent: string; begin if (Parent <> nil) and (FPropertyName <> '') then begin if FInstance = nil then begin FInstance := Parent; FPath := FPropertyName; while Pos('.', FPath) > 0 do begin Persistent := vgGetToken(FPath, '.'); if GetPropInfo(FInstance.ClassInfo, Persistent, [tkClass]) <> nil then FInstance := GetObjectProp(FInstance, Persistent); end; end; end; if (FInstance <> nil) and StartFromCurrent then begin { is float prop } if GetPropInfo(FInstance.ClassInfo, FPath, [tkFloat]) <> nil then begin StartValue := GetFloatProp(FInstance, FPath); end; end; inherited; end; procedure TvgFloatAnimation.Stop; begin inherited; FInstance := nil; end; procedure TvgFloatAnimation.ProcessAnimation; begin if FInstance <> nil then begin { is float prop } if GetPropInfo(FInstance.ClassInfo, FPath, [tkFloat]) <> nil then begin SetFloatProp(FInstance, FPath, vgInterpolateSingle(FStartFloat, FStopFloat, NormalizedTime)); end; end; end; { TvgAnimation ===================================================================} constructor TvgRectAnimation.Create(AOwner: TComponent); begin inherited; Duration := 0.2; FStartRect := TvgBounds.Create(vgRect(0, 0, 0, 0)); FStopRect := TvgBounds.Create(vgRect(0, 0, 0, 0)); FCurrent := TvgBounds.Create(vgRect(0, 0, 0, 0)); end; procedure TvgRectAnimation.Cleanup; begin FreeAndNil(FCurrent); FreeAndNil(FStartRect); FreeAndNil(FStopRect); inherited; end; procedure TvgRectAnimation.Start; var Persistent: string; Value: TObject; begin if (Parent <> nil) and (FPropertyName <> '') then begin if FInstance = nil then begin FInstance := Parent; FPath := FPropertyName; while Pos('.', FPath) > 0 do begin Persistent := vgGetToken(FPath, '.'); if GetPropInfo(FInstance.ClassInfo, Persistent, [tkClass]) <> nil then FInstance := GetObjectProp(FInstance, Persistent); end; end; end; if (FInstance <> nil) and StartFromCurrent then begin { is Rect prop } if GetPropInfo(FInstance.ClassInfo, FPropertyName, [tkClass]) <> nil then begin Value := GetObjectProp(FInstance, FPropertyName); if (Value <> nil) and (Value is TPersistent) then FStartRect.Assign(TPersistent(Value)); end; end; inherited; end; procedure TvgRectAnimation.ProcessAnimation; var Value: TObject; begin if FInstance <> nil then begin { calc value } FCurrent.Left := vgInterpolateSingle(FStartRect.Left, FStopRect.Left, NormalizedTime); FCurrent.Top := vgInterpolateSingle(FStartRect.Top, FStopRect.Top, NormalizedTime); FCurrent.Right := vgInterpolateSingle(FStartRect.Right, FStopRect.Right, NormalizedTime); FCurrent.Bottom := vgInterpolateSingle(FStartRect.Bottom, FStopRect.Bottom, NormalizedTime); { is Rect prop } if GetPropInfo(FInstance.ClassInfo, FPath, [tkClass]) <> nil then begin Value := GetObjectProp(FInstance, FPath); if (Value <> nil) and (Value is TPersistent) then TPersistent(Value).Assign(FCurrent); end; end; end; { TvgAnimation ===================================================================} constructor TvgBitmapAnimation.Create(AOwner: TComponent); begin inherited; Duration := 0.2; FStartBitmap := TvgBitmap.Create(1, 1); FStopBitmap := TvgBitmap.Create(1, 1); FCurrent := TvgBitmap.Create(1, 1); end; procedure TvgBitmapAnimation.Cleanup; begin FreeAndNil(FCurrent); FreeAndNil(FStartBitmap); FreeAndNil(FStopBitmap); inherited; end; procedure TvgBitmapAnimation.ProcessAnimation; var Persistent, Path: string; Value: TObject; begin if (Parent <> nil) and (FPropertyName <> '') then begin if FInstance = nil then begin FInstance := Parent; Path := FPropertyName; while Pos('.', FPropertyName) > 0 do begin Persistent := vgGetToken(FPropertyName, '.'); if GetPropInfo(FInstance.ClassInfo, Persistent, [tkClass]) <> nil then FInstance := GetObjectProp(FInstance, Persistent); end; end; if FInstance <> nil then begin { is Bitmap prop } if GetPropInfo(FInstance.ClassInfo, FPropertyName, [tkClass]) <> nil then begin { calc new value } Value := GetObjectProp(FInstance, FPropertyName); if (Value <> nil) and (Value is TPersistent) then begin if Inverse then begin { assign to start } FCurrent.Assign(FStopBitmap); { draw final with alpha } if TvgCanvas(FCurrent.Canvas).BeginScene then begin TvgCanvas(FCurrent.Canvas).Clear(0); TvgCanvas(FCurrent.Canvas).DrawBitmap(FStartBitmap, vgRect(0, 0, FCurrent.Width, FCurrent.Height), vgRect(0, 0, FStartBitmap.Width, FStartBitmap.Height), 1 - NormalizedTime); TvgCanvas(FCurrent.Canvas).EndScene; end; end else begin { assign to start } FCurrent.Assign(FStartBitmap); { draw final with alpha } if TvgCanvas(FCurrent.Canvas).BeginScene then begin TvgCanvas(FCurrent.Canvas).Clear(0); TvgCanvas(FCurrent.Canvas).DrawBitmap(FStopBitmap, vgRect(0, 0, FCurrent.Width, FCurrent.Height), vgRect(0, 0, FStopBitmap.Width, FStopBitmap.Height), NormalizedTime); TvgCanvas(FCurrent.Canvas).EndScene; end; end; { assign } TPersistent(Value).Assign(FCurrent); end; end; end; end; end; { TvgBitmapListAnimation } constructor TvgBitmapListAnimation.Create(AOwner: TComponent); begin inherited; Duration := 0.2; FCurrent := TvgBitmap.Create(0, 0); FAnimationBitmap := TvgBitmap.Create(0, 0); FAnimationCount := 1; FLastAnimationStep := 0; end; procedure TvgBitmapListAnimation.Cleanup; begin FreeAndNil(FCurrent); FreeAndNil(FAnimationBitmap); inherited; end; procedure TvgBitmapListAnimation.ProcessAnimation; var Persistent, Path: string; Value: TObject; LeftPos, CurrentIndex: Integer; NowValue: Single; begin if (Parent <> nil) and (FPropertyName <> '') then begin if FInstance = nil then begin FInstance := Parent; Path := FPropertyName; while Pos('.', FPropertyName) > 0 do begin Persistent := vgGetToken(FPropertyName, '.'); if GetPropInfo(FInstance.ClassInfo, Persistent, [tkClass]) <> nil then FInstance := GetObjectProp(FInstance, Persistent); end; end; if FInstance <> nil then begin { is Bitmap prop } if GetPropInfo(FInstance.ClassInfo, FPropertyName, [tkClass]) <> nil then begin { calc new value } Value := GetObjectProp(FInstance, FPropertyName); if (Value <> nil) and (Value is TvgBitmap) then begin NowValue := vgInterpolateSingle(0, FAnimationCount - 1, NormalizedTime); FCurrent.SetSize(TvgBitmap(Value).Height, TvgBitmap(Value).Width); CurrentIndex := Trunc(NowValue); LeftPos := CurrentIndex * (FAnimationBitmap.Width div FAnimationCount) + CurrentIndex; if TvgCanvas(FCurrent.Canvas).BeginScene then begin TvgCanvas(FCurrent.Canvas).Clear(0); TvgCanvas(FCurrent.Canvas).DrawBitmap(FAnimationBitmap, vgRect(LeftPos, 0, LeftPos + FCurrent.Width, FCurrent.Height), vgRect(0, 0, FAnimationBitmap.Width div FAnimationCount, FAnimationBitmap.Height), 1); TvgCanvas(FCurrent.Canvas).EndScene; end; TPersistent(Value).Assign(FCurrent); end; end; end; end; end; { Key Animation ===============================================================} { TvgKey } procedure TvgKey.SetKey(const Value: single); begin FKey := Value; if FKey < 0 then FKey := 0; if FKey > 1 then FKey := 1; end; { TvgKeys } function TvgKeys.FindKeys(const Time: single; var Key1, Key2: TvgKey): boolean; var i: integer; begin Result := false; if Count < 2 then Exit; for i := 0 to Count - 2 do if ((Time >= TvgKey(Items[i]).Key) and (Time <= TvgKey(Items[i + 1]).Key)) then begin Result := true; Key1 := TvgKey(Items[i]); Key2 := TvgKey(Items[i + 1]); Exit; end; end; { TvgColorKeyAnimation ========================================================} constructor TvgColorKeyAnimation.Create(AOwner: TComponent); begin inherited; FKeys := TvgKeys.Create(TvgColorKey); end; procedure TvgColorKeyAnimation.Cleanup; begin FreeAndNil(FKeys); inherited; end; procedure TvgColorKeyAnimation.Start; var Persistent: string; begin if (Parent <> nil) and (FPropertyName <> '') then begin if FInstance = nil then begin FInstance := Parent; FPath := FPropertyName; while Pos('.', FPath) > 0 do begin Persistent := vgGetToken(FPath, '.'); if GetPropInfo(FInstance.ClassInfo, Persistent, [tkClass]) <> nil then FInstance := GetObjectProp(FInstance, Persistent); end; end; end; if (FInstance <> nil) and StartFromCurrent then begin if Keys.Count > 0 then begin { is string prop } if GetPropInfo(FInstance.ClassInfo, FPath, [tkString, tkLString, tkWString{$IFDEF FPC},tkAString{$ENDIF}{$IFDEF KS_COMPILER11_UP}, tkUString{$ENDIF}]) <> nil then TvgColorKey(Keys.Items[0]).Value := GetStrProp(FInstance, FPath); { is int prop } if GetPropInfo(FInstance.ClassInfo, FPath, [tkInteger]) <> nil then TvgColorKey(Keys.Items[0]).Value := vgColorToStr(GetOrdProp(FInstance, FPath)); end; end; inherited; end; procedure TvgColorKeyAnimation.ProcessAnimation; var Key1, Key2: TvgKey; begin if FInstance <> nil then begin if FKeys.FindKeys(NormalizedTime, Key1, Key2) then begin if (TvgFloatKey(Key2).Key - TvgFloatKey(Key1).Key) = 0 then Exit; { is string prop } if GetPropInfo(FInstance.ClassInfo, FPath, [tkString, tkLString, tkWString{$IFDEF FPC},tkAString{$ENDIF}{$IFDEF KS_COMPILER11_UP}, tkUString{$ENDIF}]) <> nil then SetStrProp(FInstance, FPath, vgColorToStr(vgInterpolateColor(vgStrToColor(TvgColorKey(Key1).Value), vgStrToColor(TvgColorKey(Key2).Value), (NormalizedTime - TvgFloatKey(Key1).Key) / (TvgFloatKey(Key2).Key - TvgFloatKey(Key1).Key)))); { is int prop } if GetPropInfo(FInstance.ClassInfo, FPath, [tkInteger]) <> nil then SetOrdProp(FInstance, FPath, vgInterpolateColor(vgStrToColor(TvgColorKey(Key1).Value), vgStrToColor(TvgColorKey(Key2).Value), (NormalizedTime - TvgFloatKey(Key1).Key) / (TvgFloatKey(Key2).Key - TvgFloatKey(Key1).Key))); end; end; end; { TvgFloatKeyAnimation ========================================================} constructor TvgFloatKeyAnimation.Create(AOwner: TComponent); begin inherited; FKeys := TvgKeys.Create(TvgFloatKey); end; procedure TvgFloatKeyAnimation.Cleanup; begin FreeAndNil(FKeys); inherited; end; procedure TvgFloatKeyAnimation.Start; var Persistent: string; begin if (Parent <> nil) and (FPropertyName <> '') then begin if FInstance = nil then begin FInstance := Parent; FPath := FPropertyName; while Pos('.', FPath) > 0 do begin Persistent := vgGetToken(FPath, '.'); if GetPropInfo(FInstance.ClassInfo, Persistent, [tkClass]) <> nil then FInstance := GetObjectProp(FInstance, Persistent); end; end; end; if (FInstance <> nil) and StartFromCurrent then begin if Keys.Count > 0 then begin { is string prop } if GetPropInfo(FInstance.ClassInfo, FPath, [tkFloat]) <> nil then TvgFloatKey(Keys.Items[0]).Value := GetFloatProp(FInstance, FPath); end; end; inherited; end; procedure TvgFloatKeyAnimation.ProcessAnimation; var Key1, Key2: TvgKey; begin if FInstance <> nil then begin if FKeys.FindKeys(NormalizedTime, Key1, Key2) then begin if (TvgFloatKey(Key2).Key - TvgFloatKey(Key1).Key) = 0 then Exit; if GetPropInfo(FInstance.ClassInfo, FPath, [tkFloat]) <> nil then SetFloatProp(FInstance, FPath, vgInterpolateSingle(TvgFloatKey(Key1).Value, TvgFloatKey(Key2).Value, (NormalizedTime - TvgFloatKey(Key1).Key) / (TvgFloatKey(Key2).Key - TvgFloatKey(Key1).Key))); end; end; end; { TvgPathAnimation } constructor TvgPathAnimation.Create(AOwner: TComponent); begin inherited; FPath := TvgPathData.Create; end; procedure TvgPathAnimation.Cleanup; begin if FSpline <> nil then FreeAndNil(FSpline); FreeAndNil(FPath); inherited; end; procedure TvgPathAnimation.ProcessAnimation; var OldP, P1: TvgPoint; begin if (Length(FPolygon) > 0) and (FObj <> nil) then begin OldP := FObj.Position.Point; FSpline.SplineXY(NormalizedTime * Length(FPolygon), P1.X, P1.Y); FObj.Position.X := FStart.X + P1.X; FObj.Position.Y := FStart.Y + P1.Y; if FRotate and (NormalizedTime <> 0) and (NormalizedTime <> 1) and ((OldP.X <> FObj.Position.X) and (OldP.Y <> FObj.Position.Y)) then begin if Inverse then begin if vgVectorCrossProductZ(vgVector(FObj.Position.X - OldP.X, FObj.Position.Y - OldP.Y), vgVector(0, 1)) < 0 then FObj.RotateAngle := 180 + vgRadToDeg(ArcCos(vgVectorAngleCosine(vgVector(FObj.Position.X - OldP.X, FObj.Position.Y - OldP.Y), vgVector(0, 1)))) else FObj.RotateAngle := 180 - vgRadToDeg(ArcCos(vgVectorAngleCosine(vgVector(FObj.Position.X - OldP.X, FObj.Position.Y - OldP.Y), vgVector(0, 1)))) end else begin if vgVectorCrossProductZ(vgVector(FObj.Position.X - OldP.X, FObj.Position.Y - OldP.Y), vgVector(0, 1)) < 0 then FObj.RotateAngle := vgRadToDeg(ArcCos(vgVectorAngleCosine(vgVector(FObj.Position.X - OldP.X, FObj.Position.Y - OldP.Y), vgVector(0, 1)))) else FObj.RotateAngle := -vgRadToDeg(ArcCos(vgVectorAngleCosine(vgVector(FObj.Position.X - OldP.X, FObj.Position.Y - OldP.Y), vgVector(0, 1)))) end; end; end; end; procedure TvgPathAnimation.SetPath(const Value: TvgPathData); begin FPath.Assign(Value); end; procedure TvgPathAnimation.Start; var i: integer; begin inherited; if FSpline <> nil then FreeAndNil(FSpline); SetLength(FPolygon, 0); if Assigned(Scene) and (Scene.GetCanvas <> nil) then begin FPath.FlattenToPolygon(FPolygon); if Length(FPolygon) > 1 then for i := 1 to High(FPolygon) do if (FPolygon[i].X = ClosePolygon.X) and (FPolygon[i].Y = ClosePolygon.Y) then FPolygon[i] := FPolygon[i - 1]; FSpline := TvgSpline.Create(FPolygon); end; if (Parent <> nil) and (Parent.IsVisual) then FObj := TvgVisualObject(Parent.Visual) else FObj := nil; if FObj <> nil then FStart := FObj.Position.Point; end; { TvgPathSwitcher =============================================================} constructor TvgPathSwitcher.Create(AOwner: TComponent); begin inherited; Duration := 0.001; end; procedure TvgPathSwitcher.Cleanup; begin inherited; end; procedure TvgPathSwitcher.Start; begin inherited; end; procedure TvgPathSwitcher.ProcessAnimation; begin inherited; end; procedure TvgPathSwitcher.SetPathFalse(const Value: string); begin FPathFalse := Value; end; procedure TvgPathSwitcher.SetPathTrue(const Value: string); begin FPathTrue := Value; end; initialization RegisterVGObjects('Animations', [TvgColorAnimation, TvgGradientAnimation, TvgFloatAnimation, TvgRectAnimation, TvgBitmapAnimation, TvgBitmapListAnimation, TvgColorKeyAnimation, TvgFloatKeyAnimation, TvgPathAnimation, TvgPathSwitcher]); end.
namespace Sugar.Test; interface uses Sugar, Sugar.IO, RemObjects.Elements.EUnit; type FileHandleTest = public class (Test) private aFile: File; Data: Sugar.IO.FileHandle; public method Setup; override; method TearDown; override; method Close; method &Read; method &ReadOverloads; method &Write; method WriteOverloads; method Seek; method Mode; method Length; method Position; end; implementation method FileHandleTest.Setup; begin aFile := Folder.UserLocal.CreateFile("sugar.testcase.txt", false); FileUtils.WriteText(aFile.Path, ""); Data := new FileHandle(aFile.Path, FileOpenMode.ReadWrite); end; method FileHandleTest.TearDown; begin Data.Close; aFile.Delete; end; method FileHandleTest.Close; begin Data.Write([1, 2, 3]); Data.Close; Assert.Throws(->Data.Write([1, 2, 3])); Assert.Throws(->Data.Seek(0, SeekOrigin.Begin)); var Actual := new Byte[1]; Assert.Throws(->Data.Read(Actual, 1)); Assert.Throws(->Data.Length); Data := new Sugar.IO.FileHandle(aFile.Path, FileOpenMode.ReadOnly); Actual := new Byte[3]; Assert.AreEqual(Data.Read(Actual, 0, 3), 3); for i: Integer := 0 to 2 do Assert.AreEqual(Actual[i], i + 1); end; method FileHandleTest.Read; begin var Original: String := "Hello World"; Assert.AreEqual(Data.Length, 0); Data.Write(Original.ToByteArray, 0, Original.Length); Assert.AreEqual(Data.Length, Original.Length); Data.Seek(0, SeekOrigin.Begin); Assert.AreEqual(Data.Position, 0); var Actual := new Byte[5]; Assert.AreEqual(Data.Read(Actual, 0, 5), 5); Assert.AreEqual(new String(Actual, Encoding.UTF8), "Hello"); var Full := new Byte[Original.Length + 5]; Data.Position := 0; Assert.AreEqual(Data.Read(Full, 0, Original.Length + 5), Original.Length); Data.Position := 6; Assert.AreEqual(Data.Read(Actual, 0, 5), 5); Assert.AreEqual(new String(Actual, Encoding.UTF8), "World"); Data.Position := 0; var Actual2 := new Byte[Original.Length]; Assert.AreEqual(Data.Read(Actual2, 0, 5), 5); Assert.AreEqual(Data.Read(Actual2, 5, 1), 1); Assert.AreEqual(Data.Read(Actual2, 6, 5), 5); Assert.AreEqual(new String(Actual2, Encoding.UTF8), Original); Assert.Throws(->Data.Read(nil, 0, 1)); Assert.Throws(->Data.Read(Actual, -1, 1)); Assert.Throws(->Data.Read(Actual, 50, 1)); Assert.Throws(->Data.Read(Actual, 0, -1)); Assert.Throws(->Data.Read(Actual, 0, 555)); Assert.Throws(->Data.Read(Actual, 3, 5)); end; method FileHandleTest.ReadOverloads; begin Data.Write([0, 1, 2, 3]); Assert.AreEqual(Data.Length, 4); Data.Position := 0; var Actual := new Byte[2]; Assert.AreEqual(Data.Read(Actual, 2), 2); Assert.AreEqual(Actual[0], 0); Assert.AreEqual(Actual[1], 1); Data.Position := 2; var Bin := Data.Read(5); Assert.IsNotNil(Bin); Assert.AreEqual(Bin.Length, 2); Assert.AreEqual(Bin.ToArray[0], 2); Assert.AreEqual(Bin.ToArray[1], 3); end; method FileHandleTest.Write; begin var Original: String := "Hello World"; Assert.AreEqual(Data.Length, 0); Data.Write(Original.ToByteArray, 0, Original.Length); Assert.AreEqual(Data.Length, Original.Length); var Actual := new Byte[Original.Length]; Data.Position := 0; Assert.AreEqual(Data.Read(Actual, 0, Original.Length), Original.Length); Assert.AreEqual(new String(Actual, Encoding.UTF8), Original); Data.Length := 0; Data.Write(Original.ToByteArray, 6, 5); Data.Position := 0; var Actual2 := new Byte[5]; Assert.AreEqual(Data.Read(Actual2, 0, 5), 5); Assert.AreEqual(new String(Actual2, Encoding.UTF8), "World"); Assert.Throws(->Data.Write(nil, 0, 1)); Assert.Throws(->Data.Write(Actual, -1, 1)); Assert.Throws(->Data.Write(Actual, 0, -1)); Assert.Throws(->Data.Write(Actual, 55, 1)); Assert.Throws(->Data.Write(Actual, 0, 55)); Assert.Throws(->Data.Write(Actual, 7, 9)); end; method FileHandleTest.WriteOverloads; begin Data.Write([0, 1, 2, 3], 2); Assert.AreEqual(Data.Length, 2); Data.Position := 0; var Actual := Data.Read(10); Assert.AreEqual(Data.Length, 2); Assert.AreEqual(Actual.ToArray[0], 0); Assert.AreEqual(Actual.ToArray[1], 1); Data.Length := 0; Data.Write([42, 42]); Assert.AreEqual(Data.Length, 2); Data.Position := 0; Actual := Data.Read(2); Assert.AreEqual(Data.Length, 2); Assert.AreEqual(Actual.ToArray[0], 42); Assert.AreEqual(Actual.ToArray[1], 42); var Bin := new Binary([1, 2, 3]); Data.Length := 0; Data.Write(Bin); Assert.AreEqual(Data.Length, 3); Data.Position := 0; Actual := Data.Read(3); Assert.AreEqual(Data.Length, 3); Assert.AreEqual(Actual.ToArray[0], 1); Assert.AreEqual(Actual.ToArray[1], 2); Assert.AreEqual(Actual.ToArray[2], 3); Bin := nil; Assert.Throws(->Data.Write(Bin)); end; method FileHandleTest.Seek; begin Data.Write([42, 42, 42, 42], 0, 4); Data.Seek(1, SeekOrigin.Begin); Assert.AreEqual(Data.Position, 1); Data.Seek(1, SeekOrigin.Current); Assert.AreEqual(Data.Position, 2); Data.Seek(-1, SeekOrigin.End); Assert.AreEqual(Data.Position, 3); Data.Seek(-1, SeekOrigin.Current); Assert.AreEqual(Data.Position, 2); Assert.AreEqual(Data.Length, 4); Data.Seek(2, SeekOrigin.End); Assert.AreEqual(Data.Position, 6); Assert.AreEqual(Data.Length, 4); Data.Write([42], 0, 1); Assert.AreEqual(Data.Length, 7); Assert.Throws(->Data.Seek(-1, SeekOrigin.Begin)); end; method FileHandleTest.Mode; begin Data.Write([42], 0, 1); var Actual := new Byte[1]; Data.Read(Actual, 0, 1); Data.Close; Data := new Sugar.IO.FileHandle(aFile.Path, FileOpenMode.ReadOnly); Data.Read(Actual, 0, 1); Assert.Throws(->Data.Write([42], 0, 1)); Data.Close; end; method FileHandleTest.Length; begin Assert.AreEqual(Data.Length, 0); Data.Write([42], 0, 1); Assert.AreEqual(Data.Length, 1); Assert.AreEqual(Data.Position, 1); Data.Length := 5; Assert.AreEqual(Data.Length, 5); Assert.AreEqual(Data.Position, 1); Data.Length := 0; Assert.AreEqual(Data.Length, 0); Assert.AreEqual(Data.Position, 0); Assert.Throws(->begin Data.Length := -1; end); end; method FileHandleTest.Position; begin Assert.AreEqual(Data.Position, 0); Data.Write([42, 42, 42, 42], 0, 4); Assert.AreEqual(Data.Position, 4); Data.Position := 0; Assert.AreEqual(Data.Position, 0); var Actual := new Byte[4]; Data.Read(Actual, 0, 4); Assert.AreEqual(Data.Position, 4); Assert.Throws(->begin Data.Position := -1; end); end; end.
{******************************************************************************* 作者: dmzn@163.com 2009-7-23 描述: 图像分析数据 *******************************************************************************} unit UFormParseData; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UDataModule, UBgFormBase, Menus, cxLookAndFeelPainters, dxLayoutControl, cxControls, StdCtrls, cxButtons, UTransPanel, cxContainer, cxMCListBox, cxGraphics, cxMemo, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxButtonEdit, UBitmapButton; type TfFormParseData = class(TfBgFormBase) dxLayoutControl1Group_Root: TdxLayoutGroup; dxLayoutControl1: TdxLayoutControl; dxGroup1: TdxLayoutGroup; dxGroup2: TdxLayoutGroup; ListInfo1: TcxMCListBox; dxLayoutControl1Item1: TdxLayoutItem; ListInfo2: TcxMCListBox; dxLayoutControl1Item2: TdxLayoutItem; InfoItems: TcxComboBox; dxLayoutControl1Item3: TdxLayoutItem; EditInfo: TcxMemo; dxLayoutControl1Item4: TdxLayoutItem; BtnDel1: TButton; dxLayoutControl1Item5: TdxLayoutItem; BtnAdd1: TButton; dxLayoutControl1Item6: TdxLayoutItem; dxLayoutControl1Group1: TdxLayoutGroup; EditProduct: TcxTextEdit; dxLayoutControl1Item7: TdxLayoutItem; EditReason: TcxMemo; dxLayoutControl1Item8: TdxLayoutItem; BtnAdd2: TButton; dxLayoutControl1Item9: TdxLayoutItem; BtnDel2: TButton; dxLayoutControl1Item10: TdxLayoutItem; dxLayoutControl1Group2: TdxLayoutGroup; PfID: TcxButtonEdit; dxLayoutControl1Item13: TdxLayoutItem; PfName: TcxTextEdit; dxLayoutControl1Item14: TdxLayoutItem; dxLayoutControl1Group4: TdxLayoutGroup; PFList1: TcxComboBox; dxLayoutControl1Item15: TdxLayoutItem; CFList1: TcxComboBox; dxLayoutControl1Item16: TdxLayoutItem; CfID: TcxButtonEdit; dxLayoutControl1Item17: TdxLayoutItem; CfName: TcxTextEdit; dxLayoutControl1Item18: TdxLayoutItem; dxLayoutControl1Group5: TdxLayoutGroup; BtnExpand: TZnBitmapButton; EditCFType: TcxComboBox; dxLayoutControl1Item11: TdxLayoutItem; procedure BtnExpandClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BtnAdd1Click(Sender: TObject); procedure BtnDel1Click(Sender: TObject); procedure PFList1PropertiesEditValueChanged(Sender: TObject); procedure CFList1PropertiesEditValueChanged(Sender: TObject); procedure ListInfo1Click(Sender: TObject); procedure ListInfo2Click(Sender: TObject); procedure BtnDel2Click(Sender: TObject); procedure BtnAdd2Click(Sender: TObject); procedure ListInfo2DblClick(Sender: TObject); procedure PfIDPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); procedure EditReasonExit(Sender: TObject); private { Private declarations } FMemberID: string; //会员编号 FDisplayRect: TRect; //显示区域 FFormWidth,FFormHeight: integer; //窗体宽高 FProductList: TList; //产品列表 FSkinPrefixID,FPlanPrefixID: string; //前缀编号 FSkinIDLength,FPlanIDLength: integer; //前缀长度 FImageExpand,FImageCollapse: TBitmap; //按钮图标 procedure InitFormData; //初始数据 procedure ClearProductList(const nFree: Boolean); //清理资源 procedure HideAllCtrl(const nHide: Boolean); //显隐控件 procedure ExpandForm(const nExpand: Boolean); //显隐窗口 function SaveParseData(var nSkinID: string): Boolean; //保存数据 public { Public declarations } end; function ShowParseDataForm(const nMemberID: string; const nRect: TRect): TForm; procedure SetParseImage(const nImage: TPicture); procedure CloseParseDataForm; function SaveParseData(var nSkinID: string): Boolean; //入口函数 implementation {$R *.dfm} uses IniFiles, ULibFun, UAdjustForm, USysGrid, USysDB, USysConst, USysGobal, USysFun, UImageControl, UFormProductView, UFormProduct; const cHorInterval = 1; //水平边距 cVerInterval = 5; //垂直边距 var gForm: TForm = nil; //------------------------------------------------------------------------------ //Desc: 显示图像分析数据窗口 function ShowParseDataForm(const nMemberID: string; const nRect: TRect): TForm; begin Result := gForm; if Assigned(gForm) then Exit; gForm := TfFormParseData.Create(gForm); Result := gForm; with TfFormParseData(Result) do begin Position := poDesigned; FMemberID := nMemberID; FDisplayRect := nRect; InitFormData; if not Showing then Show; end; end; procedure SetParseImage(const nImage: TPicture); begin end; procedure CloseParseDataForm; begin if Assigned(gForm) then begin TfFormParseData(gForm).CloseForm; end; end; //Date: 2009-7-26 //Parm: 皮肤特征编号 //Desc: 保存分析数据 function SaveParseData(var nSkinID: string): Boolean; begin if Assigned(gForm) then begin with TfFormParseData(gForm) do Result := SaveParseData(nSkinID); end else Result := False; end; //Desc: 读取nFile图片 function MyLoadImage(const nFile: string): TBitmap; var nPic: TPicture; begin Result := nil; nPic := TPicture.Create; try nPic.LoadFromFile(nFile); Result := TBitmap.Create; Result.Width := nPic.Width; Result.Height := nPic.Height; Result.Canvas.Draw(0, 0, nPic.Graphic); FreeAndNil(nPic); except FreeAndNil(nPic); FreeAndNil(Result); end; end; //------------------------------------------------------------------------------ procedure TfFormParseData.FormCreate(Sender: TObject); var nStr: string; nIni: TIniFile; begin inherited; FFormWidth := Width; FFormHeight := Height; BtnExpand.BringToFront; FProductList := TList.Create; nIni := TIniFile.Create(gPath + sFormConfig); try FSkinPrefixID := nIni.ReadString(Name, 'SkinIDPrefix', 'PF'); FSkinIDLength := nIni.ReadInteger(Name, 'SkinIDLength', 8); FPlanPrefixID := nIni.ReadString(Name, 'PlanIDPrefix', 'FA'); FPlanIDLength := nIni.ReadInteger(Name, 'PlanIDLength', 8); FreeAndNil(nIni); nIni := TIniFile.Create(gPath + sImageConfigFile); nStr := nIni.ReadString(sImageExpandButton, sImageExpandFile, ''); nStr := StringReplace(nStr, '$Path\', gPath, [rfIgnoreCase]); if FileExists(nStr) then FImageExpand := MyLoadImage(nStr); nStr := nIni.ReadString(sImageExpandButton, sImageCollapse, ''); nStr := StringReplace(nStr, '$Path\', gPath, [rfIgnoreCase]); if FileExists(nStr) then FImageCollapse := MyLoadImage(nStr); finally nIni.Free; end; end; procedure TfFormParseData.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; if Action = caFree then begin ClearProductList(True); ReleaseCtrlData(Self); FreeAndNil(FImageExpand); FreeAndNil(FImageCollapse); gForm := nil; if Assigned(gOnCloseActiveForm) then gOnCloseActiveForm(Sender); end; end; //------------------------------------------------------------------------------ //Desc: 初始化数据 procedure TfFormParseData.InitFormData; var nStr: string; begin ExpandForm(False); if InfoItems.Properties.Items.Count < 1 then begin InfoItems.Clear; nStr := MacroValue(sQuery_SysDict, [MI('$Table', sTable_SysDict), MI('$Name', sFlag_SkinType)]); //数据字典中皮肤状况信息项 with FDM.QueryTemp(nStr) do begin First; while not Eof do begin InfoItems.Properties.Items.Add(FieldByName('D_Value').AsString); Next; end; end; end; if PFList1.Properties.Items.Count < 1 then begin PFList1.Clear; nStr := 'T_ID=Select T_ID,T_Name From %s Where T_MID is Null Or T_MID=''%s'''; nStr := Format(nStr, [sTable_SkinType, FMemberID]); FDM.FillStringsData(PFList1.Properties.Items, nStr, -1, '.'); AdjustStringsItem(PFList1.Properties.Items, False); end; if EditCFType.Properties.Items.Count < 1 then begin EditCFType.Clear; nStr := 'B_ID=Select B_ID,B_Text From %s Where B_Group=''%s'''; nStr := Format(nStr, [sTable_BaseInfo, sFlag_PlanItem]); FDM.FillStringsData(EditCFType.Properties.Items, nStr, -1, '.'); AdjustStringsItem(EditCFType.Properties.Items, False); end; end; //Desc: 显&隐所有控件 procedure TfFormParseData.HideAllCtrl(const nHide: Boolean); var i,nCount: integer; begin nCount := ControlCount - 1; for i:=0 to nCount do Controls[i].Visible := not nHide; BtnExpand.Visible := True; end; //Desc: 显示隐藏窗口 procedure TfFormParseData.ExpandForm(const nExpand: Boolean); var nX,nY: integer; nSpeed: integer; begin if nExpand then begin if ClientPanel1.Visible then Exit; if Assigned(FImageCollapse) then BtnExpand.Bitmap := FImageCollapse; Width := FFormWidth; nY := FDisplayRect.Bottom - FDisplayRect.Top - cVerInterval * 2; if nY > FFormHeight then Height := FFormHeight else Height := nY; nY := Round((FDisplayRect.Bottom - FDisplayRect.Top - Height) / 2); Top := FDisplayRect.Top + nY; ClientPanel1.Height := Height - ClientPanel1.Top - FValidRect.Bottom; //修正可显示区域,若不够则出现滚动条 Application.ProcessMessages; HideAllCtrl(False); BtnExpand.Left := 0; BtnExpand.Top := Round((Height - BtnExpand.Height) / 2); //BtnExpand.Parent := FindBgItem(cpForm); BtnExpand.BringToFront; nSpeed := 1; nX := FDisplayRect.Right - FFormWidth - cHorInterval; while Left > nX do begin nY := Left - nSpeed; if nY > nX then Left := nY else Left := nX; Application.ProcessMessages; Sleep(10); nSpeed := nSpeed + Random(8); end; end else begin if Assigned(FImageExpand) then BtnExpand.Bitmap := FImageExpand; //xxxxx nSpeed := 1; nX := FDisplayRect.Right - cHorInterval - BtnExpand.Width; while Left < nX do begin nY := Left + nSpeed; if nY < nX then Left := nY else Left := nX; Application.ProcessMessages; Sleep(10); nSpeed := nSpeed + Random(8); end; HideAllCtrl(True); BtnExpand.Left := 0; BtnExpand.Top := 0; BtnExpand.Parent := Self; BtnExpand.BringToFront; Width := BtnExpand.Width; Height := BtnExpand.Height; nY := Round((FDisplayRect.Bottom - FDisplayRect.Top - Height) / 2); Top := FDisplayRect.Top + nY; end; end; //Desc: 清理产品信息 procedure TfFormParseData.ClearProductList(const nFree: Boolean); var nIdx: integer; begin while FProductList.Count > 0 do begin nIdx := FProductList.Count - 1; Dispose(PProductItem(FProductList[nIdx])); FProductList.Delete(nIdx); end; if nFree then FProductList.Free; end; //------------------------------------------------------------------------------ //Desc: 展开&收起 procedure TfFormParseData.BtnExpandClick(Sender: TObject); begin if BtnExpand.Tag = 0 then begin ExpandForm(True); BtnExpand.Tag := 10; //BtnExpand.Caption := '>' end else begin ExpandForm(False); BtnExpand.Tag := 0; //BtnExpand.Caption := '<' end; end; //Desc: 添加症状 procedure TfFormParseData.BtnAdd1Click(Sender: TObject); begin InfoItems.Text := Trim(InfoItems.Text); if InfoItems.Text = '' then begin ListInfo1.SetFocus; FDM.ShowMsg('请填写症状名称', sHint); Exit; end; EditInfo.Text := Trim(EditInfo.Text); if EditInfo.Text = '' then begin EditInfo.SetFocus; FDM.ShowMsg('请填写描述信息', sHint); Exit; end; ListInfo1.Items.Add(InfoItems.Text + ListInfo1.Delimiter + EditInfo.Text); end; //Desc: 删除症状 procedure TfFormParseData.BtnDel1Click(Sender: TObject); var nStr: string; nIdx: integer; nItem: PProductItem; begin if ListInfo1.ItemIndex < 0 then begin ListInfo1.SetFocus; FDM.ShowMsg('请选择要删除的内容', sHint); Exit; end; nIdx := ListInfo1.ItemIndex; nStr := ListInfo1.Items[nIdx]; ListInfo1.Items.Delete(ListInfo1.ItemIndex); if nIdx >= ListInfo1.Count then Dec(nIdx); ListInfo1.ItemIndex := nIdx; nStr := Copy(nStr, 1, Pos(ListInfo1.Delimiter, nStr) - 1); for nIdx:=FProductList.Count - 1 downto 0 do begin nItem := FProductList[nIdx]; if CompareText(nItem.FSkin, nStr) <> 0 then Continue; Dispose(nItem); FProductList.Delete(nIdx); end; FDM.ShowMsg('已成功删除', sHint); end; //Desc: 添加产品 procedure TfFormParseData.BtnAdd2Click(Sender: TObject); var nStr: string; begin if ListInfo1.ItemIndex < 0 then begin ListInfo1.SetFocus; FDM.ShowMsg('请选择所针对的症状', sHint); Exit; end; nStr := ListInfo1.Items[ListInfo1.ItemIndex]; nStr := Copy(nStr, 1, Pos(ListInfo1.Delimiter, nStr) - 1); Visible := False; try if ShowSelectProductForm(FProductList, nStr, FDisplayRect) then ListInfo1Click(nil); finally Visible := True; end; end; //Desc: 删除产品 procedure TfFormParseData.BtnDel2Click(Sender: TObject); var nIdx: integer; nStr,nTmp: string; nItem: PProductItem; begin if ListInfo2.ItemIndex < 0 then begin FDM.ShowMsg('请选择要删除的产品', sHint); Exit; end; nIdx := ListInfo2.ItemIndex; nStr := ListInfo2.Items[nIdx]; ListInfo2.Items.Delete(ListInfo2.ItemIndex); if nIdx >= ListInfo2.Count then Dec(nIdx); ListInfo2.ItemIndex := nIdx; if ListInfo1.ItemIndex > -1 then begin nTmp := ListInfo1.Items[ListInfo1.ItemIndex]; nTmp := Copy(nTmp, 1, Pos(ListInfo1.Delimiter, nTmp) - 1); //症状 nStr := Copy(nStr, 1, Pos(ListInfo2.Delimiter, nStr) - 1); //产品 for nIdx:=FProductList.Count - 1 downto 0 do begin nItem := FProductList[nIdx]; if (CompareText(nItem.FProduct, nStr) <> 0) or (CompareText(nItem.FSkin, nTmp) <> 0) then Continue; //当前症状对应的产品 Dispose(nItem); FProductList.Delete(nIdx); end; end; FDM.ShowMsg('已成功删除', sHint); end; //Desc: 载入参考皮肤信息 procedure TfFormParseData.PFList1PropertiesEditValueChanged( Sender: TObject); var nStr: string; begin if PFList1.ItemIndex < 0 then Exit; PfID.Text := GetCtrlData(PFList1); nStr := PFList1.Text; System.Delete(nStr, 1, Pos('.', nStr)); PfName.Text := nStr; ListInfo1.Clear; nStr := MacroValue(sQuery_ExtInfo, [MI('$Table', sTable_ExtInfo), MI('$Group', sFlag_SkinType), MI('$ID', PfID.Text)]); //扩展信息 with FDM.QueryTemp(nStr) do if RecordCount > 0 then begin First; while not Eof do begin nStr := FieldByName('I_Item').AsString + ListInfo1.Delimiter + FieldByName('I_Info').AsString; ListInfo1.Items.Add(nStr); Next; end; end; nStr := 'P_ID=Select P_ID,P_Name From %s Where P_SkinType=''%s'''; nStr := Format(nStr, [sTable_Plan, PfID.Text]); FDM.FillStringsData(CFList1.Properties.Items, nStr, -1, '.'); AdjustStringsItem(CFList1.Properties.Items, False); end; //Dec: 载入处方信息 procedure TfFormParseData.CFList1PropertiesEditValueChanged( Sender: TObject); var nStr: string; nItem: PProductItem; begin if CFList1.ItemIndex < 0 then Exit; CfID.Text := GetCtrlData(CFList1); nStr := CFList1.Text; System.Delete(nStr, 1, Pos('.', nStr)); CfName.Text := nStr; nStr := 'Select P_PlanType From %s Where P_ID=''%s'''; nStr := Format(nStr, [sTable_Plan, CfID.Text]); with FDM.QueryTemp(nStr) do if RecordCount > 0 then begin SetCtrlData(EditCFType, Fields[0].AsString); end; nStr := 'Select * From $Ext e' + ' Left Join (Select P_ID,P_Name,' + ' (Select P_Name From $Plant Where P_ID=p.P_Plant) as P_PlantName ' + ' From $Product p) t On t.P_ID=e.E_Product ' + 'Where E_Plan=''$PID'''; nStr := MacroValue(nStr, [MI('$Ext', sTable_PlanExt), MI('$PID', CfID.Text), MI('$Plant', sTable_Plant), MI('$Product', sTable_Product)]); ListInfo2.Clear; ClearProductList(False); with FDM.QueryTemp(nStr) do if RecordCount > 0 then begin First; while not Eof do begin New(nItem); FProductList.Add(nItem); nItem.FProduct := FieldByName('P_ID').AsString; nItem.FProductName := FieldByName('P_Name').AsString; nStr := '%s 生产商:[ %s ]'; nStr := Format(nStr, [nItem.FProductName, FieldByName('P_PlantName').AsString]); nItem.FExtInfo := nStr; nItem.FSkin := FieldByName('E_Skin').AsString; nItem.FReason := FieldByName('E_Memo').AsString; nStr := nItem.FProduct + ListInfo2.Delimiter + nItem.FProductName + ' ' + ListInfo2.Delimiter + nItem.FReason + ' '; ListInfo2.Items.Add(nStr); Next; end; end; end; //Desc: 载入当前信息 procedure TfFormParseData.ListInfo1Click(Sender: TObject); var nStr: string; nIdx: integer; nItem: PProductItem; begin if ListInfo1.ItemIndex < 0 then begin InfoItems.Clear; EditInfo.Clear; Exit; end; nStr := ListInfo1.Items[ListInfo1.ItemIndex]; nIdx := Pos(ListInfo1.Delimiter, nStr); InfoItems.Text := Copy(nStr, 1, nIdx - 1); System.Delete(nStr, 1, nIdx); EditInfo.Text := nStr; ListInfo2.Clear; for nIdx:=FProductList.Count - 1 downto 0 do begin nItem := FProductList[nIdx]; if CompareText(nItem.FSkin, InfoItems.Text) <> 0 then Continue; nStr := nItem.FProduct + ListInfo2.Delimiter + nItem.FProductName + ' ' + ListInfo2.Delimiter + nItem.FReason + ' '; ListInfo2.Items.Add(nStr); end; end; //Desc: 在nList中检索标识为nID的产品 function FindProdcutInfo(const nList: TList; const nID: string): integer; var nIdx: integer; begin Result := -1; for nIdx:=nList.Count - 1 downto 0 do if CompareText(PProductItem(nList[nIdx]).FProduct, nID) = 0 then begin Result := nIdx; Break; end; end; procedure TfFormParseData.ListInfo2Click(Sender: TObject); var nStr: string; nIdx: integer; nList: TStrings; begin if ListInfo2.ItemIndex > -1 then begin nStr := ListInfo2.Items[ListInfo2.ItemIndex]; nList := TStringList.Create; try if SplitStr(nStr, nList, 3, ListInfo2.Delimiter) then begin nIdx := FindProdcutInfo(FProductList, nList[0]); if nIdx > -1 then with PProductItem(FProductList[nIdx])^ do begin EditProduct.Text := FExtInfo; EditReason.Text := FReason; Exit; end; end; finally nList.Free; end; end; EditProduct.Clear; EditReason.Clear; end; //Desc: 推荐理由 procedure TfFormParseData.EditReasonExit(Sender: TObject); var nStr: string; nIdx: integer; nList: TStrings; begin if ListInfo2.ItemIndex > -1 then begin nStr := ListInfo2.Items[ListInfo2.ItemIndex]; nList := TStringList.Create; try if SplitStr(nStr, nList, 3, ListInfo2.Delimiter) then begin nIdx := FindProdcutInfo(FProductList, nList[0]); if nIdx > -1 then with PProductItem(FProductList[nIdx])^ do begin FReason := Trim(EditReason.Text); nStr := nList[0] + ListInfo2.Delimiter + nList[1] + ' ' + ListInfo2.Delimiter + FReason + ' '; ListInfo2.Items[ListInfo2.ItemIndex] := nStr; end; end; finally nList.Free; end; end; end; //Desc: 查看产品 procedure TfFormParseData.ListInfo2DblClick(Sender: TObject); var nStr: string; nList: TStrings; begin if ListInfo2.ItemIndex > -1 then begin nStr := ListInfo2.Items[ListInfo2.ItemIndex]; nList := TStringList.Create; try if SplitStr(nStr, nList, 3, ListInfo2.Delimiter) then begin ShowViewProductForm(nList[0], FDisplayRect); end; finally Visible := True; end; end; end; //Desc: 皮肤编号 procedure TfFormParseData.PfIDPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); begin if Sender = PfID then PfID.Text := FDM.GetRandomID(FSkinPrefixID, FSkinIDLength); if Sender = CfID then CfID.Text := FDM.GetRandomID(FPlanPrefixID, FPlanIDLength); end; //Date: 2009-7-26 //Parm: 皮肤特征编号 //Desc: 若结果为True且nSkinID为空,表明该编号特征不允许修改 function TfFormParseData.SaveParseData(var nSkinID: string): Boolean; type TSaveStatus = (ssNone, ssInsert, ssUpdate); var nStr,nSQL: string; nList: TStrings; i,nCount,nIdx: integer; nSkin,nPlan: TSaveStatus; begin nSkinID := ''; Result := False; PfID.Text := Trim(PfID.Text); if PfID.Text = '' then begin ExpandForm(True); PfID.SetFocus; FDM.ShowMsg('请填写有效的皮肤症状编号', sHint); Exit; end; PfName.Text := Trim(PfName.Text); if PfName.Text = '' then begin ExpandForm(True); PfName.SetFocus; FDM.ShowMsg('请填写有效的皮肤症状名称', sHint); Exit; end; CfID.Text := Trim(CfID.Text); if CfID.Text = '' then begin ExpandForm(True); CfID.SetFocus; FDM.ShowMsg('请填写有效的处方编号', sHint); Exit; end; CfName.Text := Trim(CfName.Text); if CfName.Text = '' then begin ExpandForm(True); CfName.SetFocus; FDM.ShowMsg('请填写有效的处方名称', sHint); Exit; end; nSkin := ssInsert; nStr := 'Select T_MID From %s Where T_ID=''%s'''; nStr := Format(nStr, [sTable_SkinType, PfID.Text]); with FDM.QueryTemp(nStr) do if RecordCount > 0 then begin ExpandForm(True); PfID.SetFocus; if CompareText(Fields[0].AsString, FMemberID) = 0 then begin nStr := '该编号的皮肤特征已经存在,是否要覆盖?!'; if QueryDlg(nStr, sHint, Handle) then nSkin := ssUpdate else Exit; end else begin nStr := '该编号的皮肤特征非该会员特有,所做的修改将不会被保存!!' + #13#10 + '若要保存,请修改特征编号.继续操作请点击"确定"按钮!'; if QueryDlg(nStr, sHint, Handle) then nSkin := ssNone else Exit; end; end; nPlan := ssInsert; nStr := 'Select P_MID From %s Where P_ID=''%s'''; nStr := Format(nStr, [sTable_Plan, CfID.Text]); with FDM.QueryTemp(nStr) do if RecordCount > 0 then begin ExpandForm(True); CfID.SetFocus; if CompareText(Fields[0].AsString, FMemberID) = 0 then begin nStr := '该编号的处方已经存在,是否要覆盖?!'; if QueryDlg(nStr, sHint, Handle) then nPlan := ssUpdate else Exit; end else begin nStr := '该编号的处方已经存在,请修改处方编号'; ShowDlg(nStr, sHint, Handle); Exit; end; end; nList := nil; FDM.ADOConn.BeginTrans; try if nSkin = ssInsert then begin nSQL := 'Insert Into %s(T_ID,T_Name,T_MID,T_BID,T_Date) ' + 'Values(''%s'',''%s'',''%s'',''%s'', ''%s'')'; nSQL := Format(nSQL, [sTable_SkinType, PfID.Text, PfName.Text, FMemberID, gSysParam.FBeautyID, DateTime2Str(Now)]); FDM.ExecuteSQL(nSQL); end; if nSkin = ssUpdate then begin nSQL := 'Update %s Set T_Name=''%s'' Where T_ID=''%s'''; nSQL := Format(nSQL, [sTable_SkinType, PfName.Text, PfID.Text]); FDM.ExecuteSQL(nSQL); end; if nSkin <> ssNone then begin nSQL := 'Delete From %s Where I_Group=''%s'' and I_ItemID=''%s'''; nSQL := Format(nSQL, [sTable_ExtInfo, sFlag_SkinType, PfID.Text]); FDM.ExecuteSQL(nSQL); nList := TStringList.Create; nCount := ListInfo1.Items.Count - 1; nSQL := 'Insert Into %s(I_Group, I_ItemID, I_Item, I_Info) ' + 'Values(''%s'', ''%s'', ''%s'', ''%s'')'; //xxxxx for i:=0 to nCount do begin nStr := ListInfo1.Items[i]; if not SplitStr(nStr, nList, 2, ListInfo1.Delimiter) then Continue; nStr := Format(nSQL, [sTable_ExtInfo, sFlag_SkinType, PfID.Text, nList[0], nList[1]]); FDM.ExecuteSQL(nStr); end; if gSysDBType = dtAccess then begin nSQL := 'Insert Into %s(S_Table, S_Field, S_Value) ' + 'Values(''%s'', ''%s'', ''%s'')'; nSQL := Format(nSQL, [sTable_SyncItem, sTable_SkinType, 'T_ID', PfID.Text]); FDM.ExecuteSQL(nSQL); nSQL := 'Insert Into %s(S_Table, S_Field, S_Value, S_ExtField, S_ExtValue) ' + 'Values(''%s'', ''%s'', ''%s'', ''%s'', ''%s'')'; nSQL := Format(nSQL, [sTable_SyncItem, sTable_ExtInfo, 'I_ItemID', PfID.Text, 'I_Group', sFlag_SkinType]); FDM.ExecuteSQL(nSQL); end; //记录变更 end; //---------------------------------------------------------------------------- nStr := GetCtrlData(EditCFType); if not IsNumber(nStr, False) then nStr := '-1'; if nPlan = ssInsert then begin nSQL := 'Insert Into %s(P_ID,P_Name,P_PlanType,P_SkinType,P_MID,P_Man,P_Date) ' + 'Values(''%s'',''%s'',%s,''%s'',''%s'', ''%s'',''%s'')'; nSQL := Format(nSQL, [sTable_Plan, CfID.Text, CfName.Text, nStr, PfID.Text, FMemberID, gSysParam.FUserID, DateTime2Str(Now)]); FDM.ExecuteSQL(nSQL); end; if nPlan = ssUpdate then begin nSQL := 'Update %s Set P_Name=''%s'',P_PlanType=%s Where P_ID =''%s'''; nSQL := Format(nSQL, [sTable_Plan, CfName.Text, nStr, CfID.Text]); FDM.ExecuteSQL(nSQL); end; if gSysDBType = dtAccess then begin nSQL := 'Insert Into %s(S_Table, S_Field, S_Value) ' + 'Values(''%s'', ''%s'', ''%s'')'; nSQL := Format(nSQL, [sTable_SyncItem, sTable_Plan, 'P_ID', CfID.Text]); FDM.ExecuteSQL(nSQL); end; //记录变更 nSQL := 'Delete From %s Where E_Plan=''%s'''; nSQL := Format(nSQL, [sTable_PlanExt, CfID.Text]); FDM.ExecuteSQL(nSQL); if not Assigned(nList) then nList := TStringList.Create; nCount := ListInfo2.Items.Count - 1; nSQL := 'Insert Into %s(E_Plan, E_Product, E_Skin, E_Memo) ' + 'Values(''%s'', ''%s'', ''%s'', ''%s'')'; //xxxxx for i:=0 to nCount do begin nStr := ListInfo2.Items[i]; if not SplitStr(nStr, nList, 3, ListInfo2.Delimiter) then Continue; nIdx := FindProdcutInfo(FProductList, nList[0]); if nIdx > -1 then with PProductItem(FProductList[nIdx])^ do begin if Trim(FSkin) = '' then Continue; nStr := Format(nSQL, [sTable_PlanExt, CfID.Text, nList[0], FSkin, nList[2]]); FDM.ExecuteSQL(nStr); end; end; if gSysDBType = dtAccess then begin nSQL := 'Insert Into %s(S_Table, S_Field, S_Value) ' + 'Values(''%s'', ''%s'', ''%s'')'; nSQL := Format(nSQL, [sTable_SyncItem, sTable_PlanExt, 'E_Plan', CfID.Text]); FDM.ExecuteSQL(nSQL); end; //记录变更 if gSysParam.FGroupID = IntToStr(cBeauticianGroup) then nStr := gSysParam.FBeautyID else nStr := gSysParam.FUserID; nSQL := 'Insert Into %s(U_PID, U_MID, U_BID, U_Date) ' + ' Values(''%s'', ''%s'', ''%s'', ''%s'')'; nSQL := Format(nSQL, [sTable_PlanUsed, CfID.Text, FMemberID, nStr, DateTime2Str(Now)]); FDM.ExecuteSQL(nSQL); if gSysDBType = dtAccess then begin nSQL := 'Insert Into %s(S_Table, S_Field, S_Value) ' + 'Values(''%s'', ''%s'', ''%s'')'; nSQL := Format(nSQL, [sTable_SyncItem, sTable_PlanUsed, 'U_PID', CfID.Text]); FDM.ExecuteSQL(nSQL); end; //记录变更 //-------------------------------------------------------------------------- FDM.ADOConn.CommitTrans; if nSkin <> ssNone then nSkinID := PfID.Text; Result := True; except nList.Free; FDM.ADOConn.RollbackTrans; FDM.ShowMsg('处方数据保存失败', sError); end; end; end.
{ Copyright (C) 2018 Benito van der Zander (BeniBela) benito@benibela.de www.benibela.de This file is distributed under under the same license as Lazarus and the LCL itself: This file is distributed under the Library GNU General Public License with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. } {** @abstract(Mutable and immutable persistent sets as hash array mapped trie (HAMT)) Public generic classes: * TReadOnlySet * TMutableSet * TImmutableSet Public specialized classes: * TMutableSetString * TImmutableSetString } unit hamt.sets; {$mode objfpc}{$H+}{$ModeSwitch autoderef}{$ModeSwitch advancedrecords} interface uses sysutils, hamt.internals; type THAMTTypeInfo = hamt.internals.THAMTTypeInfo; //** @abstract(Generic read-only set) //** //** The data in this set can be read, but there are no public methods to modify it. generic TReadOnlySet<TItem, TInfo> = class(specialize TReadOnlyCustomSet<TItem, TInfo>) type PItem = ^TItem; protected function forceInclude(const item: TItem; allowOverride: boolean): boolean; inline; function forceExclude(const item: TItem): boolean; inline; public //** Returns if the set contains a certain item function contains(const item: TItem): boolean; inline; //** Default parameter, so you can test if the set contains an item @code(set[key]) property items[item: TItem]: Boolean read contains; default; end; {** @abstract(Generic mutable set) Data in this set can be read (see ancestor TReadOnlySet) and modified. Example: @longcode(# type TMutableSetString = specialize TMutableSet<string, THAMTTypeInfo>; var stringSet: TMutableSetString; p: TMutableSetString.PItem; begin stringSet := TMutableSetString.create; stringSet.Insert('hello'); stringSet.insert('foo'); writeln(stringSet['hello']); // true writeln(stringSet.contains('foo')); // true writeln(stringSet.contains('abc')); // false //enumerate all for p in stringSet do writeln(p^); stringSet.free; end. #) } generic TMutableSet<TItem, TInfo> = class(specialize TReadOnlySet<TItem, TInfo>) private procedure toggleItem(item: TItem; AValue: Boolean); public //** Creates an empty set constructor Create; //** Creates a set equal to other. No data is copied, till either set is modified (copy-on-write). constructor Create(other: specialize TReadOnlyCustomSet<TItem, TInfo>); //** Inserts an item, if the set does not contain the item or allowOverride is true. //** @returns If the set did not contain item. function include(const item: TItem; allowOverride: boolean = true): boolean; inline; //** Removes an item, //** @returns If the set did contain item. function exclude(const item: TItem): boolean; inline; //** Inserts an item, or raises an exception if the set already contains the item procedure insert(const item: TItem); inline; //** Removes an item, or raises an exception if the set did not contain the item procedure remove(const item: TItem); inline; //** Removes everything from the set; procedure clear; //** Creates a new set equal to self. No data is copied, till either set is modified (copy-on-write). function clone: TMutableSet; //** Default parameter, so you can test and update the set with @code(set[key]) property items[item: TItem]: Boolean read contains write toggleItem; default; end; {** @abstract(Generic immutable set) Data in this set can be read (see ancestor TReadOnlySet) and modified by creating new sets. Example: @longcode(# type TImmutableSetString = specialize TImmutableSet<string, THAMTTypeInfo>; var set1, set2, set3: TImmutableSetString; p: TImmutableSetString.PItem; begin set1 := TImmutableSetString.create; set2 := set1.Insert('hello'); set3 := set2.insert('foo'); writeln(set1.contains('hello')); // false writeln(set1['foo']); // false writeln(set2.contains('hello')); // true writeln(set2['foo']); // false writeln(set3.contains('hello')); // true writeln(set3['foo']); // true //enumerate all for p in set3 do writeln(p^); set1.free; set2.free; set3.free; end. #) } generic TImmutableSet<TItem, TInfo> = class(specialize TReadOnlySet<TItem, TInfo>) public //** Creates an empty set constructor Create; //** Creates a set equal to other. No data is copied, till either set is modified (copy-on-write). constructor Create(other: specialize TReadOnlyCustomSet<TItem, TInfo>); //** Creates a new set containing item @code(item). If the set does not contain item or allowOverride is true, item is inserted, otherwise the value is unchanged. //** @returns The new set function include(const item: TItem; allowOverride: boolean = true): TImmutableSet; inline; //** Removes an item //** @returns The new set without item function exclude(const item: TItem): TImmutableSet; inline; //** Inserts an item, or raises an exception if the set already contains the item //** @returns The new set function insert(const item: TItem): TImmutableSet; inline; //** Creates a new set without item, or raises an exception if the set did not contain item //** @returns The new set without item function remove(const item: TItem): TImmutableSet; inline; //** Creates a new set equal to self. No data is copied, till either set is modified (copy-on-write). function clone: TImmutableSet; end; //** @abstract(A TMutableSet containing strings.) //** The set handles reference counting and freeing of the strings. TMutableSetString = specialize TMutableSet<string, THAMTTypeInfo>; //** @abstract(A TImmutableSet containing strings.) //** The set handles reference counting and freeing of the strings. TImmutableSetString = specialize TImmutableSet<string, THAMTTypeInfo>; implementation function TReadOnlySet.forceInclude(const item: TItem; allowOverride: boolean): boolean; begin result := THAMTNode.include(@froot, item, allowOverride); if Result then Inc(fcount); end; function TReadOnlySet.forceExclude(const item: TItem): boolean; begin result := THAMTNode.exclude(@froot, item); if result then dec(fcount); end; function TReadOnlySet.contains(const item: TItem): boolean; begin result := froot.find(item) <> nil; end; {function TReadOnlySet.get(const key: TKey; const def: TValue): TValue; var pair: PPair; begin pair := find(key); if pair = nil then result := def else result := pair.value; end; function TReadOnlySet.get(const key: TKey): TValue; var pair: PPair; begin pair := find(key); if pair = nil then raiseMissingKey(key); result := pair.value; end; } procedure TMutableSet.toggleItem(item: TItem; AValue: Boolean); begin if AValue then include(item, true) else exclude(item); end; constructor TMutableSet.Create; begin froot := THAMTNode.allocateEmpty; fcount := 0; end; constructor TMutableSet.Create(other: specialize TReadOnlyCustomSet<TItem, TInfo>); begin fcount := other.fcount; froot := other.froot; InterLockedIncrement(froot.refCount); end; function TMutableSet.include(const item: TItem; allowOverride: boolean): boolean; begin result := forceInclude(item, allowOverride); end; function TMutableSet.exclude(const item: TItem): boolean; begin result := forceExclude(item); end; procedure TMutableSet.insert(const item: TItem); begin if not forceInclude(item, false) then raiseItemError(rsDuplicateItem, item); end; procedure TMutableSet.remove(const item: TItem); begin if not forceExclude(item) then raiseItemError(rsMissingItem, item); end; procedure TMutableSet.clear; begin THAMTNode.decrementRefCount(froot); froot := THAMTNode.allocateEmpty; fcount := 0; end; function TMutableSet.clone: TMutableSet; begin result := TMutableSet.Create(self); end; constructor TImmutableSet.Create; begin froot := THAMTNode.allocateEmpty; fcount := 0; end; constructor TImmutableSet.Create(other: specialize TReadOnlyCustomSet<TItem, TInfo>); begin fcount := other.fcount; froot := other.froot; InterLockedIncrement(froot.refCount); end; function TImmutableSet.include(const item: TItem; allowOverride: boolean): TImmutableSet; begin result := TImmutableSet.Create(self); result.forceInclude(item, allowOverride); end; function TImmutableSet.exclude(const item: TItem): TImmutableSet; begin result := TImmutableSet.Create(self); result.forceExclude(item); end; function TImmutableSet.insert(const item: TItem): TImmutableSet; begin result := TImmutableSet.Create(self); if not result.forceInclude(item, false) then begin result.free; raiseItemError(rsDuplicateItem, item); end; end; function TImmutableSet.remove(const item: TItem): TImmutableSet; begin result := TImmutableSet.Create(self); if not result.forceExclude(item) then begin result.free; raiseItemError(rsMissingItem, item); end; end; function TImmutableSet.clone: TImmutableSet; begin result := TImmutableSet.Create(self); end; end.
namespace Sugar.Threading; interface uses Sugar, Sugar.Collections; type {$IF COOPER} Thread = public class mapped to java.lang.Thread {$ELSEIF ECHOES} Thread = public class mapped to System.Threading.Thread {$ELSEIF TOFFEE} Thread = public class mapped to Foundation.NSThread {$ENDIF} private method GetPriority: ThreadPriority; method SetPriority(Value: ThreadPriority); method GetCallStack: List<String>; {$IF TOFFEE}method GetThreadID: IntPtr;{$ENDIF} public method Start; mapped to Start; method &Join; {$IF COOPER OR ECHOES} mapped to &Join;{$ENDIF} method &Join(Timeout: Integer); {$IF COOPER OR ECHOES}mapped to &Join(Timeout);{$ENDIF} {$HIDE W28} method Abort; mapped to {$IF ECHOES}Abort{$ELSEIF COOPER}stop{$ELSEIF TOFFEE}cancel{$ENDIF}; {$SHOW W28} class method Sleep(aTimeout: Integer); mapped to {$IF COOPER OR ECHOES}Sleep(aTimeout){$ELSEIF TOFFEE}sleepForTimeInterval(aTimeout / 1000){$ENDIF}; //property State: ThreadState read GetState write SetState; property IsAlive: Boolean read {$IF COOPER OR ECHOES}mapped.IsAlive{$ELSEIF TOFFEE}mapped.isExecuting{$ENDIF}; property Name: String read mapped.Name write {$IF COOPER OR ECHOES}mapped.Name{$ELSEIF TOFFEE}mapped.setName{$ENDIF}; {$IF COOPER OR ECHOES} property ThreadId: Int64 read {$IF COOPER}mapped.Id{$ELSEIF ECHOES}mapped.ManagedThreadId{$ENDIF}; {$ELSEIF TOFFEE} property ThreadId: IntPtr read GetThreadID; {$ENDIF} property Priority: ThreadPriority read GetPriority write SetPriority; property CallStack: List<String> read GetCallStack; {$IF TOFFEE}class property MainThread: Thread read mapped.mainThread;{$ENDIF} class property CurrentThread: Thread read mapped.currentThread; class method &Async(aBlock: block); end; ThreadState = public enum( Unstarted, Running, Waiting, Stopped ); ThreadPriority = public enum( Lowest, BelowNormal, Normal, AboveNormal, Highest ); implementation method Thread.GetPriority: ThreadPriority; begin {$IF ECHOES} {$IF WINDOWS_PHONE} exit ThreadPriority.Normal; {$ELSE} exit ThreadPriority(mapped.Priority); {$ENDIF} {$ELSEIF COOPER} case mapped.Priority of 1,2: exit ThreadPriority.Lowest; 3,4: exit ThreadPriority.BelowNormal; 5: exit ThreadPriority.Normal; 6,7: exit ThreadPriority.AboveNormal; 8,9,10: exit ThreadPriority.Highest; end; {$ENDIF} end; method Thread.SetPriority(Value: ThreadPriority); begin {$IF ECHOES} {$IF WINDOWS_PHONE} raise new SugarException("Changing thread priority is not supported on Windows Phone"); {$ELSE} mapped.Priority := System.Threading.ThreadPriority(Value); {$ENDIF} {$ELSEIF COOPER} case Value of ThreadPriority.Lowest: mapped.Priority := 2; ThreadPriority.BelowNormal: mapped.Priority := 4; ThreadPriority.Normal: mapped.Priority := 5; ThreadPriority.AboveNormal: mapped.Priority := 7; ThreadPriority.Highest: mapped.Priority := 9; end; {$ENDIF} end; {$IF TOFFEE} method Thread.GetThreadID: IntPtr; begin // Todo end; method Thread.&Join; begin end; method Thread.&Join(Timeout: Integer); begin end; {$ENDIF} method Thread.GetCallStack: List<String>; begin {$IF COOPER} {$ELSEIF ECHOES} {$ELSEIF TOFFEE} result := mapped.callStackSymbols as List<String>; {$ENDIF} end; class method Thread.Async(aBlock: block); begin async aBlock(); end; end.
unit UWebView; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.TMSNativeUIButton, FMX.TMSNativeUITextField, FMX.TMSNativeUIView, FMX.TMSNativeUIWebView, FMX.TMSNativeUIBaseControl, FMX.TMSNativeUIToolBar; type TForm1073 = class(TForm) TMSFMXNativeUIToolBar1: TTMSFMXNativeUIToolBar; TMSFMXNativeUIWebView1: TTMSFMXNativeUIWebView; TMSFMXNativeUITextField1: TTMSFMXNativeUITextField; TMSFMXNativeUIView1: TTMSFMXNativeUIView; procedure FormCreate(Sender: TObject); procedure TMSFMXNativeUIToolBar1ItemClick(ASender: TObject; AItem: TTMSFMXNativeUIToolBarItem); procedure TMSFMXNativeUIWebView1DidFinishLoad(Sender: TObject); procedure TMSFMXNativeUITextField1DidEndEditing(Sender: TObject); private { Private declarations } public { Public declarations } procedure UpdateButtons; end; var Form1073: TForm1073; implementation {$R *.fmx} procedure TForm1073.FormCreate(Sender: TObject); begin TMSFMXNativeUIWebView1.Navigate('http://www.google.com'); UpdateButtons; end; procedure TForm1073.TMSFMXNativeUITextField1DidEndEditing(Sender: TObject); begin TMSFMXNativeUIWebView1.Navigate(TMSFMXNativeUITextField1.Text); TMSFMXNativeUITextField1.TextField.resignFirstResponder; end; procedure TForm1073.TMSFMXNativeUIToolBar1ItemClick(ASender: TObject; AItem: TTMSFMXNativeUIToolBarItem); begin case AItem.Index of 1: begin TMSFMXNativeUIWebView1.Navigate(TMSFMXNativeUITextField1.Text); TMSFMXNativeUITextField1.TextField.resignFirstResponder; end; 2: TMSFMXNativeUIWebView1.GoBack; 3: TMSFMXNativeUIWebView1.GoForward; 4: TMSFMXNativeUIWebView1.LoadHTMLString( '<!DOCTYPE html>'+ '<html>'+ '<title>TTMSFMXNativeUIWebView Demo</title>'+ '<body>'+ '<form action="javascript:alert(fName.value + '' '' + lName.value);">'+ 'First name: <input id="fName" type="text" name="FirstName" value="Hello"><br>'+ 'Last name: <input id="lName" type="text" name="LastName" value="World"><br>'+ '<input type="submit" value="Submit">'+ '</form>'+ '</body>'+ '</html>'); 5: TMSFMXNativeUIWebView1.ExecuteJavaScript('alert("Hello World");'); 6: TMSFMXNativeUIWebView1.LoadFile(ExtractFilePath(ParamStr(0)) + 'sample.pdf'); end; end; procedure TForm1073.TMSFMXNativeUIWebView1DidFinishLoad(Sender: TObject); begin UpdateButtons; end; procedure TForm1073.UpdateButtons; begin TMSFMXNativeUIToolBar1.Items[2].Item.setEnabled(TMSFMXNativeUIWebView1.CanGoBack); TMSFMXNativeUIToolBar1.Items[3].Item.setEnabled(TMSFMXNativeUIWebView1.CanGoForward); end; end.
unit l3IDList; {*Лист идентификаторов с математикой (объединение, вычитание, пересечение)} // Модуль: "w:\common\components\rtl\Garant\L3\l3IDList.pas" //?? Стереотип: "SimpleClass" //?? Элемент модели: "Tl3LongintList" MUID: (47BB29D40117) {$Include w:\common\components\rtl\Garant\L3\l3Define.inc} interface uses l3LongintList, l3Interfaces; type TID = longint; //!! Нужно объединить с функциональностью l3ListOperations.imp.pas Tl3IDList = class; Il3IDList = interface(Il3Base) ['{0A44CBB6-43E0-40AE-B373-F00B0BC89505}'] function GetSelf : Tl3IDList; function Get_Count: Integer; function Get_Items(anIndex: Integer): Integer; function pm_GetEmpty: Boolean; //procedure Save(aStream: TStream); //procedure Load(aStream: TStream); procedure Clear; procedure Add(anItem : TID); procedure Delete(anItem: TID); function IndexOf(anItem: TID) : integer; procedure SubtractList(aList : Il3IDList); { - вычитание} procedure MergeList(aAddList : Il3IDList); { - добавление} procedure InvertList(aBaseList : Il3IDList); { - инверсия относительно aBaseList, т е list := aBaseList - list} procedure AndList(aList : Il3IDList); //function AsIntegerList: Tl3IntegerList; property Count: Integer read Get_Count; property Items[anIndex: Integer]: Integer read Get_Items; default; property Empty: Boolean read pm_GetEmpty; end; Tl3IDList = class(Tl3LongintList, Il3IDList) protected function Get_Count: Integer; function Get_Items(anIndex: Integer): Integer; public constructor Create; function GetSelf : Tl3IDList; procedure Add(anItem : TID); procedure Delete(anItem: TID); function IndexOf(anItem: TID) : integer; procedure SubtractList(aList : Il3IDList); { - вычитание} procedure MergeList(aAddList : Il3IDList); { - добавление} procedure InvertList(aBaseList : Il3IDList); { - инверсия относительно aBaseList, т е list := aBaseList - list} procedure AndList(aList : Il3IDList); { - пересечение} end; function l3MakeIDList : Il3IDList; implementation uses //l3LongintList, //l3CardinalList l3Base; function l3MakeIDList : Il3IDList; var lList : Tl3IDList; begin lList := Tl3IDList.Create; Result := lList; l3Free(lList); end; constructor Tl3IDList.Create; begin Inherited Create; Sorted := True; end; function Tl3IDList.GetSelf : Tl3IDList; begin Result := Self; end; function Tl3IDList.Get_Count: Integer; begin Result := Count; empty; end; function Tl3IDList.Get_Items(anIndex: Integer): Integer; begin Result := Items[anIndex]; end; procedure Tl3IDList.Add(anItem : TID); begin inherited Add(anItem); end; procedure Tl3IDList.Delete(anItem: TID); begin inherited Delete(anItem); end; function Tl3IDList.IndexOf(anItem: TID) : integer; begin Result := inherited IndexOf(anItem); end; procedure Tl3IDList.SubtractList(aList : Il3IDList); var I, J : Longint; begin I := Pred(Count); J := Pred(aList.Count); while (I >= 0) and (J >= 0) do begin //DoCompareItems(I, aList[J]); if Items[I] = aList[J] then begin Delete(I); Dec(J); Dec(I); end else if Items[I] > aList[J] then Dec(I) else Dec(J); end; end; procedure Tl3IDList.AndList(aList : Il3IDList); var I, J : Longint; begin I := Pred(Count); J := Pred(aList.Count); while (I >= 0) and (J >= 0) do begin //DoCompareItems(I, aList[J]); if Items[I] = aList[J] then begin //Delete(I); Dec(J); Dec(I); end else if Items[I] > aList[J] then begin Delete(I); Dec(I); end else Dec(J); end; while I >= 0 do begin Delete(I); Dec(I); end; end; procedure Tl3IDList.MergeList(aAddList : Il3IDList); var I : Integer; lCnt : Integer; begin lCnt := aAddList.Count; if (lCnt = 0) then Exit; Capacity := Count + lCnt; for i := 0 to Pred(lCnt) do Add(aAddList[I]); end; procedure Tl3IDList.InvertList(aBaseList : Il3IDList); var lCopyList : Tl3IDList; I, J : Cardinal; begin lCopyList := Tl3IDList.Create; try lCopyList.MergeList(Self); Clear; I := 0; J := 0; while (I < aBaseList.Count) and (J < lCopyList.Count) do if aBaseList[I] = lCopyList[J] then begin Inc(J); Inc(I); end else if aBaseList[I] > lCopyList[J] then Inc(J) else begin Add(aBaseList[I]); //прикрутить directinsert Inc(I); end; finally l3Free(lCopyList); end; //сливаем хвост while (I < aBaseList.Count) do begin Add(aBaseList[I]); //прикрутить directinsert Inc(I); end; end; end.
unit l3BoxMM; { Библиотека "L3 (Low Level Library)" } { Автор: Люлин А.В. © } { Модуль: l3BoxMM - } { Начат: 28.05.2004 19:49 } { $Id: l3BoxMM.pas,v 1.17 2013/04/08 14:50:41 lulin Exp $ } // $Log: l3BoxMM.pas,v $ // Revision 1.17 2013/04/08 14:50:41 lulin // - портируем. // // Revision 1.16 2011/10/05 09:26:18 voba // - k : 281525254 Борьба с утечками // // Revision 1.15 2007/08/14 14:30:12 lulin // - оптимизируем перемещение блоков памяти. // // Revision 1.14 2007/01/17 16:47:36 lulin // - подготавливаемся к защите при работе из разных потоков. // // Revision 1.13 2004/08/05 17:40:31 law // - избавился от ряда Warning'ов и Hint'ов. // // Revision 1.12 2004/05/31 14:12:29 law // - new class: Tl3FixedSizeMemoryManager. // // Revision 1.11 2004/05/31 13:59:34 law // - new class: Tl3BaseBoxMemoryManager. // // Revision 1.10 2004/05/31 13:49:41 law // - new method: Tl3BoxMemoryManager.InitFreed. // // Revision 1.9 2004/05/31 13:31:04 law // - new method: Tl3BoxMemoryManager.IsValidIndex. // // Revision 1.8 2004/05/31 13:27:17 law // - new methods: Tl3BoxMemoryManager.HasFreed, InitFreed. // // Revision 1.7 2004/05/31 13:20:56 law // - new methods: Tl3BoxMemoryManager.GetFreed, SetFreed. // // Revision 1.6 2004/05/31 12:30:29 law // - new behavior: в Tl3BoxMemoryManager сделана возможность задавать верхний и нижний индексы для массива кусков памяти, которые подлежат повторному использованию. // // Revision 1.5 2004/05/31 10:02:55 law // - включен define l3BoxedBitArray - так вроде с ним все заработало. // // Revision 1.4 2004/05/28 18:10:17 law // - bug fix: были несбалансированы скобки выделения/освобождения. // // Revision 1.3 2004/05/28 18:03:35 law // - new define: l3BoxedBitArray - пока выключен. // // Revision 1.2 2004/05/28 17:12:58 law // - промежуточный commit. // // Revision 1.1 2004/05/28 15:57:09 law // - new unit: l3BoxMM. // {$I l3Define.inc } interface uses l3Types, l3Base, l3SimpleMM ; type Tl3BaseBoxMemoryManager = class(Tl3SimpleMemoryManager) private // internal fields f_Lost : Integer; protected // internal methods procedure FreeBlocks; override; {-} function SizeSize: Cardinal; virtual; abstract; {-} function Size2Index(aSize: Cardinal): Integer; virtual; abstract; {-} function AlignSize(aSize: Cardinal): Cardinal; virtual; abstract; {-} function GetPSz(aPt: PAnsiChar): Cardinal; virtual; abstract; {-} procedure SetPSz(aPt: PAnsiChar; aValue: Cardinal); virtual; abstract; {-} function HasFreed: Boolean; virtual; abstract; {-} procedure InitFreed; virtual; abstract; {-} procedure ClearFreed; virtual; abstract; {-} function IsValidIndex(anIndex: Integer): Boolean; virtual; abstract; {-} function GetFreed(anIndex: Integer): Pointer; virtual; abstract; procedure SetFreed(anIndex: Integer; aValue: Pointer); virtual; abstract; {-} public // public methods constructor Create(aBlockSize : Cardinal); override; {* - создает менеджер. } function GetSize(aPt: Pointer): Cardinal; {-} procedure DoGetMem(var P; aSize : Cardinal); override; {* - выделяет блок памяти. } procedure DoFreeMem(var P); override; {* - освобождает блок памяти. } procedure ReallocMem(var P; aNewSize: Cardinal); {* - перераспределяет блок памяти. } end;//Tl3BaseBoxMemoryManager Tl3BoxMemoryManager = class(Tl3BaseBoxMemoryManager) private // internal fields f_Freed : PAnsiChar; f_LowIndex : Integer; f_HighIndex : Integer; f_SizeSize : Cardinal; protected // internal methods function SizeSize: Cardinal; override; {-} function Size2Index(aSize: Cardinal): Integer; override; {-} function AlignSize(aSize: Cardinal): Cardinal; override; {-} function GetPSz(aPt: PAnsiChar): Cardinal; override; {-} procedure SetPSz(aPt: PAnsiChar; aValue: Cardinal); override; {-} function HasFreed: Boolean; override; {-} procedure InitFreed; override; {-} procedure ClearFreed; override; {-} function IsValidIndex(anIndex: Integer): Boolean; override; {-} function GetFreed(anIndex: Integer): Pointer; override; procedure SetFreed(anIndex: Integer; aValue: Pointer); override; {-} public // public methods constructor Create(aBlockSize : Long; aHighIndex : Integer = 8; aLowIndex : Integer = 0); reintroduce; {* - создает менеджер. } end;//Tl3BoxMemoryManager Tl3FixedSizeMemoryManager = class(Tl3BaseBoxMemoryManager) private // internal fields f_Freed : PPointer; f_PartSize : Cardinal; protected // internal methods function SizeSize: Cardinal; override; {-} function Size2Index(aSize: Cardinal): Integer; override; {-} function AlignSize(aSize: Cardinal): Cardinal; override; {-} function GetPSz(aPt: PAnsiChar): Cardinal; override; {-} procedure SetPSz(aPt: PAnsiChar; aValue: Cardinal); override; {-} function HasFreed: Boolean; override; {-} procedure InitFreed; override; {-} procedure ClearFreed; override; {-} function IsValidIndex(anIndex: Integer): Boolean; override; {-} function GetFreed(anIndex: Integer): Pointer; override; procedure SetFreed(anIndex: Integer; aValue: Pointer); override; {-} public // public methods constructor Create(aBlockSize : Long; aPartSize : Cardinal); reintroduce; {* - создает менеджер. } end;//Tl3FixedSizeMemoryManager implementation uses l3MinMax, l3Memory ; // start class Tl3BaseBoxMemoryManager constructor Tl3BaseBoxMemoryManager.Create(aBlockSize: Cardinal); //override; {* - создает менеджер. } begin inherited Create(aBlockSize); end; procedure Tl3BaseBoxMemoryManager.FreeBlocks; //override; {-} begin ClearFreed; inherited; end; function Tl3BaseBoxMemoryManager.GetSize(aPt: Pointer): Cardinal; {-} begin if (aPt = nil) then Result := 0 else Result := GetPSz(PAnsiChar(aPt) - SizeSize); end; procedure Tl3BaseBoxMemoryManager.DoGetMem(var P; aSize : Cardinal); //override; {* - выделяет блок памяти. } var l_Index : Integer; l_Sz : Cardinal; begin if (aSize = 0) then Pointer(P) := nil else begin l_Index := Size2Index(aSize); Assert(IsValidIndex(l_Index), 'Запрошен неверный размер куска памяти Tl3BaseBoxMemoryManager.DoGetMem'); if HasFreed AND IsValidIndex(l_Index) then begin Pointer(P) := GetFreed(l_Index); if (Pointer(P) <> nil) then begin // - удалось взять освобожденный кусок Inc(f_AllocCount); // - увеличиваем число взятых кусков SetFreed(l_Index, PPointer(P)^); // - указываем на другой освобожденный Exit; // - выходим, т.к уже все выделили end else l_Sz := AlignSize(aSize); // - надо выровнять размер куска end else l_Sz := aSize; Inc(l_Sz, SizeSize); // - резервируем место под размер inherited DoGetMem(P, l_Sz); SetPSz(PAnsiChar(P), l_Sz - SizeSize); Inc(PAnsiChar(P), SizeSize); // - сдвигаем на размер размера куска end;//l_Sz = 0 end; procedure Tl3BaseBoxMemoryManager.DoFreeMem(var P); //override; {* - освобождает блок памяти. } var l_Sz : Integer; l_Index : Integer; begin if (Pointer(P) = nil) then Exit; l_Sz := GetSize(Pointer(P)); if (l_Sz > 0) then begin // - если действительно что-то освобождаем l_Index := Size2Index(l_Sz); // - вычисляем индекс в массиве уже освобожденных if IsValidIndex(l_Index) then begin // - надо положить этот кусок в массив освобожденных InitFreed; PPointer(P)^ := GetFreed(l_Index); SetFreed(l_Index, Pointer(P)); end else begin Inc(f_Lost); Assert(false, 'Коробка создана неправильно Tl3BaseBoxMemoryManager.DoFreeMem'); end;//IsValidIndex(l_Index) end;//l_Sz > 0 Dec(PAnsiChar(P), SizeSize); // - сдвигаем на размер размера куска inherited DoFreeMem(P); end; procedure Tl3BaseBoxMemoryManager.ReallocMem(var P; aNewSize: Cardinal); {* - перераспределяет блок памяти. } var l_OldSz : Integer; l_NewSz : Integer; l_OldPt : Pointer; l_NewPt : Pointer; begin l_OldSz := GetSize(Pointer(P)); l_NewSz := AlignSize(aNewSize); if (l_OldSz <> l_NewSz) then begin l_OldPt := Pointer(P); GetMem(l_NewPt, l_NewSz); Pointer(P) := l_NewPt; if (l_OldPt <> nil) then l3Move(l_OldPt^, l_NewPt^, Min(l_OldSz, l_NewSz)); FreeMem(l_OldPt); end;//l_OldSz <> l_NewSz end; // start class Tl3BoxMemoryManager const cStep = 4; constructor Tl3BoxMemoryManager.Create(aBlockSize : Long; aHighIndex : Integer = 8; aLowIndex : Integer = 0); //override; {* - создает менеджер. } begin inherited Create(aBlockSize); f_SizeSize := 1; f_LowIndex := aLowIndex; f_HighIndex := aHighIndex; end; function Tl3BoxMemoryManager.SizeSize: Cardinal; //override; {-} begin Result := f_SizeSize; end; function Tl3BoxMemoryManager.Size2Index(aSize: Cardinal): Integer; {-} begin Result := ((aSize - 1) div cStep) - 1; end; function Tl3BoxMemoryManager.AlignSize(aSize: Cardinal): Cardinal; {-} begin Result := (((aSize - 1) div cStep) + 1) * cStep; end; function Tl3BoxMemoryManager.GetPSz(aPt: PAnsiChar): Cardinal; {-} begin Case SizeSize of 1: Result := PByte(aPt)^; 2: Result := PWord(aPt)^; 4: Result := PLong(aPt)^; else begin Result := 0; Assert(false); end;//else end;//Case SizeSize end; procedure Tl3BoxMemoryManager.SetPSz(aPt: PAnsiChar; aValue: Cardinal); {-} begin Case SizeSize of 1: PByte(aPt)^ := aValue; 2: PWord(aPt)^ := aValue; 4: PLong(aPt)^ := aValue; else Assert(false); end;//Case SizeSize end; function Tl3BoxMemoryManager.HasFreed: Boolean; {-} begin Result := (f_Freed <> nil); end; procedure Tl3BoxMemoryManager.InitFreed; {-} begin if (f_Freed = nil) then l3System.GetLocalMemZ(f_Freed, (f_HighIndex - f_LowIndex + 1) * SizeOf(Pointer)); end; procedure Tl3BoxMemoryManager.ClearFreed; {-} begin l3System.FreeLocalMem(f_Freed); end; function Tl3BoxMemoryManager.IsValidIndex(anIndex: Integer): Boolean; {-} begin Result := (anIndex >= f_LowIndex) AND (anIndex <= f_HighIndex); end; function Tl3BoxMemoryManager.GetFreed(anIndex: Integer): Pointer; {-} begin Result := PPointer(f_Freed + (anIndex - f_LowIndex) * SizeOf(Pointer))^; end; procedure Tl3BoxMemoryManager.SetFreed(anIndex: Integer; aValue: Pointer); {-} begin PPointer(f_Freed + (anIndex - f_LowIndex) * SizeOf(Pointer))^ := aValue; end; // start class Tl3FixedSizeMemoryManager constructor Tl3FixedSizeMemoryManager.Create(aBlockSize : Long; aPartSize : Cardinal); //override; {* - создает менеджер. } begin inherited Create(aBlockSize); f_PartSize := aPartSize; end; function Tl3FixedSizeMemoryManager.SizeSize: Cardinal; //override; {-} begin Result := 0; end; function Tl3FixedSizeMemoryManager.Size2Index(aSize: Cardinal): Integer; {-} begin Assert(aSize = f_PartSize); Result := 0; end; function Tl3FixedSizeMemoryManager.AlignSize(aSize: Cardinal): Cardinal; {-} begin Assert(aSize = f_PartSize); Result := aSize; end; function Tl3FixedSizeMemoryManager.GetPSz(aPt: PAnsiChar): Cardinal; {-} begin Result := f_PartSize; end; procedure Tl3FixedSizeMemoryManager.SetPSz(aPt: PAnsiChar; aValue: Cardinal); {-} begin Assert(aValue = f_PartSize); end; function Tl3FixedSizeMemoryManager.HasFreed: Boolean; {-} begin Result := (f_Freed <> nil); end; procedure Tl3FixedSizeMemoryManager.InitFreed; {-} begin end; procedure Tl3FixedSizeMemoryManager.ClearFreed; {-} begin f_Freed := nil; end; function Tl3FixedSizeMemoryManager.IsValidIndex(anIndex: Integer): Boolean; {-} begin Result := (anIndex = 0); end; function Tl3FixedSizeMemoryManager.GetFreed(anIndex: Integer): Pointer; {-} begin Result := f_Freed^; end; procedure Tl3FixedSizeMemoryManager.SetFreed(anIndex: Integer; aValue: Pointer); {-} begin f_Freed^ := aValue; end; end.
unit np.common; interface uses SysUtils; const {$IFDEF LINUX64} NODEPAS_LIB = 'libnodepas.so'; {$ENDIF} {$IFDEF WIN64} NODEPAS_LIB = 'nodepaslib64.dll'; {$ENDIF} {$IFDEF WIN32} NODEPAS_LIB = 'nodepaslib32.dll'; // {$Message Error 'only 64 bit windows support!'} {$ENDIF} type SIZE_T = NativeUInt; psize_t = ^SIZE_T; SSIZE_T = NativeInt; {$IFDEF NEXTGEN} PAnsiChar = pUtf8char; {$ELSE} pansichar = pUtf8char; {$ENDIF} ULONG = Cardinal; DWORD = Cardinal; Long = Integer; THex1 = 0..$F; THex2 = $10..$FF; THex3 = $100..$FFF; {$IFDEF NEXTGEN} AnsiString = UTF8String; {$ENDIF} TProc_APointer = TProc<Pointer>; IEventHandler = interface ['{2205ED21-A159-4085-8EF5-5C3715A4F6F4}'] procedure remove; procedure invoke(args: Pointer); function GetID: integer; property ID: integer read GetID; end; IEventEmitter = Interface ['{1C509C46-A6CC-492E-9117-8BF72F10244C}'] function on_(id: integer; p: TProc_APointer) : IEventHandler; overload; function on_(id: integer; p : Tproc) : IEventHandler; overload; function once(id: integer; p : TProc) : IEventHandler; overload; function once(id: integer; p : TProc_APointer) : IEventHandler;overload; procedure RemoveAll; procedure Remove(var handler: IEventHandler); function isEmpty: Boolean; function CountOf(id : integer) : int64; procedure emit(eventId: integer; eventArguments : Pointer = nil); end; let<T> = record type TLetMethod = procedure(a1:T) of object; class function call(a:T; proc: TProc<T> ) : TProc; overload; static; class function call(a:T; proc: TLetMethod ) : TProc;overload; static; end; let<T,T2> = record type TLetMethod = procedure(a:T;a2:T2) of object; class function call(a:T; a2:T2; proc: TProc<T,T2> ) : TProc; overload; static; class function call(a:T; a2:T2; proc: TLetMethod ) : TProc; overload; static; end; let<T,T2,T3> = record type TLetMethod = procedure(a:T;a2:T2;a3:T3) of object; class function call(a:T; a2:T2; a3:T3; proc: TProc<T,T2,T3> ) : TProc; overload; static; class function call(a:T; a2:T2; a3:T3; proc: TLetMethod ) : TProc; overload; static; end; let<T,T2,T3,T4> = record type TLetMethod = procedure(a1:T;a2:T2;a3:T3;a4:T4) of object; class function call(a:T; a2:T2; a3:T3; a4:T4; proc: TProc<T,T2,T3,T4> ) : TProc; overload; static; class function call(a:T; a2:T2; a3:T3; a4:T4; proc: TLetMethod ) : TProc; overload; static; end; function h2o(h:THex1) : word; inline; overload; function h2o(h:THex2) : word; inline; overload; function h2o(h:THex3) : word; inline; overload; function CStrLen(const str: PAnsiChar) : SIZE_T; function CStrUtf8( const p: PUtf8Char) : UTF8String; procedure scope(const proc: TProc ); var g_FormatUs : TFormatSettings; implementation function h2o(h:THex1) : word; begin result := h and 7; end; function h2o(h:THex2) : word; begin result := (h and 7) or (h and $70 shr 1); end; function h2o(h:THex3) : word; begin result := (h and 7) or (h and $70 shr 1) or (h and $700 shr 2); end; function CStrLen(const str: PAnsiChar) : SIZE_T; var ch : PAnsiChar; begin if str = nil then exit(0); ch := Str; while ch^ <> #0 do inc(ch); result := (ch-str); end; function CStrUtf8( const p: PUtf8Char) : UTF8String; begin result := UTF8String(p); end; procedure scope(const proc: TProc ); begin if assigned(proc) then proc(); end; class function let<T>.call(a: T; proc:TProc<T> ) : TProc; begin result:= procedure begin if assigned(proc) then proc(a); end; end; class function let<T>.call(a: T; proc: TLetMethod): TProc; begin result:= procedure begin if assigned(proc) then proc(a); end; end; class function let<T,T2>.call(a: T; a2:T2; proc:TProc<T,T2> ) : TProc; begin result:= procedure begin if assigned(proc) then proc(a,a2); end; end; class function let<T,T2>.call(a: T; a2:T2; proc:TLetMethod ) : TProc; begin result:= procedure begin if assigned(proc) then proc(a,a2); end; end; class function let<T,T2,T3>.call(a: T; a2:T2; a3:T3; proc:TProc<T,T2,T3> ) : TProc; begin result:= procedure begin if assigned(proc) then proc(a,a2,a3); end; end; class function let<T,T2,T3>.call(a: T; a2:T2; a3:T3; proc:TLetMethod ) : TProc; begin result:= procedure begin if assigned(proc) then proc(a,a2,a3); end; end; class function let<T,T2,T3,T4>.call(a: T; a2:T2; a3:T3; a4:T4; proc:TProc<T,T2,T3,T4> ) : TProc; begin result:= procedure begin if assigned(proc) then proc(a,a2,a3,a4); end; end; class function let<T,T2,T3,T4>.call(a: T; a2:T2; a3:T3; a4:T4; proc:TLetMethod ) : TProc; begin result:= procedure begin if assigned(proc) then proc(a,a2,a3,a4); end; end; initialization g_FormatUs := TFormatSettings.Create('en-US'); end.
{ cmdline.pas Command line parsing methods Copyright (C) 2006-2007 Felipe Monteiro de Carvalho This file is part of MkSymbian build tool. MkSymbian is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. MkSymbian 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. Please note that the General Public License version 2 does not permit incorporating MkSymbian into proprietary programs. } unit cmdline; {$ifdef fpc} {$mode delphi}{$H+} {$endif} interface uses Classes, SysUtils, constants; type { TCmdLine } TCmdLine = class(TObject) public procedure Usage; procedure ShowPath; procedure ParseCmdLineOptions(var opts: TMkSymbianOptions); end; var vCmdLine: TCmdLine; implementation uses sdkutil, projectparser; { TCmdLine } {******************************************************************* * TCmdLine.Usage () * * DESCRIPTION: Shows a usage message for the tool * * PARAMETERS: None * * RETURNS: Nothing * *******************************************************************} procedure TCmdLine.Usage; begin WriteLn('mksymbian - Build tool for Free Pascal for SymbianOS'); WriteLn(''); WriteLn('The parameters you specifyed are wrong.'); WriteLn(''); WriteLn('Usage: mksymbian [command] [project file]'); WriteLn(''); WriteLn('Possible commands: '); WriteLn(''); WriteLn('build - Builds an application'); WriteLn('bindings - Builds the c++ bindings for pascal'); WriteLn('showpath - Show the paths the tool is using'); WriteLn(''); end; {******************************************************************* * TCmdLine.ShowPath () * * DESCRIPTION: Shows in which paths (sdk, fpc, etc) mksymbian is using * * PARAMETERS: None * * RETURNS: Nothing * *******************************************************************} procedure TCmdLine.ShowPath; begin WriteLn('mksymbian - Build tool for Free Pascal for SymbianOS'); WriteLn(''); WriteLn('SDK Version: ' + vSDKUtil.StrSDKVersion); WriteLn('Location of SDK: ' + vSDKUtil.SDKFolder); WriteLn('Location of Free Pascal Compiler: ' + vProject.CompilerPath); WriteLn(''); end; {******************************************************************* * TCmdLine.ParseCmdLineOptions () * * DESCRIPTION: Parses the command line options utilized to call mksymbian * * PARAMETERS: None * * RETURNS: Nothing * *******************************************************************} procedure TCmdLine.ParseCmdLineOptions(var opts: TMkSymbianOptions); begin FillChar(opts, SizeOf(TMkSymbianOptions), #0); if (ParamCount = 0) then begin Usage; Exit; end; opts.ProjectFile := ParamStr(2); if CompareText(ParamStr(1), paramBuild) = 0 then opts.task := stBuildApp else if CompareText(ParamStr(1), paramBindings) = 0 then opts.task := stBuildBindings else if CompareText(ParamStr(1), paramShowPath) = 0 then begin opts.task := stNothing; vProject.ParseFile; ShowPath; end else begin opts.task := stNothing; Usage; end; end; end.
unit DataStructuresU; interface type TProjectData = class(TObject) public ID, Caption, FileName :String; constructor Create(); end; implementation { TProjectData } constructor TProjectData.Create; begin ID := ''; Caption := '(object)'; FileName := ''; end; end.
unit signup_test; interface uses System.JSON, DUnitX.TestFramework, signup, account, http_intf, controller_intf, add_account, delphi.mocks, email_validator_intf; type ITypeSut = interface ['{6B289352-E5CA-4F63-845F-523EC2A99E86}'] function MockSut: IController; function EmailValidator: TMock<IEmailValidator>; function AddAccount: TMock<IAddAccount>; end; TTypeSut = class(TInterfacedObject, ITypeSut) private FMockSut: TSignupController; FEmailValidator: TMock<IEmailValidator>; FAddAccount: TMock<IAddAccount>; function MockSut: IController; function AddAccount: TMock<IAddAccount>; function EmailValidator: TMock<IEmailValidator>; constructor Create; private class function New: ITypeSut; end; [TestFixture] TSignupTest = class(TObject) private FHTTPRequest: IHttpRequest; FHTTPResponse: IHttpResponse; function MakeSut: ITypeSut; function MakeSutWithInvalidEmail: ITypeSut; function MakeSutWithEmailValidatorThrows: ITypeSut; function MakeSutWithAddAccountThrows: ITypeSut; function MakeHttpRequestWithAnyValues: IHttpRequest; procedure AssertResponseMissinParam(const AParamName: String); public [Test] procedure MissingParamName; [Test] procedure MissingParamEmail; [Test] procedure MissingParamPassword; [Test] procedure MissingParamPasswordConfirmation; [Test] procedure PasswordConfirmationFails; [Test] procedure InvalidParamErrorEmail; [Test] procedure ShouldCallEmailValidatorWithCorrectEmail; [Test] procedure ShouldReturnError500IfEmailValidatorThrows; [Test] procedure ShouldReturnError500ifAddAccounthrows; [Test] procedure ShouldReturn200ifValidDataProvided; end; implementation uses System.Rtti, System.SysUtils, missing_param_error, invalid_param_error; function TSignupTest.MakeHttpRequestWithAnyValues: IHttpRequest; begin result := THttpRequest.New.body( // TJsonObject.Create // .AddPair('name', 'any_name') // .AddPair('email', 'any_email.com') // .AddPair('password', 'any_password') // .AddPair('passwordConfirmation', 'any_password') // ); end; function TSignupTest.MakeSut: ITypeSut; var FakeAccount: IAccountModel; begin FakeAccount := TAccountModel.New // .id('valid_id') // .name('valid_name') // .email('valid_email') // .password('valid_password'); result := TTypeSut.New; result.EmailValidator.Setup.WillReturnDefault('isValid', true); result.AddAccount.Setup.WillReturnDefault('add', TValue.From(FakeAccount)); end; function TSignupTest.MakeSutWithAddAccountThrows: ITypeSut; begin result := TTypeSut.New; result.AddAccount.Setup.WillRaise('add', EMockException); end; function TSignupTest.MakeSutWithEmailValidatorThrows: ITypeSut; begin result := TTypeSut.New; result.EmailValidator.Setup.WillRaise('isValid', EMockException); end; function TSignupTest.MakeSutWithInvalidEmail: ITypeSut; begin result := TTypeSut.New; result.EmailValidator.Setup.WillReturnDefault('isValid', false); end; procedure TSignupTest.MissingParamEmail; begin FHTTPRequest := THttpRequest.New // .body(TJsonObject.Create // .AddPair('name', 'any_name') // .AddPair('password', 'any_password') // .AddPair('passwordConfirmation', 'any_password')); FHTTPResponse := MakeSut.MockSut.handle(FHTTPRequest); Assert.IsTrue(FHTTPResponse.statusCode.ToString.Equals('400'), 'Should return: StatusCode 400'); AssertResponseMissinParam('email'); end; procedure TSignupTest.MissingParamName; begin FHTTPRequest := THttpRequest.New // .body(TJsonObject.Create // .AddPair('email', 'any_email') // .AddPair('password', 'any_password') // .AddPair('passwordConfirmation', 'any_password')); FHTTPResponse := MakeSut.MockSut.handle(FHTTPRequest); Assert.IsTrue(FHTTPResponse.statusCode.ToString.Equals('400'), 'Should return: StatusCode 400'); AssertResponseMissinParam('name'); end; procedure TSignupTest.MissingParamPassword; begin FHTTPRequest := THttpRequest.New // .body(TJsonObject.Create // .AddPair('name', 'any_name') // .AddPair('email', 'any_email') // .AddPair('passwordConfirmation', 'any_passwordConfirmation')); FHTTPResponse := MakeSut.MockSut.handle(FHTTPRequest); Assert.IsTrue(FHTTPResponse.statusCode.ToString.Equals('400'), 'Should return: StatusCode 400'); AssertResponseMissinParam('password'); end; procedure TSignupTest.MissingParamPasswordConfirmation; begin FHTTPRequest := THttpRequest.New // .body(TJsonObject.Create // .AddPair('name', 'any_name') // .AddPair('email', 'any_email') // .AddPair('password', 'any_password')); FHTTPResponse := MakeSut.MockSut.handle(FHTTPRequest); Assert.IsTrue(FHTTPResponse.statusCode.ToString.Equals('400'), 'Should return: StatusCode 400'); AssertResponseMissinParam('passwordConfirmation'); end; procedure TSignupTest.PasswordConfirmationFails; begin FHTTPRequest := THttpRequest.New // .body(TJsonObject.Create // .AddPair('name', 'any_name') // .AddPair('email', 'any_email') // .AddPair('password', 'any_password') // .AddPair('passwordConfirmation', 'invalid_passwordConfirmation')); FHTTPResponse := MakeSut.MockSut.handle(FHTTPRequest); Assert.IsTrue(FHTTPResponse.statusCode.ToString.Equals('400'), 'Should return: StatusCode 400'); Assert.IsTrue(FHTTPResponse.body.ToJSON.Equals('{"error":"Invalid param: passwordConfirmation"}'), format('Deve retornar %s, valor retornado %s', [FHTTPResponse.body.ToJSON, '{"error":"Invalid param: passwordConfirmation"}'])); end; procedure TSignupTest.ShouldCallEmailValidatorWithCorrectEmail; var lTypeSut: ITypeSut; begin lTypeSut := MakeSutWithInvalidEmail; lTypeSut.EmailValidator.Setup.Expect.Once.When.isValid('any_email.com'); lTypeSut.MockSut.handle(MakeHttpRequestWithAnyValues); lTypeSut.EmailValidator.Verify('Should Call ''isValid'' with correct email'); end; procedure TSignupTest.ShouldReturn200ifValidDataProvided; begin FHTTPResponse := MakeSut.MockSut.handle(MakeHttpRequestWithAnyValues); Assert.IsTrue(FHTTPResponse.statusCode.ToString.Equals('200'), 'Should return: StatusCode 200'); Assert.IsTrue(FHTTPResponse.body.GetValue('id').Value.Equals('valid_id'), 'Should return: valid_id'); Assert.IsTrue(FHTTPResponse.body.GetValue('name').Value.Equals('valid_name'), 'Should return: valid_name'); Assert.IsTrue(FHTTPResponse.body.GetValue('email').Value.Equals('valid_email'), 'Should return: valid_email'); Assert.IsTrue(FHTTPResponse.body.GetValue('password').Value.Equals('valid_password'), 'Should return: valid_password'); end; procedure TSignupTest.ShouldReturnError500ifAddAccounthrows; begin FHTTPResponse := MakeSutWithAddAccountThrows.MockSut.handle(MakeHttpRequestWithAnyValues); Assert.IsTrue(FHTTPResponse.statusCode.ToString.Equals('500'), 'Shoud return: StatusCode500'); Assert.IsTrue(FHTTPResponse.body.ToJSON.Equals('{"error":"Internal Server Error"}'), 'Should return: {"error":"Internal Server Error"}'); end; procedure TSignupTest.ShouldReturnError500IfEmailValidatorThrows; begin FHTTPResponse := MakeSutWithEmailValidatorThrows.MockSut.handle(MakeHttpRequestWithAnyValues); Assert.IsTrue(FHTTPResponse.statusCode.ToString.Equals('500'), 'Shoud return: StatusCode500'); Assert.IsTrue(FHTTPResponse.body.ToJSON.Equals('{"error":"Internal Server Error"}'), 'Should return: {"error":"Internal Server Error"}'); end; procedure TSignupTest.InvalidParamErrorEmail; begin FHTTPResponse := MakeSutWithInvalidEmail.MockSut.handle(MakeHttpRequestWithAnyValues); Assert.IsTrue(FHTTPResponse.statusCode.ToString.Equals('400'), 'Should return: StatusCode 400'); Assert.IsTrue(FHTTPResponse.body.ToJSON.Equals('{"error":"Invalid param: email"}'), format('Should return %s, valor retornado %s', [FHTTPResponse.body.ToJSON, '{"error":"Invalid param: email"}'])); end; procedure TSignupTest.AssertResponseMissinParam(const AParamName: String); var lResponseJson: String; begin lResponseJson := format('{"error":"Missing param: %s"}', [AParamName]); Assert.IsTrue(FHTTPResponse.body.ToJSON.Equals(lResponseJson), format('Should return: %s, value returned %s', [FHTTPResponse.body.ToJSON, lResponseJson])); end; function TTypeSut.AddAccount: TMock<IAddAccount>; begin result := FAddAccount; end; constructor TTypeSut.Create; begin FEmailValidator := TMock<IEmailValidator>.Create; FAddAccount := TMock<IAddAccount>.Create; FMockSut := TSignupController.Create(FEmailValidator, FAddAccount); end; function TTypeSut.EmailValidator: TMock<IEmailValidator>; begin result := FEmailValidator; end; function TTypeSut.MockSut: IController; begin result := FMockSut; end; class function TTypeSut.New: ITypeSut; begin result := TTypeSut.Create; end; initialization TDUnitX.RegisterTestFixture(TSignupTest); end.
program ProgramName(input, output, acct11, out11); { Chapter 11 Assignment Alberto Villalobos May 15, 2014 Description: This program simulates an online credit system, in which accounts are stored in Input: A file with account information. Interactive input from the user, account number and amount. Negative account numbers signal end of input. Output: First output an account report with all the accounts and balances that were input into the program. Also output a new balance sheet every time. level 0: Reset & Rewrite files Initialize variables Read accounts into program Output loaded accounts report Start interactivity read account read balance If negative account, save & exit else search for account index in array by account number if non-existant, throw error do an estimate of transaction, if over limit, throw error else add to the balance if negative account, write new file and exit } {main program vars & types} Type account = record name : packed array[1..20] of char; acctno: Integer; balance : Real; climit : Real; end; acctary = array[1..100] of account; acctfile = file of account; var out11, acct11: acctfile; numcust, actInput: Integer; purchase: real; list: acctary; procedure loadarray( var list:acctary; var numcust:Integer; var acct11:acctfile); begin numcust := 0; Reset(acct11); writeln('NAME':10,'ACCOUNT':10,'BALANCE':10,'LIMIT':10); while not eof(acct11) do begin numcust := numcust +1; Read(acct11, list[numcust]); writeln(list[numcust].name:10, list[numcust].acctno:10, list[numcust].balance:10:2, list[numcust].climit:10:2); end; end; {return index of account found, return 0 if none found} function findAccount(var accountToFind: integer; var tryList:acctary) : integer; var searchIterator, found, indexFound : integer; begin found:=0; indexFound := 0; for searchIterator := 1 to 11 do begin if (tryList[searchIterator].acctno = accountToFind) and (found=0) then begin indexFound:= searchIterator; found := 1; end; end; findAccount := indexFound; end; procedure tryPurchase(var tryAccountNo: integer; var tryPurchaseAmount: real; var tryList:acctary); var accountIndex : integer; overdraft: real; begin accountIndex:= findAccount(tryAccountNo, tryList); if accountIndex > 0 then begin if (tryList[accountIndex].balance + tryPurchaseAmount) > tryList[accountIndex].climit then begin overdraft := tryList[accountIndex].balance + tryPurchaseAmount - tryList[accountIndex].climit; writeln('We cannot authorize this purchase at this time as it would put you $', overdraft:6:2, ' over your credit limit'); end else begin tryList[accountIndex].balance := tryList[accountIndex].balance + purchase; writeln('Thank you for your business'); end; end else begin writeln('Invalid account number - re-enter data!'); end; if purchase < 0 then writeln('Do not entercredits at this terminal - re-enter data'); end; procedure writeToFile(var tryList:acctary); var writeIterator: integer; begin rewrite(out11); for writeIterator:=1 to 11 do begin write(out11, list[numcust]); end; end; { main program} begin loadarray(list, numcust, acct11); actInput := 1; while actInput > 0 do begin writeln('Enter account number:' ); read(actInput); writeln('Enter amount of purchase:'); read(purchase); if actInput > 0 then tryPurchase(actInput, purchase, list); end; writeToFile(list); end.
unit DW.OSDevice.Linux; {*******************************************************} { } { Kastri Free } { } { DelphiWorlds Cross-Platform Library } { } {*******************************************************} {$I DW.GlobalDefines.inc} interface type /// <remarks> /// DO NOT ADD ANY FMX UNITS TO THESE FUNCTIONS /// </remarks> TPlatformOSDevice = record public class function GetDeviceName: string; static; class function GetPackageID: string; static; class function GetPackageVersion: string; static; class function GetUniqueDeviceID: string; static; class function IsTouchDevice: Boolean; static; end; implementation uses // Posix Posix.UniStd; { TPlatformOSDevice } class function TPlatformOSDevice.GetDeviceName: string; const cMaxHostName = 255; var LHost: array[0..cMaxHostName] of Byte; LHostPtr: TPtrWrapper; begin LHostPtr := TPtrWrapper.Create(@LHost[0]); gethostname(LHostPtr.ToPointer, cMaxHostName); Result := TMarshal.ReadStringAsAnsi(LHostPtr); end; class function TPlatformOSDevice.GetPackageID: string; begin Result := ''; // None yet end; class function TPlatformOSDevice.GetPackageVersion: string; begin Result := ''; // None yet end; class function TPlatformOSDevice.GetUniqueDeviceID: string; begin Result := ''; end; class function TPlatformOSDevice.IsTouchDevice: Boolean; begin Result := False; end; end.
unit CommentInTableAndScrollTest; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "TestFormsTest" // Модуль: "w:/common/components/gui/Garant/Daily/CommentInTableAndScrollTest.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<TestCase::Class>> Shared Delphi Operations For Tests::TestFormsTest::Everest::TCommentInTableAndScrollTest // // Тест вставки комметария в таблицу // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! interface {$If defined(nsTest) AND not defined(NoVCM)} uses nevTools, CommentAndScrollTest, PrimTextLoad_Form ; {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} type TCommentInTableAndScrollTest = {abstract} class(TCommentAndScrollTest) {* Тест вставки комметария в таблицу } private // private methods function IsUserComment(const aView: InevInputView): Boolean; {* Проверяет указывает ли якорь на пользовательский комментарий. } protected // overridden protected methods procedure CheckTopAnchor(const aView: InevInputView); override; {* проверить якорь начала отрисовки после окончания прокрутки } function GetFolder: AnsiString; override; {* Папка в которую входит тест } procedure MoveCursor4Insert(aForm: TPrimTextLoadForm); override; {* Переместить курсор перед вставкой комментария. } function GetUserComment(const aPoint: InevBasePoint): InevBasePoint; override; {* Получить пользовательский комментарий } procedure DoScroll(aForm: TPrimTextLoadForm); override; {* Прокрутка текста в редакторе (если нужна). } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TCommentInTableAndScrollTest {$IfEnd} //nsTest AND not NoVCM implementation {$If defined(nsTest) AND not defined(NoVCM)} uses evOp, TableCell_Const, nevBase, SBSCell_Const, CommentPara_Const, TestFrameWork ; {$IfEnd} //nsTest AND not NoVCM {$If defined(nsTest) AND not defined(NoVCM)} // start class TCommentInTableAndScrollTest function TCommentInTableAndScrollTest.IsUserComment(const aView: InevInputView): Boolean; //#UC START# *4CA983690025_4CA2F3AA0033_var* var l_Real : InevBasePoint; l_Anchor : InevBasePoint; //#UC END# *4CA983690025_4CA2F3AA0033_var* begin //#UC START# *4CA983690025_4CA2F3AA0033_impl* Result := False; l_Anchor := aView.TopAnchor; while l_Anchor <> nil do begin if l_Anchor.InheritsFrom(k2_idCommentPara) then begin Result := True; Break; end; // if l_Anchor.InheritsFrom(k2_idCommentPara) then if l_Anchor.HasBaseLine then l_Anchor := l_Anchor.InnerFor(l_Anchor.Obj^.ToList.Obj[0], l_Real) else l_Anchor := l_Anchor.Inner; end; // while l_Anchor <> nil do //#UC END# *4CA983690025_4CA2F3AA0033_impl* end;//TCommentInTableAndScrollTest.IsUserComment procedure TCommentInTableAndScrollTest.CheckTopAnchor(const aView: InevInputView); //#UC START# *4C1F0A260192_4CA2F3AA0033_var* //#UC END# *4C1F0A260192_4CA2F3AA0033_var* begin //#UC START# *4C1F0A260192_4CA2F3AA0033_impl* CheckFalse(IsUserComment(aView), 'Комментарий мы уже удалили! А TopAnchor его еще держит!'); //#UC END# *4C1F0A260192_4CA2F3AA0033_impl* end;//TCommentInTableAndScrollTest.CheckTopAnchor function TCommentInTableAndScrollTest.GetFolder: AnsiString; {-} begin Result := 'Everest'; end;//TCommentInTableAndScrollTest.GetFolder procedure TCommentInTableAndScrollTest.MoveCursor4Insert(aForm: TPrimTextLoadForm); //#UC START# *4CA2F33F01E5_4CA2F3AA0033_var* var l_Tag: InevTag; //#UC END# *4CA2F33F01E5_4CA2F3AA0033_var* begin //#UC START# *4CA2F33F01E5_4CA2F3AA0033_impl* l_Tag := aForm.Text.Selection.Cursor.MostInner.Owner; while not l_Tag.InheritsFrom(k2_idTableCell) or l_Tag.InheritsFrom(k2_idSBSCell) do begin aForm.Text.Selection.Cursor.Move(aForm.Text.View, ev_ocLineDown); l_Tag := aForm.Text.Selection.Cursor.MostInner.Owner; end; // while not l_Tag.InheritsFrom(k2_idTableCell) ... aForm.Text.Selection.Cursor.Move(aForm.Text.View, ev_ocLineDown); //aForm.Text.Selection.Cursor.Move(aForm.Text.View, ev_ocLineDown); //#UC END# *4CA2F33F01E5_4CA2F3AA0033_impl* end;//TCommentInTableAndScrollTest.MoveCursor4Insert function TCommentInTableAndScrollTest.GetUserComment(const aPoint: InevBasePoint): InevBasePoint; //#UC START# *4CA982110056_4CA2F3AA0033_var* var l_PrevPoint: InevBasePoint; //#UC END# *4CA982110056_4CA2F3AA0033_var* begin //#UC START# *4CA982110056_4CA2F3AA0033_impl* Result := aPoint; while not Result.InheritsFrom(k2_idCommentPara) do begin l_PrevPoint := Result; Result := Result.Inner; if Result = nil then Result := l_PrevPoint.Obj^.ToList.Obj[l_PrevPoint.Obj^.ChildrenCount - 1].MakePoint; end; // while not Result.InheritsFrom(k2_idCommentPara) do //#UC END# *4CA982110056_4CA2F3AA0033_impl* end;//TCommentInTableAndScrollTest.GetUserComment procedure TCommentInTableAndScrollTest.DoScroll(aForm: TPrimTextLoadForm); //#UC START# *4CA982800281_4CA2F3AA0033_var* //#UC END# *4CA982800281_4CA2F3AA0033_var* begin //#UC START# *4CA982800281_4CA2F3AA0033_impl* while not IsUserComment(aForm.Text.View) do ScrollByLine(aForm, 1, False, False); //#UC END# *4CA982800281_4CA2F3AA0033_impl* end;//TCommentInTableAndScrollTest.DoScroll function TCommentInTableAndScrollTest.GetModelElementGUID: AnsiString; {-} begin Result := '4CA2F3AA0033'; end;//TCommentInTableAndScrollTest.GetModelElementGUID {$IfEnd} //nsTest AND not NoVCM end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpBerApplicationSpecific; {$I ..\Include\CryptoLib.inc} interface uses ClpIAsn1EncodableVector, ClpIBerApplicationSpecific, ClpDerApplicationSpecific; type TBerApplicationSpecific = class(TDerApplicationSpecific, IBerApplicationSpecific) public constructor Create(tagNo: Int32; const vec: IAsn1EncodableVector); end; implementation { TBerApplicationSpecific } constructor TBerApplicationSpecific.Create(tagNo: Int32; const vec: IAsn1EncodableVector); begin inherited Create(tagNo, vec); end; end.
unit unit_Samples; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.ThreadSafe, FMX.Controls.Presentation, FMX.StdCtrls, FMX.ScrollBox, FMX.Memo; type TForm2 = class(TForm) Button1: TButton; Memo1: TMemo; Button2: TButton; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); // private { Private declarations } private strList: TThreadSafeStringList; { Public declarations } end; var Form2: TForm2; implementation {$R *.fmx} procedure TForm2.Button1Click(Sender: TObject); var x: integer; t1, t2: TThread; begin strList.Clear; // Thread 1 t1 := TThread.CreateAnonymousThread( procedure var x: integer; begin for x := 0 to random(1000) do begin strList.Add('X' + intToStr(x)); TThread.Sleep(random(10)); end; strList.Add('X-FIM'); end); t1.start; // Thread 2 t2 := TThread.CreateAnonymousThread( procedure var x: integer; begin for x := 0 to random(1000) do begin strList.Add('Z' + intToStr(x)); TThread.Sleep(random(10)); end; strList.Add('Z-FIM'); TThread.Queue(nil, procedure begin strList.AssingTo(Memo1.lines); end); end); t2.start; end; procedure TForm2.FormCreate(Sender: TObject); begin strList := TThreadSafeStringList.create; end; procedure TForm2.FormDestroy(Sender: TObject); begin strList.free; end; end.
UNIT A6Q1TPU ; INTERFACE type nodeptr = ^node ; stackitem = string ; node = record value: stackitem ; next: nodeptr end ; stack = nodeptr ; var memory_count: integer ; procedure get_node( var P: nodeptr ); procedure return_node(var P: nodeptr) ; procedure create(var S:stack); procedure destroy(var S: stack); function is_empty(S:stack): boolean ; procedure top( s:stack; var v:stackitem ); procedure pop(var S:stack); procedure push(v:stackitem; var S:stack); IMPLEMENTATION {******* MEMORY MANAGEMENT PROCEDURES **********} { get_node - Returns a pointer to a new node. } procedure get_node( var P: nodeptr ); BEGIN memory_count := memory_count + 1 ; new( P ) END; { return_node - returns the dynamic memory to which P points to the global pool. } procedure return_node(var P: nodeptr) ; BEGIN memory_count := memory_count - 1 ; P^.value := 'I am free' ; P^.next := nil ; dispose( P ) END; {************ IMPLEMENTATION of 'STACK' *****************} procedure create(var S:stack); BEGIN S := nil END; { procedure create() } procedure destroy(var S: stack); BEGIN if S <> nil then BEGIN destroy(S^.next); return_node(S) ; S := nil { optional, simply as an aid to debugging } END ; END; { procedure destroy() } function is_empty(S:stack): boolean ; BEGIN is_empty := (S = nil) END; { fxn is_empty() } procedure top( s:stack; var v:stackitem ); BEGIN if is_empty(S) then BEGIN writeln('** error, tried to top an empty stack **') ; writeln('hit enter once or twice to halt the program'); readln; { clears the input if there is any left } readln; { this is the one the user enters } halt END { if } else v := s^.value ; END; { procedure top() } procedure pop(var S:stack); var temp: nodeptr; BEGIN if is_empty(S) then BEGIN writeln('** error, tried to pop an empty stack **') ; writeln('hit enter once or twice to halt the program'); readln; { clears the input if there is any left } readln; { this is the one the user enters } halt END { if } else BEGIN temp := S; S := S^.next ; return_node(temp) END { else } END; { procedure pop() } procedure push(v:stackitem; var S:stack); var temp: nodeptr; BEGIN temp := S ; get_node( S ); S^.value := v ; S^.next := temp END; { procedure push() } END. { UNIT A6Q1TPU }
unit uMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Math.Vectors, FMX.MaterialSources, FMX.Controls3D, FMX.Objects3D, FMX.Viewport3D, FMX.Ani, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts, FMX.Edit, FMX.EditBox, FMX.NumberBox, FMX.SpinBox; type TMainForm = class(TForm) Cube1: TCube; LightMaterialSource1: TLightMaterialSource; Viewport3D1: TViewport3D; FloatAnimation1: TFloatAnimation; Layout1: TLayout; TrackBarX: TTrackBar; TrackBarZ: TTrackBar; TrackBarY: TTrackBar; Layout2: TLayout; NumberBoxX: TNumberBox; Label1: TLabel; Label2: TLabel; NumberBoxY: TNumberBox; Label3: TLabel; NumberBoxZ: TNumberBox; Label4: TLabel; Label5: TLabel; Label6: TLabel; SpinBoxX: TSpinBox; SpinBoxY: TSpinBox; SpinBoxZ: TSpinBox; procedure TrackBarXChange(Sender: TObject); procedure TrackBarYChange(Sender: TObject); procedure TrackBarZChange(Sender: TObject); procedure NumberBoxXChange(Sender: TObject); procedure NumberBoxYChange(Sender: TObject); procedure NumberBoxZChange(Sender: TObject); procedure SpinBoxXChange(Sender: TObject); procedure SpinBoxYChange(Sender: TObject); procedure SpinBoxZChange(Sender: TObject); private { Private declarations } public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.fmx} procedure TMainForm.NumberBoxXChange(Sender: TObject); begin Cube1.Position.X := NumberBoxX.Value; end; procedure TMainForm.NumberBoxYChange(Sender: TObject); begin Cube1.Position.Y := NumberBoxY.Value; end; procedure TMainForm.NumberBoxZChange(Sender: TObject); begin Cube1.Position.Z := NumberBoxZ.Value; end; procedure TMainForm.SpinBoxXChange(Sender: TObject); begin Cube1.RotationAngle.X := SpinBoxX.Value; end; procedure TMainForm.SpinBoxYChange(Sender: TObject); begin Cube1.RotationAngle.Y := SpinBoxY.Value; end; procedure TMainForm.SpinBoxZChange(Sender: TObject); begin Cube1.RotationAngle.Z := SpinBoxZ.Value; end; procedure TMainForm.TrackBarXChange(Sender: TObject); begin Cube1.Scale.X := TrackBarX.Value; end; procedure TMainForm.TrackBarYChange(Sender: TObject); begin Cube1.Scale.Y := TrackBarY.Value; end; procedure TMainForm.TrackBarZChange(Sender: TObject); begin Cube1.Scale.Z := TrackBarZ.Value; end; end.
program astronomia; const dimF = 53; type galaxia = record nombre :string; tipo :integer; masa :real; distancia :real; end; picos = record primero :galaxia; segundo :galaxia; end; galaxias = array[1..dimF] of galaxia; cantidades = array[1..4] of integer; procedure leerGalaxia(var g:galaxia); begin writeln('Ingrese el nombre de la galaxia: '); readln(g.nombre); writeln('Ingrese el tipo(1.elíptica/2.espiral/3.lenticular/4.irregular): '); readln(g.tipo); writeln('Ingrese la masa: '); readln(g.masa); writeln('Ingrese la distancia: '); readln(g.distancia); end; // Cond 1 procedure comprobarTipo(var c:cantidades; g:galaxia); var tipo :integer; begin tipo := g.tipo; c[tipo] := c[tipo] + 1; end; // Cond 2 procedure comprobarPrincipales(var mPrincipales :real; g:galaxia); var nombre :string; begin nombre := g.nombre; if ( (nombre = 'Vía Láctea') or (nombre = 'Andrómeda') or (nombre = 'Triángulo') ) then mPrincipales := mPrincipales + g.masa; end; // Cond 3 procedure comprobarCond3(var cant:integer; g:galaxia); begin if ((g.tipo <> 4) and (g.distancia < 1000)) then cant := cant + 1; end; // Maximos y minimos(Cond 4) procedure reasignar(var actual:galaxia; nuevo:galaxia); begin actual.masa := nuevo.masa; actual.nombre := nuevo.nombre; end; // Maximos procedure comprobarMaximos(var m:picos; g:galaxia); begin if (g.masa >= m.primero.masa) then begin reasignar(m.segundo, m.primero); reasignar(m.primero, g); end else if(g.masa >= m.segundo.masa) then reasignar(m.segundo, g); end; // Minimos procedure comprobarMinimos(var m:picos; g:galaxia); begin if (g.masa <= m.primero.masa) then begin reasignar(m.segundo, m.primero); reasignar(m.primero, g); end else if (g.masa <= m.segundo.masa) then reasignar(m.segundo, g); end; var i :integer; gs :galaxias; g:galaxia; maximos :picos; minimos :picos; cantidadCond1 :cantidades; cantidadCond3 :integer; masaPrincipales :real; masaTotal :real; begin // Inicializo las cantidades por tipo for i:=1 to 4 do cantidadCond1[i] := 0; masaPrincipales := 0; masaTotal := 0; for i:=1 to dimF do begin leerGalaxia(gs[i]); end; for i:=1 to dimF do begin g := gs[i]; comprobarTipo(cantidadCond1, g); comprobarPrincipales(masaPrincipales, g); comprobarCond3(cantidadCond3, g); comprobarMaximos(maximos,g); comprobarMinimos(minimos,g); masaTotal := masaTotal + g.masa; end; for i:=1 to 4 do writeln( 'La cantidad de galaxias del tipo ', i, ' es ', cantidadCond1[i], '.' ); writeln( 'La masa acumulada de las principales es: ', masaPrincipales:8:2, ', ', ((masaPrincipales/masaTotal)*100):3:2, '% sobre el total.' ); writeln( 'La cantidad de galaxias no regulares que se encuentan a menos de 1000pc es:', cantidadCond3 ); writeln( 'Las dos galaxias con menos masa son: ', minimos.primero.nombre, ' y ', minimos.segundo.nombre, '.' ); writeln( 'Las dos galaxias con mayor masa son: ', maximos.primero.nombre, ' y ', maximos.segundo.nombre, '.' ); end.
{ Copyright (C) 2013-2019 Tim Sinaeve tim.sinaeve@gmail.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. } unit LogViewer.Events; { Dispatches events on the active view. } interface uses Spring, LogViewer.Interfaces; type TLogViewerEvents = class(TInterfaceBase, ILogViewerEvents) // no refcount private FManager : ILogViewerManager; FOnAddLogViewer : Event<TLogViewerEvent>; FOnAddReceiver : Event<TChannelReceiverEvent>; FOnActiveViewChange : Event<TLogViewerEvent>; protected {$REGION 'property access methods'} function GetOnActiveViewChange: IEvent<TLogViewerEvent>; function GetOnAddLogViewer: IEvent<TLogViewerEvent>; function GetOnAddReceiver: IEvent<TChannelReceiverEvent>; {$ENDREGION} {$REGION 'event dispatch methods'} procedure DoAddLogViewer(ALogViewer: ILogViewer); virtual; procedure DoActiveViewChange(ALogViewer: ILogViewer); virtual; procedure DoAddReceiver(AReceiver: IChannelReceiver); virtual; {$ENDREGION} procedure Clear; public constructor Create(AManager: ILogViewerManager); procedure BeforeDestruction; override; property OnActiveViewChange: IEvent<TLogViewerEvent> read GetOnActiveViewChange; property OnAddLogViewer: IEvent<TLogViewerEvent> read GetOnAddLogViewer; property OnAddReceiver: IEvent<TChannelReceiverEvent> read GetOnAddReceiver; end; implementation uses DDuce.Logger; {$REGION 'construction and destruction'} constructor TLogViewerEvents.Create(AManager: ILogViewerManager); begin Guard.CheckNotNull(AManager, 'AManager'); FManager := AManager; end; procedure TLogViewerEvents.BeforeDestruction; begin Logger.Track('TLogViewerEvents.BeforeDestruction'); Clear; FManager := nil; inherited BeforeDestruction; end; {$ENDREGION} {$REGION 'property access methods'} function TLogViewerEvents.GetOnActiveViewChange: IEvent<TLogViewerEvent>; begin Result := FOnActiveViewChange; end; function TLogViewerEvents.GetOnAddLogViewer: IEvent<TLogViewerEvent>; begin Result := FOnAddLogViewer; end; function TLogViewerEvents.GetOnAddReceiver: IEvent<TChannelReceiverEvent>; begin Result := FOnAddReceiver; end; {$ENDREGION} {$REGION 'event dispatch methods'} procedure TLogViewerEvents.DoActiveViewChange(ALogViewer: ILogViewer); begin FOnActiveViewChange.Invoke(Self, ALogViewer); end; procedure TLogViewerEvents.DoAddLogViewer(ALogViewer: ILogViewer); begin FOnAddLogViewer.Invoke(Self, ALogViewer); end; procedure TLogViewerEvents.DoAddReceiver(AReceiver: IChannelReceiver); begin FOnAddReceiver.Invoke(Self, AReceiver); end; {$ENDREGION} {$REGION 'protected methods'} procedure TLogViewerEvents.Clear; begin FOnAddLogViewer.Clear; FOnAddReceiver.Clear; FOnActiveViewChange.Clear; end; {$ENDREGION} end.
unit LUX.GPU.Vulkan.Buffer.Unifor; interface //#################################################################### ■ uses vulkan_core, LUX.GPU.Vulkan.Buffer; type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】 TVkUniBuf<TVkDevice_:class> = class; TVkUniBuf<TVkDevice_:class;TValue_:record> = class; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkUniBuf<TVkDevice_> TVkUniBuf<TVkDevice_:class> = class( TVkBuffer<TVkDevice_> ) private protected public constructor Create; override; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkBuffer<TVkDevice_,TValue_> TVkUniBuf<TVkDevice_:class;TValue_:record> = class( TVkUniBuf<TVkDevice_> ) private protected _Value :TValue_; ///// アクセス function GetValue :TValue_; virtual; procedure SetValue( const Value_:TValue_ ); virtual; ///// プロパティ property Size :VkDeviceSize read GetSize write SetSize; public constructor Create; override; ///// プロパティ property Value :TValue_ read GetValue write SetValue; end; //const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】 //var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 implementation //############################################################### ■ uses LUX.GPU.Vulkan; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkUniBuf<TVkDevice_> //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TVkUniBuf<TVkDevice_>.Create; begin inherited; Usage := Ord( VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT ); end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TVkBuffer<TVkDevice_,TValue_> //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TVkUniBuf<TVkDevice_,TValue_>.GetValue :TValue_; begin Result := _Value; end; procedure TVkUniBuf<TVkDevice_,TValue_>.SetValue( const Value_:TValue_ ); var P :Pointer; begin _Value := Value_; _Memory.Map( P ); Move( _Value, P^, Size ); _Memory.Unmap; end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TVkUniBuf<TVkDevice_,TValue_>.Create; begin inherited; Size := SizeOf( TValue_ ); end; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 end. //######################################################################### ■
unit WinSockRDOConnection; interface uses {$IFNDEF AutoServer} SmartThreads, {$ENDIF} Classes, ComObj, Windows, {$IFDEF AutoServer} RDOClient_TLB, {$ENDIF} RDOInterfaces, SocketComp, SyncObjs; {$IFDEF AutoServer} type TSmartThread = TThread; {$ENDIF} type TWinSockRDOConnection = {$IFDEF AutoServer} class(TAutoObject, IRDOConnectionInit, IRDOServerConnection, IRDOConnection) {$ELSE} class( TInterfacedObject, IRDOConnectionInit, IRDOServerConnection, IRDOConnection ) {$ENDIF} {$IFDEF AutoServer} public procedure Initialize; override; {$ELSE} public constructor Create(aLabel : string); {$ENDIF} destructor Destroy; override; protected // IRDOConnectionInit function Get_Server : WideString; safecall; procedure Set_Server( const Value : WideString ); safecall; function Get_Port : Integer; safecall; procedure Set_Port( Value : Integer ); safecall; function Connect( TimeOut : Integer ) : WordBool; safecall; procedure Disconnect; safecall; protected // IRDOServerConnection procedure SetQueryServer( const QueryServer : IRDOQueryServer ); function GetMaxQueryThreads : integer; procedure SetMaxQueryThreads( MaxQueryThreads : integer ); public // IRDOConnection function Alive : boolean; function SendReceive( const QueryText : string; out ErrorCode : integer; TimeOut : integer ) : string; stdcall; procedure Send( const QueryText : string ); stdcall; function GetLocalAddress : string; stdcall; function GetRemoteAddress : string; stdcall; function GetLocalHost : string; stdcall; function GetLocalPort : integer; stdcall; function GetOnConnect : TRDOClientConnectEvent; procedure SetOnConnect( OnConnectHandler : TRDOClientConnectEvent ); function GetOnDisconnect : TRDOClientDisconnectEvent; procedure SetOnDisconnect( OnDisconnectHandler : TRDOClientDisconnectEvent ); function GetTimeOut : integer; procedure SetTimeOut(TimeOut : integer); procedure SetData(data : pointer); function GetData : pointer; private procedure CloseSocket; procedure KillThreads; private fTimeout : integer; fConnected : boolean; fPort : integer; fServer : string; //fUnsentQueries : TList; fSentQueries : TList; fSenderThread : TSmartThread; fMsgLoopThread : TSmartThread; fUnsentQueriesLock : TCriticalSection; fSentQueriesLock : TCriticalSection; fSocketComponent : TClientSocket; fReceivedText : string; fConnectionEvent : THandle; fUnsentQueryWaiting : THandle; fQueryServer : IRDOQueryServer; fQueryQueue : TList; fQueryWaiting : THandle; fQueryQueueLock : TCriticalSection; fQueryThreads : TList; fMaxQueryThreads : integer; fTerminateEvent : THandle; fOnConnect : TRDOClientConnectEvent; fOnDisconnect : TRDOClientDisconnectEvent; fData : pointer; procedure DoRead( Sender : TObject; Socket : TCustomWinSocket ); procedure HandleError( Sender : TObject; Socket : TCustomWinSocket; ErrorEvent : TErrorEvent; var ErrorCode : integer ); procedure HandleConnect( Sender : TObject; Socket : TCustomWinSocket ); procedure HandleDisconnect( Sender : TObject; Socket : TCustomWinSocket ); private fLabel : string; public property theLabel : string read fLabel write fLabel; end; implementation uses {$IFDEF AutoServer} ComServ, {$ENDIF} SysUtils, ActiveX, WinSock, RDOUtils, RDOProtocol, {$IFDEF USELogs} Logs, {$ENDIF} ErrorCodes; // Query id generation routines and variables const DefRDOPort = 5000; const DefMaxQueryThreads = 5; var LastQueryId : word; function GenerateQueryId : integer; begin Result := LastQueryId; LastQueryId := ( LastQueryId + 1 ) mod 65536 end; type TQueryToSend = record Id : word; Text : string; WaitForAnsw : boolean; Result : string; Event : THandle; ErrorCode : integer; end; PQueryToSend = ^TQueryToSend; type TQueryToService = record QueryText : string; end; PQueryToService = ^TQueryToService; // Delphi classes associated to the threads in charge of the connection type TMsgLoopThread = class( TSmartThread ) private fConnection : TWinSockRDOConnection; constructor Create( theConnection : TWinSockRDOConnection ); protected procedure Execute; override; public property Connection : TWinSockRDOConnection read fConnection write fConnection; end; type TQueryThread = class( TSmartThread ) private fConnection : TWinSockRDOConnection; fQueryStatus : integer; fRDOCallCnt : integer; public constructor Create( theConnection : TWinSockRDOConnection ); procedure Execute; override; end; // TMsgLoopThread constructor TMsgLoopThread.Create( theConnection : TWinSockRDOConnection ); begin inherited Create(true); fConnection := theConnection; FreeOnTerminate := true; Resume; end; procedure TMsgLoopThread.Execute; var Msg : TMsg; alive : boolean; begin try try fConnection.fSocketComponent.Open; except Terminate; {$IFDEF USELogs} Logs.Log( 'Survival', '(3)- Error establishing connection' ); // (3) {$ENDIF} end; alive := true; while not Terminated and (fConnection <> nil) and alive do if PeekMessage( Msg, 0, 0, 0, PM_REMOVE ) then try DispatchMessage( Msg ) except {$IFDEF USELogs} Logs.Log( 'Survival', '(4)- Internal TMsgLoopThread error' ); // (4) {$ENDIF} end else if fConnection <> nil then alive := MsgWaitForMultipleObjects( 1, fConnection.fTerminateEvent, false, INFINITE, QS_ALLINPUT ) = WAIT_OBJECT_0 + 1 except {$IFDEF USELogs} Logs.Log( 'Survival', '(5)- Abnormal TMsgLoopThread termination' ); // (5) {$ENDIF} end; end; // TQueryThread constructor TQueryThread.Create( theConnection : TWinSockRDOConnection ); begin fConnection := theConnection; inherited Create( false ) end; procedure TQueryThread.Execute; var QueryResult : string; QueryToService : PQueryToService; QueryThreadEvents : array [ 1 .. 2 ] of THandle; begin CoInitialize(nil); try with fConnection do begin QueryThreadEvents[ 1 ] := fQueryWaiting; QueryThreadEvents[ 2 ] := fTerminateEvent; while not Terminated do begin // Check if the Termination event was signaled if WaitForMultipleObjects( 2, @QueryThreadEvents[ 1 ], false, INFINITE ) = WAIT_OBJECT_0 + 1 then Terminate; // sos if not Terminated then begin fQueryQueueLock.Acquire; try if fQueryQueue.Count <> 0 then begin QueryToService := fQueryQueue[ 0 ]; fQueryQueue.Delete( 0 ) end else begin QueryToService := nil; ResetEvent( fQueryWaiting ) end finally fQueryQueueLock.Release end; end else QueryToService := nil; if QueryToService <> nil then begin QueryResult := fQueryServer.ExecQuery( QueryToService.QueryText, integer(fSocketComponent.Socket), fQueryStatus, fRDOCallCnt ); Dispose( QueryToService ); if QueryResult <> '' then try fSocketComponent.Socket.SendText( AnswerId + QueryResult ); {$IFDEF Logs} Logs.Log( 'Survival', 'Result : ' + QueryResult ); {$ENDIF} except {$IFDEF USELogs} Logs.Log( 'Survival', '(6)- Socket error sending query result' ) // (6) {$ENDIF} end else begin {$IFDEF Logs} Logs.Log( 'Survival', 'No result' ) {$ENDIF} end end end end finally CoUninitialize; end; end; // TWinSockRDOConnection {$IFDEF AutoServer} procedure TWinSockRDOConnection.Initialize; const aLabel = 'AutoCnx'; begin inherited Initialize; {$ELSE} constructor TWinSockRDOConnection.Create; begin inherited Create; {$ENDIF} fLabel := aLabel; fSocketComponent := TClientSocket.Create( nil ); fSocketComponent.Active := false; fUnsentQueriesLock := TCriticalSection.Create; fSentQueriesLock := TCriticalSection.Create; fSentQueries := TList.Create; fPort := DefRDOPort; fConnectionEvent := CreateEvent( nil, false, false, nil ); fUnsentQueryWaiting := CreateEvent( nil, true, false, nil ); fQueryQueue := TList.Create; fQueryThreads := TList.Create; fMaxQueryThreads := DefMaxQueryThreads; fQueryWaiting := CreateEvent( nil, true, false, nil ); fQueryQueueLock := TCriticalSection.Create; fTerminateEvent := CreateEvent( nil, true, false, nil ) end; procedure TWinSockRDOConnection.SetData(data : pointer); begin fData := data; end; function TWinSockRDOConnection.GetData : pointer; begin result := fData; end; destructor TWinSockRDOConnection.Destroy; procedure FreeQueryQueue; var i : integer; begin for i := 0 to pred(fQueryQueue.Count) do Dispose( PQueryToService( fQueryQueue[i] ) ); fQueryQueue.Free; end; begin Disconnect; fUnsentQueriesLock.Free; fSentQueriesLock.Free; fSocketComponent.Free; fSentQueries.Free; CloseHandle( fConnectionEvent ); CloseHandle( fUnsentQueryWaiting ); fQueryThreads.Free; FreeQueryQueue; CloseHandle( fQueryWaiting ); fQueryQueueLock.Free; CloseHandle( fTerminateEvent ); inherited; end; function TWinSockRDOConnection.Get_Server : WideString; begin Result := fServer end; procedure TWinSockRDOConnection.Set_Server( const Value : WideString ); begin fServer := Value end; function TWinSockRDOConnection.Get_Port : Integer; begin Result := fPort end; procedure TWinSockRDOConnection.Set_Port( Value : Integer ); begin fPort := Value end; function TWinSockRDOConnection.GetLocalHost : string; begin Result := fSocketComponent.Socket.LocalHost end; function TWinSockRDOConnection.GetLocalAddress : string; begin Result := fSocketComponent.Socket.LocalAddress end; function TWinSockRDOConnection.GetRemoteAddress : string; begin Result := fSocketComponent.Socket.RemoteAddress; end; function TWinSockRDOConnection.GetLocalPort : integer; begin Result := fSocketComponent.Socket.LocalPort end; function TWinSockRDOConnection.GetOnConnect : TRDOClientConnectEvent; begin result := fOnConnect; end; procedure TWinSockRDOConnection.SetOnConnect( OnConnectHandler : TRDOClientConnectEvent ); begin fOnConnect := OnConnectHandler end; function TWinSockRDOConnection.GetOnDisconnect : TRDOClientDisconnectEvent; begin result := fOnDisconnect; end; procedure TWinSockRDOConnection.SetOnDisconnect( OnDisconnectHandler : TRDOClientDisconnectEvent ); begin fOnDisconnect := OnDisconnectHandler end; function TWinSockRDOConnection.GetTimeOut : integer; begin result := fTimeout; end; procedure TWinSockRDOConnection.SetTimeOut(TimeOut : integer); begin fTimeout := TimeOut; end; procedure TWinSockRDOConnection.CloseSocket; begin if fSocketComponent.Active then try fSocketComponent.Close; except {$IFDEF USELogs} Logs.Log( 'Survival', '(8)- Error closing connection' ); // (8) {$ENDIF} end; end; procedure TWinSockRDOConnection.KillThreads; procedure FreeQueryThreads; var i : integer; aQueryThread : TSmartThread; begin for i := 0 to pred(fQueryThreads.Count) do begin aQueryThread := TSmartThread(fQueryThreads[i]); aQueryThread.Free; end; fQueryThreads.Clear; end; begin SetEvent( fTerminateEvent ); fMsgLoopThread := nil; { if fMsgLoopThread <> nil then begin TMsgLoopThread(fMsgLoopThread).fConnection := nil; fMsgLoopThread := nil; end; } if fSenderThread <> nil then begin fSenderThread.Free; fSenderThread := nil; end; if fQueryThreads <> nil then FreeQueryThreads; end; function TWinSockRDOConnection.Connect( TimeOut : Integer ) : WordBool; var waitres : cardinal; Events : array [0..1] of THandle; begin fTimeout := TimeOut; Result := true; try ResetEvent( fTerminateEvent ); with fSocketComponent do if not Active then begin //ClientType := ctNonBlocking; if inet_addr( PChar( fServer ) ) = u_long(INADDR_NONE) // >> Delphi 4 then Host := fServer else Address := fServer; Port := fPort; OnRead := DoRead; OnError := HandleError; OnConnect := HandleConnect; OnDisconnect := HandleDisconnect; ResetEvent( fConnectionEvent ); fMsgLoopThread := TMsgLoopThread.Create( Self ); Events[0] := fConnectionEvent; Events[1] := fTerminateEvent; waitres := WaitForMultipleObjects( 2, @Events[0], false, TimeOut ); if waitres = WAIT_OBJECT_0 then //fSenderThread := TSenderThread.Create( Self ) else begin fMsgLoopThread.Terminate; SetEvent( fTerminateEvent ); fMsgLoopThread := nil; end; Result := waitres = WAIT_OBJECT_0; end; except Disconnect; Result := false; end end; procedure TWinSockRDOConnection.Disconnect; begin CloseSocket; KillThreads; end; procedure TWinSockRDOConnection.SetQueryServer( const QueryServer : IRDOQueryServer ); var i : integer; begin fQueryServer := QueryServer; for i := 1 to fMaxQueryThreads do fQueryThreads.Add(TQueryThread.Create(Self)); end; function TWinSockRDOConnection.GetMaxQueryThreads : integer; begin Result := fMaxQueryThreads end; procedure TWinSockRDOConnection.SetMaxQueryThreads( MaxQueryThreads : integer ); begin fMaxQueryThreads := MaxQueryThreads end; function TWinSockRDOConnection.Alive : boolean; begin result := fConnected; end; function TWinSockRDOConnection.SendReceive( const QueryText : string; out ErrorCode : integer; TimeOut : integer ) : string; var theQuery : PQueryToSend; Events : array [0..1] of THandle; begin if fConnected then try new(theQuery); try theQuery.Id := GenerateQueryId; theQuery.Text := QueryText; {$IFDEF Logs} Logs.Log( 'Survival', 'Sending and waiting: ' + QueryText ); {$ENDIF} theQuery.WaitForAnsw := true; theQuery.Result := ''; theQuery.Event := CreateEvent( nil, false, false, nil ); try theQuery.ErrorCode := errNoError; try // Add the query to the wait queue fSentQueriesLock.Acquire; try fSentQueries.Add( theQuery ) finally fSentQueriesLock.Release end; // send it to the net try fSocketComponent.Socket.SendText( CallId + Blank + IntToStr( theQuery.Id ) + Blank + theQuery.Text ) except {$IFDEF USELogs} Logs.Log( 'Survival', '(1)- Error sending query' ); // (1) {$ENDIF} fSentQueriesLock.Acquire; try SetEvent(theQuery.Event); fSentQueries.Remove(theQuery); finally fSentQueriesLock.Release; end; end; //fSocketComponent.Socket. Events[0] := theQuery.Event; Events[1] := fTerminateEvent; case WaitForMultipleObjects(2, @Events[0], false, TimeOut) of WAIT_OBJECT_0 : begin Result := theQuery.Result; ErrorCode := theQuery.ErrorCode; {$IFDEF Logs} Logs.Log( 'Survival', 'Result : ' + Result ) {$ENDIF} end; WAIT_OBJECT_0 + 1: begin result := ''; ErrorCode := errQueryTimedOut; end; WAIT_TIMEOUT : begin Result := ''; {$IFDEF USELogs} Logs.Log( 'Survival', DateTimeToStr(Now) + ' <' + fLabel + '> (10)- Query timed out ' + theQuery.Text + ' Time: ' + IntToStr(TimeOut) + ' Thread: ' + IntToStr(GetCurrentThread)); // (10) {$ENDIF} ErrorCode := errQueryTimedOut; end; end; except //fUnsentQueriesLock.Release; ErrorCode := errQueryQueueOverflow; end; finally // remove the query fSentQueriesLock.Acquire; try fSentQueries.Remove(theQuery); CloseHandle(theQuery.Event); finally fSentQueriesLock.Release; end; end; finally dispose(theQuery); end; except ErrorCode := errUnknownError; end; end; procedure TWinSockRDOConnection.Send(const QueryText : string); begin if fConnected then try fSocketComponent.Socket.SendText(CallId + Blank + QueryText); except {$IFDEF USELogs} Logs.Log('Survival', '(10)- Error sending query'); // (10) {$ENDIF} end; end; procedure TWinSockRDOConnection.DoRead( Sender : TObject; Socket : TCustomWinSocket ); function FindQuery( QueryText : string ) : PQueryToSend; var CharIdx : integer; IdDigits : string; QueryId : integer; QueryIdx : integer; SentQueries : integer; Query : PQueryToSend; QueryTextLen : integer; begin IdDigits := ''; CharIdx := 1; SkipSpaces( QueryText, CharIdx ); IdDigits := ReadNumber( QueryText, CharIdx ); try QueryId := StrToInt( IdDigits ); except QueryId := -1 end; if QueryId <> -1 then begin QueryIdx := 0; SentQueries := fSentQueries.Count; while ( QueryIdx < SentQueries ) and ( QueryId <> PQueryToSend( fSentQueries[ QueryIdx ] ).Id ) do inc( QueryIdx ); if QueryIdx < SentQueries then begin Query := fSentQueries[ QueryIdx ]; QueryTextLen := Length( QueryText ); while CharIdx <= QueryTextLen do begin Query.Result := Query.Result + QueryText[ CharIdx ]; inc( CharIdx ); end; Result := Query; end else Result := nil; end else Result := nil; end; var ServicedQuery : PQueryToSend; QueryText : string; QueryToService : PQueryToService; NonWSPCharIdx : integer; begin try fReceivedText := fReceivedText + Socket.ReceiveText; except {$IFDEF USELogs} Logs.Log( 'Survival', '(11)- Error reading from socket' ); // (11) {$ENDIF} end; QueryText := GetQueryText( fReceivedText ); if QueryText <> '' then repeat NonWSPCharIdx := 1; SkipSpaces( QueryText, NonWSPCharIdx ); if QueryText[ NonWSPCharIdx ] = AnswerId then begin Delete( QueryText, NonWSPCharIdx, 1 ); fSentQueriesLock.Acquire; try ServicedQuery := FindQuery( QueryText ); if ServicedQuery <> nil then begin fSentQueries.Remove( ServicedQuery ); ServicedQuery.ErrorCode := errNoError; SetEvent( ServicedQuery.Event ); end else {$IFDEF USELogs} Logs.Log( 'Survival', DateTimeToStr(Now) + ' Ignored result: ' + QueryText + ' in ' + fLabel); {$ENDIF} finally fSentQueriesLock.Release; end; end else if QueryText[ NonWSPCharIdx ] = CallId then begin Delete( QueryText, NonWSPCharIdx, 1 ); if fQueryServer <> nil then begin New( QueryToService ); QueryToService.QueryText := QueryText; fQueryQueueLock.Acquire; try fQueryQueue.Add( QueryToService ); if fQueryQueue.Count = 1 then SetEvent( fQueryWaiting ); finally fQueryQueueLock.Release; end; end else Socket.SendText( AnswerId + CreateErrorMessage( errRDOServerNotInitialized ) ); end; QueryText := GetQueryText( fReceivedText ); until QueryText = ''; end; procedure TWinSockRDOConnection.HandleError( Sender : TObject; Socket : TCustomWinSocket; ErrorEvent : TErrorEvent; var ErrorCode : integer ); var aux : string; begin aux := DateTimeToStr(Now) + ' ' + theLabel + ' Code: ' + IntToStr(ErrorCode); ErrorCode := 0; case ErrorEvent of {$IFDEF USELogs} eeGeneral: Logs.Log( 'Survival', aux + ' General socket error' ); eeSend: Logs.Log( 'Survival', aux + ' Error writing to socket' ); eeReceive: Logs.Log( 'Survival', aux + ' Error reading from socket' ); {$ENDIF} eeConnect: begin ErrorCode := 0; SetEvent( fTerminateEvent ); {$IFDEF USELogs} Logs.Log( 'Survival', aux + ' Cannot connect to Server: ' + fServer + ' Port: ' + IntToStr(fPort)); {$ENDIF} end; eeDisconnect: begin ErrorCode := 0; {$IFDEF USELogs} Logs.Log( 'Survival', aux + ' Error closing connection' ); {$ENDIF} end; {$IFDEF USELogs} eeAccept: Logs.Log( 'Survival', aux + ' Error accepting connection' ); {$ENDIF} end end; procedure TWinSockRDOConnection.HandleConnect( Sender : TObject; Socket : TCustomWinSocket ); begin fConnected := true; SetEvent( fConnectionEvent ); if Assigned( fOnConnect ) then fOnConnect( Self as IRDOConnection ); end; procedure TWinSockRDOConnection.HandleDisconnect( Sender : TObject; Socket : TCustomWinSocket ); begin {$IFDEF USELogs} Logs.Log( 'Survival', 'Start disconnecting: (' + theLabel + ') ' + DateTimeToStr(Now)); {$ENDIF} try fConnected := false; if Assigned( fOnDisconnect ) then fOnDisconnect( Self as IRDOConnection ); KillThreads; finally {$IFDEF USELogs} Logs.Log( 'Survival', 'End disconnecting: (' + theLabel + ') '); {$ENDIF} end; end; initialization LastQueryId := 0; {$IFDEF AutoServer} TAutoObjectFactory.Create( ComServer, TWinSockRDOConnection, Class_WinSockRDOConnection, ciMultiInstance, tmApartment ); {$ENDIF} end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { { Rev 1.5 2/23/2005 6:34:28 PM JPMugaas { New property for displaying permissions ina GUI column. Note that this { should not be used like a CHMOD because permissions are different on { different platforms - you have been warned. } { { Rev 1.4 10/26/2004 9:46:34 PM JPMugaas { Updated refs. } { { Rev 1.3 4/19/2004 5:06:10 PM JPMugaas { Class rework Kudzu wanted. } { { Rev 1.2 2004.02.03 5:45:40 PM czhower { Name changes } { Rev 1.1 10/19/2003 2:27:20 PM DSiders Added localization comments. } { { Rev 1.0 4/7/2003 04:11:38 PM JPMugaas { I mistakenly omitted the OS-9 parser when restructuring. Restored. } unit IdFTPListParseMicrowareOS9; interface uses IdFTPList, IdFTPListParseBase,IdFTPListTypes, IdObjs; type TIdMicrowareOS9FTPListItem = class(TIdOwnerFTPListItem) protected FOS9OwnerPermissions : String; FOS9PublicPermissions : String; FOS9MiscPermissions : String; FOS9Sector: Cardinal; public property OS9OwnerPermissions : String read FOS9OwnerPermissions write FOS9OwnerPermissions; property OS9PublicPermissions : String read FOS9PublicPermissions write FOS9PublicPermissions; property OS9MiscPermissions : String read FOS9MiscPermissions write FOS9MiscPermissions; property OS9Sector : Cardinal read FOS9Sector write FOS9Sector; end; TIdFTPLPMicrowareOS9 = class(TIdFTPListBaseHeader) protected class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override; class function IsHeader(const AData: String): Boolean; override; class function ParseLine(const AItem : TIdFTPListItem; const APath : String=''): Boolean; override; public class function GetIdent : String; override; end; implementation uses IdGlobal, IdFTPCommon, IdGlobalProtocols, IdStrings, IdSys; const MICROWARE_OS9 = 'MicroWare OS-9'; {do not localize} { TIdFTPLPMicrowareOS9 } class function TIdFTPLPMicrowareOS9.GetIdent: String; begin Result := MICROWARE_OS9; end; class function TIdFTPLPMicrowareOS9.IsHeader(const AData: String): Boolean; var LWrds : TIdStrings; {The banner is usually something like this: Directory of . 11:44:44 Owner Last modified Attributes Sector Bytecount Name ––––––– ––––––––––––– –––––––––– –––––– ––––––––– –––– } begin LWrds := TIdStringList.Create; try Result := False; SplitColumns(AData,LWrds); if (LWrds.Count > 2) then begin Result := (LWrds[0] = 'Directory') and (LWrds[1] = 'of') and {do not localize} (PatternsInStr(':',LWrds[LWrds.Count - 1])=2); if Result = False then begin Result := (LWrds.Count = 7) and (LWrds[0] = 'Owner') and (LWrds[1] = 'Last') and (LWrds[2] = 'modified') and {do not localize} (LWrds[3] = 'Attributes') and (LWrds[4] = 'Sector') and (LWrds[5] = 'Bytecount') and {do not localize} (LWrds[6] = 'Name'); {do not localize} end; end; finally Sys.FreeAndNil(LWrds); end; end; class function TIdFTPLPMicrowareOS9.MakeNewItem( AOwner: TIdFTPListItems): TIdFTPListItem; begin Result := TIdMicrowareOS9FTPListItem.Create(AOwner); end; class function TIdFTPLPMicrowareOS9.ParseLine(const AItem: TIdFTPListItem; const APath: String): Boolean; var LBuf : String; LPerms : String; LI : TIdMicrowareOS9FTPListItem; begin LI := AItem as TIdMicrowareOS9FTPListItem; LBuf := Sys.TrimLeft(LI.Data); //Owner LI.OwnerName := Fetch(LBuf); LBuf := Sys.TrimLeft(LBuf); //Modified date LI.ModifiedDate := DateYYMMDD(Fetch(LBuf)); LBuf := Sys.TrimLeft(LBuf); //not sure what this number is Fetch(LBuf); LBuf := Sys.TrimLeft(LBuf); //permissions LPerms := Fetch(LBuf); LBuf := Sys.TrimLeft(LBuf); if Copy(LPerms,1,1)='d' then begin LI.ItemType := ditDirectory; end else begin LI.ItemType := ditFile; end; LI.PermissionDisplay := LPerms; LI.OS9MiscPermissions := Copy(LPerms,1,2); LI.OS9PublicPermissions := Copy(LPerms,3,3); LI.OS9OwnerPermissions := Copy(LPerms,5,3); //sector LI.OS9Sector := Sys.StrToInt64('$'+Fetch(LBuf),0); LBuf := Sys.TrimLeft(LBuf); //size not sure if in decimal or hexidecimal LI.Size := Sys.StrToInt64(Fetch(LBuf),0); //name LI.FileName := LBuf; Result := True; end; initialization IdFTPListParseBase.RegisterFTPListParser(TIdFTPLPMicrowareOS9); end.
unit fMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, StdCtrls, ComCtrls, ActnList, Panel, StrUtils; const _SUF_OBJECT = '.opnl'; _SUF_SERVER = '.spnl'; type TF_Main = class(TForm) MM_Main: TMainMenu; MI_Help: TMenuItem; MI_About: TMenuItem; MI_File: TMenuItem; MI_FileOpen: TMenuItem; N1: TMenuItem; MI_AppExit: TMenuItem; OD_OpenOpnl: TOpenDialog; SD_SaveSpnl: TSaveDialog; GB_InputFiles: TGroupBox; LV_InputFiles: TListView; B_FileAdd: TButton; B_FileClose: TButton; GB_Check: TGroupBox; B_LoadAndCheck: TButton; AL_Main: TActionList; F_FileOpen: TAction; A_FileClose: TAction; A_Check: TAction; SB_Main: TStatusBar; GB_Export: TGroupBox; Label1: TLabel; E_OutputFileName: TEdit; B_OutputProchazet: TButton; B_Export: TButton; A_Export: TAction; procedure MI_AboutClick(Sender: TObject); procedure LV_InputFilesChange(Sender: TObject; Item: TListItem; Change: TItemChange); procedure F_FileOpenExecute(Sender: TObject); procedure A_FileCloseExecute(Sender: TObject); procedure A_CheckExecute(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure B_OutputProchazetClick(Sender: TObject); procedure A_ExportExecute(Sender: TObject); procedure MI_AppExitClick(Sender: TObject); procedure LV_InputFilesDblClick(Sender: TObject); private { Private declarations } public Relief:TRelief; procedure AddFile(filename:string); end; var F_Main: TF_Main; implementation {$R *.dfm} uses Verze, fDataCheck; procedure TF_Main.A_CheckExecute(Sender: TObject); var return,i:Integer; fnames:TStrings; begin fnames := TStringList.Create(); fnames.Clear(); for i := 0 to Self.LV_InputFiles.Items.Count-1 do fnames.Add(Self.LV_InputFiles.Items.Item[i].Caption); //nacteni souboru return := Self.Relief.FilesLoad(fnames); fnames.Free(); if (return <> 0) then begin Application.MessageBox(PChar('Chyba při načítání souborů reliéfů: chyba '+IntToStr(return)+#13#10+'Opravte chyby v souboru panelu a načtětě soubor znovu!'),'Chyba',MB_OK OR MB_ICONERROR); Exit; end; //spojeni dat Self.Relief.Merge(); //kontrola dat fnames := Self.Relief.CheckValid(); F_DataCheck.OpenForm(fnames); end;//procedure procedure TF_Main.A_ExportExecute(Sender: TObject); var return:Byte; begin return := Self.Relief.ExportData(Self.E_OutputFileName.Text); if (return = 0) then begin Application.MessageBox(PChar('Export proběhl úspěšně'+#13#10+'Vytvořen soubor '+Self.E_OutputFileName.Text),'Info',MB_OK OR MB_ICONINFORMATION); end; if (return = 1) then begin Application.MessageBox(PChar('Export se nezdařil !'+#13#10+'Výstupní soubor '+Self.E_OutputFileName.Text+' nelze zapsat'),'Varování',MB_OK OR MB_ICONWARNING); end; end;//procedure procedure TF_Main.A_FileCloseExecute(Sender: TObject); begin Self.LV_InputFiles.Items.Delete(Self.LV_InputFiles.ItemIndex); if (Self.LV_InputFiles.Items.Count = 0) then Self.A_Check.Enabled := false; Self.A_Export.Enabled := false; end;//procedure procedure TF_Main.B_OutputProchazetClick(Sender: TObject); begin if (Self.SD_SaveSpnl.Execute(Self.Handle)) then begin Self.E_OutputFileName.Text := Self.SD_SaveSpnl.FileName; if (RightStr(Self.E_OutputFileName.Text,5) <> '.spnl') then Self.E_OutputFileName.Text := Self.E_OutputFileName.Text + '.spnl'; Self.A_Export.Enabled := true; end; end;//procedure procedure TF_Main.FormCreate(Sender: TObject); begin Self.Relief := TRelief.Create(); end; procedure TF_Main.FormDestroy(Sender: TObject); begin FreeAndNil(Self.Relief); end; procedure TF_Main.F_FileOpenExecute(Sender: TObject); var i:Integer; begin if (Self.OD_OpenOpnl.Execute(Self.Handle)) then begin for i := 0 to Self.OD_OpenOpnl.Files.Count-1 do Self.AddFile(Self.OD_OpenOpnl.Files[i]); end;//if end;//procedure procedure TF_Main.LV_InputFilesChange(Sender: TObject; Item: TListItem; Change: TItemChange); begin if ((Sender as TListView).Selected <> nil) then Self.A_FileClose.Enabled := true else Self.A_FileClose.Enabled := false; end;//procedure procedure TF_Main.LV_InputFilesDblClick(Sender: TObject); begin if ((Sender as TListView).Selected = nil) then begin Self.F_FileOpenExecute(self); end else begin Self.A_FileCloseExecute(self); end; end; procedure TF_Main.MI_AboutClick(Sender: TObject); begin Application.MessageBox(PChar('hJOPmerger'+#13#10+'Verze: '+GetVer(Application.ExeName)+#13#10+'Vytvořil Jan Horáček (c) 2013-2017 pro KMŽ Brno I'),'Info',MB_OK OR MB_ICONINFORMATION); end; procedure TF_Main.MI_AppExitClick(Sender: TObject); begin Self.Close(); end;//procedure procedure TF_Main.AddFile(filename:string); var LI:TListItem; begin LI := Self.LV_InputFiles.Items.Add; LI.Caption := filename; Self.A_Check.Enabled := true; if (Self.A_Export.Enabled) then Self.A_Export.Enabled := false; end;//procedure end.//unit
program main; {$I express.inc} uses Classes, SysUtils, CustApp, Math, Windows, xpr.utils, xpr.bytecode, xpr.AST, xpr.parser, xpr.lexer, xpr.interpreter, xpr.errors; type TMyApplication = class(TCustomApplication) protected procedure DoRun; override; public constructor Create(TheOwner: TComponent); override; destructor Destroy; override; end; function LoadFileContents(fileName:String): String; var f:TStringList; begin if FileExists(fileName) then begin f := TStringList.Create(); f.LoadFromFile(fileName); Result := f.Text; f.Free(); end else raise NotFoundError.CreateFmt('File `%s` not found!', [fileName]); end; procedure TestExecute2(filename:String); var script:String; node:TBaseNode; code:TByteCode; CodeRunner:TInterpreter; v:Int32; t:Double; begin script := LoadFileContents(filename); try t := marktime(); node := Parse(Tokenize(script)); code := CompileAST(node); WriteFancy('[LWHITE]Compiling took: '+ Format('%3f ms', [marktime() - t])); except on E:SyntaxError do begin WriteLn(); WriteFancy('[LRED]Compiling failed with Error: '+#13#10+' '+E.Message); WriteLn(); Exit; end; end; v := StrToIntDef(ParamStr(2), 50); if Length(code.Code) <= v then begin WriteLn(); WriteFancy('[GRAY]======================================'); WriteFancy(code.ToString); WriteFancy('[GRAY]======================================'); WriteLn(); end else begin WriteLn(); WriteFancy('[RED]Code is too long to print: '+ IntToStr(Length(Code.Code)) +' operations'); WriteLn(); end; WriteFancy('[LWHITE]Executing..: '); WriteLn(); CodeRunner := TInterpreter.Create(code); try t := marktime(); CodeRunner.ExecuteSafe; t := marktime() - t; except on E:RuntimeError do begin WriteLn(); WriteFancy('[LRED]Execution failed with Error: '+#13#10+' '+E.Message); WriteLn(); CodeRunner.Free; Exit; end; end; WriteLn(); WriteFancy('[LWHITE]Executed in: '+ Format('%3f ms', [t])); WriteLn(); if CodeRunner.Frame.StackPos >= 0 then begin WriteFancy('[RED]There are variables on the stack:'); WriteFancy(' '+ CodeRunner.Frame.StackToString); end; CodeRunner.Free; end; procedure TMyApplication.DoRun; begin if ParamStr(1) = '' then begin TestExecute2('tests/quicksort.xpr'); WriteLn(); WriteFancy('[GRAY]======================================'); WriteLn(); WriteFancy('[LRED]Recieved no arguments, executed a test-script.'); end; try TestExecute2(ParamStr(1)); except on E:NotFoundError do begin if ParamStr(1) <> '' then WriteFancy('[RED]' + E.Message); WriteLn(Format('Usage: main.exe path/to/script.xpr [bc_max_print_size]', [ParamStr(0)])); end; end; while True do Sleep(500); Terminate; end; constructor TMyApplication.Create(TheOwner: TComponent); begin inherited Create(TheOwner); StopOnException := True; end; destructor TMyApplication.Destroy; begin inherited Destroy; end; var Application: TMyApplication; begin Application := TMyApplication.Create(nil); Application.Title := 'My Application'; Application.Run; Application.Free; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpDerPrintableString; {$I ..\Include\CryptoLib.inc} interface uses Classes, SysUtils, StrUtils, ClpDerStringBase, ClpAsn1Tags, ClpAsn1OctetString, ClpAsn1Object, ClpIProxiedInterface, ClpDerOutputStream, ClpCryptoLibTypes, ClpIAsn1TaggedObject, ClpIDerPrintableString, ClpConverters; resourcestring SIllegalObject = 'Illegal Object in GetInstance: %s'; SIllegalCharacters = 'String Contains Illegal Characters "str"'; SStrNil = '"str"'; type /// <summary> /// Der PrintableString object. /// </summary> TDerPrintableString = class(TDerStringBase, IDerPrintableString) strict private var FStr: String; function GetStr: String; inline; strict protected function Asn1Equals(const asn1Object: IAsn1Object): Boolean; override; public /// <summary> /// basic constructor - with bytes. /// </summary> constructor Create(const Str: TCryptoLibByteArray); overload; /// <summary> /// basic constructor - without validation. /// </summary> constructor Create(const Str: String); overload; /// <summary> /// Constructor with optional validation. /// </summary> /// <param name="Str"> /// the base string to wrap. /// </param> /// <param name="validate"> /// whether or not to check the string. /// </param> /// <exception cref="ClpCryptoLibTypes|EArgumentCryptoLibException"> /// if validate is true and the string contains characters that should /// not be in an PrintableString. /// </exception> constructor Create(const Str: String; validate: Boolean); overload; function GetString(): String; override; function GetOctets(): TCryptoLibByteArray; inline; procedure Encode(const derOut: TStream); override; property Str: String read GetStr; /// <summary> /// return a printable string from the passed in object. /// </summary> /// <param name="obj"> /// a DerPrintableString or an object that can be converted into one. /// </param> /// <returns> /// return a DerPrintableString instance, or null. /// </returns> /// <exception cref="ClpCryptoLibTypes|EArgumentCryptoLibException"> /// if the object cannot be converted. /// </exception> class function GetInstance(const obj: TObject): IDerPrintableString; overload; static; inline; /// <summary> /// return a Printable string from a tagged object. /// </summary> /// <param name="obj"> /// the tagged object holding the object we want /// </param> /// <param name="isExplicit"> /// true if the object is meant to be explicitly tagged false otherwise. /// </param> /// <exception cref="ClpCryptoLibTypes|EArgumentCryptoLibException"> /// if the tagged object cannot be converted. /// </exception> class function GetInstance(const obj: IAsn1TaggedObject; isExplicit: Boolean): IDerPrintableString; overload; static; inline; /// <summary> /// return true if the passed in String can be represented without loss /// as a PrintableString, false otherwise. /// </summary> /// <param name="Str"> /// string to validate. /// </param> /// <returns> /// return true if in printable set, false otherwise. /// </returns> class function IsPrintableString(const Str: String): Boolean; static; inline; end; implementation { TDerPrintableString } function TDerPrintableString.GetStr: String; begin result := FStr; end; function TDerPrintableString.GetString: String; begin result := Str; end; function TDerPrintableString.GetOctets: TCryptoLibByteArray; begin result := TConverters.ConvertStringToBytes(Str, TEncoding.ASCII); end; class function TDerPrintableString.IsPrintableString(const Str: String) : Boolean; var ch: Char; begin for ch in Str do begin if ((Ord(ch) > $007F)) then begin result := false; Exit; end; // if (char.IsLetterOrDigit(ch)) if CharInSet(ch, ['a' .. 'z', 'A' .. 'Z', '0' .. '9']) then begin continue; end; case IndexStr(UnicodeString(ch), [''' ''', '\', '(', ')', '+', '-', '.', ':', '=', '?', '/', ',']) of 0 .. 11: begin continue; end; end; result := false; Exit; end; result := true; end; function TDerPrintableString.Asn1Equals(const asn1Object: IAsn1Object): Boolean; var other: IDerPrintableString; begin if (not Supports(asn1Object, IDerPrintableString, other)) then begin result := false; Exit; end; result := Str = other.Str; end; constructor TDerPrintableString.Create(const Str: TCryptoLibByteArray); begin Create(TConverters.ConvertBytesToString(Str, TEncoding.ASCII), false); end; constructor TDerPrintableString.Create(const Str: String); begin Create(Str, false); end; constructor TDerPrintableString.Create(const Str: String; validate: Boolean); begin Inherited Create(); if (Str = '') then begin raise EArgumentNilCryptoLibException.CreateRes(@SStrNil); end; if (validate and (not IsPrintableString(Str))) then begin raise EArgumentCryptoLibException.CreateRes(@SIllegalCharacters); end; FStr := Str; end; procedure TDerPrintableString.Encode(const derOut: TStream); begin (derOut as TDerOutputStream).WriteEncoded(TAsn1Tags.PrintableString, GetOctets()); end; class function TDerPrintableString.GetInstance(const obj: TObject) : IDerPrintableString; begin if ((obj = Nil) or (obj is TDerPrintableString)) then begin result := obj as TDerPrintableString; Exit; end; raise EArgumentCryptoLibException.CreateResFmt(@SIllegalObject, [obj.ClassName]); end; class function TDerPrintableString.GetInstance(const obj: IAsn1TaggedObject; isExplicit: Boolean): IDerPrintableString; var o: IAsn1Object; begin o := obj.GetObject(); if ((isExplicit) or (Supports(o, IDerPrintableString))) then begin result := GetInstance(o as TAsn1Object); Exit; end; result := TDerPrintableString.Create (TAsn1OctetString.GetInstance(o as TAsn1Object).GetOctets()); end; end.
unit uEnumerador; interface const CRegistroNaoEncontrado: string = 'Registro não Encontrado.'; CRegistroInativo: string = 'Registro Inativo.'; DataEmBranco: string = '/ /'; HoraEmBranco: string = ':'; CDisplayFormatCliente: string = '000000'; CDisplayFormatCodigo: string = '0000'; QUEBRA_LINHA = #13 + #10; CChamadoPrograma: Integer = 1; CVisitaPrograma: Integer = 2; CSolicitacaoPrograma: Integer = 3; CVersaoPrograma: Integer = 4; CBaseConhPrograma: Integer = 6; CRevendaPrograma: Integer = 100; CProdutoPrograma: Integer = 101; CModuloPrograma: Integer = 102; CClientePrograma: Integer = 103; CClienteEmailPrograma: Integer = 1031; CClienteModuloPrograma: Integer = 1033; CUsuarioPrograma: Integer = 104; CDepartamentoPrograma: Integer = 105; CDepartamentoAcessoPrograma: Integer = 1051; CTipoPrograma: Integer = 106; CStatusPrograma: Integer = 107; CClienteEspPrograma: Integer = 108; CParametrosPrograma: integer = 109; CContaEmailPrograma: Integer = 110; CAtividadePrograma: Integer = 111; CAgendamentoPrograma: Integer = 112; CProspectPrograma: Integer = 113; COrcamentoPrograma: Integer = 114; CFormaPagto: Integer = 115; CObservacao: Integer = 116; CModeloRelatorio: Integer = 117; CRamal: Integer = 118; CRecadoPrograma: Integer = 119; CEscala: Integer = 120; CCidade: Integer = 121; CLicenca: Integer = 122; CFeriado: Integer = 123; CCategoriaPrograma: Integer = 124; cTabelaPreco: Integer = 125; type TOperacao = (opIncluir, opEditar, opNavegar); TEnumPrograma = (prTodos = 0, prChamado = 1, prVisita = 2, prSolicitacao = 3, prVersao = 4, prQualidade = 5, prBase = 6, prAtividade = 7, prAgendamento = 8, prOrcamento = 9, prOrcamentoNAprovado = 91, prRecado = 10, prTabelaPreco = 11); TEnumSolicitacao = (solAnalise, solOcorrGeral, solOcorrTecnica, solOcorrRegra, solTodos); TEnumChamadoAtividade = (caChamado = 1, caAtividade = 2); TEnumTipoPrograma = (tpChamado = 1, tpAtividade = 111, tpSolicitacao = 3); TEnumAgendamento = (ageAbertura, ageCancelamento, ageReagendamento, ageEncerrado); implementation end.
unit Tox; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls; type TfTox = class(TForm) procedure FormPaint(Sender: TObject); procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure FormClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } MX, MY, MM: Integer; BB: TBitmap; public { Public declarations } end; var fTox: TfTox; implementation uses New, Main, uUtils, uImage2; {$R *.dfm} procedure TfTox.FormPaint(Sender: TObject); begin Canvas.Draw(0, 0, BB); end; procedure TfTox.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if (X >= 0) and (X <= (BB.Width)) then MX := X div 32; if (Y >= 0) and (Y <= BB.Height) then MY := Y div 32; MM := (MY * (BB.Width div 32)) + MX; end; procedure TfTox.FormClick(Sender: TObject); begin if (MM < 0) then Exit; fNew.DCC := MM; fNew.Image1.Canvas.Draw(0, 0, GetImage(Path + fMain.DungeonTileset, MM)); ModalResult := mrOK; end; procedure TfTox.FormShow(Sender: TObject); begin with fMain do BB.LoadFromFile(Path + DungeonTileset); ClientWidth := BB.Width; ClientHeight := BB.Height; Canvas.Draw(0, 0, BB); end; procedure TfTox.FormCreate(Sender: TObject); begin BB := TBitmap.Create; end; procedure TfTox.FormDestroy(Sender: TObject); begin BB.Free; end; end.
// ********************************************************************** // // Copyright (c) 2001 MT Tools. // // All Rights Reserved // // MT_DORB is based in part on the product DORB, // written by Shadrin Victor // // See Readme.txt for contact information // // ********************************************************************** unit disp; interface {$I dorb.inc} {$IFNDEF USELIB} uses orbtypes,orb_int,orb,{$IFDEF WIN32}WinSock{$ENDIF}{$IFDEF LINUX}Libc{$ENDIF}, Classes,disp_int,SysUtils,osthread; type {$IFDEF WIN32} TSocketPair = packed array[0..1] of TSocket; {$ENDIF} TSelectDispatcher = class(TInterfacedObject,ISelectDispatcher,IORBDispatcher) private {** list of event records } FEventList : TList; FEventListMutex: TMutex; FLocks: integer; FModified : Boolean; FIntRead, FIntWrite: TSocket; FPendingRead, FInBlockingSelect, FInterrupt: boolean; private procedure createFdPair(var fds: TSocketPair); procedure clearInterruptFd(); procedure setInterruptFd(); function IsInterrupted(): boolean; protected procedure run(infinite: Boolean); procedure handle_fevents(rset,wset,xset: TFDSet); procedure update_fevents(var rset,wset,xset: TFDSet; var nfds: integer); procedure interrupt_dispatch(); function dispatch_one_event(const timeout: long): boolean; procedure socketevent(const cb: IORBDispCallback; fd: TSocket;evt: TDispEvent); procedure timeevent(const cb: IORBDispCallback; timeout: longint); procedure move(const disp: IORBDispatcher); procedure remove(const cb: IORBDispCallback;evt: TDispEvent); function idle(): Boolean; procedure block(b: boolean); function isblocking: boolean; public constructor CreateEx(); destructor Destroy(); override; end; PFileEvent = ^TFileEvent; TFileEvent = record EventType: TDispEvent; Desc : TSocket; Cb : IORBDispCallBack; Deleted : Boolean; end; implementation uses throw, except_int; var selectDispatcherIsBlocking: boolean; //************************************************************** // TSelectDispatcher //************************************************************** constructor TSelectDispatcher.CreateEx(); var fds: TSocketPair; {$IFDEF WIN32} arg: integer; {$ENDIF} begin inherited Create(); FLocks := 0; FModified := false; FEventList := TList.Create; FEventListMutex := TMutex.Create(); FPendingRead := false; FInBlockingSelect := false; FInterrupt := false; CreateFdPair(fds); FIntRead := fds[0]; // Set the fd to be non-blocking {$IFDEF WIN32} arg := 1; ioctlsocket(FIntRead, FIONBIO, arg); {$ENDIF} {$IFDEF LINUX} fcntl(FIntRead, F_SETFL, O_NONBLOCK); {$ENDIF} FIntWrite := fds[1]; end; destructor TSelectDispatcher.Destroy; var i : integer; begin for i := 0 to Pred(FEventList.count) do begin PFileEvent(FEventList[i])^.Cb := nil; FreeMem(PFileEvent(FEventList[i])); end; FreeAndNil(FEventList); FreeAndNil(FEventListMutex); {$IFDEF WIN32} closesocket(FIntWrite); closesocket(FIntRead); {$ENDIF} {$IFDEF LINUX} __close(FIntWrite); __close(FIntRead); {$ENDIF} inherited Destroy(); end; {** Selects state of specified sockets and call handle_fevents on success. **} procedure TSelectDispatcher.run(infinite: Boolean); var rset,wset,xset : TFDSet; res : longint; nfds: integer; begin while true do begin // The filedescriptor sets parameter for select() update_fevents(rset, wset, xset, nfds); FInBlockingSelect := true; res := select(nfds, @rset, nil, nil, nil); FInBlockingSelect := false; if res = -1 then begin if IsInterrupted() then Continue; end; // Evaluate file descriptor sets if not interrupted if (res > 0) and not FInterrupt then handle_fevents(rset,wset,xset); if not infinite then break; end; end; procedure TSelectDispatcher.remove(const cb: IORBDispCallback;evt: TDispEvent); var i : integer; sync: ISynchronized; begin sync := TSynchronized.Create(FEventListMutex); setInterruptFd(); for i := Pred(FEventList.Count) downto 0 do if ((PFileEvent(FEventList[i])^.EventType = evt) or (evt = _All)) and (PFileEvent(FEventList[i])^.cb = cb) then begin PFileEvent(FEventList[i])^.Cb := nil; FreeMem(PFileEvent(FEventList[i])); FEventList.Delete(i); end; end; procedure TSelectDispatcher.socketevent(const cb: IORBDispCallback; fd: TSocket; evt: TDispEvent); var event : PFileEvent; sync: ISynchronized; begin event := AllocMem(sizeof(TFileEvent)); event^.EventType := evt; event^.Desc := fd; event^.cb := cb; event^.deleted := false; sync := TSynchronized.Create(FEventListMutex); setInterruptFd(); FEventList.add(event); end; function TSelectDispatcher.idle: Boolean; var rset,wset,xset : TFDSet; res : longint; nfds: integer; time : TimeVal; begin result := false; if FEventList.Count > 0 then begin // The filedescriptor sets parameter for select() update_fevents(rset, wset, xset, nfds); time.tv_sec := 0; time.tv_usec := 0; res := select(nfds, @rset, @wset, @xset, @time); if res > 0 then exit; end; result := true; end; procedure TSelectDispatcher.move(const disp: IORBDispatcher); var sync: ISynchronized; i : integer; begin sync := TSynchronized.Create(FEventListMutex); for i := 0 to Pred(FEventList.Count) do with PFileEvent(FEventList[i])^ do if not deleted then begin Cb.callback(disp,_Moved); disp.socketevent(Cb,Desc,EventType); end; for i := 0 to Pred(FEventList.count) do begin PFileEvent(FEventList[i])^.Cb := nil; FreeMem(PFileEvent(FEventList[i])); end; end; procedure TSelectDispatcher.timeevent(const cb: IORBDispCallback; timeout: longint); begin assert(false,'not implemented'); end; procedure TSelectDispatcher.update_fevents(var rset,wset,xset: TFDSet; var nfds: integer); var i : integer; sync: ISynchronized; begin sync := TSynchronized.Create(FEventListMutex); FModified := true; FD_ZERO(rset); FD_ZERO(wset); FD_ZERO(xset); nfds := FIntRead + 1; // Clear any pending interrupts clearInterruptFd(); // Add the interrupt read file descriptor FD_SET(FIntRead, rset); // Add all event handlers for i := 0 to Pred(FEventList.Count) do with PFileEvent(FEventList[i])^ do if not deleted then begin case EventType of _Read: FD_SET(Desc,rset); _Write: FD_SET(Desc,wset); _Except: FD_SET(Desc,xset); else assert(false,'not implemented'); end; if Desc >= nfds then nfds := Desc + 1; end; end; {** Passes trough event list and executes callback procedures for specified sockets **} procedure TSelectDispatcher.handle_fevents(rset,wset,xset: TFDSet); var i : integer; sync: ISynchronized; tmpEventList: TList; event : PFileEvent; begin // Work on a partial copy of FEventList, so that other // threads can register or unregister event handler while this // operation is running. This also ensures that the event handler // is not released while handle_fEvents() is executing. tmpEventList := TList.Create; try // SYNCHRONIZED sync := TSynchronized.Create(FEventListMutex); for i := 0 to FEventList.count-1 do if not PFileEvent(FEventList[i])^.Deleted then begin event := AllocMem(sizeof(TFileEvent)); TFileEvent(event^) := TFileEvent(PFileEvent(FEventList[i])^); tmpEventList.Add(event); end; sync := nil; for i := 0 to tmpEventList.count-1 do with PFileEvent(tmpEventList[i])^ do case EventType of _Read : if FD_ISSET(Desc,rset) then begin CB.callback(self,_Read); end; _Write : if FD_ISSET(Desc,wset) then CB.callback(self,_Write); _Except : if FD_ISSET(Desc,xset) then CB.callback(self,_Except); else assert(false,'not implemented'); end; finally for i := 0 to tmpEventList.count-1 do begin PFileEvent(tmpEventList[i])^.Cb := nil; FreeMem(PFileEvent(tmpEventList[i]), sizeof(TFileEvent)); end; FreeAndNil(tmpEventList); end; { try/finally } end; procedure TSelectDispatcher.block(b: boolean); begin selectDispatcherIsBlocking := b; end; function TSelectDispatcher.isblocking: boolean; begin result := selectDispatcherIsBlocking; end; procedure TSelectDispatcher.createFdPair(var fds: TSocketPair); {$IFDEF WIN32} var s: TSocket; no, len, res: integer; addr: TSockAddrIn; function CreateSocket(): TSocket; begin result := socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); end; {$ENDIF} begin {$IFDEF WIN32} s := -1; fds[0] := -1; fds[1] := -1; try // Create a server socket s := CreateSocket(); if s = -1 then dorb_throw(st_COMM_FAILURE, MinorSocket, COMPLETED_NO); // Set TCP_NODELAY option no := 1; if setsockopt(s, IPPROTO_TCP, TCP_NODELAY, PAnsiChar(@no), SizeOf(no)) = -1 then dorb_throw(st_COMM_FAILURE, MinorSetsockopt, COMPLETED_NO); // Get the address FillChar(addr, SizeOf(TSockAddrIn), 0); with addr do begin sin_family := AF_INET; sin_addr.s_addr := inet_addr('127.0.0.1'); sin_port := 0; end; { with } // Bind if bind(s, addr, sizeof(addr)) = -1 then dorb_throw(st_COMM_FAILURE, MinorBind, COMPLETED_NO); // Listen on socket if listen(s, 1) = -1 then dorb_throw(st_COMM_FAILURE, MinorListen, COMPLETED_NO); // Find out the port to which this socket is connected to len := SizeOf(addr); res := getsockname(s, addr, len); assert(res <> -1); // Create the client socket fds[0] := CreateSocket(); if fds[0] = -1 then dorb_throw(st_COMM_FAILURE, MinorSocket, COMPLETED_NO); // Set TCP_NODELAY option no := 1; if setsockopt(fds[0], IPPROTO_TCP, TCP_NODELAY, PAnsiChar(@no), SizeOf(no)) = -1 then dorb_throw(st_COMM_FAILURE, MinorSetsockopt, COMPLETED_NO); // Connect to the server socket if connect(fds[0], addr, sizeof(addr)) = -1 then dorb_throw(st_COMM_FAILURE, MinorConnect, COMPLETED_NO); // Accept the connection FillChar(addr, SizeOf(TSockAddrIn), 0); repeat len := SizeOf(addr); fds[1] := accept(s, @addr, @len); if fds[1] = -1 then begin if IsInterrupted() then continue; dorb_throw(st_COMM_FAILURE, MinorAccept, COMPLETED_NO); end; until fds[1] <> -1; // Set TCP_NODELAY option no := 1; if setsockopt(fds[1], IPPROTO_TCP, TCP_NODELAY, PAnsiChar(@no), SizeOf(no)) = -1 then dorb_throw(st_COMM_FAILURE, MinorSetsockopt, COMPLETED_NO); except if s <> -1 then closesocket(s); if fds[0] <> -1 then closesocket(fds[0]); if fds[1] <> -1 then closesocket(fds[1]); raise; end; { try/except } closesocket(s); {$ENDIF} {$IFDEF LINUX} if pipe(@fds) <> 0 then dorb_throw(st_COMM_FAILURE, MinorPipe, COMPLETED_NO); {$ENDIF} end; procedure TSelectDispatcher.clearInterruptFd; var c: char; begin if FPendingRead then begin // This should be set to false before reading the data FPendingRead := false; // Read all the data off the read fd, Note under UNIX // since a pipe is used recv cannot be used. {$IFDEF MSWINDOWS} while recv(FIntRead, c, 1, 0) = 1 do; {$ELSE} while __read(FIntRead, c, 1) = 1 do; {$ENDIF} end; end; procedure TSelectDispatcher.setInterruptFd; var c: char; begin // Only set the interrupt file descriptor if the reactor is in a // blocking select call. if FInBlockingSelect then begin // Write one byte down the interrupt fd. Note under UNIX since // a pipe is used send cannot be used. c := chr(0); {$IFDEF MSWINDOWS} send(FIntWrite, c, 1, 0); {$ELSE} __write(FIntWrite, c, 1); {$ENDIF} // The FPendingRead flag should be set to true after writing // the data FPendingRead := true; end; end; procedure TSelectDispatcher.interrupt_dispatch; begin // Don't interrupt twice if FInterrupt then Exit; // Set the interrupt flag FInterrupt := true; setInterruptFd(); end; function TSelectDispatcher.IsInterrupted: boolean; begin {$IFDEF WIN32} result := WSAGetLastError() = WSAEINTR; {$ENDIF} {$IFDEF LINUX} result := errno() = EINTR; {$ENDIF} end; function TSelectDispatcher.dispatch_one_event( const timeout: long): boolean; var rset,wset,xset : TFDSet; nfds, res: integer; tout: TTimeVal; begin // The filedescriptor sets and the nfds parameter for select() update_fevents(rset, wset, xset, nfds); // Do select while true do begin if timeout >= 0 then begin tout.tv_sec := timeout div 1000; tout.tv_usec := (timeout - tout.tv_sec * 1000) * 1000; FInBlockingSelect := true; res := select(nfds, @rset, @wset, nil, @tout); FInBlockingSelect := false; end else res := select(nfds, @rset, @wset, nil, nil); if (res = 0) then begin Assert(timeout >= 0); result := false; Exit; end; // Select error? if (res = -1) then begin // If select was interrupted as a result of a signal then // continue if IsInterrupted() then Continue; dorb_throw(st_COMM_FAILURE, MinorSelect, COMPLETED_NO); end; Break; end; // Evaluate file descriptor sets handle_fevents(rset, wset, xset); result := true; end; initialization {$IFDEF HAVE_THREADS} selectDispatcherIsBlocking := false; {$ELSE} selectDispatcherIsBlocking := false; {$ENDIF} {$ELSE} implementation {$ENDIF} end.
{ *************************************************************************** Copyright (c) 2015-2021 Kike Pérez Unit : Quick.AutoMapper Description : Auto Mapper object properties Author : Kike Pérez Version : 1.5 Created : 25/08/2018 Modified : 07/04/2021 This file is part of QuickLib: https://github.com/exilon/QuickLib *************************************************************************** Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************** } unit Quick.AutoMapper; {$i QuickLib.inc} interface uses SysUtils, Generics.Collections, typinfo, Quick.Value, {$IFDEF FPC} Variants, {$ENDIF} RTTI, Quick.RTTI.Utils; //enable use of property paths (like namespaces) in custom mapping {$DEFINE PROPERTYPATH_MODE} type {$IFNDEF FPC} TFlexValue = TValue; {$ELSE} TFlexValue = variant; {$ENDIF} {$IFNDEF FPC} TMappingProc<TClass1> = reference to procedure(const aSrcObj : TClass1; const aTargetName : string; out Value : TFlexValue); TAfterMappingProc<TClass1,TClass2> = reference to procedure(const aSrcObj : TClass1; aTgtObj : TClass2); {$ELSE} TMappingProc<TObject> = procedure(const aSrcObj : TObject; const aTargetName : string; out Value : TFlexValue) of object; TAfterMappingProc<TClass1,TClass2> = procedure(const aSrcObj : TClass1; aTgtObj : TClass2) of object; {$ENDIF} TCustomMapping = class private fMapDictionary : TDictionary<string,string>; public constructor Create; destructor Destroy; override; procedure AddMap(const aName, aMapName : string); function GetMap(const aName : string; out vMapName : string) : Boolean; function Count : Integer; end; TObjMapper = class public class procedure Map(aSrcObj : TObject; aTgtObj : TObject; aCustomMapping: TCustomMapping = nil); overload; {$IFNDEF FPC} class procedure Map<Tm>(aSrcObj : TObject; aTgtObj : TObject; aDoMappingProc : TMappingProc<Tm>; aCustomMapping: TCustomMapping = nil); overload; {$ELSE} class procedure Map(aSrcObj : TObject; aTgtObj : TObject; aDoMappingProc : TMappingProc<TObject>; aCustomMapping: TCustomMapping = nil); overload; {$ENDIF} end; TListMapper = class public class procedure Map(aSrcList, aTgtList: TObject; aCustomMapping: TCustomMapping); end; TObjListMapper = class public class procedure Map(aSrcObjList : TObject; aTgtObjList : TObject; aCustomMapping : TCustomMapping = nil); overload; {$IFNDEF FPC} class procedure Map<Tm>(aSrcObjList : TObject; aTgtObjList : TObject; aDoMappingProc : TMappingProc<Tm>; aCustomMapping : TCustomMapping = nil); overload; {$ELSE} class procedure Map(aSrcObjList : TObject; aTgtObjList : TObject; aDoMappingProc : TMappingProc<TObject>; aCustomMapping : TCustomMapping = nil); overload; {$ENDIF} end; {$IFNDEF FPC} TMapper = class public class function Map<T : class, constructor>(aSrcObj : TObject) : T; end; {$ENDIF} TMapper<T : class, constructor> = class public class function Map(aSrcObj : TObject; aCustomMapping: TCustomMapping = nil): T; overload; class procedure Map(aSrcObj : TObject; aTgtObj : T; aCustomMapping : TCustomMapping = nil); overload; {$IFNDEF FPC} class function Map<Tm>(aSrcObj : TObject; aDoMappingProc : TMappingProc<Tm>; aCustomMapping: TCustomMapping = nil): T; overload; class procedure Map<Tm>(aSrcObj : TObject; aTgtObj : T; aDoMappingProc : TMappingProc<Tm>; aCustomMapping: TCustomMapping = nil); overload; {$ELSE} class function Map(aSrcObj : TObject; aDoMappingProc : TMappingProc<TObject>; aCustomMapping: TCustomMapping = nil): T; overload; class procedure Map(aSrcObj : TObject; aTgtObj : T; aDoMappingProc : TMappingProc<TObject>; aCustomMapping: TCustomMapping); {$ENDIF} end; IAutoMapper<TClass1, TClass2 : class, constructor> = interface ['{9F7B2DEA-76D8-4DD1-95D0-22C22AEB5DD0}'] function Map(aSrcObj : TClass1) : TClass2; overload; {$IFNDEF FPC} function Map(aSrcObj : TClass2) : TClass1; overload; procedure SetOnDoMapping(CustomProc : TMappingProc<TClass1>); procedure SetOnAfterMapping(CustomProc : TAfterMappingProc<TClass1,TClass2>); {$ELSE} //freepascal detects overload with generic types as duplicated function, added dummy field to avoid this function Map(aSrcObj : TClass2; dummy : Boolean = True) : TClass1; overload; {$ENDIF} end; TAutoMapper<TClass1, TClass2 : class, constructor> = class(TInterfacedObject, IAutoMapper<TClass1, TClass2>) private fCustomMapping : TCustomMapping; {$IFNDEF FPC} fOnDoMapping : TMappingProc<TClass1>; {$ELSE} fOnDoMapping : TMappingProc<TObject>; {$ENDIF} fOnAfterMapping : TAfterMappingProc<TClass1,TClass2>; public constructor Create; destructor Destroy; override; property CustomMapping : TCustomMapping read fCustomMapping write fCustomMapping; {$IFNDEF FPC} property OnDoMapping : TMappingProc<TClass1> read fOnDoMapping write fOnDoMapping; {$ELSE} property OnDoMapping : TMappingProc<TObject> read fOnDoMapping write fOnDoMapping; {$ENDIF} property OnAfterMapping : TAfterMappingProc<TClass1,TClass2> read fOnAfterMapping write fOnAfterMapping; function Map(aSrcObj : TClass1) : TClass2; overload; {$IFNDEF FPC} function Map(aSrcObj : TClass2) : TClass1; overload; procedure SetOnDoMapping(CustomProc : TMappingProc<TClass1>); procedure SetOnAfterMapping(CustomProc : TAfterMappingProc<TClass1,TClass2>); {$ELSE} //freepascal detects overload with generic types as duplicated function, added dummy field to avoid this function Map(aSrcObj : TClass2; dummy : Boolean = True) : TClass1; overload; {$ENDIF} end; EAutoMapperError = class(Exception); implementation { TObjMapper } class procedure TObjMapper.Map(aSrcObj : TObject; aTgtObj : TObject; aCustomMapping: TCustomMapping = nil); begin Map{$IFNDEF FPC}<TObject>{$ENDIF}(aSrcObj,aTgtObj,nil,aCustomMapping); end; {$IFNDEF FPC} class procedure TObjMapper.Map<Tm>(aSrcObj : TObject; aTgtObj : TObject; aDoMappingProc : TMappingProc<Tm>; aCustomMapping: TCustomMapping = nil); {$ELSE} class procedure TObjMapper.Map(aSrcObj : TObject; aTgtObj : TObject; aDoMappingProc : TMappingProc<TObject>; aCustomMapping: TCustomMapping = nil); {$ENDIF} var ctx : TRttiContext; rType : TRttiType; tgtprop : TRttiProperty; mapname : string; obj : TObject; manualmapping : Boolean; value : TFlexValue; {$IFNDEF FPC} clname : string; objvalue : TValue; {$ENDIF} begin //if aTgtObj = nil then aTgtObj := GetTypeData(aTgtObj.ClassInfo).classType.Create; if aTgtObj = nil then raise EAutoMapperError.Create('TObjMapper: Target Object passed must be created before'); {$IFNDEF FPC} objvalue := TValue.From(aSrcObj); {$ENDIF} rType := ctx.GetType(aSrcObj.ClassInfo); for tgtprop in ctx.GetType(aTgtObj.ClassInfo).GetProperties do begin if tgtprop.IsWritable then begin if not tgtprop.PropertyType.IsInstance then begin if Assigned(aCustomMapping) and (not Assigned(aDoMappingProc)) then begin if aCustomMapping.GetMap(tgtprop.Name,mapname) then begin {$IFNDEF PROPERTYPATH_MODE} if rType.GetProperty(mapname) = nil then raise EAutoMapperError.CreateFmt('No valid custom mapping (Source: %s - Target: %s)',[mapname,tgtprop.Name]); begin try {$IFNDEF FPC} tgtprop.SetValue(aTgtObj,rType.GetProperty(mapname).GetValue(aSrcObj)); {$ELSE} SetPropValue(aTgtObj,tgtprop.Name,GetPropValue(aSrcObj,mapname)); {$ENDIF} except on E : Exception do raise EAutoMapperError.CreateFmt('Error mapping property "%s" : %s',[tgtprop.Name,e.message]); end; end; {$ELSE} if not TRTTI.PathExists(aSrcObj,mapname) then raise EAutoMapperError.CreateFmt('No valid custom mapping (Source: %s - Target: %s)',[mapname,tgtprop.Name]); TRTTI.SetPathValue(aTgtObj,tgtprop.Name,TRTTI.GetPathValue(aSrcObj,mapname)); {$ENDIF} end else begin if rType.GetProperty(tgtprop.Name) <> nil then try {$IFNDEF FPC} tgtprop.SetValue(aTgtObj,rType.GetProperty(tgtprop.Name).GetValue(aSrcObj)); {$ELSE} SetPropValue(aTgtObj,tgtprop.Name,GetPropValue(aSrcObj,tgtprop.Name)); {$ENDIF} except on E : Exception do raise EAutoMapperError.CreateFmt('Error mapping property "%s" : %s',[tgtprop.Name,e.message]); end; end; end else begin try if Assigned(aDoMappingProc) then begin {$IFNDEF FPC} aDoMappingProc(objvalue.AsType<Tm>,tgtprop.Name,value); manualmapping := not value.IsEmpty; {$ELSE} aDoMappingProc(aSrcObj,tgtprop.Name,value); manualmapping := not varType(value) = varEmpty; {$ENDIF} end else manualmapping := False; if manualmapping then begin {$IFNDEF FPC} tgtprop.SetValue(aTgtObj,value); {$ELSE} SetPropValue(aTgtObj,tgtprop.Name,value); {$ENDIF} end else begin {$IFNDEF FPC} if rType.GetProperty(tgtprop.Name) <> nil then tgtprop.SetValue(aTgtObj,rType.GetProperty(tgtprop.Name).GetValue(aSrcObj)); {$ELSE} if rType.GetProperty(tgtprop.Name) <> nil then SetPropValue(aTgtObj,tgtprop.Name,GetPropValue(aSrcObj,tgtprop.Name)); {$ENDIF} end; except on E : Exception do raise EAUtoMapperError.CreateFmt('Error mapping property "%s" : %s',[tgtprop.Name,e.message]); end; end; end else begin obj := tgtprop.GetValue(aTgtObj).AsObject; {$IFNDEF FPC} if obj = nil then obj := GetObjectProp(aSrcObj,tgtprop.Name).ClassType.Create;// TObject.Create; {$ELSE} if obj = nil then obj := GetObjectProp(aSrcObj,tgtprop.Name).ClassType.Create; {$ENDIF} if obj <> nil then begin {$IFNDEF FPC} try if (rType.GetProperty(tgtprop.Name) <> nil) and (not rType.GetProperty(tgtprop.Name).GetValue(aSrcObj).IsEmpty) then clname := rType.GetProperty(tgtprop.Name).GetValue(aSrcObj).AsObject.ClassName else Continue; except on E : Exception do raise EAUtoMapperError.CreateFmt('Error mapping property "%s" : %s',[tgtprop.Name,e.message]); end; if clname.StartsWith('TList') then TListMapper.Map(rType.GetProperty(tgtprop.Name).GetValue(aSrcObj).AsObject,obj,aCustomMapping) else if clname.StartsWith('TObjectList') then TObjListMapper.Map(rType.GetProperty(tgtprop.Name).GetValue(aSrcObj).AsObject,obj,aCustomMapping) else TObjMapper.Map(rType.GetProperty(tgtprop.Name).GetValue(aSrcObj).AsObject,obj,aCustomMapping) {$ELSE} TObjMapper.Map(GetObjectProp(aSrcObj,tgtprop.Name),obj,aCustomMapping); SetObjectProp(aTgtObj,tgtprop.Name,obj); {$ENDIF} end else raise EAutoMapperError.CreateFmt('Target object "%s" not autocreated by class',[tgtprop.Name]); end; end; end; end; class function TMapper<T>.Map(aSrcObj : TObject; aCustomMapping: TCustomMapping = nil) : T; begin Result := Map{$IFNDEF FPC}<TObject>{$ENDIF}(aSrcObj,nil,aCustomMapping); end; {$IFNDEF FPC} class function TMapper<T>.Map<Tm>(aSrcObj : TObject; aDoMappingProc : TMappingProc<Tm>; aCustomMapping: TCustomMapping = nil): T; {$ELSE} class function TMapper<T>.Map(aSrcObj : TObject; aDoMappingProc : TMappingProc<TObject>; aCustomMapping: TCustomMapping = nil): T; {$ENDIF} var obj : T; begin obj := T.Create; {$IFNDEF FPC} TObjMapper.Map<Tm>(aSrcObj,obj,aDoMappingProc,aCustomMapping); {$ELSE} TObjMapper.Map(aSrcObj,obj,aDoMappingProc,aCustomMapping); {$ENDIF} Result := obj; end; class procedure TMapper<T>.Map(aSrcObj : TObject; aTgtObj : T; aCustomMapping : TCustomMapping = nil); begin {$IFNDEF FPC} Map<T>(aSrcObj,aTgtObj,nil,aCustomMapping); {$ELSE} Map(aSrcObj,aTgtObj,nil,aCustomMapping); {$ENDIF} end; {$IFNDEF FPC} class procedure TMapper<T>.Map<Tm>(aSrcObj : TObject; aTgtObj : T; aDoMappingProc : TMappingProc<Tm>; aCustomMapping : TCustomMapping = nil); {$ELSE} class procedure TMapper<T>.Map(aSrcObj : TObject; aTgtObj : T; aDoMappingProc : TMappingProc<TObject>; aCustomMapping : TCustomMapping); {$ENDIF} begin {$IFNDEF FPC} TObjMapper.Map<Tm>(aSrcObj, aTgtObj, aDoMappingProc, aCustomMapping); {$ELSE} TObjMapper.Map(aSrcObj, aTgtObj, aDoMappingProc, aCustomMapping); {$ENDIF} end; { TAutoMapper<TClass1, TClass2> } constructor TAutoMapper<TClass1, TClass2>.Create; begin fCustomMapping := TCustomMapping.Create; fOnDoMapping := nil; fOnAfterMapping := nil; end; destructor TAutoMapper<TClass1, TClass2>.Destroy; begin if Assigned(fCustomMapping) then fCustomMapping.Free; fOnDoMapping := nil; fOnAfterMapping := nil; inherited; end; function TAutoMapper<TClass1, TClass2>.Map(aSrcObj: TClass1): TClass2; var objvalue : TValue; obj : TObject; begin obj := aSrcObj as TObject; //objvalue := TValue.From(aSrcObj).AsObject; {$IFNDEF FPC} Result := TMapper<TClass2>.Map<TClass1>(obj,fOnDoMapping,fCustomMapping); {$ELSE} Result := TMapper<TClass2>.Map(obj,fOnDoMapping,fCustomMapping); {$ENDIF} if Assigned(fOnAfterMapping) then fOnAfterMapping(aSrcObj,Result); end; {$IFNDEF FPC} function TAutoMapper<TClass1, TClass2>.Map(aSrcObj: TClass2): TClass1; begin Result := TMapper<TClass1>.Map<TClass1>(aSrcObj,fOnDoMapping,fCustomMapping); end; procedure TAutoMapper<TClass1, TClass2>.SetOnAfterMapping(CustomProc: TAfterMappingProc<TClass1, TClass2>); begin fOnAfterMapping := CustomProc; end; procedure TAutoMapper<TClass1, TClass2>.SetOnDoMapping(CustomProc: TMappingProc<TClass1>); begin fOnDoMapping := CustomProc; end; {$ELSE} function TAutoMapper<TClass1, TClass2>.Map(aSrcObj: TClass2; dummy : Boolean = True): TClass1; begin Result := TMapper<TClass1>.Map(aSrcObj,fOnDoMapping,fCustomMapping); end; {$ENDIF} { TCustomMapping } procedure TCustomMapping.AddMap(const aName, aMapName: string); begin //add map fields fMapDictionary.Add(aName,aMapName); //add reverse lookup if not same name if aName <> aMapName then fMapDictionary.Add(aMapName,aName); end; function TCustomMapping.Count: Integer; begin Result := fMapDictionary.Count; end; constructor TCustomMapping.Create; begin fMapDictionary := TDictionary<string,string>.Create; end; destructor TCustomMapping.Destroy; begin fMapDictionary.Free; inherited; end; function TCustomMapping.GetMap(const aName: string; out vMapName: string): Boolean; begin Result := fMapDictionary.TryGetValue(aName,vMapName); end; { TListMapper } class procedure TListMapper.Map(aSrcList, aTgtList: TObject; aCustomMapping: TCustomMapping); {$IFNDEF FPC} var rtype: TRttiType; rtype2 : TRttiType; typinfo : PTypeInfo; methToArray: TRttiMethod; value: TValue; valuecop : TValue; obj : TObject; i : Integer; rprop : TRttiProperty; ctx : TRttiContext; begin rtype := ctx.GetType(aSrcList.ClassInfo); methToArray := rtype.GetMethod('ToArray'); if Assigned(methToArray) then begin value := methToArray.Invoke(aSrcList,[]); Assert(value.IsArray); rtype2 := ctx.GetType(aTgtList.ClassInfo); rProp := rtype2.GetProperty('List'); typinfo := GetTypeData(rProp.PropertyType.Handle).DynArrElType^; case typinfo.Kind of tkChar, tkString, tkWChar, tkWString : TList<string>(aTgtList).Capacity := value.GetArrayLength; tkInteger, tkInt64 : TList<Integer>(aTgtList).Capacity := value.GetArrayLength; tkFloat : TList<Extended>(aTgtList).Capacity := value.GetArrayLength; tkRecord : begin TObjMapper.Map(aSrcList,aTgtList,aCustomMapping); exit; end; else TList<TObject>(aTgtList).Capacity := value.GetArrayLength; end; for i := 0 to value.GetArrayLength - 1 do begin if typinfo.Kind = tkClass then begin obj := typinfo.TypeData.ClassType.Create; TObjMapper.Map(value.GetArrayElement(i).AsObject,obj,aCustomMapping); TList<TObject>(aTgtList).Add(obj); end else begin valuecop := value.GetArrayElement(i); case typinfo.Kind of tkChar, tkString, tkWChar, tkWString : TList<string>(aTgtList).Add(valuecop.AsString); tkInteger, tkInt64 : TList<Integer>(aTgtList).Add(valuecop.AsInt64); tkFloat : TList<Extended>(aTgtList).Add(valuecop.AsExtended); end; end; end; end; end; {$ELSE} begin end; {$ENDIF} { TObjListMapper } class procedure TObjListMapper.Map(aSrcObjList, aTgtObjList: TObject; aCustomMapping: TCustomMapping); begin {$IFNDEF FPC} Map<TObject>(aSrcObjList,aTgtObjList,nil,aCustomMapping); {$ELSE} Map(aSrcObjList,aTgtObjList,nil,aCustomMapping); {$ENDIF} end; {$IFNDEF FPC} class procedure TObjListMapper.Map<Tm>(aSrcObjList : TObject; aTgtObjList : TObject; aDoMappingProc : TMappingProc<Tm>; aCustomMapping : TCustomMapping = nil); var rtype: TRttiType; rtype2 : TRttiType; typinfo : PTypeInfo; methToArray: TRttiMethod; value: TValue; obj : TObject; i : Integer; rprop : TRttiProperty; ctx : TRttiContext; begin rtype := ctx.GetType(aSrcObjList.ClassInfo); methToArray := rtype.GetMethod('ToArray'); if Assigned(methToArray) then begin value := methToArray.Invoke(aSrcObjList,[]); Assert(value.IsArray); rtype2 := ctx.GetType(aTgtObjList.ClassInfo); rProp := rtype2.GetProperty('List'); typinfo := GetTypeData(rProp.PropertyType.Handle).DynArrElType^; TObjectList<TObject>(aTgtObjList).Capacity := value.GetArrayLength; for i := 0 to value.GetArrayLength - 1 do begin obj := typinfo.TypeData.ClassType.Create; TObjMapper.Map<Tm>(value.GetArrayElement(i).AsObject,obj,aDoMappingProc,aCustomMapping); TObjectList<TObject>(aTgtObjList).Add(obj); end; end; end; {$ELSE} class procedure TObjListMapper.Map(aSrcObjList : TObject; aTgtObjList : TObject; aDoMappingProc : TMappingProc<TObject>; aCustomMapping : TCustomMapping = nil); begin end; {$ENDIF} { TMapper } {$IFNDEF FPC} class function TMapper.Map<T>(aSrcObj: TObject): T; begin Result := T.Create; TObjMapper.Map(aSrcObj,Result,nil); end; {$ENDIF} end.
unit CalcDemos; interface uses SysUtils, Classes, tfTypes, tfBytes, tfHashes; procedure FluentCalcHash(const FileName: string); procedure CalcHash(const FileName: string); procedure SHA1_HMAC_File(const FileName: string; const Key: ByteArray); procedure DeriveKeys(const Password, Salt: ByteArray); implementation procedure FluentCalcHash(const FileName: string); begin Writeln('MD5: ', THash.MD5.UpdateFile(FileName).Digest.ToHex); Writeln('SHA1: ', THash.SHA1.UpdateFile(FileName).Digest.ToHex); Writeln('CRC32: ', IntToHex(LongWord(THash.CRC32.UpdateFile(FileName).Digest), 8)); Writeln('CRC32: ', THash.CRC32.UpdateFile(FileName).Digest.ToHex); end; procedure CalcHash(const FileName: string); const BufSize = 16 * 1024; var MD5, SHA1: THash; Stream: TStream; Buffer: array[0 .. BufSize - 1] of Byte; N: Integer; begin MD5:= THash.MD5; SHA1:= THash.SHA1; // try Stream:= TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try repeat N:= Stream.Read(Buffer, BufSize); if N <= 0 then Break else begin MD5.Update(Buffer, N); SHA1.Update(Buffer, N); end; until False; finally Stream.Free; end; Writeln('MD5: ', MD5.Digest.ToHex); Writeln('SHA1: ', SHA1.Digest.ToHex); // finally // MD5.Burn; // SHA1.Burn; // end; end; procedure SHA1_HMAC_File(const FileName: string; const Key: ByteArray); begin Writeln('SHA1-HMAC: ', THMAC.SHA1.ExpandKey(Key).UpdateFile(FileName).Digest.ToHex); end; procedure DeriveKeys(const Password, Salt: ByteArray); begin Writeln('PBKDF1 Key: ', THash.SHA1.DeriveKey(Password, Salt, 10000, // number of rounds 16 // key length in bytes ).ToHex); Writeln('PBKDF2 Key: ', THMAC.SHA1.DeriveKey(Password, Salt, 10000, // number of rounds 32 // key length in bytes ).ToHex); end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { { Rev 1.1 2004.02.03 5:44:18 PM czhower { Name changes } { { Rev 1.0 11/13/2002 08:00:40 AM JPMugaas } { Base class for any mechanism that needs a username/password. This links to a TIdUserPassProvider to allow application programmers to only set the username/password once, instead of having to set it for all SASL mechanisms they might want to use. } unit IdSASLUserPass; interface uses IdResourceStringsProtocols, IdSASL, IdUserPassProvider, IdObjs, IdBaseComponent, IdException; type TIdSASLUserPass = class(TIdSASL) protected FUserPassProvider: TIdUserPassProvider; procedure SetUserPassProvider(const Value: TIdUserPassProvider); procedure Notification(AComponent: TIdNativeComponent; Operation: TIdOperation); override; function GetUsername: string; function GetPassword: string; published property UserPassProvider: TIdUserPassProvider read FUserPassProvider write SetUserPassProvider; end; EIdUserPassProviderUnassigned = class(EIdException); implementation { TIdSASLUserPass } function TIdSASLUserPass.GetPassword: string; begin if Assigned(FUserPassProvider) then begin Result := FUserPassProvider.GetPassword; end else begin raise EIdUserPassProviderUnassigned.Create(RSUnassignedUserPassProv); end; end; function TIdSASLUserPass.GetUsername: string; begin if Assigned(FUserPassProvider) then begin Result := FUserPassProvider.GetUsername; end else begin raise EIdUserPassProviderUnassigned.Create(RSUnassignedUserPassProv); end; end; procedure TIdSASLUserPass.Notification(AComponent: TIdNativeComponent; Operation: TIdOperation); begin if Operation = opRemove then begin if AComponent = FUserPassProvider then begin FUserPassProvider := nil; end; end; inherited; end; procedure TIdSASLUserPass.SetUserPassProvider( const Value: TIdUserPassProvider); begin FUserPassProvider := Value; if Assigned(FUserPassProvider) then begin FUserPassProvider.FreeNotification(Self); end; end; end.
(** This module contains methods for initialising all the various wizard interfaces required by the application. @Version 1.0 @Author David Hoyle @Date 19 Dec 2016 **) Unit InitialiseOTAInterface; Interface Uses ToolsAPI; {$INCLUDE 'CompilerDefinitions.inc'} Procedure Register; Function InitWizard(Const BorlandIDEServices : IBorlandIDEServices; RegisterProc : TWizardRegisterProc; var Terminate: TWizardTerminateProc) : Boolean; StdCall; Exports InitWizard Name WizardEntryPoint; Implementation Uses SysUtils, Forms, Windows, WizardInterface, KeyboardBindingInterface, UtilityFunctions, DockableBrowserForm; Type (** An enumerate to define the type of wizard to be created. **) TWizardType = (wtPackageWizard, wtDLLWizard); Const (** This is a constant which is initially assigned to all wizard indexes to signify a failed initialisation state. **) iWizardFailState = -1; Var {$IFDEF D2005} (** A variable to hold the version information for the application. **) VersionInfo : TVersionInfo; (** A variable to hold the bitmap for the application. **) {$IFDEF D2007} (** This is a 24x24 butmap variabes for the splash scren in RAD Studio 2007 and above. **) bmSplashScreen24x24 : HBITMAP; {$ENDIF} (** This is a 48x48 butmap variabes for the splash scren in RAD Studio 2005/6 and the about box in 2005 and above. **) bmSplashScreen48x48 : HBITMAP; {$ENDIF} (** A variabel to hold the wizard index for the main wizard. **) iWizardIndex : Integer = iWizardFailState; {$IFDEF D0006} (** A variabel to hold the wizard index for the about pluging. **) iAboutPluginIndex : Integer = iWizardFailState; {$ENDIF} (** A variabel to hold the wizard index for the key binding wizard. **) iKeyBindingIndex : Integer = iWizardFailState; {$IFDEF D2005} Const (** This constant represents a zero based list of bug fix letters. **) strRevision : String = ' abcdefghijklmnopqrstuvwxyz'; ResourceString (** This resource string is the for splash screen name. **) strSplashScreenName = 'IDE Help Helper %d.%d%s for %s'; (** This resource string is for the splash screen build information. **) strSplashScreenBuild = 'Freeware by David Hoyle (Build %d.%d.%d.%d)'; {$ENDIF} (** This method is called when the wizard is initialised. @precon None. @postcon Initialises all the wizard interfaces for this application. @param WizardType as a TWizardType @return a TWizardTemplate **) Function InitialiseWizard(WizardType : TWizardType) : TWizardTemplate; Var Svcs : IOTAServices; Begin Svcs := BorlandIDEServices As IOTAServices; ToolsAPI.BorlandIDEServices := BorlandIDEServices; Application.Handle := Svcs.GetParentHandle; {$IFDEF D2005} // Aboutbox plugin bmSplashScreen48x48 := LoadBitmap(hInstance, 'DGHIDEHelpHelperSplashScreenBitMap48x48'); With VersionInfo Do iAboutPluginIndex := (BorlandIDEServices As IOTAAboutBoxServices).AddPluginInfo( Format(strSplashScreenName, [iMajor, iMinor, Copy(strRevision, iBugFix + 1, 1), Application.Title]), 'A wizard to intercept F1 calls and look up help on the web if not handled by the IDE..', bmSplashScreen48x48, False, Format(strSplashScreenBuild, [iMajor, iMinor, iBugfix, iBuild]), Format('SKU Build %d.%d.%d.%d', [iMajor, iMinor, iBugfix, iBuild])); {$ENDIF} // Create Wizard / Menu Wizard Result := TWizardTemplate.Create; If WizardType = wtPackageWizard Then // Only register main wizard this way if PACKAGE iWizardIndex := (BorlandIDEServices As IOTAWizardServices).AddWizard(Result); // Create Keyboard Binding Interface iKeyBindingIndex := (BorlandIDEServices As IOTAKeyboardServices).AddKeyboardBinding( TKeybindingTemplate.Create); End; (** This method is required for Package experts to initialise the expert. @precon None. @postcon The experts is initialised. **) procedure Register; begin InitialiseWizard(wtPackageWizard); end; (** This method is required by DLL experts for the IDE to initialise the expert. @precon None. @postcon Initialises the interfaces by calling the InitaliseWizard method and pass this to the RegisterProc method of the IDE. @param BorlandIDEServices as an IBorlandIDEServices as a constant @param RegisterProc as a TWizardRegisterProc @param Terminate as a TWizardTerminateProc as a reference @return a Boolean **) Function InitWizard(Const BorlandIDEServices : IBorlandIDEServices; RegisterProc : TWizardRegisterProc; var Terminate: TWizardTerminateProc) : Boolean; StdCall; Begin Result := BorlandIDEServices <> Nil; If Result Then RegisterProc(InitialiseWizard(wtDLLWizard)); End; (** The initialisation section creates the dockable browser form and adds an item to the splash screen for the application. **) Initialization TfrmDockableBrowser.CreateDockableBrowser; {$IFDEF D2005} BuildNumber(VersionInfo); // Add Splash Screen {$IFDEF D2007} bmSplashScreen24x24 := LoadBitmap(hInstance, 'DGHIDEHelpHelperSplashScreenBitMap24x24'); {$ELSE} bmSplashScreen48x48 := LoadBitmap(hInstance, 'DGHIDEHelpHelperSplashScreenBitMap48x48'); {$ENDIF} With VersionInfo Do (SplashScreenServices As IOTASplashScreenServices).AddPluginBitmap( Format(strSplashScreenName, [iMajor, iMinor, Copy(strRevision, iBugFix + 1, 1), Application.Title]), {$IFDEF D2007} bmSplashScreen24x24, {$ELSE} bmSplashScreen48x48, {$ENDIF} False, Format(strSplashScreenBuild, [iMajor, iMinor, iBugfix, iBuild])); {$ENDIF} (** The finalisation section removes the about boc, splash screen entries and wizard interfaces and frees the dockable browser. **) Finalization // Remove Wizard Interface If iWizardIndex > iWizardFailState Then (BorlandIDEServices As IOTAWizardServices).RemoveWizard(iWizardIndex); {$IFDEF D2005} // Remove Aboutbox Plugin Interface If iAboutPluginIndex > iWizardFailState Then (BorlandIDEServices As IOTAAboutBoxServices).RemovePluginInfo(iAboutPluginIndex); {$ENDIF} // Remove Keyboard Binding Interface If iKeyBindingIndex > iWizardFailState Then (BorlandIDEServices As IOTAKeyboardServices).RemoveKeyboardBinding(iKeyBindingIndex); TfrmDockableBrowser.RemoveDockableBrowser; End.